[gcc]
[official-gcc.git] / gcc / ada / s-fileio.adb
blob6c449389fd81599742badedeb0d580ce596d509e
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-2017, 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;
34 with Ada.Unchecked_Deallocation;
36 with Interfaces.C_Streams; use Interfaces.C_Streams;
38 with System.Case_Util; use System.Case_Util;
39 with System.CRTL;
40 with System.OS_Lib;
41 with System.Soft_Links;
43 package body System.File_IO is
45 use System.File_Control_Block;
47 package SSL renames System.Soft_Links;
49 use type CRTL.size_t;
51 ----------------------
52 -- Global Variables --
53 ----------------------
55 Open_Files : AFCB_Ptr;
56 -- This points to a list of AFCB's for all open files. This is a doubly
57 -- linked list, with the Prev pointer of the first entry, and the Next
58 -- pointer of the last entry containing null. Note that this global
59 -- variable must be properly protected to provide thread safety.
61 type Temp_File_Record;
62 type Temp_File_Record_Ptr is access all Temp_File_Record;
64 type Temp_File_Record is record
65 File : AFCB_Ptr;
66 Next : aliased Temp_File_Record_Ptr;
67 Name : String (1 .. max_path_len + 1);
68 end record;
69 -- One of these is allocated for each temporary file created
71 Temp_Files : aliased Temp_File_Record_Ptr;
72 -- Points to list of names of temporary files. Note that this global
73 -- variable must be properly protected to provide thread safety.
75 procedure Free is new Ada.Unchecked_Deallocation
76 (Temp_File_Record, Temp_File_Record_Ptr);
78 type File_IO_Clean_Up_Type is new Limited_Controlled with null record;
79 -- The closing of all open files and deletion of temporary files is an
80 -- action that takes place at the end of execution of the main program.
81 -- This action is implemented using a library level object that gets
82 -- finalized at the end of program execution. Note that the type is
83 -- limited, in order to stop the compiler optimizing away the declaration
84 -- which would be allowed in the non-limited case.
86 procedure Finalize (V : in out File_IO_Clean_Up_Type);
87 -- This is the finalize operation that is used to do the cleanup
89 File_IO_Clean_Up_Object : File_IO_Clean_Up_Type;
90 pragma Warnings (Off, File_IO_Clean_Up_Object);
91 -- This is the single object of the type that triggers the finalization
92 -- call. Since it is at the library level, this happens just before the
93 -- environment task is finalized.
95 text_translation_required : Boolean;
96 for text_translation_required'Size use Character'Size;
97 pragma Import
98 (C, text_translation_required, "__gnat_text_translation_required");
99 -- If true, add appropriate suffix to control string for Open
101 -----------------------
102 -- Local Subprograms --
103 -----------------------
105 procedure Free_String is new Ada.Unchecked_Deallocation (String, Pstring);
107 subtype Fopen_String is String (1 .. 4);
108 -- Holds open string (longest is "w+b" & nul)
110 procedure Fopen_Mode
111 (Namestr : String;
112 Mode : File_Mode;
113 Text : Boolean;
114 Creat : Boolean;
115 Amethod : Character;
116 Fopstr : out Fopen_String);
117 -- Determines proper open mode for a file to be opened in the given Ada
118 -- mode. Namestr is the NUL-terminated file name. Text is true for a text
119 -- file and false otherwise, and Creat is true for a create call, and False
120 -- for an open call. The value stored in Fopstr is a nul-terminated string
121 -- suitable for a call to fopen or freopen. Amethod is the character
122 -- designating the access method from the Access_Method field of the FCB.
124 function Errno_Message
125 (Name : String;
126 Errno : Integer := OS_Lib.Errno) return String;
127 -- Return Errno_Message for Errno, with file name prepended
129 procedure Raise_Device_Error
130 (File : AFCB_Ptr;
131 Errno : Integer := OS_Lib.Errno);
132 pragma No_Return (Raise_Device_Error);
133 -- Clear error indication on File and raise Device_Error with an exception
134 -- message providing errno information.
136 ----------------
137 -- Append_Set --
138 ----------------
140 procedure Append_Set (File : AFCB_Ptr) is
141 begin
142 if File.Mode = Append_File then
143 if fseek (File.Stream, 0, SEEK_END) /= 0 then
144 Raise_Device_Error (File);
145 end if;
146 end if;
147 end Append_Set;
149 ----------------
150 -- Chain_File --
151 ----------------
153 procedure Chain_File (File : AFCB_Ptr) is
154 begin
155 -- Take a task lock, to protect the global data value Open_Files
157 SSL.Lock_Task.all;
159 -- Do the chaining operation locked
161 File.Next := Open_Files;
162 File.Prev := null;
163 Open_Files := File;
165 if File.Next /= null then
166 File.Next.Prev := File;
167 end if;
169 SSL.Unlock_Task.all;
171 exception
172 when others =>
173 SSL.Unlock_Task.all;
174 raise;
175 end Chain_File;
177 ---------------------
178 -- Check_File_Open --
179 ---------------------
181 procedure Check_File_Open (File : AFCB_Ptr) is
182 begin
183 if File = null then
184 raise Status_Error with "file not open";
185 end if;
186 end Check_File_Open;
188 -----------------------
189 -- Check_Read_Status --
190 -----------------------
192 procedure Check_Read_Status (File : AFCB_Ptr) is
193 begin
194 if File = null then
195 raise Status_Error with "file not open";
196 elsif File.Mode not in Read_File_Mode then
197 raise Mode_Error with "file not readable";
198 end if;
199 end Check_Read_Status;
201 ------------------------
202 -- Check_Write_Status --
203 ------------------------
205 procedure Check_Write_Status (File : AFCB_Ptr) is
206 begin
207 if File = null then
208 raise Status_Error with "file not open";
209 elsif File.Mode = In_File then
210 raise Mode_Error with "file not writable";
211 end if;
212 end Check_Write_Status;
214 -----------
215 -- Close --
216 -----------
218 procedure Close (File_Ptr : access AFCB_Ptr) is
219 Close_Status : int := 0;
220 Dup_Strm : Boolean := False;
221 Errno : Integer := 0;
223 File : AFCB_Ptr renames File_Ptr.all;
225 begin
226 -- Take a task lock, to protect the global variables Open_Files and
227 -- Temp_Files, and the chains they point to.
229 SSL.Lock_Task.all;
231 Check_File_Open (File);
232 AFCB_Close (File);
234 -- Sever the association between the given file and its associated
235 -- external file. The given file is left closed. Do not perform system
236 -- closes on the standard input, output and error files and also do not
237 -- attempt to close a stream that does not exist (signalled by a null
238 -- stream value -- happens in some error situations).
240 if not File.Is_System_File and then File.Stream /= NULL_Stream then
242 -- Do not do an fclose if this is a shared file and there is at least
243 -- one other instance of the stream that is open.
245 if File.Shared_Status = Yes then
246 declare
247 P : AFCB_Ptr;
249 begin
250 P := Open_Files;
251 while P /= null loop
252 if P /= File and then File.Stream = P.Stream then
253 Dup_Strm := True;
254 exit;
255 end if;
257 P := P.Next;
258 end loop;
259 end;
260 end if;
262 -- Do the fclose unless this was a duplicate in the shared case
264 if not Dup_Strm then
265 Close_Status := fclose (File.Stream);
267 if Close_Status /= 0 then
268 Errno := OS_Lib.Errno;
269 end if;
270 end if;
271 end if;
273 -- Dechain file from list of open files and then free the storage
275 if File.Prev = null then
276 Open_Files := File.Next;
277 else
278 File.Prev.Next := File.Next;
279 end if;
281 if File.Next /= null then
282 File.Next.Prev := File.Prev;
283 end if;
285 -- If it's a temp file, remove the corresponding record from Temp_Files,
286 -- and delete the file. There are unlikely to be large numbers of temp
287 -- files open, so a linear search is sufficiently efficient. Note that
288 -- we don't need to check for end of list, because the file must be
289 -- somewhere on the list. Note that as for Finalize, we ignore any
290 -- errors while attempting the unlink operation.
292 if File.Is_Temporary_File then
293 declare
294 Temp : access Temp_File_Record_Ptr := Temp_Files'Access;
295 -- Note the double indirection here
297 Discard : int;
298 New_Temp : Temp_File_Record_Ptr;
300 begin
301 while Temp.all.all.File /= File loop
302 Temp := Temp.all.all.Next'Access;
303 end loop;
305 Discard := unlink (Temp.all.all.Name'Address);
306 New_Temp := Temp.all.all.Next;
307 Free (Temp.all);
308 Temp.all := New_Temp;
309 end;
310 end if;
312 -- Deallocate some parts of the file structure that were kept in heap
313 -- storage with the exception of system files (standard input, output
314 -- and error) since they had some information allocated in the stack.
316 if not File.Is_System_File then
317 Free_String (File.Name);
318 Free_String (File.Form);
319 AFCB_Free (File);
320 end if;
322 File := null;
324 if Close_Status /= 0 then
325 Raise_Device_Error (null, Errno);
326 end if;
328 SSL.Unlock_Task.all;
330 exception
331 when others =>
332 SSL.Unlock_Task.all;
333 raise;
334 end Close;
336 ------------
337 -- Delete --
338 ------------
340 procedure Delete (File_Ptr : access AFCB_Ptr) is
341 File : AFCB_Ptr renames File_Ptr.all;
343 begin
344 Check_File_Open (File);
346 if not File.Is_Regular_File then
347 raise Use_Error with "cannot delete non-regular file";
348 end if;
350 declare
351 Filename : aliased constant String := File.Name.all;
352 Is_Temporary_File : constant Boolean := File.Is_Temporary_File;
354 begin
355 Close (File_Ptr);
357 -- Now unlink the external file. Note that we use the full name in
358 -- this unlink, because the working directory may have changed since
359 -- we did the open, and we want to unlink the right file. However, if
360 -- it's a temporary file, then closing it already unlinked it.
362 if not Is_Temporary_File then
363 if unlink (Filename'Address) = -1 then
364 raise Use_Error with OS_Lib.Errno_Message;
365 end if;
366 end if;
367 end;
368 end Delete;
370 -----------------
371 -- End_Of_File --
372 -----------------
374 function End_Of_File (File : AFCB_Ptr) return Boolean is
375 begin
376 Check_File_Open (File);
378 if feof (File.Stream) /= 0 then
379 return True;
381 else
382 Check_Read_Status (File);
384 if ungetc (fgetc (File.Stream), File.Stream) = EOF then
385 clearerr (File.Stream);
386 return True;
387 else
388 return False;
389 end if;
390 end if;
391 end End_Of_File;
393 -------------------
394 -- Errno_Message --
395 -------------------
397 function Errno_Message
398 (Name : String;
399 Errno : Integer := OS_Lib.Errno) return String
401 begin
402 return Name & ": " & OS_Lib.Errno_Message (Err => Errno);
403 end Errno_Message;
405 --------------
406 -- Finalize --
407 --------------
409 procedure Finalize (V : in out File_IO_Clean_Up_Type) is
410 pragma Warnings (Off, V);
412 Fptr1 : aliased AFCB_Ptr;
413 Fptr2 : AFCB_Ptr;
415 Discard : int;
417 begin
418 -- Take a lock to protect global Open_Files data structure
420 SSL.Lock_Task.all;
422 -- First close all open files (the slightly complex form of this loop is
423 -- required because Close nulls out its argument).
425 Fptr1 := Open_Files;
426 while Fptr1 /= null loop
427 Fptr2 := Fptr1.Next;
428 Close (Fptr1'Access);
429 Fptr1 := Fptr2;
430 end loop;
432 -- Now unlink all temporary files. We do not bother to free the blocks
433 -- because we are just about to terminate the program. We also ignore
434 -- any errors while attempting these unlink operations.
436 while Temp_Files /= null loop
437 Discard := unlink (Temp_Files.Name'Address);
438 Temp_Files := Temp_Files.Next;
439 end loop;
441 SSL.Unlock_Task.all;
443 exception
444 when others =>
445 SSL.Unlock_Task.all;
446 raise;
447 end Finalize;
449 -----------
450 -- Flush --
451 -----------
453 procedure Flush (File : AFCB_Ptr) is
454 begin
455 Check_Write_Status (File);
457 if fflush (File.Stream) /= 0 then
458 Raise_Device_Error (File);
459 end if;
460 end Flush;
462 ----------------
463 -- Fopen_Mode --
464 ----------------
466 -- The fopen mode to be used is shown by the following table:
468 -- OPEN CREATE
469 -- Append_File "r+" "w+"
470 -- In_File "r" "w+"
471 -- Out_File (Direct_IO, Stream_IO) "r+" [*] "w"
472 -- Out_File (others) "w" "w"
473 -- Inout_File "r+" "w+"
475 -- [*] Except that for Out_File, if the file exists and is a fifo (i.e. a
476 -- named pipe), we use "w" instead of "r+". This is necessary to make a
477 -- write to the fifo block until a reader is ready.
479 -- Note: we do not use "a" or "a+" for Append_File, since this would not
480 -- work in the case of stream files, where even if in append file mode,
481 -- you can reset to earlier points in the file. The caller must use the
482 -- Append_Set routine to deal with the necessary positioning.
484 -- Note: in several cases, the fopen mode used allows reading and writing,
485 -- but the setting of the Ada mode is more restrictive. For instance,
486 -- Create in In_File mode uses "w+" which allows writing, but the Ada mode
487 -- In_File will cause any write operations to be rejected with Mode_Error
488 -- in any case.
490 -- Note: for the Out_File/Open cases for other than the Direct_IO case, an
491 -- initial call will be made by the caller to first open the file in "r"
492 -- mode to be sure that it exists. The real open, in "w" mode, will then
493 -- destroy this file. This is peculiar, but that's what Ada semantics
494 -- require and the ACATS tests insist on.
496 -- If text file translation is required, then either "b" or "t" is appended
497 -- to the mode, depending on the setting of Text.
499 procedure Fopen_Mode
500 (Namestr : String;
501 Mode : File_Mode;
502 Text : Boolean;
503 Creat : Boolean;
504 Amethod : Character;
505 Fopstr : out Fopen_String)
507 Fptr : Positive;
509 function is_fifo (Path : Address) return Integer;
510 pragma Import (C, is_fifo, "__gnat_is_fifo");
512 begin
513 case Mode is
514 when In_File =>
515 if Creat then
516 Fopstr (1) := 'w';
517 Fopstr (2) := '+';
518 Fptr := 3;
519 else
520 Fopstr (1) := 'r';
521 Fptr := 2;
522 end if;
524 when Out_File =>
525 if Amethod in 'D' | 'S'
526 and then not Creat
527 and then is_fifo (Namestr'Address) = 0
528 then
529 Fopstr (1) := 'r';
530 Fopstr (2) := '+';
531 Fptr := 3;
532 else
533 Fopstr (1) := 'w';
534 Fptr := 2;
535 end if;
537 when Append_File
538 | Inout_File
540 Fopstr (1) := (if Creat then 'w' else 'r');
541 Fopstr (2) := '+';
542 Fptr := 3;
543 end case;
545 -- If text_translation_required is true then we need to append either a
546 -- "t" or "b" to the string to get the right mode.
548 if text_translation_required then
549 Fopstr (Fptr) := (if Text then 't' else 'b');
550 Fptr := Fptr + 1;
551 end if;
553 Fopstr (Fptr) := ASCII.NUL;
554 end Fopen_Mode;
556 ----------
557 -- Form --
558 ----------
560 function Form (File : AFCB_Ptr) return String is
561 begin
562 if File = null then
563 raise Status_Error with "Form: file not open";
564 else
565 return File.Form.all (1 .. File.Form'Length - 1);
566 end if;
567 end Form;
569 ------------------
570 -- Form_Boolean --
571 ------------------
573 function Form_Boolean
574 (Form : String;
575 Keyword : String;
576 Default : Boolean) return Boolean
578 V1, V2 : Natural;
579 pragma Unreferenced (V2);
581 begin
582 Form_Parameter (Form, Keyword, V1, V2);
584 if V1 = 0 then
585 return Default;
586 elsif Form (V1) = 'y' then
587 return True;
588 elsif Form (V1) = 'n' then
589 return False;
590 else
591 raise Use_Error with "invalid Form";
592 end if;
593 end Form_Boolean;
595 ------------------
596 -- Form_Integer --
597 ------------------
599 function Form_Integer
600 (Form : String;
601 Keyword : String;
602 Default : Integer) return Integer
604 V1, V2 : Natural;
605 V : Integer;
607 begin
608 Form_Parameter (Form, Keyword, V1, V2);
610 if V1 = 0 then
611 return Default;
613 else
614 V := 0;
616 for J in V1 .. V2 loop
617 if Form (J) not in '0' .. '9' then
618 raise Use_Error with "invalid Form";
619 else
620 V := V * 10 + Character'Pos (Form (J)) - Character'Pos ('0');
621 end if;
623 if V > 999_999 then
624 raise Use_Error with "invalid Form";
625 end if;
626 end loop;
628 return V;
629 end if;
630 end Form_Integer;
632 --------------------
633 -- Form_Parameter --
634 --------------------
636 procedure Form_Parameter
637 (Form : String;
638 Keyword : String;
639 Start : out Natural;
640 Stop : out Natural)
642 Klen : constant Integer := Keyword'Length;
644 begin
645 for J in Form'First + Klen .. Form'Last - 1 loop
646 if Form (J) = '='
647 and then Form (J - Klen .. J - 1) = Keyword
648 then
649 Start := J + 1;
650 Stop := Start - 1;
651 while Form (Stop + 1) /= ASCII.NUL
652 and then Form (Stop + 1) /= ','
653 loop
654 Stop := Stop + 1;
655 end loop;
657 return;
658 end if;
659 end loop;
661 Start := 0;
662 Stop := 0;
663 end Form_Parameter;
665 -------------
666 -- Is_Open --
667 -------------
669 function Is_Open (File : AFCB_Ptr) return Boolean is
670 begin
671 -- We return True if the file is open, and the underlying file stream is
672 -- usable. In particular on Windows an application linked with -mwindows
673 -- option set does not have a console attached. In this case standard
674 -- files (Current_Output, Current_Error, Current_Input) are not created.
675 -- We want Is_Open (Current_Output) to return False in this case.
677 return File /= null and then fileno (File.Stream) /= -1;
678 end Is_Open;
680 -------------------
681 -- Make_Buffered --
682 -------------------
684 procedure Make_Buffered
685 (File : AFCB_Ptr;
686 Buf_Siz : Interfaces.C_Streams.size_t)
688 status : Integer;
689 pragma Unreferenced (status);
691 begin
692 status := setvbuf (File.Stream, Null_Address, IOFBF, Buf_Siz);
693 end Make_Buffered;
695 ------------------------
696 -- Make_Line_Buffered --
697 ------------------------
699 procedure Make_Line_Buffered
700 (File : AFCB_Ptr;
701 Line_Siz : Interfaces.C_Streams.size_t)
703 status : Integer;
704 pragma Unreferenced (status);
706 begin
707 status := setvbuf (File.Stream, Null_Address, IOLBF, Line_Siz);
708 -- No error checking???
709 end Make_Line_Buffered;
711 ---------------------
712 -- Make_Unbuffered --
713 ---------------------
715 procedure Make_Unbuffered (File : AFCB_Ptr) is
716 status : Integer;
717 pragma Unreferenced (status);
719 begin
720 status := setvbuf (File.Stream, Null_Address, IONBF, 0);
721 -- No error checking???
722 end Make_Unbuffered;
724 ----------
725 -- Mode --
726 ----------
728 function Mode (File : AFCB_Ptr) return File_Mode is
729 begin
730 if File = null then
731 raise Status_Error with "Mode: file not open";
732 else
733 return File.Mode;
734 end if;
735 end Mode;
737 ----------
738 -- Name --
739 ----------
741 function Name (File : AFCB_Ptr) return String is
742 begin
743 if File = null then
744 raise Status_Error with "Name: file not open";
745 elsif File.Is_Temporary_File then
746 raise Use_Error with "Name: temporary file has no name";
747 else
748 return File.Name.all (1 .. File.Name'Length - 1);
749 end if;
750 end Name;
752 ----------
753 -- Open --
754 ----------
756 procedure Open
757 (File_Ptr : in out AFCB_Ptr;
758 Dummy_FCB : AFCB'Class;
759 Mode : File_Mode;
760 Name : String;
761 Form : String;
762 Amethod : Character;
763 Creat : Boolean;
764 Text : Boolean;
765 C_Stream : FILEs := NULL_Stream)
767 pragma Warnings (Off, Dummy_FCB);
768 -- Yes we know this is never assigned a value. That's intended, since
769 -- all we ever use of this value is the tag for dispatching purposes.
771 procedure Tmp_Name (Buffer : Address);
772 pragma Import (C, Tmp_Name, "__gnat_tmp_name");
773 -- Set buffer (a String address) with a temporary filename
775 function Get_Case_Sensitive return Integer;
776 pragma Import (C, Get_Case_Sensitive,
777 "__gnat_get_file_names_case_sensitive");
779 procedure Record_AFCB;
780 -- Create and record new AFCB into the runtime, note that the
781 -- implementation uses the variables below which corresponds to the
782 -- status of the opened file.
784 File_Names_Case_Sensitive : constant Boolean := Get_Case_Sensitive /= 0;
785 -- Set to indicate whether the operating system convention is for file
786 -- names to be case sensitive (e.g., in Unix, set True), or not case
787 -- sensitive (e.g., in Windows, set False). Declared locally to avoid
788 -- breaking the Preelaborate rule that disallows function calls at the
789 -- library level.
791 Stream : FILEs := C_Stream;
792 -- Stream which we open in response to this request
794 Shared : Shared_Status_Type;
795 -- Setting of Shared_Status field for file
797 Fopstr : aliased Fopen_String;
798 -- Mode string used in fopen call
800 Formstr : aliased String (1 .. Form'Length + 1);
801 -- Form string with ASCII.NUL appended, folded to lower case
803 Text_Encoding : Content_Encoding;
805 Tempfile : constant Boolean := Name = "";
806 -- Indicates temporary file case, which is indicated by an empty file
807 -- name.
809 Namelen : constant Integer := max_path_len;
810 -- Length required for file name, not including final ASCII.NUL.
811 -- Note that we used to reference L_tmpnam here, which is not reliable
812 -- since __gnat_tmp_name does not always use tmpnam.
814 Namestr : aliased String (1 .. Namelen + 1);
815 -- Name as given or temporary file name with ASCII.NUL appended
817 Fullname : aliased String (1 .. max_path_len + 1);
818 -- Full name (as required for Name function, and as stored in the
819 -- control block in the Name field) with ASCII.NUL appended.
821 Full_Name_Len : Integer;
822 -- Length of name actually stored in Fullname
824 Encoding : CRTL.Filename_Encoding;
825 -- Filename encoding specified into the form parameter
827 -----------------
828 -- Record_AFCB --
829 -----------------
831 procedure Record_AFCB is
832 begin
833 File_Ptr := AFCB_Allocate (Dummy_FCB);
835 -- Note that we cannot use an aggregate here as File_Ptr is a
836 -- class-wide access to a limited type (Root_Stream_Type).
838 File_Ptr.Is_Regular_File := is_regular_file (fileno (Stream)) /= 0;
839 File_Ptr.Is_System_File := False;
840 File_Ptr.Text_Encoding := Text_Encoding;
841 File_Ptr.Shared_Status := Shared;
842 File_Ptr.Access_Method := Amethod;
843 File_Ptr.Stream := Stream;
844 File_Ptr.Form := new String'(Formstr);
845 File_Ptr.Name := new String'(Fullname
846 (1 .. Full_Name_Len));
847 File_Ptr.Mode := Mode;
848 File_Ptr.Is_Temporary_File := Tempfile;
849 File_Ptr.Encoding := Encoding;
851 Chain_File (File_Ptr);
852 Append_Set (File_Ptr);
853 end Record_AFCB;
855 -- Start of processing for Open
857 begin
858 if File_Ptr /= null then
859 raise Status_Error with "file already open";
860 end if;
862 -- Acquire form string, setting required NUL terminator
864 Formstr (1 .. Form'Length) := Form;
865 Formstr (Formstr'Last) := ASCII.NUL;
867 -- Convert form string to lower case
869 for J in Formstr'Range loop
870 if Formstr (J) in 'A' .. 'Z' then
871 Formstr (J) := Character'Val (Character'Pos (Formstr (J)) + 32);
872 end if;
873 end loop;
875 -- Acquire setting of shared parameter
877 declare
878 V1, V2 : Natural;
880 begin
881 Form_Parameter (Formstr, "shared", V1, V2);
883 if V1 = 0 then
884 Shared := None;
885 elsif Formstr (V1 .. V2) = "yes" then
886 Shared := Yes;
887 elsif Formstr (V1 .. V2) = "no" then
888 Shared := No;
889 else
890 raise Use_Error with "invalid Form";
891 end if;
892 end;
894 -- Acquire setting of encoding parameter
896 declare
897 V1, V2 : Natural;
899 begin
900 Form_Parameter (Formstr, "encoding", V1, V2);
902 if V1 = 0 then
903 Encoding := CRTL.Unspecified;
904 elsif Formstr (V1 .. V2) = "utf8" then
905 Encoding := CRTL.UTF8;
906 elsif Formstr (V1 .. V2) = "8bits" then
907 Encoding := CRTL.ASCII_8bits;
908 else
909 raise Use_Error with "invalid Form";
910 end if;
911 end;
913 -- Acquire setting of text_translation parameter. Only needed if this is
914 -- a [Wide_[Wide_]]Text_IO file, in which case we default to True, but
915 -- if the Form says Text_Translation=No, we use binary mode, so new-line
916 -- will be just LF, even on Windows.
918 if Text then
919 Text_Encoding := Default_Text;
920 else
921 Text_Encoding := None;
922 end if;
924 if Text_Encoding in Text_Content_Encoding then
925 declare
926 V1, V2 : Natural;
928 begin
929 Form_Parameter (Formstr, "text_translation", V1, V2);
931 if V1 = 0 then
932 null;
933 elsif Formstr (V1 .. V2) = "no" then
934 Text_Encoding := None;
935 elsif Formstr (V1 .. V2) = "text"
936 or else Formstr (V1 .. V2) = "yes"
937 then
938 Text_Encoding := Interfaces.C_Streams.Text;
939 elsif Formstr (V1 .. V2) = "wtext" then
940 Text_Encoding := Wtext;
941 elsif Formstr (V1 .. V2) = "u8text" then
942 Text_Encoding := U8text;
943 elsif Formstr (V1 .. V2) = "u16text" then
944 Text_Encoding := U16text;
945 else
946 raise Use_Error with "invalid Form";
947 end if;
948 end;
949 end if;
951 -- If we were given a stream (call from xxx.C_Streams.Open), then set
952 -- the full name to the given one, and skip to end of processing.
954 if Stream /= NULL_Stream then
955 Full_Name_Len := Name'Length + 1;
956 Fullname (1 .. Full_Name_Len - 1) := Name;
957 Fullname (Full_Name_Len) := ASCII.NUL;
959 -- Normal case of Open or Create
961 else
962 -- If temporary file case, get temporary file name and add to the
963 -- list of temporary files to be deleted on exit.
965 if Tempfile then
966 if not Creat then
967 raise Name_Error with "opening temp file without creating it";
968 end if;
970 Tmp_Name (Namestr'Address);
972 if Namestr (1) = ASCII.NUL then
973 raise Use_Error with "invalid temp file name";
974 end if;
976 -- Normal case of non-empty name given (i.e. not a temp file)
978 else
979 if Name'Length > Namelen then
980 raise Name_Error with "file name too long";
981 end if;
983 Namestr (1 .. Name'Length) := Name;
984 Namestr (Name'Length + 1) := ASCII.NUL;
985 end if;
987 -- Get full name in accordance with the advice of RM A.8.2(22)
989 full_name (Namestr'Address, Fullname'Address);
991 if Fullname (1) = ASCII.NUL then
992 raise Use_Error with Errno_Message (Name);
993 end if;
995 Full_Name_Len := 1;
996 while Full_Name_Len < Fullname'Last
997 and then Fullname (Full_Name_Len) /= ASCII.NUL
998 loop
999 Full_Name_Len := Full_Name_Len + 1;
1000 end loop;
1002 -- Fullname is generated by calling system's full_name. The problem
1003 -- is, full_name does nothing about the casing, so a file name
1004 -- comparison may generally speaking not be valid on non-case-
1005 -- sensitive systems, and in particular we get unexpected failures
1006 -- on Windows/Vista because of this. So we use s-casuti to force
1007 -- the name to lower case.
1009 if not File_Names_Case_Sensitive then
1010 To_Lower (Fullname (1 .. Full_Name_Len));
1011 end if;
1013 -- If Shared=None or Shared=Yes, then check for the existence of
1014 -- another file with exactly the same full name.
1016 if Shared /= No then
1017 declare
1018 P : AFCB_Ptr;
1020 begin
1021 -- Take a task lock to protect Open_Files
1023 SSL.Lock_Task.all;
1025 -- Search list of open files
1027 P := Open_Files;
1028 while P /= null loop
1029 if Fullname (1 .. Full_Name_Len) = P.Name.all then
1031 -- If we get a match, and either file has Shared=None,
1032 -- then raise Use_Error, since we don't allow two files
1033 -- of the same name to be opened unless they specify the
1034 -- required sharing mode.
1036 if Shared = None
1037 or else P.Shared_Status = None
1038 then
1039 raise Use_Error with "reopening shared file";
1041 -- If both files have Shared=Yes, then we acquire the
1042 -- stream from the located file to use as our stream.
1044 elsif Shared = Yes
1045 and then P.Shared_Status = Yes
1046 then
1047 Stream := P.Stream;
1049 Record_AFCB;
1050 pragma Assert (not Tempfile);
1052 exit;
1054 -- Otherwise one of the files has Shared=Yes and one has
1055 -- Shared=No. If the current file has Shared=No then all
1056 -- is well but we don't want to share any other file's
1057 -- stream. If the current file has Shared=Yes, we would
1058 -- like to share a stream, but not from a file that has
1059 -- Shared=No, so either way, we just continue the search.
1061 else
1062 null;
1063 end if;
1064 end if;
1066 P := P.Next;
1067 end loop;
1069 SSL.Unlock_Task.all;
1071 exception
1072 when others =>
1073 SSL.Unlock_Task.all;
1074 raise;
1075 end;
1076 end if;
1078 -- Open specified file if we did not find an existing stream,
1079 -- otherwise we just return as there is nothing more to be done.
1081 if Stream /= NULL_Stream then
1082 return;
1084 else
1085 Fopen_Mode
1086 (Namestr => Namestr,
1087 Mode => Mode,
1088 Text => Text_Encoding in Text_Content_Encoding,
1089 Creat => Creat,
1090 Amethod => Amethod,
1091 Fopstr => Fopstr);
1093 -- A special case, if we are opening (OPEN case) a file and the
1094 -- mode returned by Fopen_Mode is not "r" or "r+", then we first
1095 -- make sure that the file exists as required by Ada semantics.
1097 if not Creat and then Fopstr (1) /= 'r' then
1098 if file_exists (Namestr'Address) = 0 then
1099 raise Name_Error with Errno_Message (Name);
1100 end if;
1101 end if;
1103 -- Now open the file. Note that we use the name as given in the
1104 -- original Open call for this purpose, since that seems the
1105 -- clearest implementation of the intent. It would presumably
1106 -- work to use the full name here, but if there is any difference,
1107 -- then we should use the name used in the call.
1109 -- Note: for a corresponding delete, we will use the full name,
1110 -- since by the time of the delete, the current working directory
1111 -- may have changed and we do not want to delete a different file.
1113 Stream :=
1114 fopen (Namestr'Address, Fopstr'Address, Encoding);
1116 if Stream = NULL_Stream then
1118 -- Raise Name_Error if trying to open a non-existent file.
1119 -- Otherwise raise Use_Error.
1121 -- Should we raise Device_Error for ENOSPC???
1123 declare
1124 function Is_File_Not_Found_Error
1125 (Errno_Value : Integer) return Integer;
1126 pragma Import
1127 (C, Is_File_Not_Found_Error,
1128 "__gnat_is_file_not_found_error");
1129 -- Non-zero when the given errno value indicates a non-
1130 -- existing file.
1132 Errno : constant Integer := OS_Lib.Errno;
1133 Message : constant String := Errno_Message (Name, Errno);
1135 begin
1136 if Is_File_Not_Found_Error (Errno) /= 0 then
1137 raise Name_Error with Message;
1138 else
1139 raise Use_Error with Message;
1140 end if;
1141 end;
1142 end if;
1143 end if;
1144 end if;
1146 -- Stream has been successfully located or opened, so now we are
1147 -- committed to completing the opening of the file. Allocate block on
1148 -- heap and fill in its fields.
1150 Record_AFCB;
1152 if Tempfile then
1153 -- Chain to temp file list, ensuring thread safety with a lock
1155 begin
1156 SSL.Lock_Task.all;
1157 Temp_Files :=
1158 new Temp_File_Record'
1159 (File => File_Ptr, Name => Namestr, Next => Temp_Files);
1160 SSL.Unlock_Task.all;
1162 exception
1163 when others =>
1164 SSL.Unlock_Task.all;
1165 raise;
1166 end;
1167 end if;
1168 end Open;
1170 ------------------------
1171 -- Raise_Device_Error --
1172 ------------------------
1174 procedure Raise_Device_Error
1175 (File : AFCB_Ptr;
1176 Errno : Integer := OS_Lib.Errno)
1178 begin
1179 -- Clear error status so that the same error is not reported twice
1181 if File /= null then
1182 clearerr (File.Stream);
1183 end if;
1185 raise Device_Error with OS_Lib.Errno_Message (Err => Errno);
1186 end Raise_Device_Error;
1188 --------------
1189 -- Read_Buf --
1190 --------------
1192 procedure Read_Buf (File : AFCB_Ptr; Buf : Address; Siz : size_t) is
1193 Nread : size_t;
1195 begin
1196 Nread := fread (Buf, 1, Siz, File.Stream);
1198 if Nread = Siz then
1199 return;
1201 elsif ferror (File.Stream) /= 0 then
1202 Raise_Device_Error (File);
1204 elsif Nread = 0 then
1205 raise End_Error;
1207 else -- 0 < Nread < Siz
1208 raise Data_Error with "not enough data read";
1209 end if;
1210 end Read_Buf;
1212 procedure Read_Buf
1213 (File : AFCB_Ptr;
1214 Buf : Address;
1215 Siz : Interfaces.C_Streams.size_t;
1216 Count : out Interfaces.C_Streams.size_t)
1218 begin
1219 Count := fread (Buf, 1, Siz, File.Stream);
1221 if Count = 0 and then ferror (File.Stream) /= 0 then
1222 Raise_Device_Error (File);
1223 end if;
1224 end Read_Buf;
1226 -----------
1227 -- Reset --
1228 -----------
1230 -- The reset which does not change the mode simply does a rewind
1232 procedure Reset (File_Ptr : access AFCB_Ptr) is
1233 File : AFCB_Ptr renames File_Ptr.all;
1234 begin
1235 Check_File_Open (File);
1236 Reset (File_Ptr, File.Mode);
1237 end Reset;
1239 -- The reset with a change in mode is done using freopen, and is not
1240 -- permitted except for regular files (since otherwise there is no name for
1241 -- the freopen, and in any case it seems meaningless).
1243 procedure Reset (File_Ptr : access AFCB_Ptr; Mode : File_Mode) is
1244 File : AFCB_Ptr renames File_Ptr.all;
1245 Fopstr : aliased Fopen_String;
1247 begin
1248 Check_File_Open (File);
1250 -- Change of mode not allowed for shared file or file with no name or
1251 -- file that is not a regular file, or for a system file. Note that we
1252 -- allow the "change" of mode if it is not in fact doing a change.
1254 if Mode /= File.Mode then
1255 if File.Shared_Status = Yes then
1256 raise Use_Error with "cannot change mode of shared file";
1257 elsif File.Name'Length <= 1 then
1258 raise Use_Error with "cannot change mode of temp file";
1259 elsif File.Is_System_File then
1260 raise Use_Error with "cannot change mode of system file";
1261 elsif not File.Is_Regular_File then
1262 raise Use_Error with "cannot change mode of non-regular file";
1263 end if;
1264 end if;
1266 -- For In_File or Inout_File for a regular file, we can just do a rewind
1267 -- if the mode is unchanged, which is more efficient than doing a full
1268 -- reopen.
1270 if Mode = File.Mode
1271 and then Mode in Read_File_Mode
1272 then
1273 rewind (File.Stream);
1275 -- Here the change of mode is permitted, we do it by reopening the file
1276 -- in the new mode and replacing the stream with a new stream.
1278 else
1279 Fopen_Mode
1280 (Namestr => File.Name.all,
1281 Mode => Mode,
1282 Text => File.Text_Encoding in Text_Content_Encoding,
1283 Creat => False,
1284 Amethod => File.Access_Method,
1285 Fopstr => Fopstr);
1287 File.Stream := freopen
1288 (File.Name.all'Address, Fopstr'Address, File.Stream,
1289 File.Encoding);
1291 if File.Stream = NULL_Stream then
1292 Close (File_Ptr);
1293 raise Use_Error;
1294 else
1295 File.Mode := Mode;
1296 Append_Set (File);
1297 end if;
1298 end if;
1299 end Reset;
1301 ---------------
1302 -- Write_Buf --
1303 ---------------
1305 procedure Write_Buf (File : AFCB_Ptr; Buf : Address; Siz : size_t) is
1306 begin
1307 -- Note: for most purposes, the Siz and 1 parameters in the fwrite call
1308 -- could be reversed, but we have encountered systems where this is a
1309 -- better choice, since for some file formats, reversing the parameters
1310 -- results in records of one byte each.
1312 SSL.Abort_Defer.all;
1314 if fwrite (Buf, Siz, 1, File.Stream) /= 1 then
1315 if Siz /= 0 then
1316 SSL.Abort_Undefer.all;
1317 Raise_Device_Error (File);
1318 end if;
1319 end if;
1321 SSL.Abort_Undefer.all;
1322 end Write_Buf;
1324 end System.File_IO;