* gcc.dg/guality/guality.exp: Skip on AIX.
[official-gcc.git] / gcc / ada / s-fileio.adb
blob64b89926753b657236dbc78951b17be40ef5620a
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT RUN-TIME COMPONENTS --
4 -- --
5 -- S Y S T E M . F I L E _ I O --
6 -- --
7 -- B o d y --
8 -- --
9 -- Copyright (C) 1992-2013, Free Software Foundation, Inc. --
10 -- --
11 -- GNAT is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 3, or (at your option) any later ver- --
14 -- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. --
17 -- --
18 -- As a special exception under Section 7 of GPL version 3, you are granted --
19 -- additional permissions described in the GCC Runtime Library Exception, --
20 -- version 3.1, as published by the Free Software Foundation. --
21 -- --
22 -- You should have received a copy of the GNU General Public License and --
23 -- a copy of the GCC Runtime Library Exception along with this program; --
24 -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
25 -- <http://www.gnu.org/licenses/>. --
26 -- --
27 -- GNAT was originally developed by the GNAT team at New York University. --
28 -- Extensive contributions were provided by Ada Core Technologies Inc. --
29 -- --
30 ------------------------------------------------------------------------------
32 with Ada.Finalization; use Ada.Finalization;
33 with Ada.IO_Exceptions; use Ada.IO_Exceptions;
35 with Interfaces.C;
36 with Interfaces.C.Strings; use Interfaces.C.Strings;
37 with Interfaces.C_Streams; use Interfaces.C_Streams;
39 with System.CRTL.Runtime;
40 with System.Case_Util; use System.Case_Util;
41 with System.OS_Lib;
42 with System.Soft_Links;
44 with Ada.Unchecked_Deallocation;
46 package body System.File_IO is
48 use System.File_Control_Block;
50 package SSL renames System.Soft_Links;
52 use type Interfaces.C.int;
53 use type CRTL.size_t;
55 subtype String_Access is System.OS_Lib.String_Access;
56 procedure Free (X : in out String_Access) renames System.OS_Lib.Free;
58 function "=" (X, Y : String_Access) return Boolean
59 renames System.OS_Lib."=";
61 ----------------------
62 -- Global Variables --
63 ----------------------
65 Open_Files : AFCB_Ptr;
66 -- This points to a list of AFCB's for all open files. This is a doubly
67 -- linked list, with the Prev pointer of the first entry, and the Next
68 -- pointer of the last entry containing null. Note that this global
69 -- variable must be properly protected to provide thread safety.
71 type Temp_File_Record;
72 type Temp_File_Record_Ptr is access all Temp_File_Record;
74 type Temp_File_Record is record
75 Name : String (1 .. max_path_len + 1);
76 Next : Temp_File_Record_Ptr;
77 end record;
78 -- One of these is allocated for each temporary file created
80 Temp_Files : Temp_File_Record_Ptr;
81 -- Points to list of names of temporary files. Note that this global
82 -- variable must be properly protected to provide thread safety.
84 type File_IO_Clean_Up_Type is new Limited_Controlled with null record;
85 -- The closing of all open files and deletion of temporary files is an
86 -- action that takes place at the end of execution of the main program.
87 -- This action is implemented using a library level object which gets
88 -- finalized at the end of program execution. Note that the type is
89 -- limited, in order to stop the compiler optimizing away the declaration
90 -- which would be allowed in the non-limited case.
92 procedure Finalize (V : in out File_IO_Clean_Up_Type);
93 -- This is the finalize operation that is used to do the cleanup
95 File_IO_Clean_Up_Object : File_IO_Clean_Up_Type;
96 pragma Warnings (Off, File_IO_Clean_Up_Object);
97 -- This is the single object of the type that triggers the finalization
98 -- call. Since it is at the library level, this happens just before the
99 -- environment task is finalized.
101 text_translation_required : Boolean;
102 for text_translation_required'Size use Character'Size;
103 pragma Import
104 (C, text_translation_required, "__gnat_text_translation_required");
105 -- If true, add appropriate suffix to control string for Open
107 VMS_Formstr : String_Access := null;
108 -- For special VMS RMS keywords and values
110 -----------------------
111 -- Local Subprograms --
112 -----------------------
114 procedure Free_String is new Ada.Unchecked_Deallocation (String, Pstring);
116 subtype Fopen_String is String (1 .. 4);
117 -- Holds open string (longest is "w+b" & nul)
119 procedure Fopen_Mode
120 (Mode : File_Mode;
121 Text : Boolean;
122 Creat : Boolean;
123 Amethod : Character;
124 Fopstr : out Fopen_String);
125 -- Determines proper open mode for a file to be opened in the given
126 -- Ada mode. Text is true for a text file and false otherwise, and
127 -- Creat is true for a create call, and False for an open call. The
128 -- value stored in Fopstr is a nul-terminated string suitable for a
129 -- call to fopen or freopen. Amethod is the character designating
130 -- the access method from the Access_Method field of the FCB.
132 function Errno_Message
133 (Errno : Integer := OS_Lib.Errno) return String;
134 function Errno_Message
135 (Name : String;
136 Errno : Integer := OS_Lib.Errno) return String;
137 -- Return a message suitable for "raise ... with Errno_Message (...)".
138 -- Errno defaults to the current errno, but should be passed explicitly if
139 -- there is significant code in between the call that sets errno and the
140 -- call to Errno_Message, in case that code also sets errno. The version
141 -- with Name includes that file name in the message.
143 procedure Raise_Device_Error
144 (File : AFCB_Ptr;
145 Errno : Integer := OS_Lib.Errno);
146 pragma No_Return (Raise_Device_Error);
147 -- Clear error indication on File and raise Device_Error with an exception
148 -- message providing errno information.
150 procedure Form_VMS_RMS_Keys (Form : String; VMS_Form : out String_Access);
151 -- Parse the RMS Keys
153 function Form_RMS_Context_Key
154 (Form : String;
155 VMS_Form : String_Access) return Natural;
156 -- Parse the RMS Context Key
158 ----------------
159 -- Append_Set --
160 ----------------
162 procedure Append_Set (File : AFCB_Ptr) is
163 begin
164 if File.Mode = Append_File then
165 if fseek (File.Stream, 0, SEEK_END) /= 0 then
166 Raise_Device_Error (File);
167 end if;
168 end if;
169 end Append_Set;
171 ----------------
172 -- Chain_File --
173 ----------------
175 procedure Chain_File (File : AFCB_Ptr) is
176 begin
177 -- Take a task lock, to protect the global data value Open_Files
179 SSL.Lock_Task.all;
181 -- Do the chaining operation locked
183 File.Next := Open_Files;
184 File.Prev := null;
185 Open_Files := File;
187 if File.Next /= null then
188 File.Next.Prev := File;
189 end if;
191 SSL.Unlock_Task.all;
193 exception
194 when others =>
195 SSL.Unlock_Task.all;
196 raise;
197 end Chain_File;
199 ---------------------
200 -- Check_File_Open --
201 ---------------------
203 procedure Check_File_Open (File : AFCB_Ptr) is
204 begin
205 if File = null then
206 raise Status_Error with "file not open";
207 end if;
208 end Check_File_Open;
210 -----------------------
211 -- Check_Read_Status --
212 -----------------------
214 procedure Check_Read_Status (File : AFCB_Ptr) is
215 begin
216 if File = null then
217 raise Status_Error with "file not open";
218 elsif File.Mode not in Read_File_Mode then
219 raise Mode_Error with "file not readable";
220 end if;
221 end Check_Read_Status;
223 ------------------------
224 -- Check_Write_Status --
225 ------------------------
227 procedure Check_Write_Status (File : AFCB_Ptr) is
228 begin
229 if File = null then
230 raise Status_Error with "file not open";
231 elsif File.Mode = In_File then
232 raise Mode_Error with "file not writable";
233 end if;
234 end Check_Write_Status;
236 -----------
237 -- Close --
238 -----------
240 procedure Close (File_Ptr : access AFCB_Ptr) is
241 Close_Status : int := 0;
242 Dup_Strm : Boolean := False;
243 File : AFCB_Ptr renames File_Ptr.all;
244 Errno : Integer;
246 begin
247 -- Take a task lock, to protect the global data value Open_Files
249 SSL.Lock_Task.all;
251 Check_File_Open (File);
252 AFCB_Close (File);
254 -- Sever the association between the given file and its associated
255 -- external file. The given file is left closed. Do not perform system
256 -- closes on the standard input, output and error files and also do not
257 -- attempt to close a stream that does not exist (signalled by a null
258 -- stream value -- happens in some error situations).
260 if not File.Is_System_File and then File.Stream /= NULL_Stream then
262 -- Do not do an fclose if this is a shared file and there is at least
263 -- one other instance of the stream that is open.
265 if File.Shared_Status = Yes then
266 declare
267 P : AFCB_Ptr;
269 begin
270 P := Open_Files;
271 while P /= null loop
272 if P /= File and then File.Stream = P.Stream then
273 Dup_Strm := True;
274 exit;
275 end if;
277 P := P.Next;
278 end loop;
279 end;
280 end if;
282 -- Do the fclose unless this was a duplicate in the shared case
284 if not Dup_Strm then
285 Close_Status := fclose (File.Stream);
287 if Close_Status /= 0 then
288 Errno := OS_Lib.Errno;
289 end if;
290 end if;
291 end if;
293 -- Dechain file from list of open files and then free the storage
295 if File.Prev = null then
296 Open_Files := File.Next;
297 else
298 File.Prev.Next := File.Next;
299 end if;
301 if File.Next /= null then
302 File.Next.Prev := File.Prev;
303 end if;
305 -- Deallocate some parts of the file structure that were kept in heap
306 -- storage with the exception of system files (standard input, output
307 -- and error) since they had some information allocated in the stack.
309 if not File.Is_System_File then
310 Free_String (File.Name);
311 Free_String (File.Form);
312 AFCB_Free (File);
313 end if;
315 File := null;
317 if Close_Status /= 0 then
318 Raise_Device_Error (null, Errno);
319 end if;
321 SSL.Unlock_Task.all;
323 exception
324 when others =>
325 SSL.Unlock_Task.all;
326 raise;
327 end Close;
329 ------------
330 -- Delete --
331 ------------
333 procedure Delete (File_Ptr : access AFCB_Ptr) is
334 File : AFCB_Ptr renames File_Ptr.all;
336 begin
337 Check_File_Open (File);
339 if not File.Is_Regular_File then
340 raise Use_Error with "cannot delete non-regular file";
341 end if;
343 declare
344 Filename : aliased constant String := File.Name.all;
346 begin
347 Close (File_Ptr);
349 -- Now unlink the external file. Note that we use the full name in
350 -- this unlink, because the working directory may have changed since
351 -- we did the open, and we want to unlink the right file!
353 if unlink (Filename'Address) = -1 then
354 raise Use_Error with Errno_Message;
355 end if;
356 end;
357 end Delete;
359 -----------------
360 -- End_Of_File --
361 -----------------
363 function End_Of_File (File : AFCB_Ptr) return Boolean is
364 begin
365 Check_File_Open (File);
367 if feof (File.Stream) /= 0 then
368 return True;
370 else
371 Check_Read_Status (File);
373 if ungetc (fgetc (File.Stream), File.Stream) = EOF then
374 clearerr (File.Stream);
375 return True;
376 else
377 return False;
378 end if;
379 end if;
380 end End_Of_File;
382 -------------------
383 -- Errno_Message --
384 -------------------
386 function Errno_Message (Errno : Integer := OS_Lib.Errno) return String is
387 Message : constant chars_ptr := CRTL.Runtime.strerror (Errno);
389 begin
390 if Message = Null_Ptr then
391 return "errno =" & Errno'Img;
392 else
393 return Value (Message);
394 end if;
395 end Errno_Message;
397 function Errno_Message
398 (Name : String;
399 Errno : Integer := OS_Lib.Errno) return String
401 begin
402 return Name & ": " & String'(Errno_Message (Errno));
403 end Errno_Message;
405 --------------
406 -- Finalize --
407 --------------
409 -- Note: we do not need to worry about locking against multiple task access
410 -- in this routine, since it is called only from the environment task just
411 -- before terminating execution.
413 procedure Finalize (V : in out File_IO_Clean_Up_Type) is
414 pragma Warnings (Off, V);
416 Fptr1 : aliased AFCB_Ptr;
417 Fptr2 : AFCB_Ptr;
419 Discard : int;
420 pragma Unreferenced (Discard);
422 begin
423 -- Take a lock to protect global Open_Files data structure
425 SSL.Lock_Task.all;
427 -- First close all open files (the slightly complex form of this loop is
428 -- required because Close as a side effect nulls out its argument).
430 Fptr1 := Open_Files;
431 while Fptr1 /= null loop
432 Fptr2 := Fptr1.Next;
433 Close (Fptr1'Access);
434 Fptr1 := Fptr2;
435 end loop;
437 -- Now unlink all temporary files. We do not bother to free the blocks
438 -- because we are just about to terminate the program. We also ignore
439 -- any errors while attempting these unlink operations.
441 while Temp_Files /= null loop
442 Discard := unlink (Temp_Files.Name'Address);
443 Temp_Files := Temp_Files.Next;
444 end loop;
446 SSL.Unlock_Task.all;
448 exception
449 when others =>
450 SSL.Unlock_Task.all;
451 raise;
452 end Finalize;
454 -----------
455 -- Flush --
456 -----------
458 procedure Flush (File : AFCB_Ptr) is
459 begin
460 Check_Write_Status (File);
462 if fflush (File.Stream) /= 0 then
463 Raise_Device_Error (File);
464 end if;
465 end Flush;
467 ----------------
468 -- Fopen_Mode --
469 ----------------
471 -- The fopen mode to be used is shown by the following table:
473 -- OPEN CREATE
474 -- Append_File "r+" "w+"
475 -- In_File "r" "w+"
476 -- Out_File (Direct_IO) "r+" "w"
477 -- Out_File (all others) "w" "w"
478 -- Inout_File "r+" "w+"
480 -- Note: we do not use "a" or "a+" for Append_File, since this would not
481 -- work in the case of stream files, where even if in append file mode,
482 -- you can reset to earlier points in the file. The caller must use the
483 -- Append_Set routine to deal with the necessary positioning.
485 -- Note: in several cases, the fopen mode used allows reading and writing,
486 -- but the setting of the Ada mode is more restrictive. For instance,
487 -- Create in In_File mode uses "w+" which allows writing, but the Ada mode
488 -- In_File will cause any write operations to be rejected with Mode_Error
489 -- in any case.
491 -- Note: for the Out_File/Open cases for other than the Direct_IO case, an
492 -- initial call will be made by the caller to first open the file in "r"
493 -- mode to be sure that it exists. The real open, in "w" mode, will then
494 -- destroy this file. This is peculiar, but that's what Ada semantics
495 -- require and the ACATS tests insist on!
497 -- If text file translation is required, then either "b" or "t" is appended
498 -- to the mode, depending on the setting of Text.
500 procedure Fopen_Mode
501 (Mode : File_Mode;
502 Text : Boolean;
503 Creat : Boolean;
504 Amethod : Character;
505 Fopstr : out Fopen_String)
507 Fptr : Positive;
509 begin
510 case Mode is
511 when In_File =>
512 if Creat then
513 Fopstr (1) := 'w';
514 Fopstr (2) := '+';
515 Fptr := 3;
516 else
517 Fopstr (1) := 'r';
518 Fptr := 2;
519 end if;
521 when Out_File =>
522 if Amethod = 'D' and then not Creat then
523 Fopstr (1) := 'r';
524 Fopstr (2) := '+';
525 Fptr := 3;
526 else
527 Fopstr (1) := 'w';
528 Fptr := 2;
529 end if;
531 when Inout_File | Append_File =>
532 Fopstr (1) := (if Creat then 'w' else 'r');
533 Fopstr (2) := '+';
534 Fptr := 3;
535 end case;
537 -- If text_translation_required is true then we need to append either a
538 -- "t" or "b" to the string to get the right mode.
540 if text_translation_required then
541 Fopstr (Fptr) := (if Text then 't' else 'b');
542 Fptr := Fptr + 1;
543 end if;
545 Fopstr (Fptr) := ASCII.NUL;
546 end Fopen_Mode;
548 ----------
549 -- Form --
550 ----------
552 function Form (File : AFCB_Ptr) return String is
553 begin
554 if File = null then
555 raise Status_Error with "Form: file not open";
556 else
557 return File.Form.all (1 .. File.Form'Length - 1);
558 end if;
559 end Form;
561 ------------------
562 -- Form_Boolean --
563 ------------------
565 function Form_Boolean
566 (Form : String;
567 Keyword : String;
568 Default : Boolean) return Boolean
570 V1, V2 : Natural;
571 pragma Unreferenced (V2);
573 begin
574 Form_Parameter (Form, Keyword, V1, V2);
576 if V1 = 0 then
577 return Default;
578 elsif Form (V1) = 'y' then
579 return True;
580 elsif Form (V1) = 'n' then
581 return False;
582 else
583 raise Use_Error with "invalid Form";
584 end if;
585 end Form_Boolean;
587 ------------------
588 -- Form_Integer --
589 ------------------
591 function Form_Integer
592 (Form : String;
593 Keyword : String;
594 Default : Integer) return Integer
596 V1, V2 : Natural;
597 V : Integer;
599 begin
600 Form_Parameter (Form, Keyword, V1, V2);
602 if V1 = 0 then
603 return Default;
605 else
606 V := 0;
608 for J in V1 .. V2 loop
609 if Form (J) not in '0' .. '9' then
610 raise Use_Error with "invalid Form";
611 else
612 V := V * 10 + Character'Pos (Form (J)) - Character'Pos ('0');
613 end if;
615 if V > 999_999 then
616 raise Use_Error with "invalid Form";
617 end if;
618 end loop;
620 return V;
621 end if;
622 end Form_Integer;
624 --------------------
625 -- Form_Parameter --
626 --------------------
628 procedure Form_Parameter
629 (Form : String;
630 Keyword : String;
631 Start : out Natural;
632 Stop : out Natural)
634 Klen : constant Integer := Keyword'Length;
636 begin
637 for J in Form'First + Klen .. Form'Last - 1 loop
638 if Form (J) = '='
639 and then Form (J - Klen .. J - 1) = Keyword
640 then
641 Start := J + 1;
642 Stop := Start - 1;
643 while Form (Stop + 1) /= ASCII.NUL
644 and then Form (Stop + 1) /= ','
645 loop
646 Stop := Stop + 1;
647 end loop;
649 return;
650 end if;
651 end loop;
653 Start := 0;
654 Stop := 0;
655 end Form_Parameter;
657 --------------------------
658 -- Form_RMS_Context_Key --
659 --------------------------
661 function Form_RMS_Context_Key
662 (Form : String;
663 VMS_Form : String_Access) return Natural
665 type Context_Parms is
666 (Binary_Data, Convert_Fortran_Carriage_Control, Force_Record_Mode,
667 Force_Stream_Mode, Explicit_Write);
668 -- Ada-fied list of all possible Context keyword values
670 Pos : Natural := 0;
671 Klen : Natural := 0;
672 Index : Natural;
674 begin
675 -- Find the end of the occupation
677 for J in VMS_Form'First .. VMS_Form'Last loop
678 if VMS_Form (J) = ASCII.NUL then
679 Pos := J;
680 exit;
681 end if;
682 end loop;
684 Index := Form'First;
685 while Index < Form'Last loop
686 if Form (Index) = '=' then
687 Index := Index + 1;
689 -- Loop through the context values and look for a match
691 for Parm in Context_Parms loop
692 declare
693 KImage : String := Context_Parms'Image (Parm);
695 begin
696 Klen := KImage'Length;
697 To_Lower (KImage);
699 if Index + Klen - 1 <= Form'Last
700 and then Form (Index .. Index + Klen - 1) = KImage
701 then
702 case Parm is
703 when Force_Record_Mode =>
704 VMS_Form (Pos) := '"';
705 Pos := Pos + 1;
706 VMS_Form (Pos .. Pos + 6) := "ctx=rec";
707 Pos := Pos + 7;
708 VMS_Form (Pos) := '"';
709 Pos := Pos + 1;
710 VMS_Form (Pos) := ',';
711 return Index + Klen;
713 when Force_Stream_Mode =>
714 VMS_Form (Pos) := '"';
715 Pos := Pos + 1;
716 VMS_Form (Pos .. Pos + 6) := "ctx=stm";
717 Pos := Pos + 7;
718 VMS_Form (Pos) := '"';
719 Pos := Pos + 1;
720 VMS_Form (Pos) := ',';
721 return Index + Klen;
723 when others =>
724 raise Use_Error
725 with "unimplemented RMS Context Value";
726 end case;
727 end if;
728 end;
729 end loop;
731 raise Use_Error with "unrecognized RMS Context Value";
732 end if;
733 end loop;
735 raise Use_Error with "malformed RMS Context Value";
736 end Form_RMS_Context_Key;
738 -----------------------
739 -- Form_VMS_RMS_Keys --
740 -----------------------
742 procedure Form_VMS_RMS_Keys (Form : String; VMS_Form : out String_Access)
744 VMS_RMS_Keys_Token : constant String := "vms_rms_keys";
745 Klen : Natural := VMS_RMS_Keys_Token'Length;
746 Index : Natural;
748 -- Ada-fied list of all RMS keywords, translated from the HP C Run-Time
749 -- Library Reference Manual, Table REF-3: RMS Valid Keywords and Values.
751 type RMS_Keys is
752 (Access_Callback, Allocation_Quantity, Block_Size, Context,
753 Default_Extension_Quantity, Default_File_Name_String, Error_Callback,
754 File_Processing_Options, Fixed_Header_Size, Global_Buffer_Count,
755 Multiblock_Count, Multibuffer_Count, Maximum_Record_Size,
756 Terminal_Input_Prompt, Record_Attributes, Record_Format,
757 Record_Processing_Options, Retrieval_Pointer_Count, Sharing_Options,
758 Timeout_IO_Value);
760 begin
761 Index := Form'First + Klen - 1;
762 while Index < Form'Last loop
763 Index := Index + 1;
765 -- Scan for the token signalling VMS RMS Keys ahead. Should
766 -- whitespace be eaten???
768 if Form (Index - Klen .. Index - 1) = VMS_RMS_Keys_Token then
770 -- Allocate the VMS form string that will contain the cryptic
771 -- CRTL RMS strings and initialize it to all nulls. Since the
772 -- CRTL strings are always shorter than the Ada-fied strings,
773 -- it follows that an allocation of the original size will be
774 -- more than adequate.
775 VMS_Form := new String'(Form (Form'First .. Form'Last));
776 VMS_Form.all := (others => ASCII.NUL);
778 if Form (Index) = '=' then
779 Index := Index + 1;
780 if Form (Index) = '(' then
781 while Index < Form'Last loop
782 Index := Index + 1;
784 -- Loop through the RMS Keys and dispatch.
786 for Key in RMS_Keys loop
787 declare
788 KImage : String := RMS_Keys'Image (Key);
790 begin
791 Klen := KImage'Length;
792 To_Lower (KImage);
794 if Form (Index .. Index + Klen - 1) = KImage then
795 case Key is
796 when Context =>
797 Index := Form_RMS_Context_Key
798 (Form (Index + Klen .. Form'Last),
799 VMS_Form);
800 exit;
802 when others =>
803 raise Use_Error
804 with "unimplemented VMS RMS Form Key";
805 end case;
806 end if;
807 end;
808 end loop;
810 if Form (Index) = ')' then
812 -- Done, erase the unneeded trailing comma and return
814 for J in reverse VMS_Form'First .. VMS_Form'Last loop
815 if VMS_Form (J) = ',' then
816 VMS_Form (J) := ASCII.NUL;
817 return;
818 end if;
819 end loop;
821 -- Shouldn't be possible to get here
823 raise Use_Error;
825 elsif Form (Index) = ',' then
827 -- Another key ahead, exit inner loop
829 null;
831 else
833 -- Keyword value not terminated correctly
835 raise Use_Error with "malformed VMS RMS Form";
836 end if;
837 end loop;
838 end if;
839 end if;
841 -- Found the keyword, but not followed by correct syntax
843 raise Use_Error with "malformed VMS RMS Form";
844 end if;
845 end loop;
846 end Form_VMS_RMS_Keys;
848 -------------
849 -- Is_Open --
850 -------------
852 function Is_Open (File : AFCB_Ptr) return Boolean is
853 begin
854 -- We return True if the file is open, and the underlying file stream is
855 -- usable. In particular on Windows an application linked with -mwindows
856 -- option set does not have a console attached. In this case standard
857 -- files (Current_Output, Current_Error, Current_Input) are not created.
858 -- We want Is_Open (Current_Output) to return False in this case.
860 return File /= null and then fileno (File.Stream) /= -1;
861 end Is_Open;
863 -------------------
864 -- Make_Buffered --
865 -------------------
867 procedure Make_Buffered
868 (File : AFCB_Ptr;
869 Buf_Siz : Interfaces.C_Streams.size_t)
871 status : Integer;
872 pragma Unreferenced (status);
874 begin
875 status := setvbuf (File.Stream, Null_Address, IOFBF, Buf_Siz);
876 end Make_Buffered;
878 ------------------------
879 -- Make_Line_Buffered --
880 ------------------------
882 procedure Make_Line_Buffered
883 (File : AFCB_Ptr;
884 Line_Siz : Interfaces.C_Streams.size_t)
886 status : Integer;
887 pragma Unreferenced (status);
889 begin
890 status := setvbuf (File.Stream, Null_Address, IOLBF, Line_Siz);
891 -- No error checking???
892 end Make_Line_Buffered;
894 ---------------------
895 -- Make_Unbuffered --
896 ---------------------
898 procedure Make_Unbuffered (File : AFCB_Ptr) is
899 status : Integer;
900 pragma Unreferenced (status);
902 begin
903 status := setvbuf (File.Stream, Null_Address, IONBF, 0);
904 -- No error checking???
905 end Make_Unbuffered;
907 ----------
908 -- Mode --
909 ----------
911 function Mode (File : AFCB_Ptr) return File_Mode is
912 begin
913 if File = null then
914 raise Status_Error with "Mode: file not open";
915 else
916 return File.Mode;
917 end if;
918 end Mode;
920 ----------
921 -- Name --
922 ----------
924 function Name (File : AFCB_Ptr) return String is
925 begin
926 if File = null then
927 raise Status_Error with "Name: file not open";
928 else
929 return File.Name.all (1 .. File.Name'Length - 1);
930 end if;
931 end Name;
933 ----------
934 -- Open --
935 ----------
937 procedure Open
938 (File_Ptr : in out AFCB_Ptr;
939 Dummy_FCB : AFCB'Class;
940 Mode : File_Mode;
941 Name : String;
942 Form : String;
943 Amethod : Character;
944 Creat : Boolean;
945 Text : Boolean;
946 C_Stream : FILEs := NULL_Stream)
948 pragma Warnings (Off, Dummy_FCB);
949 -- Yes we know this is never assigned a value. That's intended, since
950 -- all we ever use of this value is the tag for dispatching purposes.
952 procedure Tmp_Name (Buffer : Address);
953 pragma Import (C, Tmp_Name, "__gnat_tmp_name");
954 -- Set buffer (a String address) with a temporary filename
956 function Get_Case_Sensitive return Integer;
957 pragma Import (C, Get_Case_Sensitive,
958 "__gnat_get_file_names_case_sensitive");
960 File_Names_Case_Sensitive : constant Boolean := Get_Case_Sensitive /= 0;
961 -- Set to indicate whether the operating system convention is for file
962 -- names to be case sensitive (e.g., in Unix, set True), or not case
963 -- sensitive (e.g., in Windows, set False). Declared locally to avoid
964 -- breaking the Preelaborate rule that disallows function calls at the
965 -- library level.
967 Stream : FILEs := C_Stream;
968 -- Stream which we open in response to this request
970 Shared : Shared_Status_Type;
971 -- Setting of Shared_Status field for file
973 Fopstr : aliased Fopen_String;
974 -- Mode string used in fopen call
976 Formstr : aliased String (1 .. Form'Length + 1);
977 -- Form string with ASCII.NUL appended, folded to lower case
979 Is_Text_File : Boolean;
981 Tempfile : constant Boolean := (Name'Length = 0);
982 -- Indicates temporary file case
984 Namelen : constant Integer := max_path_len;
985 -- Length required for file name, not including final ASCII.NUL.
986 -- Note that we used to reference L_tmpnam here, which is not reliable
987 -- since __gnat_tmp_name does not always use tmpnam.
989 Namestr : aliased String (1 .. Namelen + 1);
990 -- Name as given or temporary file name with ASCII.NUL appended
992 Fullname : aliased String (1 .. max_path_len + 1);
993 -- Full name (as required for Name function, and as stored in the
994 -- control block in the Name field) with ASCII.NUL appended.
996 Full_Name_Len : Integer;
997 -- Length of name actually stored in Fullname
999 Encoding : CRTL.Filename_Encoding;
1000 -- Filename encoding specified into the form parameter
1002 begin
1003 if File_Ptr /= null then
1004 raise Status_Error with "file already open";
1005 end if;
1007 -- Acquire form string, setting required NUL terminator
1009 Formstr (1 .. Form'Length) := Form;
1010 Formstr (Formstr'Last) := ASCII.NUL;
1012 -- Convert form string to lower case
1014 for J in Formstr'Range loop
1015 if Formstr (J) in 'A' .. 'Z' then
1016 Formstr (J) := Character'Val (Character'Pos (Formstr (J)) + 32);
1017 end if;
1018 end loop;
1020 -- Acquire setting of shared parameter
1022 declare
1023 V1, V2 : Natural;
1025 begin
1026 Form_Parameter (Formstr, "shared", V1, V2);
1028 if V1 = 0 then
1029 Shared := None;
1030 elsif Formstr (V1 .. V2) = "yes" then
1031 Shared := Yes;
1032 elsif Formstr (V1 .. V2) = "no" then
1033 Shared := No;
1034 else
1035 raise Use_Error with "invalid Form";
1036 end if;
1037 end;
1039 -- Acquire setting of encoding parameter
1041 declare
1042 V1, V2 : Natural;
1044 begin
1045 Form_Parameter (Formstr, "encoding", V1, V2);
1047 if V1 = 0 then
1048 Encoding := CRTL.Unspecified;
1049 elsif Formstr (V1 .. V2) = "utf8" then
1050 Encoding := CRTL.UTF8;
1051 elsif Formstr (V1 .. V2) = "8bits" then
1052 Encoding := CRTL.ASCII_8bits;
1053 else
1054 raise Use_Error with "invalid Form";
1055 end if;
1056 end;
1058 -- Acquire setting of text_translation parameter. Only needed if this is
1059 -- a [Wide_[Wide_]]Text_IO file, in which case we default to True, but
1060 -- if the Form says Text_Translation=No, we use binary mode, so new-line
1061 -- will be just LF, even on Windows.
1063 Is_Text_File := Text;
1065 if Is_Text_File then
1066 Is_Text_File :=
1067 Form_Boolean (Formstr, "text_translation", Default => True);
1068 end if;
1070 -- Acquire settings of target specific form parameters on VMS. Only
1071 -- Context is currently implemented, for forcing a byte stream mode
1072 -- read. On non-VMS systems, the settings are ultimately ignored in
1073 -- the implementation of __gnat_fopen.
1075 -- Should a warning be issued on non-VMS systems? That's not possible
1076 -- without testing System.OpenVMS boolean which isn't present in most
1077 -- non-VMS versions of package System.
1079 Form_VMS_RMS_Keys (Formstr, VMS_Formstr);
1081 -- If we were given a stream (call from xxx.C_Streams.Open), then set
1082 -- the full name to the given one, and skip to end of processing.
1084 if Stream /= NULL_Stream then
1085 Full_Name_Len := Name'Length + 1;
1086 Fullname (1 .. Full_Name_Len - 1) := Name;
1087 Fullname (Full_Name_Len) := ASCII.NUL;
1089 -- Normal case of Open or Create
1091 else
1092 -- If temporary file case, get temporary file name and add to the
1093 -- list of temporary files to be deleted on exit.
1095 if Tempfile then
1096 if not Creat then
1097 raise Name_Error with "opening temp file without creating it";
1098 end if;
1100 Tmp_Name (Namestr'Address);
1102 if Namestr (1) = ASCII.NUL then
1103 raise Use_Error with "invalid temp file name";
1104 end if;
1106 -- Chain to temp file list, ensuring thread safety with a lock
1108 begin
1109 SSL.Lock_Task.all;
1110 Temp_Files :=
1111 new Temp_File_Record'(Name => Namestr, Next => Temp_Files);
1112 SSL.Unlock_Task.all;
1114 exception
1115 when others =>
1116 SSL.Unlock_Task.all;
1117 raise;
1118 end;
1120 -- Normal case of non-null name given
1122 else
1123 if Name'Length > Namelen then
1124 raise Name_Error with "file name too long";
1125 end if;
1127 Namestr (1 .. Name'Length) := Name;
1128 Namestr (Name'Length + 1) := ASCII.NUL;
1129 end if;
1131 -- Get full name in accordance with the advice of RM A.8.2(22)
1133 full_name (Namestr'Address, Fullname'Address);
1135 if Fullname (1) = ASCII.NUL then
1136 raise Use_Error with Errno_Message (Name);
1137 end if;
1139 Full_Name_Len := 1;
1140 while Full_Name_Len < Fullname'Last
1141 and then Fullname (Full_Name_Len) /= ASCII.NUL
1142 loop
1143 Full_Name_Len := Full_Name_Len + 1;
1144 end loop;
1146 -- Fullname is generated by calling system's full_name. The problem
1147 -- is, full_name does nothing about the casing, so a file name
1148 -- comparison may generally speaking not be valid on non-case-
1149 -- sensitive systems, and in particular we get unexpected failures
1150 -- on Windows/Vista because of this. So we use s-casuti to force
1151 -- the name to lower case.
1153 if not File_Names_Case_Sensitive then
1154 To_Lower (Fullname (1 .. Full_Name_Len));
1155 end if;
1157 -- If Shared=None or Shared=Yes, then check for the existence of
1158 -- another file with exactly the same full name.
1160 if Shared /= No then
1161 declare
1162 P : AFCB_Ptr;
1164 begin
1165 -- Take a task lock to protect Open_Files
1167 SSL.Lock_Task.all;
1169 -- Search list of open files
1171 P := Open_Files;
1172 while P /= null loop
1173 if Fullname (1 .. Full_Name_Len) = P.Name.all then
1175 -- If we get a match, and either file has Shared=None,
1176 -- then raise Use_Error, since we don't allow two files
1177 -- of the same name to be opened unless they specify the
1178 -- required sharing mode.
1180 if Shared = None
1181 or else P.Shared_Status = None
1182 then
1183 raise Use_Error with "reopening shared file";
1185 -- If both files have Shared=Yes, then we acquire the
1186 -- stream from the located file to use as our stream.
1188 elsif Shared = Yes
1189 and then P.Shared_Status = Yes
1190 then
1191 Stream := P.Stream;
1192 exit;
1194 -- Otherwise one of the files has Shared=Yes and one has
1195 -- Shared=No. If the current file has Shared=No then all
1196 -- is well but we don't want to share any other file's
1197 -- stream. If the current file has Shared=Yes, we would
1198 -- like to share a stream, but not from a file that has
1199 -- Shared=No, so either way, we just continue the search.
1201 else
1202 null;
1203 end if;
1204 end if;
1206 P := P.Next;
1207 end loop;
1209 SSL.Unlock_Task.all;
1211 exception
1212 when others =>
1213 SSL.Unlock_Task.all;
1214 raise;
1215 end;
1216 end if;
1218 -- Open specified file if we did not find an existing stream
1220 if Stream = NULL_Stream then
1221 Fopen_Mode (Mode, Is_Text_File, Creat, Amethod, Fopstr);
1223 -- A special case, if we are opening (OPEN case) a file and the
1224 -- mode returned by Fopen_Mode is not "r" or "r+", then we first
1225 -- make sure that the file exists as required by Ada semantics.
1227 if not Creat and then Fopstr (1) /= 'r' then
1228 if file_exists (Namestr'Address) = 0 then
1229 raise Name_Error with Errno_Message (Name);
1230 end if;
1231 end if;
1233 -- Now open the file. Note that we use the name as given in the
1234 -- original Open call for this purpose, since that seems the
1235 -- clearest implementation of the intent. It would presumably
1236 -- work to use the full name here, but if there is any difference,
1237 -- then we should use the name used in the call.
1239 -- Note: for a corresponding delete, we will use the full name,
1240 -- since by the time of the delete, the current working directory
1241 -- may have changed and we do not want to delete a different file!
1243 if VMS_Formstr = null then
1244 Stream := fopen (Namestr'Address, Fopstr'Address, Encoding,
1245 Null_Address);
1246 else
1247 Stream := fopen (Namestr'Address, Fopstr'Address, Encoding,
1248 VMS_Formstr.all'Address);
1249 end if;
1251 -- No need to keep this around
1253 if VMS_Formstr /= null then
1254 Free (VMS_Formstr);
1255 end if;
1257 if Stream = NULL_Stream then
1259 -- Raise Name_Error if trying to open a non-existent file.
1260 -- Otherwise raise Use_Error.
1262 -- Should we raise Device_Error for ENOSPC???
1264 declare
1265 function Is_File_Not_Found_Error
1266 (Errno_Value : Integer) return Integer;
1267 pragma Import
1268 (C, Is_File_Not_Found_Error,
1269 "__gnat_is_file_not_found_error");
1270 -- Non-zero when the given errno value indicates a non-
1271 -- existing file.
1273 Errno : constant Integer := OS_Lib.Errno;
1274 Message : constant String := Errno_Message (Name, Errno);
1276 begin
1277 if Is_File_Not_Found_Error (Errno) /= 0 then
1278 raise Name_Error with Message;
1279 else
1280 raise Use_Error with Message;
1281 end if;
1282 end;
1283 end if;
1284 end if;
1285 end if;
1287 -- Stream has been successfully located or opened, so now we are
1288 -- committed to completing the opening of the file. Allocate block on
1289 -- heap and fill in its fields.
1291 File_Ptr := AFCB_Allocate (Dummy_FCB);
1293 File_Ptr.Is_Regular_File := (is_regular_file (fileno (Stream)) /= 0);
1294 File_Ptr.Is_System_File := False;
1295 File_Ptr.Is_Text_File := Is_Text_File;
1296 File_Ptr.Shared_Status := Shared;
1297 File_Ptr.Access_Method := Amethod;
1298 File_Ptr.Stream := Stream;
1299 File_Ptr.Form := new String'(Formstr);
1300 File_Ptr.Name := new String'(Fullname (1 .. Full_Name_Len));
1301 File_Ptr.Mode := Mode;
1302 File_Ptr.Is_Temporary_File := Tempfile;
1303 File_Ptr.Encoding := Encoding;
1305 Chain_File (File_Ptr);
1306 Append_Set (File_Ptr);
1307 end Open;
1309 ------------------------
1310 -- Raise_Device_Error --
1311 ------------------------
1313 procedure Raise_Device_Error
1314 (File : AFCB_Ptr;
1315 Errno : Integer := OS_Lib.Errno)
1317 begin
1318 -- Clear error status so that the same error is not reported twice
1320 if File /= null then
1321 clearerr (File.Stream);
1322 end if;
1324 raise Device_Error with Errno_Message (Errno);
1325 end Raise_Device_Error;
1327 --------------
1328 -- Read_Buf --
1329 --------------
1331 procedure Read_Buf (File : AFCB_Ptr; Buf : Address; Siz : size_t) is
1332 Nread : size_t;
1334 begin
1335 Nread := fread (Buf, 1, Siz, File.Stream);
1337 if Nread = Siz then
1338 return;
1340 elsif ferror (File.Stream) /= 0 then
1341 Raise_Device_Error (File);
1343 elsif Nread = 0 then
1344 raise End_Error;
1346 else -- 0 < Nread < Siz
1347 raise Data_Error with "not enough data read";
1348 end if;
1349 end Read_Buf;
1351 procedure Read_Buf
1352 (File : AFCB_Ptr;
1353 Buf : Address;
1354 Siz : Interfaces.C_Streams.size_t;
1355 Count : out Interfaces.C_Streams.size_t)
1357 begin
1358 Count := fread (Buf, 1, Siz, File.Stream);
1360 if Count = 0 and then ferror (File.Stream) /= 0 then
1361 Raise_Device_Error (File);
1362 end if;
1363 end Read_Buf;
1365 -----------
1366 -- Reset --
1367 -----------
1369 -- The reset which does not change the mode simply does a rewind
1371 procedure Reset (File_Ptr : access AFCB_Ptr) is
1372 File : AFCB_Ptr renames File_Ptr.all;
1373 begin
1374 Check_File_Open (File);
1375 Reset (File_Ptr, File.Mode);
1376 end Reset;
1378 -- The reset with a change in mode is done using freopen, and is not
1379 -- permitted except for regular files (since otherwise there is no name for
1380 -- the freopen, and in any case it seems meaningless).
1382 procedure Reset (File_Ptr : access AFCB_Ptr; Mode : File_Mode) is
1383 File : AFCB_Ptr renames File_Ptr.all;
1384 Fopstr : aliased Fopen_String;
1386 begin
1387 Check_File_Open (File);
1389 -- Change of mode not allowed for shared file or file with no name or
1390 -- file that is not a regular file, or for a system file. Note that we
1391 -- allow the "change" of mode if it is not in fact doing a change.
1393 if Mode /= File.Mode then
1394 if File.Shared_Status = Yes then
1395 raise Use_Error with "cannot change mode of shared file";
1396 elsif File.Name'Length <= 1 then
1397 raise Use_Error with "cannot change mode of temp file";
1398 elsif File.Is_System_File then
1399 raise Use_Error with "cannot change mode of system file";
1400 elsif not File.Is_Regular_File then
1401 raise Use_Error with "cannot change mode of non-regular file";
1402 end if;
1403 end if;
1405 -- For In_File or Inout_File for a regular file, we can just do a rewind
1406 -- if the mode is unchanged, which is more efficient than doing a full
1407 -- reopen.
1409 if Mode = File.Mode
1410 and then Mode in Read_File_Mode
1411 then
1412 rewind (File.Stream);
1414 -- Here the change of mode is permitted, we do it by reopening the file
1415 -- in the new mode and replacing the stream with a new stream.
1417 else
1418 Fopen_Mode
1419 (Mode, File.Is_Text_File, False, File.Access_Method, Fopstr);
1421 Form_VMS_RMS_Keys (File.Form.all, VMS_Formstr);
1423 if VMS_Formstr = null then
1424 File.Stream := freopen
1425 (File.Name.all'Address, Fopstr'Address, File.Stream,
1426 File.Encoding, Null_Address);
1427 else
1428 File.Stream := freopen
1429 (File.Name.all'Address, Fopstr'Address, File.Stream,
1430 File.Encoding, VMS_Formstr.all'Address);
1431 end if;
1433 if VMS_Formstr /= null then
1434 Free (VMS_Formstr);
1435 end if;
1437 if File.Stream = NULL_Stream then
1438 Close (File_Ptr);
1439 raise Use_Error;
1440 else
1441 File.Mode := Mode;
1442 Append_Set (File);
1443 end if;
1444 end if;
1445 end Reset;
1447 ---------------
1448 -- Write_Buf --
1449 ---------------
1451 procedure Write_Buf (File : AFCB_Ptr; Buf : Address; Siz : size_t) is
1452 begin
1453 -- Note: for most purposes, the Siz and 1 parameters in the fwrite call
1454 -- could be reversed, but on VMS, this is a better choice, since for
1455 -- some file formats, reversing the parameters results in records of one
1456 -- byte each.
1458 SSL.Abort_Defer.all;
1460 if fwrite (Buf, Siz, 1, File.Stream) /= 1 then
1461 if Siz /= 0 then
1462 SSL.Abort_Undefer.all;
1463 Raise_Device_Error (File);
1464 end if;
1465 end if;
1467 SSL.Abort_Undefer.all;
1468 end Write_Buf;
1470 end System.File_IO;