OSDN Git Service

* env.c [__alpha__ && __osf__] (AES_SOURCE): Define.
[pf3gnuchains/gcc-fork.git] / gcc / ada / s-fileio.adb
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-2009, 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 ------------------------------------------------------------------------------
31
32 with Ada.Finalization;            use Ada.Finalization;
33 with Ada.IO_Exceptions;           use Ada.IO_Exceptions;
34 with Interfaces.C;
35 with Interfaces.C_Streams;        use Interfaces.C_Streams;
36
37 with System.CRTL;
38 with System.Case_Util;            use System.Case_Util;
39 with System.OS_Lib;
40 with System.Soft_Links;
41
42 with Ada.Unchecked_Deallocation;
43
44 package body System.File_IO is
45
46    use System.File_Control_Block;
47
48    package SSL renames System.Soft_Links;
49
50    use type Interfaces.C.int;
51    use type System.CRTL.size_t;
52
53    ----------------------
54    -- Global Variables --
55    ----------------------
56
57    Open_Files : AFCB_Ptr;
58    --  This points to a list of AFCB's for all open files. This is a doubly
59    --  linked list, with the Prev pointer of the first entry, and the Next
60    --  pointer of the last entry containing null. Note that this global
61    --  variable must be properly protected to provide thread safety.
62
63    type Temp_File_Record;
64    type Temp_File_Record_Ptr is access all Temp_File_Record;
65
66    type Temp_File_Record is record
67       Name : String (1 .. max_path_len + 1);
68       Next : Temp_File_Record_Ptr;
69    end record;
70    --  One of these is allocated for each temporary file created
71
72    Temp_Files : Temp_File_Record_Ptr;
73    --  Points to list of names of temporary files. Note that this global
74    --  variable must be properly protected to provide thread safety.
75
76    type File_IO_Clean_Up_Type is new Limited_Controlled with null record;
77    --  The closing of all open files and deletion of temporary files is an
78    --  action that takes place at the end of execution of the main program.
79    --  This action is implemented using a library level object which gets
80    --  finalized at the end of program execution. Note that the type is
81    --  limited, in order to stop the compiler optimizing away the declaration
82    --  which would be allowed in the non-limited case.
83
84    procedure Finalize (V : in out File_IO_Clean_Up_Type);
85    --  This is the finalize operation that is used to do the cleanup
86
87    File_IO_Clean_Up_Object : File_IO_Clean_Up_Type;
88    pragma Warnings (Off, File_IO_Clean_Up_Object);
89    --  This is the single object of the type that triggers the finalization
90    --  call. Since it is at the library level, this happens just before the
91    --  environment task is finalized.
92
93    text_translation_required : Boolean;
94    for text_translation_required'Size use Character'Size;
95    pragma Import
96      (C, text_translation_required, "__gnat_text_translation_required");
97    --  If true, add appropriate suffix to control string for Open
98
99    function Get_Case_Sensitive return Integer;
100    pragma Import (C, Get_Case_Sensitive,
101                   "__gnat_get_file_names_case_sensitive");
102    File_Names_Case_Sensitive : constant Boolean := Get_Case_Sensitive /= 0;
103    --  Set to indicate whether the operating system convention is for file
104    --  names to be case sensitive (e.g., in Unix, set True), or non case
105    --  sensitive (e.g., in OS/2, set False).
106
107    -----------------------
108    -- Local Subprograms --
109    -----------------------
110
111    procedure Free_String is new Ada.Unchecked_Deallocation (String, Pstring);
112
113    subtype Fopen_String is String (1 .. 4);
114    --  Holds open string (longest is "w+b" & nul)
115
116    procedure Fopen_Mode
117      (Mode    : File_Mode;
118       Text    : Boolean;
119       Creat   : Boolean;
120       Amethod : Character;
121       Fopstr  : out Fopen_String);
122    --  Determines proper open mode for a file to be opened in the given
123    --  Ada mode. Text is true for a text file and false otherwise, and
124    --  Creat is true for a create call, and False for an open call. The
125    --  value stored in Fopstr is a nul-terminated string suitable for a
126    --  call to fopen or freopen. Amethod is the character designating
127    --  the access method from the Access_Method field of the FCB.
128
129    ----------------
130    -- Append_Set --
131    ----------------
132
133    procedure Append_Set (File : AFCB_Ptr) is
134    begin
135       if File.Mode = Append_File then
136          if fseek (File.Stream, 0, SEEK_END) /= 0 then
137             raise Device_Error;
138          end if;
139       end if;
140    end Append_Set;
141
142    ----------------
143    -- Chain_File --
144    ----------------
145
146    procedure Chain_File (File : AFCB_Ptr) is
147    begin
148       --  Take a task lock, to protect the global data value Open_Files
149
150       SSL.Lock_Task.all;
151
152       --  Do the chaining operation locked
153
154       File.Next := Open_Files;
155       File.Prev := null;
156       Open_Files := File;
157
158       if File.Next /= null then
159          File.Next.Prev := File;
160       end if;
161
162       SSL.Unlock_Task.all;
163
164    exception
165       when others =>
166          SSL.Unlock_Task.all;
167          raise;
168    end Chain_File;
169
170    ---------------------
171    -- Check_File_Open --
172    ---------------------
173
174    procedure Check_File_Open (File : AFCB_Ptr) is
175    begin
176       if File = null then
177          raise Status_Error;
178       end if;
179    end Check_File_Open;
180
181    -----------------------
182    -- Check_Read_Status --
183    -----------------------
184
185    procedure Check_Read_Status (File : AFCB_Ptr) is
186    begin
187       if File = null then
188          raise Status_Error;
189       elsif File.Mode > Inout_File then
190          raise Mode_Error;
191       end if;
192    end Check_Read_Status;
193
194    ------------------------
195    -- Check_Write_Status --
196    ------------------------
197
198    procedure Check_Write_Status (File : AFCB_Ptr) is
199    begin
200       if File = null then
201          raise Status_Error;
202       elsif File.Mode = In_File then
203          raise Mode_Error;
204       end if;
205    end Check_Write_Status;
206
207    -----------
208    -- Close --
209    -----------
210
211    procedure Close (File_Ptr : access AFCB_Ptr) is
212       Close_Status : int := 0;
213       Dup_Strm     : Boolean := False;
214       File         : AFCB_Ptr renames File_Ptr.all;
215
216    begin
217       --  Take a task lock, to protect the global data value Open_Files
218
219       SSL.Lock_Task.all;
220
221       Check_File_Open (File);
222       AFCB_Close (File);
223
224       --  Sever the association between the given file and its associated
225       --  external file. The given file is left closed. Do not perform system
226       --  closes on the standard input, output and error files and also do
227       --  not attempt to close a stream that does not exist (signalled by a
228       --  null stream value -- happens in some error situations).
229
230       if not File.Is_System_File
231         and then File.Stream /= NULL_Stream
232       then
233          --  Do not do an fclose if this is a shared file and there is
234          --  at least one other instance of the stream that is open.
235
236          if File.Shared_Status = Yes then
237             declare
238                P   : AFCB_Ptr;
239
240             begin
241                P := Open_Files;
242                while P /= null loop
243                   if P /= File
244                     and then File.Stream = P.Stream
245                   then
246                      Dup_Strm := True;
247                      exit;
248                   end if;
249
250                   P := P.Next;
251                end loop;
252             end;
253          end if;
254
255          --  Do the fclose unless this was a duplicate in the shared case
256
257          if not Dup_Strm then
258             Close_Status := fclose (File.Stream);
259          end if;
260       end if;
261
262       --  Dechain file from list of open files and then free the storage
263
264       if File.Prev = null then
265          Open_Files := File.Next;
266       else
267          File.Prev.Next := File.Next;
268       end if;
269
270       if File.Next /= null then
271          File.Next.Prev := File.Prev;
272       end if;
273
274       --  Deallocate some parts of the file structure that were kept in heap
275       --  storage with the exception of system files (standard input, output
276       --  and error) since they had some information allocated in the stack.
277
278       if not File.Is_System_File then
279          Free_String (File.Name);
280          Free_String (File.Form);
281          AFCB_Free (File);
282       end if;
283
284       File := null;
285
286       if Close_Status /= 0 then
287          raise Device_Error;
288       end if;
289
290       SSL.Unlock_Task.all;
291
292    exception
293       when others =>
294          SSL.Unlock_Task.all;
295          raise;
296    end Close;
297
298    ------------
299    -- Delete --
300    ------------
301
302    procedure Delete (File_Ptr : access AFCB_Ptr) is
303       File : AFCB_Ptr renames File_Ptr.all;
304    begin
305       Check_File_Open (File);
306
307       if not File.Is_Regular_File then
308          raise Use_Error;
309       end if;
310
311       declare
312          Filename : aliased constant String := File.Name.all;
313
314       begin
315          Close (File_Ptr);
316
317          --  Now unlink the external file. Note that we use the full name
318          --  in this unlink, because the working directory may have changed
319          --  since we did the open, and we want to unlink the right file!
320
321          if unlink (Filename'Address) = -1 then
322             raise Use_Error;
323          end if;
324       end;
325    end Delete;
326
327    -----------------
328    -- End_Of_File --
329    -----------------
330
331    function End_Of_File (File : AFCB_Ptr) return Boolean is
332    begin
333       Check_File_Open (File);
334
335       if feof (File.Stream) /= 0 then
336          return True;
337
338       else
339          Check_Read_Status (File);
340
341          if ungetc (fgetc (File.Stream), File.Stream) = EOF then
342             clearerr (File.Stream);
343             return True;
344          else
345             return False;
346          end if;
347       end if;
348    end End_Of_File;
349
350    --------------
351    -- Finalize --
352    --------------
353
354    --  Note: we do not need to worry about locking against multiple task
355    --  access in this routine, since it is called only from the environment
356    --  task just before terminating execution.
357
358    procedure Finalize (V : in out File_IO_Clean_Up_Type) is
359       pragma Warnings (Off, V);
360
361       Fptr1   : aliased AFCB_Ptr;
362       Fptr2   : AFCB_Ptr;
363
364       Discard : int;
365       pragma Unreferenced (Discard);
366
367    begin
368       --  Take a lock to protect global Open_Files data structure
369
370       SSL.Lock_Task.all;
371
372       --  First close all open files (the slightly complex form of this loop
373       --  is required because Close as a side effect nulls out its argument)
374
375       Fptr1 := Open_Files;
376       while Fptr1 /= null loop
377          Fptr2 := Fptr1.Next;
378          Close (Fptr1'Access);
379          Fptr1 := Fptr2;
380       end loop;
381
382       --  Now unlink all temporary files. We do not bother to free the
383       --  blocks because we are just about to terminate the program. We
384       --  also ignore any errors while attempting these unlink operations.
385
386       while Temp_Files /= null loop
387          Discard := unlink (Temp_Files.Name'Address);
388          Temp_Files := Temp_Files.Next;
389       end loop;
390
391       SSL.Unlock_Task.all;
392
393    exception
394       when others =>
395          SSL.Unlock_Task.all;
396          raise;
397    end Finalize;
398
399    -----------
400    -- Flush --
401    -----------
402
403    procedure Flush (File : AFCB_Ptr) is
404    begin
405       Check_Write_Status (File);
406
407       if fflush (File.Stream) = 0 then
408          return;
409       else
410          raise Device_Error;
411       end if;
412    end Flush;
413
414    ----------------
415    -- Fopen_Mode --
416    ----------------
417
418    --  The fopen mode to be used is shown by the following table:
419
420    --                                     OPEN         CREATE
421    --     Append_File                     "r+"           "w+"
422    --     In_File                         "r"            "w+"
423    --     Out_File (Direct_IO)            "r+"           "w"
424    --     Out_File (all others)           "w"            "w"
425    --     Inout_File                      "r+"           "w+"
426
427    --  Note: we do not use "a" or "a+" for Append_File, since this would not
428    --  work in the case of stream files, where even if in append file mode,
429    --  you can reset to earlier points in the file. The caller must use the
430    --  Append_Set routine to deal with the necessary positioning.
431
432    --  Note: in several cases, the fopen mode used allows reading and
433    --  writing, but the setting of the Ada mode is more restrictive. For
434    --  instance, Create in In_File mode uses "w+" which allows writing,
435    --  but the Ada mode In_File will cause any write operations to be
436    --  rejected with Mode_Error in any case.
437
438    --  Note: for the Out_File/Open cases for other than the Direct_IO case,
439    --  an initial call will be made by the caller to first open the file in
440    --  "r" mode to be sure that it exists. The real open, in "w" mode, will
441    --  then destroy this file. This is peculiar, but that's what Ada semantics
442    --  require and the ACVT tests insist on!
443
444    --  If text file translation is required, then either b or t is
445    --  added to the mode, depending on the setting of Text.
446
447    procedure Fopen_Mode
448      (Mode    : File_Mode;
449       Text    : Boolean;
450       Creat   : Boolean;
451       Amethod : Character;
452       Fopstr  : out Fopen_String)
453    is
454       Fptr : Positive;
455
456    begin
457       case Mode is
458          when In_File =>
459             if Creat then
460                Fopstr (1) := 'w';
461                Fopstr (2) := '+';
462                Fptr := 3;
463             else
464                Fopstr (1) := 'r';
465                Fptr := 2;
466             end if;
467
468          when Out_File =>
469             if Amethod = 'D' and then not Creat then
470                Fopstr (1) := 'r';
471                Fopstr (2) := '+';
472                Fptr := 3;
473             else
474                Fopstr (1) := 'w';
475                Fptr := 2;
476             end if;
477
478          when Inout_File | Append_File =>
479             if Creat then
480                Fopstr (1) := 'w';
481             else
482                Fopstr (1) := 'r';
483             end if;
484
485             Fopstr (2) := '+';
486             Fptr := 3;
487
488       end case;
489
490       --  If text_translation_required is true then we need to append
491       --  either a t or b to the string to get the right mode
492
493       if text_translation_required then
494          if Text then
495             Fopstr (Fptr) := 't';
496          else
497             Fopstr (Fptr) := 'b';
498          end if;
499
500          Fptr := Fptr + 1;
501       end if;
502
503       Fopstr (Fptr) := ASCII.NUL;
504    end Fopen_Mode;
505
506    ----------
507    -- Form --
508    ----------
509
510    function Form (File : AFCB_Ptr) return String is
511    begin
512       if File = null then
513          raise Status_Error;
514       else
515          return File.Form.all (1 .. File.Form'Length - 1);
516       end if;
517    end Form;
518
519    ------------------
520    -- Form_Boolean --
521    ------------------
522
523    function Form_Boolean
524      (Form    : String;
525       Keyword : String;
526       Default : Boolean)
527       return    Boolean
528    is
529       V1, V2 : Natural;
530       pragma Unreferenced (V2);
531
532    begin
533       Form_Parameter (Form, Keyword, V1, V2);
534
535       if V1 = 0 then
536          return Default;
537
538       elsif Form (V1) = 'y' then
539          return True;
540
541       elsif Form (V1) = 'n' then
542          return False;
543
544       else
545          raise Use_Error;
546       end if;
547    end Form_Boolean;
548
549    ------------------
550    -- Form_Integer --
551    ------------------
552
553    function Form_Integer
554      (Form    : String;
555       Keyword : String;
556       Default : Integer)
557       return    Integer
558    is
559       V1, V2 : Natural;
560       V      : Integer;
561
562    begin
563       Form_Parameter (Form, Keyword, V1, V2);
564
565       if V1 = 0 then
566          return Default;
567
568       else
569          V := 0;
570
571          for J in V1 .. V2 loop
572             if Form (J) not in '0' .. '9' then
573                raise Use_Error;
574             else
575                V := V * 10 + Character'Pos (Form (J)) - Character'Pos ('0');
576             end if;
577
578             if V > 999_999 then
579                raise Use_Error;
580             end if;
581          end loop;
582
583          return V;
584       end if;
585    end Form_Integer;
586
587    --------------------
588    -- Form_Parameter --
589    --------------------
590
591    procedure Form_Parameter
592      (Form    : String;
593       Keyword : String;
594       Start   : out Natural;
595       Stop    : out Natural)
596   is
597       Klen : constant Integer := Keyword'Length;
598
599    --  Start of processing for Form_Parameter
600
601    begin
602       for J in Form'First + Klen .. Form'Last - 1 loop
603          if Form (J) = '='
604            and then Form (J - Klen .. J - 1) = Keyword
605          then
606             Start := J + 1;
607             Stop := Start - 1;
608
609             while Form (Stop + 1) /= ASCII.NUL
610               and then Form (Stop + 1) /= ','
611             loop
612                Stop := Stop + 1;
613             end loop;
614
615             return;
616          end if;
617       end loop;
618
619       Start := 0;
620       Stop  := 0;
621    end Form_Parameter;
622
623    -------------
624    -- Is_Open --
625    -------------
626
627    function Is_Open (File : AFCB_Ptr) return Boolean is
628    begin
629       --  We return True if the file is open, and the underlying file stream is
630       --  usable. In particular on Windows an application linked with -mwindows
631       --  option set does not have a console attached. In this case standard
632       --  files (Current_Output, Current_Error, Current_Input) are not created.
633       --  We want Is_Open (Current_Output) to return False in this case.
634
635       return File /= null and then fileno (File.Stream) /= -1;
636    end Is_Open;
637
638    -------------------
639    -- Make_Buffered --
640    -------------------
641
642    procedure Make_Buffered
643      (File    : AFCB_Ptr;
644       Buf_Siz : Interfaces.C_Streams.size_t)
645    is
646       status : Integer;
647       pragma Unreferenced (status);
648
649    begin
650       status := setvbuf (File.Stream, Null_Address, IOFBF, Buf_Siz);
651    end Make_Buffered;
652
653    ------------------------
654    -- Make_Line_Buffered --
655    ------------------------
656
657    procedure Make_Line_Buffered
658      (File     : AFCB_Ptr;
659       Line_Siz : Interfaces.C_Streams.size_t)
660    is
661       status : Integer;
662       pragma Unreferenced (status);
663
664    begin
665       status := setvbuf (File.Stream, Null_Address, IOLBF, Line_Siz);
666    end Make_Line_Buffered;
667
668    ---------------------
669    -- Make_Unbuffered --
670    ---------------------
671
672    procedure Make_Unbuffered (File : AFCB_Ptr) is
673       status : Integer;
674       pragma Unreferenced (status);
675
676    begin
677       status := setvbuf (File.Stream, Null_Address, IONBF, 0);
678    end Make_Unbuffered;
679
680    ----------
681    -- Mode --
682    ----------
683
684    function Mode (File : AFCB_Ptr) return File_Mode is
685    begin
686       if File = null then
687          raise Status_Error;
688       else
689          return File.Mode;
690       end if;
691    end Mode;
692
693    ----------
694    -- Name --
695    ----------
696
697    function Name (File : AFCB_Ptr) return String is
698    begin
699       if File = null then
700          raise Status_Error;
701       else
702          return File.Name.all (1 .. File.Name'Length - 1);
703       end if;
704    end Name;
705
706    ----------
707    -- Open --
708    ----------
709
710    procedure Open
711      (File_Ptr  : in out AFCB_Ptr;
712       Dummy_FCB : AFCB'Class;
713       Mode      : File_Mode;
714       Name      : String;
715       Form      : String;
716       Amethod   : Character;
717       Creat     : Boolean;
718       Text      : Boolean;
719       C_Stream  : FILEs := NULL_Stream)
720    is
721       pragma Warnings (Off, Dummy_FCB);
722       --  Yes we know this is never assigned a value. That's intended, since
723       --  all we ever use of this value is the tag for dispatching purposes.
724
725       procedure Tmp_Name (Buffer : Address);
726       pragma Import (C, Tmp_Name, "__gnat_tmp_name");
727       --  set buffer (a String address) with a temporary filename
728
729       Stream : FILEs := C_Stream;
730       --  Stream which we open in response to this request
731
732       Shared : Shared_Status_Type;
733       --  Setting of Shared_Status field for file
734
735       Fopstr : aliased Fopen_String;
736       --  Mode string used in fopen call
737
738       Formstr : aliased String (1 .. Form'Length + 1);
739       --  Form string with ASCII.NUL appended, folded to lower case
740
741       Is_Text_File : Boolean;
742
743       Tempfile : constant Boolean := (Name'Length = 0);
744       --  Indicates temporary file case
745
746       Namelen : constant Integer := max_path_len;
747       --  Length required for file name, not including final ASCII.NUL
748       --  Note that we used to reference L_tmpnam here, which is not
749       --  reliable since __gnat_tmp_name does not always use tmpnam.
750
751       Namestr : aliased String (1 .. Namelen + 1);
752       --  Name as given or temporary file name with ASCII.NUL appended
753
754       Fullname : aliased String (1 .. max_path_len + 1);
755       --  Full name (as required for Name function, and as stored in the
756       --  control block in the Name field) with ASCII.NUL appended.
757
758       Full_Name_Len : Integer;
759       --  Length of name actually stored in Fullname
760
761       Encoding : System.CRTL.Filename_Encoding;
762       --  Filename encoding specified into the form parameter
763
764    begin
765       if File_Ptr /= null then
766          raise Status_Error;
767       end if;
768
769       --  Acquire form string, setting required NUL terminator
770
771       Formstr (1 .. Form'Length) := Form;
772       Formstr (Formstr'Last) := ASCII.NUL;
773
774       --  Convert form string to lower case
775
776       for J in Formstr'Range loop
777          if Formstr (J) in 'A' .. 'Z' then
778             Formstr (J) := Character'Val (Character'Pos (Formstr (J)) + 32);
779          end if;
780       end loop;
781
782       --  Acquire setting of shared parameter
783
784       declare
785          V1, V2 : Natural;
786
787       begin
788          Form_Parameter (Formstr, "shared", V1, V2);
789
790          if V1 = 0 then
791             Shared := None;
792
793          elsif Formstr (V1 .. V2) = "yes" then
794             Shared := Yes;
795
796          elsif Formstr (V1 .. V2) = "no" then
797             Shared := No;
798
799          else
800             raise Use_Error;
801          end if;
802       end;
803
804       --  Acquire setting of encoding parameter
805
806       declare
807          V1, V2 : Natural;
808
809       begin
810          Form_Parameter (Formstr, "encoding", V1, V2);
811
812          if V1 = 0 then
813             Encoding := System.CRTL.Unspecified;
814
815          elsif Formstr (V1 .. V2) = "utf8" then
816             Encoding := System.CRTL.UTF8;
817
818          elsif Formstr (V1 .. V2) = "8bits" then
819             Encoding := System.CRTL.ASCII_8bits;
820
821          else
822             raise Use_Error;
823          end if;
824       end;
825
826       --  Acquire setting of text_translation parameter. Only needed if this is
827       --  a [Wide_[Wide_]]Text_IO file, in which case we default to True, but
828       --  if the Form says Text_Translation=No, we use binary mode, so new-line
829       --  will be just LF, even on Windows.
830
831       Is_Text_File := Text;
832
833       if Is_Text_File then
834          Is_Text_File :=
835            Form_Boolean (Formstr, "text_translation", Default => True);
836       end if;
837
838       --  If we were given a stream (call from xxx.C_Streams.Open), then set
839       --  the full name to the given one, and skip to end of processing.
840
841       if Stream /= NULL_Stream then
842          Full_Name_Len := Name'Length + 1;
843          Fullname (1 .. Full_Name_Len - 1) := Name;
844          Fullname (Full_Name_Len) := ASCII.NUL;
845
846       --  Normal case of Open or Create
847
848       else
849          --  If temporary file case, get temporary file name and add to the
850          --  list of temporary files to be deleted on exit.
851
852          if Tempfile then
853             if not Creat then
854                raise Name_Error;
855             end if;
856
857             Tmp_Name (Namestr'Address);
858
859             if Namestr (1) = ASCII.NUL then
860                raise Use_Error;
861             end if;
862
863             --  Chain to temp file list, ensuring thread safety with a lock
864
865             begin
866                SSL.Lock_Task.all;
867                Temp_Files :=
868                  new Temp_File_Record'(Name => Namestr, Next => Temp_Files);
869                SSL.Unlock_Task.all;
870
871             exception
872                when others =>
873                   SSL.Unlock_Task.all;
874                   raise;
875             end;
876
877          --  Normal case of non-null name given
878
879          else
880             if Name'Length > Namelen then
881                raise Name_Error;
882             end if;
883
884             Namestr (1 .. Name'Length) := Name;
885             Namestr (Name'Length + 1)  := ASCII.NUL;
886          end if;
887
888          --  Get full name in accordance with the advice of RM A.8.2(22)
889
890          full_name (Namestr'Address, Fullname'Address);
891
892          if Fullname (1) = ASCII.NUL then
893             raise Use_Error;
894          end if;
895
896          Full_Name_Len := 1;
897          while Full_Name_Len < Fullname'Last
898            and then Fullname (Full_Name_Len) /= ASCII.NUL
899          loop
900             Full_Name_Len := Full_Name_Len + 1;
901          end loop;
902
903          --  Fullname is generated by calling system's full_name. The problem
904          --  is, full_name does nothing about the casing, so a file name
905          --  comparison may generally speaking not be valid on non-case
906          --  sensitive systems, and in particular we get unexpected failures
907          --  on Windows/Vista because of this. So we use s-casuti to force
908          --  the name to lower case.
909
910          if not File_Names_Case_Sensitive then
911             To_Lower (Fullname (1 .. Full_Name_Len));
912          end if;
913
914          --  If Shared=None or Shared=Yes, then check for the existence
915          --  of another file with exactly the same full name.
916
917          if Shared /= No then
918             declare
919                P : AFCB_Ptr;
920
921             begin
922                --  Take a task lock to protect Open_Files
923
924                SSL.Lock_Task.all;
925
926                --  Search list of open files
927
928                P := Open_Files;
929                while P /= null loop
930                   if Fullname (1 .. Full_Name_Len) = P.Name.all then
931
932                      --  If we get a match, and either file has Shared=None,
933                      --  then raise Use_Error, since we don't allow two files
934                      --  of the same name to be opened unless they specify the
935                      --  required sharing mode.
936
937                      if Shared = None
938                        or else P.Shared_Status = None
939                      then
940                         raise Use_Error;
941
942                      --  If both files have Shared=Yes, then we acquire the
943                      --  stream from the located file to use as our stream.
944
945                      elsif Shared = Yes
946                        and then P.Shared_Status = Yes
947                      then
948                         Stream := P.Stream;
949                         exit;
950
951                      --  Otherwise one of the files has Shared=Yes and one has
952                      --  Shared=No. If the current file has Shared=No then all
953                      --  is well but we don't want to share any other file's
954                      --  stream. If the current file has Shared=Yes, we would
955                      --  like to share a stream, but not from a file that has
956                      --  Shared=No, so either way, we just continue the search.
957
958                      else
959                         null;
960                      end if;
961                   end if;
962
963                   P := P.Next;
964                end loop;
965
966                SSL.Unlock_Task.all;
967
968             exception
969                when others =>
970                   SSL.Unlock_Task.all;
971                   raise;
972             end;
973          end if;
974
975          --  Open specified file if we did not find an existing stream
976
977          if Stream = NULL_Stream then
978             Fopen_Mode (Mode, Is_Text_File, Creat, Amethod, Fopstr);
979
980             --  A special case, if we are opening (OPEN case) a file and the
981             --  mode returned by Fopen_Mode is not "r" or "r+", then we first
982             --  make sure that the file exists as required by Ada semantics.
983
984             if not Creat and then Fopstr (1) /= 'r' then
985                if file_exists (Namestr'Address) = 0 then
986                   raise Name_Error;
987                end if;
988             end if;
989
990             --  Now open the file. Note that we use the name as given in the
991             --  original Open call for this purpose, since that seems the
992             --  clearest implementation of the intent. It would presumably
993             --  work to use the full name here, but if there is any difference,
994             --  then we should use the name used in the call.
995
996             --  Note: for a corresponding delete, we will use the full name,
997             --  since by the time of the delete, the current working directory
998             --  may have changed and we do not want to delete a different file!
999
1000             Stream := fopen (Namestr'Address, Fopstr'Address, Encoding);
1001
1002             if Stream = NULL_Stream then
1003
1004                --  Raise Name_Error if trying to open a non-existent file.
1005                --  Otherwise raise Use_Error.
1006
1007                --  Should we raise Device_Error for ENOSPC???
1008
1009                declare
1010                   subtype Cint is Interfaces.C.int;
1011
1012                   function Is_File_Not_Found_Error
1013                     (Errno_Value : Cint) return Cint;
1014                   --  Non-zero when the given errno value indicates a non-
1015                   --  existing file.
1016
1017                   pragma Import
1018                     (C, Is_File_Not_Found_Error,
1019                      "__gnat_is_file_not_found_error");
1020
1021                begin
1022                   if
1023                     Is_File_Not_Found_Error (Cint (System.OS_Lib.Errno)) /= 0
1024                   then
1025                      raise Name_Error;
1026                   else
1027                      raise Use_Error;
1028                   end if;
1029                end;
1030             end if;
1031          end if;
1032       end if;
1033
1034       --  Stream has been successfully located or opened, so now we are
1035       --  committed to completing the opening of the file. Allocate block
1036       --  on heap and fill in its fields.
1037
1038       File_Ptr := AFCB_Allocate (Dummy_FCB);
1039
1040       File_Ptr.Is_Regular_File   := (is_regular_file (fileno (Stream)) /= 0);
1041       File_Ptr.Is_System_File    := False;
1042       File_Ptr.Is_Text_File      := Is_Text_File;
1043       File_Ptr.Shared_Status     := Shared;
1044       File_Ptr.Access_Method     := Amethod;
1045       File_Ptr.Stream            := Stream;
1046       File_Ptr.Form              := new String'(Formstr);
1047       File_Ptr.Name              := new String'(Fullname (1 .. Full_Name_Len));
1048       File_Ptr.Mode              := Mode;
1049       File_Ptr.Is_Temporary_File := Tempfile;
1050       File_Ptr.Encoding          := Encoding;
1051
1052       Chain_File (File_Ptr);
1053       Append_Set (File_Ptr);
1054    end Open;
1055
1056    --------------
1057    -- Read_Buf --
1058    --------------
1059
1060    procedure Read_Buf (File : AFCB_Ptr; Buf : Address; Siz : size_t) is
1061       Nread : size_t;
1062
1063    begin
1064       Nread := fread (Buf, 1, Siz, File.Stream);
1065
1066       if Nread = Siz then
1067          return;
1068
1069       elsif ferror (File.Stream) /= 0 then
1070          raise Device_Error;
1071
1072       elsif Nread = 0 then
1073          raise End_Error;
1074
1075       else -- 0 < Nread < Siz
1076          raise Data_Error;
1077       end if;
1078
1079    end Read_Buf;
1080
1081    procedure Read_Buf
1082      (File  : AFCB_Ptr;
1083       Buf   : Address;
1084       Siz   : Interfaces.C_Streams.size_t;
1085       Count : out Interfaces.C_Streams.size_t)
1086    is
1087    begin
1088       Count := fread (Buf, 1, Siz, File.Stream);
1089
1090       if Count = 0 and then ferror (File.Stream) /= 0 then
1091          raise Device_Error;
1092       end if;
1093    end Read_Buf;
1094
1095    -----------
1096    -- Reset --
1097    -----------
1098
1099    --  The reset which does not change the mode simply does a rewind
1100
1101    procedure Reset (File_Ptr : access AFCB_Ptr) is
1102       File : AFCB_Ptr renames File_Ptr.all;
1103    begin
1104       Check_File_Open (File);
1105       Reset (File_Ptr, File.Mode);
1106    end Reset;
1107
1108    --  The reset with a change in mode is done using freopen, and is
1109    --  not permitted except for regular files (since otherwise there
1110    --  is no name for the freopen, and in any case it seems meaningless)
1111
1112    procedure Reset (File_Ptr : access AFCB_Ptr; Mode : File_Mode) is
1113       File   : AFCB_Ptr renames File_Ptr.all;
1114       Fopstr : aliased Fopen_String;
1115
1116    begin
1117       Check_File_Open (File);
1118
1119       --  Change of mode not allowed for shared file or file with no name or
1120       --  file that is not a regular file, or for a system file. Note that we
1121       --  allow the "change" of mode if it is not in fact doing a change.
1122
1123       if Mode /= File.Mode
1124         and then (File.Shared_Status = Yes
1125                    or else File.Name'Length <= 1
1126                    or else File.Is_System_File
1127                    or else not File.Is_Regular_File)
1128       then
1129          raise Use_Error;
1130
1131       --  For In_File or Inout_File for a regular file, we can just do a
1132       --  rewind if the mode is unchanged, which is more efficient than
1133       --  doing a full reopen.
1134
1135       elsif Mode = File.Mode
1136         and then Mode <= Inout_File
1137       then
1138          rewind (File.Stream);
1139
1140       --  Here the change of mode is permitted, we do it by reopening the
1141       --  file in the new mode and replacing the stream with a new stream.
1142
1143       else
1144          Fopen_Mode
1145            (Mode, File.Is_Text_File, False, File.Access_Method, Fopstr);
1146
1147          File.Stream := freopen
1148            (File.Name.all'Address, Fopstr'Address, File.Stream, File.Encoding);
1149
1150          if File.Stream = NULL_Stream then
1151             Close (File_Ptr);
1152             raise Use_Error;
1153
1154          else
1155             File.Mode := Mode;
1156             Append_Set (File);
1157          end if;
1158       end if;
1159    end Reset;
1160
1161    ---------------
1162    -- Write_Buf --
1163    ---------------
1164
1165    procedure Write_Buf (File : AFCB_Ptr; Buf : Address; Siz : size_t) is
1166    begin
1167       --  Note: for most purposes, the Siz and 1 parameters in the fwrite
1168       --  call could be reversed, but on VMS, this is a better choice, since
1169       --  for some file formats, reversing the parameters results in records
1170       --  of one byte each.
1171
1172       SSL.Abort_Defer.all;
1173
1174       if fwrite (Buf, Siz, 1, File.Stream) /= 1 then
1175          if Siz /= 0 then
1176             SSL.Abort_Undefer.all;
1177             raise Device_Error;
1178          end if;
1179       end if;
1180
1181       SSL.Abort_Undefer.all;
1182    end Write_Buf;
1183
1184 end System.File_IO;