1------------------------------------------------------------------------------
2--                                                                          --
3--                         GNAT COMPILER COMPONENTS                         --
4--                                                                          --
5--                        S Y S T E M . O S _ L I B                         --
6--                                                                          --
7--                                 S p e c                                  --
8--                                                                          --
9--          Copyright (C) 1995-2021, 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--  Operating system interface facilities
33
34--  This package contains types and procedures for interfacing to the
35--  underlying OS. It is used by the GNAT compiler and by tools associated
36--  with the GNAT compiler, and therefore works for the various operating
37--  systems to which GNAT has been ported. This package will undoubtedly grow
38--  as new services are needed by various tools.
39
40--  This package tends to use fairly low-level Ada in order to not bring in
41--  large portions of the RTL. For example, functions return access to string
42--  as part of avoiding functions returning unconstrained types.
43
44--  Except where specifically noted, these routines are portable across all
45--  GNAT implementations on all supported operating systems.
46
47--  Note: this package is in the System hierarchy so that it can be directly
48--  be used by other predefined packages. User access to this package is via
49--  a renaming of this package in GNAT.OS_Lib (file g-os_lib.ads).
50
51pragma Compiler_Unit_Warning;
52
53with System;
54with System.Strings;
55
56package System.OS_Lib is
57   pragma Preelaborate;
58
59   -----------------------
60   -- String Operations --
61   -----------------------
62
63   --  These are reexported from package Strings (which was introduced to
64   --  avoid different packages declaring different types unnecessarily).
65   --  See package System.Strings for details.
66
67   subtype String_Access is Strings.String_Access;
68
69   function "=" (Left : String_Access; Right : String_Access) return Boolean
70     renames Strings."=";
71
72   procedure Free (X : in out String_Access) renames Strings.Free;
73
74   subtype String_List is Strings.String_List;
75
76   function "=" (Left : String_List; Right : String_List) return Boolean
77     renames Strings."=";
78
79   function "&" (Left : String_Access; Right : String_Access)
80     return String_List renames Strings."&";
81   function "&" (Left : String_Access; Right : String_List)
82     return String_List renames Strings."&";
83   function "&" (Left : String_List; Right : String_Access)
84     return String_List renames Strings."&";
85   function "&" (Left : String_List; Right : String_List)
86     return String_List renames Strings."&";
87
88   subtype String_List_Access is Strings.String_List_Access;
89
90   function "="
91     (Left  : String_List_Access;
92      Right : String_List_Access) return Boolean renames Strings."=";
93
94   procedure Free (Arg : in out String_List_Access) renames Strings.Free;
95
96   ---------------------
97   -- Time/Date Stuff --
98   ---------------------
99
100   type OS_Time is private;
101   --  The OS's notion of time is represented by the private type OS_Time. This
102   --  is the type returned by the File_Time_Stamp functions to obtain the time
103   --  stamp of a specified file. Functions and a procedure (modeled after the
104   --  similar subprograms in package Calendar) are provided for extracting
105   --  information from a value of this type. Although these are called GM, the
106   --  intention in the case of time stamps is not that they provide GMT times
107   --  in all cases but rather the actual (time-zone independent) time stamp of
108   --  the file (of course in Unix systems, this *is* in GMT form).
109
110   Invalid_Time : constant OS_Time;
111   --  A special unique value used to flag an invalid time stamp value
112
113   function "<"  (X : OS_Time; Y : OS_Time) return Boolean;
114   function ">"  (X : OS_Time; Y : OS_Time) return Boolean;
115   function ">=" (X : OS_Time; Y : OS_Time) return Boolean;
116   function "<=" (X : OS_Time; Y : OS_Time) return Boolean;
117   --  Basic comparison operators on OS_Time with obvious meanings. Note that
118   --  these have Intrinsic convention, so for example it is not permissible
119   --  to create accesses to any of these functions.
120
121   subtype Year_Type   is Integer range 1900 .. 2099;
122   subtype Month_Type  is Integer range    1 ..   12;
123   subtype Day_Type    is Integer range    1 ..   31;
124   subtype Hour_Type   is Integer range    0 ..   23;
125   subtype Minute_Type is Integer range    0 ..   59;
126   subtype Second_Type is Integer range    0 ..   59;
127   --  Declarations similar to those in Calendar, breaking down the time
128
129   function Current_Time return OS_Time;
130   --  Return the system clock value as OS_Time
131
132   function Current_Time_String return String;
133   --  Returns current local time in the form YYYY-MM-DD HH:MM:SS. The result
134   --  has bounds 1 .. 19.
135
136   function GM_Year    (Date : OS_Time) return Year_Type;
137   function GM_Month   (Date : OS_Time) return Month_Type;
138   function GM_Day     (Date : OS_Time) return Day_Type;
139   function GM_Hour    (Date : OS_Time) return Hour_Type;
140   function GM_Minute  (Date : OS_Time) return Minute_Type;
141   function GM_Second  (Date : OS_Time) return Second_Type;
142   --  Functions to extract information from OS_Time value in GMT form
143
144   procedure GM_Split
145     (Date   : OS_Time;
146      Year   : out Year_Type;
147      Month  : out Month_Type;
148      Day    : out Day_Type;
149      Hour   : out Hour_Type;
150      Minute : out Minute_Type;
151      Second : out Second_Type);
152   --  Analogous to the Split routine in Ada.Calendar, takes an OS_Time and
153   --  provides a representation of it as a set of component parts, to be
154   --  interpreted as a date point in UTC.
155
156   function GM_Time_Of
157     (Year   : Year_Type;
158      Month  : Month_Type;
159      Day    : Day_Type;
160      Hour   : Hour_Type;
161      Minute : Minute_Type;
162      Second : Second_Type) return OS_Time;
163   --  Analogous to the Time_Of routine in Ada.Calendar, takes a set of time
164   --  component parts to be interpreted in the local time zone, and returns
165   --  an OS_Time. Returns Invalid_Time if the creation fails.
166
167   ------------------
168   -- Time_t Stuff --
169   ------------------
170
171   --  Note: Do not use time_t in the compiler and host-based tools; instead
172   --  use OS_Time.
173
174   subtype time_t is Long_Long_Integer;
175   --  C time_t can be either long or long long, so we choose the Ada
176   --  equivalent of the latter because eventually that will be the
177   --  type used out of necessity. This may affect some user code on 32-bit
178   --  targets that have not yet migrated to the Posix 2008 standard,
179   --  particularly pre version 5 32-bit Linux. Do not change this
180   --  declaration without coordinating it with conversions in Ada.Calendar.
181
182   function To_C (Time : OS_Time) return time_t;
183   --  Convert OS_Time to C time_t type
184
185   function To_Ada (Time : time_t) return OS_Time;
186   --  Convert C time_t type to OS_Time
187
188   ----------------
189   -- File Stuff --
190   ----------------
191
192   --  These routines give access to the open/creat/close/read/write level of
193   --  I/O routines in the typical C library (these functions are not part of
194   --  the ANSI C standard, but are typically available in all systems). See
195   --  also package Interfaces.C_Streams for access to the stream level
196   --  routines.
197
198   --  Note on file names. If a file name is passed as type String in any of
199   --  the following specifications, then the name is a normal Ada string and
200   --  need not be NUL-terminated. However, a trailing NUL character is
201   --  permitted, and will be ignored (more accurately, the NUL and any
202   --  characters that follow it will be ignored).
203
204   type File_Descriptor is new Integer;
205   --  Corresponds to the int file handle values used in the C routines
206
207   Standin  : constant File_Descriptor := 0;
208   Standout : constant File_Descriptor := 1;
209   Standerr : constant File_Descriptor := 2;
210   --  File descriptors for standard input output files
211
212   Invalid_FD : constant File_Descriptor := -1;
213   --  File descriptor returned when error in opening/creating file
214
215   Null_FD : constant File_Descriptor := -2;
216   --  Uninitialized file descriptor
217
218   procedure Close (FD : File_Descriptor; Status : out Boolean);
219   --  Close file referenced by FD. Status is False if the underlying service
220   --  failed. Reasons for failure include: disk full, disk quotas exceeded
221   --  and invalid file descriptor (the file may have been closed twice).
222
223   procedure Close (FD : File_Descriptor);
224   --  Close file referenced by FD. This form is used when the caller wants to
225   --  ignore any possible error (see above for error cases).
226
227   type Copy_Mode is
228     (Copy,
229      --  Copy the file. It is an error if the target file already exists. The
230      --  time stamps and other file attributes are preserved in the copy.
231
232      Overwrite,
233      --  If the target file exists, the file is replaced otherwise the file
234      --  is just copied. The time stamps and other file attributes are
235      --  preserved in the copy.
236
237      Append);
238      --  If the target file exists, the contents of the source file is
239      --  appended at the end. Otherwise the source file is just copied. The
240      --  time stamps and other file attributes are preserved if the
241      --  destination file does not exist.
242
243   type Attribute is
244     (Time_Stamps,
245      --  Copy time stamps from source file to target file. All other
246      --  attributes are set to normal default values for file creation.
247
248      Full,
249      --  All attributes are copied from the source file to the target file.
250      --  This includes the timestamps, and for example also includes
251      --  read/write/execute attributes in Unix systems.
252
253      None);
254      --  No attributes are copied. All attributes including the time stamp
255      --  values are set to normal default values for file creation.
256
257   --  Note: The default is Time_Stamps, which corresponds to the normal
258   --  default on Windows style systems. Full corresponds to the typical
259   --  effect of "cp -p" on Unix systems, and None corresponds to the typical
260   --  effect of "cp" on Unix systems.
261
262   --  Note: Time_Stamps and Full are not supported on VxWorks 5
263
264   procedure Copy_File
265     (Name     : String;
266      Pathname : String;
267      Success  : out Boolean;
268      Mode     : Copy_Mode := Copy;
269      Preserve : Attribute := Time_Stamps);
270   --  Copy a file. Name must designate a single file (no wildcards allowed).
271   --  Pathname can be a filename or directory name. In the latter case Name
272   --  is copied into the directory preserving the same file name. Mode
273   --  defines the kind of copy, see above with the default being a normal
274   --  copy in which the target file must not already exist. Success is set to
275   --  True or False indicating if the copy is successful (depending on the
276   --  specified Mode).
277
278   procedure Copy_File_Attributes
279      (From             : String;
280       To               : String;
281       Success          : out Boolean;
282       Copy_Timestamp   : Boolean := True;
283       Copy_Permissions : Boolean := True);
284   --  Copy some of the file attributes from one file to another. Both files
285   --  must exist, or Success is set to False.
286
287   procedure Copy_Time_Stamps
288     (Source  : String;
289      Dest    : String;
290      Success : out Boolean);
291   --  Copy Source file time stamps (last modification and last access time
292   --  stamps) to Dest file. Source and Dest must be valid filenames,
293   --  furthermore Dest must be writable. Success will be set to True if the
294   --  operation was successful and False otherwise.
295   --
296   --  Note: this procedure is not supported on VxWorks 5. On this platform,
297   --  Success is always set to False.
298
299   type Mode is (Binary, Text);
300   for Mode'Size use Integer'Size;
301   for Mode use (Binary => 0, Text => 1);
302   --  Used in all the Open and Create calls to specify if the file is to be
303   --  opened in binary mode or text mode. In systems like Unix, this has no
304   --  effect, but in systems capable of text mode translation, the use of
305   --  Text as the mode parameter causes the system to do CR/LF translation
306   --  and also to recognize the DOS end of file character on input. The use
307   --  of Text where appropriate allows programs to take a portable Unix view
308   --  of DOS-format files and process them appropriately.
309
310   function Create_File
311     (Name  : String;
312      Fmode : Mode) return File_Descriptor;
313   --  Creates new file with given name for writing, returning file descriptor
314   --  for subsequent use in Write calls. If the file already exists, it is
315   --  overwritten. File descriptor returned is Invalid_FD if file cannot be
316   --  successfully created.
317
318   function Create_New_File
319     (Name  : String;
320      Fmode : Mode) return File_Descriptor;
321   --  Create new file with given name for writing, returning file descriptor
322   --  for subsequent use in Write calls. This differs from Create_File in
323   --  that it fails if the file already exists. File descriptor returned is
324   --  Invalid_FD if the file exists or cannot be created.
325
326   function Create_Output_Text_File (Name : String) return File_Descriptor;
327   --  Creates new text file with given name suitable to redirect standard
328   --  output, returning file descriptor. File descriptor returned is
329   --  Invalid_FD if file cannot be successfully created.
330
331   Temp_File_Len : constant Integer := 12;
332   --  Length of name returned by Create_Temp_File call (GNAT-XXXXXX & NUL)
333
334   subtype Temp_File_Name is String (1 .. Temp_File_Len);
335   --  String subtype set by Create_Temp_File
336
337   procedure Create_Temp_File
338     (FD   : out File_Descriptor;
339      Name : out Temp_File_Name);
340   --  Create and open for writing a temporary file in the current working
341   --  directory. The name of the file and the File Descriptor are returned.
342   --  The File Descriptor returned is Invalid_FD in the case of failure. No
343   --  mode parameter is provided. Since this is a temporary file, there is no
344   --  point in doing text translation on it.
345   --
346   --  On some operating systems, the maximum number of temp files that can be
347   --  created with this procedure may be limited. When the maximum is reached,
348   --  this procedure returns Invalid_FD. On some operating systems, there may
349   --  be a race condition between processes trying to create temp files at the
350   --  same time in the same directory using this procedure.
351
352   procedure Create_Temp_File
353     (FD   : out File_Descriptor;
354      Name : out String_Access);
355   --  Create and open for writing a temporary file in the current working
356   --  directory. The name of the file and the File Descriptor are returned.
357   --  It is the responsibility of the caller to deallocate the access value
358   --  returned in Name.
359   --
360   --  The file is opened in binary mode (no text translation).
361   --
362   --  This procedure will always succeed if the current working directory is
363   --  writable. If the current working directory is not writable, then
364   --  Invalid_FD is returned for the file descriptor and null for the Name.
365   --  There is no race condition problem between processes trying to create
366   --  temp files at the same time in the same directory.
367
368   procedure Create_Temp_Output_File
369     (FD   : out File_Descriptor;
370      Name : out String_Access);
371   --  Create and open for writing a temporary file in the current working
372   --  directory suitable to redirect standard output. The name of the file and
373   --  the File Descriptor are returned. It is the responsibility of the caller
374   --  to deallocate the access value returned in Name.
375   --
376   --  The file is opened in text mode
377   --
378   --  This procedure will always succeed if the current working directory is
379   --  writable. If the current working directory is not writable, then
380   --  Invalid_FD is returned for the file descriptor and null for the Name.
381   --  There is no race condition problem between processes trying to create
382   --  temp files at the same time in the same directory.
383
384   procedure Delete_File (Name : String; Success : out Boolean);
385   --  Deletes file. Success is set True or False indicating if the delete is
386   --  successful.
387
388   function File_Length (FD : File_Descriptor) return Long_Integer;
389   pragma Import (C, File_Length, "__gnat_file_length_long");
390
391   type Large_File_Size is range -2**63 .. 2**63 - 1;
392   --  Maximum supported size for a file (8 exabytes = 8 million terabytes,
393   --  should be enough to accommodate all possible needs for quite a while).
394
395   function File_Length64 (FD : File_Descriptor) return Large_File_Size;
396   pragma Import (C, File_Length64, "__gnat_file_length");
397   --  Get length of file from file descriptor FD
398
399   function File_Time_Stamp (Name : String) return OS_Time;
400   --  Given the name of a file or directory, Name, obtains and returns the
401   --  time stamp. This function can be used for an unopened file. Returns
402   --  Invalid_Time if Name doesn't correspond to an existing file.
403
404   function File_Time_Stamp (FD : File_Descriptor) return OS_Time;
405   --  Get time stamp of file from file descriptor FD Returns Invalid_Time is
406   --  FD doesn't correspond to an existing file.
407
408   function Get_Debuggable_Suffix return String_Access;
409   --  Return the debuggable suffix convention. Usually this is the same as
410   --  the convention for Get_Executable_Suffix. The result is allocated on
411   --  the heap and should be freed after use to avoid storage leaks.
412
413   function Get_Executable_Suffix return String_Access;
414   --  Return the executable suffix convention. The result is allocated on the
415   --  heap and should be freed after use to avoid storage leaks.
416
417   function Get_Object_Suffix return String_Access;
418   --  Return the object suffix convention. The result is allocated on the heap
419   --  and should be freed after use to avoid storage leaks.
420
421   function Get_Target_Debuggable_Suffix return String_Access;
422   --  Return the target debuggable suffix convention. Usually this is the same
423   --  as the convention for Get_Executable_Suffix. The result is allocated on
424   --  the heap and should be freed after use to avoid storage leaks.
425
426   function Get_Target_Executable_Suffix return String_Access;
427   --  Return the target executable suffix convention. The result is allocated
428   --  on the heap and should be freed after use to avoid storage leaks.
429
430   function Get_Target_Object_Suffix return String_Access;
431   --  Return the target object suffix convention. The result is allocated on
432   --  the heap and should be freed after use to avoid storage leaks.
433
434   function Is_Absolute_Path (Name : String) return Boolean;
435   --  Returns True if Name is an absolute path name, i.e. it designates a
436   --  file or directory absolutely rather than relative to another directory.
437
438   function Is_Directory (Name : String) return Boolean;
439   --  Determines if the given string, Name, is the name of a directory.
440   --  Returns True if so, False otherwise. Name may be an absolute path
441   --  name or a relative path name, including a simple file name. If it is
442   --  a relative path name, it is relative to the current working directory.
443
444   function Is_Executable_File (Name : String) return Boolean;
445   --  Determines if the given string, Name, is the name of an existing file
446   --  that is executable. Returns True if so, False otherwise. Note that this
447   --  function simply interrogates the file attributes (e.g. using the C
448   --  function stat), so it does not indicate a situation in which a file may
449   --  not actually be readable due to some other process having exclusive
450   --  access.
451
452   function Is_Owner_Readable_File (Name : String) return Boolean;
453   --  Determines if the given string, Name, is the name of an existing file
454   --  that is readable. Returns True if so, False otherwise. Note that this
455   --  function simply interrogates the file attributes (e.g. using the C
456   --  function stat), so it does not indicate a situation in which a file may
457   --  not actually be readable due to some other process having exclusive
458   --  access.
459
460   function Is_Regular_File (Name : String) return Boolean;
461   --  Determines if the given string, Name, is the name of an existing
462   --  regular file. Returns True if so, False otherwise. Name may be an
463   --  absolute path name or a relative path name, including a simple file
464   --  name. If it is a relative path name, it is relative to the current
465   --  working directory.
466
467   function Is_Symbolic_Link (Name : String) return Boolean;
468   --  Determines if the given string, Name, is the path of a symbolic link on
469   --  systems that support it. Returns True if so, False if the path is not a
470   --  symbolic link or if the system does not support symbolic links.
471   --
472   --  A symbolic link is an indirect pointer to a file; its directory entry
473   --  contains the name of the file to which it is linked. Symbolic links may
474   --  span file systems and may refer to directories.
475
476   function Is_Owner_Writable_File (Name : String) return Boolean;
477   --  Determines if the given string, Name, is the name of an existing file
478   --  that is writable. Returns True if so, False otherwise. Note that this
479   --  function simply interrogates the file attributes (e.g. using the C
480   --  function stat), so it does not indicate a situation in which a file may
481   --  not actually be writable due to some other process having exclusive
482   --  access.
483
484   function Is_Read_Accessible_File (Name : String) return Boolean;
485   --  Determines if the given string, Name, is the name of an existing file
486   --  that is readable. Returns True if so, False otherwise.
487
488   function Is_Write_Accessible_File (Name : String) return Boolean;
489   --  Determines if the given string, Name, is the name of an existing file
490   --  that is writable. Returns True if so, False otherwise.
491
492   function Is_Readable_File (Name : String) return Boolean
493     renames Is_Read_Accessible_File;
494   function Is_Writable_File (Name : String) return Boolean
495     renames Is_Write_Accessible_File;
496   --  These subprograms provided for backward compatibility and should not be
497   --  used. Use Is_Owner_Readable_File/Is_Owner_Writable_File or
498   --  Is_Read_Accessible_File/Is_Write_Accessible_File instead.
499
500   function Locate_Exec_On_Path (Exec_Name : String) return String_Access;
501   --  Try to locate an executable whose name is given by Exec_Name in the
502   --  directories listed in the environment Path. If the Exec_Name does not
503   --  have the executable suffix, it will be appended before the search.
504   --  Otherwise works like Locate_Regular_File below. If the executable is
505   --  not found, null is returned.
506   --
507   --  Note that this function allocates memory for the returned value. This
508   --  memory needs to be deallocated after use.
509
510   function Locate_Regular_File
511     (File_Name : String;
512      Path      : String) return String_Access;
513   --  Try to locate a regular file whose name is given by File_Name in the
514   --  directories listed in Path. If a file is found, its full pathname is
515   --  returned; otherwise, a null pointer is returned. If the File_Name given
516   --  is an absolute pathname, then Locate_Regular_File just checks that the
517   --  file exists and is a regular file. Otherwise, if the File_Name given
518   --  includes directory information, Locate_Regular_File first checks if the
519   --  file exists relative to the current directory. If it does not, or if
520   --  the File_Name given is a simple file name, the Path argument is parsed
521   --  according to OS conventions, and for each directory in the Path a check
522   --  is made if File_Name is a relative pathname of a regular file from that
523   --  directory.
524   --
525   --  Note that this function allocates some memory for the returned value.
526   --  This memory needs to be deallocated after use.
527
528   Seek_Cur : constant := 1;
529   Seek_End : constant := 2;
530   Seek_Set : constant := 0;
531   --  Used to indicate origin for Lseek call
532
533   procedure Lseek
534     (FD     : File_Descriptor;
535      offset : Long_Integer;
536      origin : Integer);
537   pragma Import (C, Lseek, "__gnat_lseek");
538   --  Sets the current file pointer to the indicated offset value, relative
539   --  to the current position (origin = SEEK_CUR), end of file (origin =
540   --  SEEK_END), or start of file (origin = SEEK_SET).
541
542   function Normalize_Pathname
543     (Name           : String;
544      Directory      : String  := "";
545      Resolve_Links  : Boolean := True;
546      Case_Sensitive : Boolean := True) return String;
547   --  Returns a file name as an absolute path name, resolving all relative
548   --  directories, and symbolic links. If Name is a relative path, it is
549   --  interpreted relative to Directory, or to the current directory if
550   --  Directory is the empty string (the default). The result returned is
551   --  the normalized name of the file, containing no "." or ".." components,
552   --  and no duplicated directory separators. For most cases, if two file
553   --  names designate the same file through different paths,
554   --  Normalize_Pathname will return the same canonical name in both cases.
555   --  However, there are cases when this is not true; for example, this is
556   --  not true in Unix for two hard links designating the same file.
557   --
558   --  On Windows, the returned path will start with a drive letter. If
559   --  Directory is empty (the default) and Name is a relative path or an
560   --  absolute path without drive letter, the letter of the current drive
561   --  will start the returned path. If Case_Sensitive is True (the default),
562   --  then this drive letter will be forced to upper case ("C:\...").
563   --
564   --  If Resolve_Links is set to True, then the symbolic links, on systems
565   --  that support them, will be fully converted to the name of the file or
566   --  directory pointed to. This is slightly less efficient, since it
567   --  requires system calls.
568   --
569   --  If Name is empty or the path contains symbolic links that can't be
570   --  resolved (for example there is a symbolic link circularity,
571   --  e.g. A is a symbolic link for B, and B is a symbolic link for A), then
572   --  Normalize_Pathname returns an empty string.
573   --
574   --  For case-sensitive file systems, the value of Case_Sensitive parameter
575   --  is ignored. For file systems that are not case-sensitive, such as
576   --  Windows, if this parameter is set to False, then the file and directory
577   --  names are folded to lower case. This allows checking whether two files
578   --  are the same by applying this function to their names and comparing the
579   --  results. If Case_Sensitive is set to True, this function does not change
580   --  the casing of file and directory names.
581
582   function Open_Append
583     (Name  : String;
584      Fmode : Mode) return File_Descriptor;
585   --  Opens file Name for appending, returning its file descriptor. File
586   --  descriptor returned is Invalid_FD if the file cannot be successfully
587   --  opened.
588
589   function Open_Read
590     (Name  : String;
591      Fmode : Mode) return File_Descriptor;
592   --  Open file Name for reading, returning its file descriptor. File
593   --  descriptor returned is Invalid_FD if the file cannot be opened.
594
595   function Open_Read_Write
596     (Name  : String;
597      Fmode : Mode) return File_Descriptor;
598   --  Open file Name for both reading and writing, returning its file
599   --  descriptor. File descriptor returned is Invalid_FD if the file
600   --  cannot be opened.
601
602   function Read
603     (FD : File_Descriptor;
604      A  : System.Address;
605      N  : Integer) return Integer;
606   --  Read N bytes to address A from file referenced by FD. Returned value is
607   --  count of bytes actually read, which can be less than N at EOF.
608
609   procedure Rename_File
610     (Old_Name : String;
611      New_Name : String;
612      Success  : out Boolean);
613   --  Rename a file. Success is set True or False indicating if the rename is
614   --  successful or not.
615   --
616   --  WARNING: In one very important respect, this function is significantly
617   --  non-portable. If New_Name already exists then on Unix systems, the call
618   --  deletes the existing file, and the call signals success. On Windows, the
619   --  call fails, without doing the rename operation. See also the procedure
620   --  Ada.Directories.Rename, which portably provides the windows semantics,
621   --  i.e. fails if the output file already exists.
622
623   --  The following defines the mode for the Copy_File procedure below. Note
624   --  that "time stamps and other file attributes" in the descriptions below
625   --  refers to the creation and last modification times, and also the file
626   --  access (read/write/execute) status flags.
627
628   procedure Set_Close_On_Exec
629     (FD            : File_Descriptor;
630      Close_On_Exec : Boolean;
631      Status        : out Boolean);
632   --  When Close_On_Exec is True, mark FD to be closed automatically when new
633   --  program is executed by the calling process (i.e. prevent FD from being
634   --  inherited by child processes). When Close_On_Exec is False, mark FD to
635   --  not be closed on exec (i.e. allow it to be inherited). Status is False
636   --  if the operation could not be performed.
637
638   S_Owner  : constant := 1;
639   S_Group  : constant := 2;
640   S_Others : constant := 4;
641   --  Constants for use in Mode parameter to Set_Executable
642
643   procedure Set_Executable (Name : String; Mode : Positive := S_Owner);
644   --  Change permissions on the file given by Name to make it executable
645   --  for its owner, group or others, according to the setting of Mode.
646   --  As indicated, the default if no Mode parameter is given is owner.
647
648   procedure Set_File_Last_Modify_Time_Stamp (Name : String; Time : OS_Time);
649   --  Given the name of a file or directory, Name, set the last modification
650   --  time stamp. This function must be used for an unopened file.
651
652   procedure Set_Non_Readable (Name : String);
653   --  Change permissions on the named file to make it non-readable for
654   --  its owner. The writable and executable permissions are not
655   --  modified.
656
657   procedure Set_Non_Writable (Name : String);
658   --  Change permissions on the named file to make it non-writable for its
659   --  owner. The readable and executable permissions are not modified.
660
661   procedure Set_Read_Only (Name : String) renames Set_Non_Writable;
662   --  This renaming is provided for backwards compatibility with previous
663   --  versions. The use of Set_Non_Writable is preferred (clearer name).
664
665   procedure Set_Readable (Name : String);
666   --  Change permissions on the named file to make it readable for its
667   --  owner.
668
669   procedure Set_Writable (Name : String);
670   --  Change permissions on the named file to make it writable for its owner
671
672   function Write
673     (FD : File_Descriptor;
674      A  : System.Address;
675      N  : Integer) return Integer;
676   --  Write N bytes from address A to file referenced by FD. The returned
677   --  value is the number of bytes written, which can be less than N if a
678   --  disk full condition was detected.
679
680   --  The following section contains low-level routines using addresses to
681   --  pass file name and executable name. In each routine the name must be
682   --  Nul-Terminated. For complete documentation refer to the equivalent
683   --  routine (using String in place of C_File_Name) defined above.
684
685   subtype C_File_Name is System.Address;
686   --  This subtype is used to document that a parameter is the address of a
687   --  null-terminated string containing the name of a file.
688
689   procedure Copy_File
690     (Name     : C_File_Name;
691      Pathname : C_File_Name;
692      Success  : out Boolean;
693      Mode     : Copy_Mode := Copy;
694      Preserve : Attribute := Time_Stamps);
695
696   procedure Copy_Time_Stamps
697     (Source  : C_File_Name;
698      Dest    : C_File_Name;
699      Success : out Boolean);
700
701   function Create_File
702     (Name  : C_File_Name;
703      Fmode : Mode) return File_Descriptor;
704
705   function Create_New_File
706     (Name  : C_File_Name;
707      Fmode : Mode) return File_Descriptor;
708
709   procedure Delete_File (Name : C_File_Name; Success : out Boolean);
710
711   function File_Time_Stamp (Name : C_File_Name) return OS_Time;
712
713   function Is_Directory (Name : C_File_Name) return Boolean;
714   function Is_Executable_File (Name : C_File_Name) return Boolean;
715   function Is_Owner_Readable_File (Name : C_File_Name) return Boolean;
716   function Is_Regular_File (Name : C_File_Name) return Boolean;
717   function Is_Symbolic_Link (Name : C_File_Name) return Boolean;
718   function Is_Owner_Writable_File (Name : C_File_Name) return Boolean;
719
720   function Locate_Regular_File
721     (File_Name : C_File_Name;
722      Path      : C_File_Name) return String_Access;
723
724   function Open_Append
725     (Name  : C_File_Name;
726      Fmode : Mode) return File_Descriptor;
727
728   function Open_Read
729     (Name  : C_File_Name;
730      Fmode : Mode) return File_Descriptor;
731
732   function Open_Read_Write
733     (Name  : C_File_Name;
734      Fmode : Mode) return File_Descriptor;
735
736   procedure Rename_File
737     (Old_Name : C_File_Name;
738      New_Name : C_File_Name;
739      Success  : out Boolean);
740
741   ------------------
742   -- Subprocesses --
743   ------------------
744
745   subtype Argument_List is String_List;
746   --  Type used for argument list in call to Spawn. The lower bound of the
747   --  array should be 1, and the length of the array indicates the number of
748   --  arguments.
749
750   subtype Argument_List_Access is String_List_Access;
751   --  Type used to return Argument_List without dragging in secondary stack.
752   --  Note that there is a Free procedure declared for this subtype which
753   --  frees the array and all referenced strings.
754
755   type Process_Id is private;
756   --  A private type used to identify a process activated by the following
757   --  non-blocking calls. The only meaningful operation on this type is a
758   --  comparison for equality.
759
760   Invalid_Pid : constant Process_Id;
761   --  A special value used to indicate errors, as described below
762
763   function Current_Process_Id return Process_Id;
764   --  Returns the current process id or Invalid_Pid if not supported by the
765   --  runtime.
766
767   function Argument_String_To_List
768     (Arg_String : String) return Argument_List_Access;
769   --  Take a string that is a program and its arguments and parse it into an
770   --  Argument_List. Note that the result is allocated on the heap, and must
771   --  be freed by the programmer (when it is no longer needed) to avoid
772   --  memory leaks.
773   --  On Windows, backslashes are used as directory separators. On Unix,
774   --  however, they are used to escape the following character, so that for
775   --  instance "-d=name\ with\ space" is a single argument. In the result
776   --  list, the backslashes have been cleaned up when needed. The previous
777   --  example will thus result a single-element array, where the element is
778   --  "-d=name with space" (Unix) or "-d=name\ with\ space" (windows).
779
780   procedure Kill (Pid : Process_Id; Hard_Kill : Boolean := True);
781   --  Kill the process designated by Pid. Does nothing if Pid is Invalid_Pid
782   --  or on platforms where it is not supported, such as VxWorks. Hard_Kill
783   --  is True by default, and when True the process is terminated immediately.
784   --  If Hard_Kill is False, then a signal SIGINT is sent to the process on
785   --  POSIX OS or a ctrl-C event on Windows, allowing the process a chance to
786   --  terminate properly using a corresponding handler.
787
788   procedure Kill_Process_Tree (Pid : Process_Id; Hard_Kill : Boolean := True);
789   --  Kill the process designated by Pid and all it's children processes.
790   --  Does nothing if Pid is Invalid_Pid or on platforms where it is not
791   --  supported, such as VxWorks. Hard_Kill is True by default, and when True
792   --  the processes are terminated immediately. If Hard_Kill is False, then a
793   --  signal SIGINT is sent to the processes on POSIX OS or a ctrl-C event
794   --  on Windows, allowing the processes a chance to terminate properly
795   --  using a corresponding handler.
796   --
797   --  Note that this routine is not atomic and is supported only on Linux
798   --  and Windows. On other OS it will only kill the process identified by
799   --  Pid.
800
801   function Non_Blocking_Spawn
802     (Program_Name : String;
803      Args         : Argument_List) return Process_Id;
804   --  This is a non blocking call. The Process_Id of the spawned process is
805   --  returned. Parameters are to be used as in Spawn. If Invalid_Pid is
806   --  returned the program could not be spawned.
807   --
808   --  Spawning processes from tasking programs is not recommended. See
809   --  "NOTE: Spawn in tasking programs" below.
810   --
811   --  This function will always return Invalid_Pid under VxWorks, since there
812   --  is no notion of executables under this OS.
813
814   function Non_Blocking_Spawn
815     (Program_Name           : String;
816      Args                   : Argument_List;
817      Output_File_Descriptor : File_Descriptor;
818      Err_To_Out             : Boolean := True) return Process_Id;
819   --  Similar to the procedure above, but redirects the output to the file
820   --  designated by Output_File_Descriptor. If Err_To_Out is True, then the
821   --  Standard Error output is also redirected. Invalid_Pid is returned
822   --  if the program could not be spawned successfully.
823   --
824   --  Spawning processes from tasking programs is not recommended. See
825   --  "NOTE: Spawn in tasking programs" below.
826   --
827   --  This function will always return Invalid_Pid under VxWorks, since there
828   --  is no notion of executables under this OS.
829
830   function Non_Blocking_Spawn
831     (Program_Name : String;
832      Args         : Argument_List;
833      Output_File  : String;
834      Err_To_Out   : Boolean := True) return Process_Id;
835   --  Similar to the procedure above, but saves the output of the command to
836   --  a file with the name Output_File.
837   --
838   --  Invalid_Pid is returned if the output file could not be created or if
839   --  the program could not be spawned successfully.
840   --
841   --  Spawning processes from tasking programs is not recommended. See
842   --  "NOTE: Spawn in tasking programs" below.
843   --
844   --  This function will always return Invalid_Pid under VxWorks, since there
845   --  is no notion of executables under this OS.
846
847   function Non_Blocking_Spawn
848     (Program_Name : String;
849      Args         : Argument_List;
850      Stdout_File  : String;
851      Stderr_File  : String) return Process_Id;
852   --  Similar to the procedure above, but saves the standard output of the
853   --  command to a file with the name Stdout_File and the standard output
854   --  of the command to a file with the name Stderr_File.
855
856   procedure Normalize_Arguments (Args : in out Argument_List);
857   --  Normalize all arguments in the list. This ensure that the argument list
858   --  is compatible with the running OS and will works fine with Spawn and
859   --  Non_Blocking_Spawn for example. If Normalize_Arguments is called twice
860   --  on the same list it will do nothing the second time. Note that Spawn
861   --  and Non_Blocking_Spawn call Normalize_Arguments automatically, but
862   --  since there is a guarantee that a second call does nothing, this
863   --  internal call will have no effect if Normalize_Arguments is called
864   --  before calling Spawn. The call to Normalize_Arguments assumes that the
865   --  individual referenced arguments in Argument_List are on the heap, and
866   --  may free them and reallocate if they are modified.
867
868   function Pid_To_Integer (Pid : Process_Id) return Integer;
869   --  Convert a process id to an Integer. Useful for writing hash functions
870   --  for type Process_Id or to compare two Process_Id (e.g. for sorting).
871
872   procedure Spawn
873     (Program_Name : String;
874      Args         : Argument_List;
875      Success      : out Boolean);
876   --  This procedure spawns a program with a given list of arguments. The
877   --  first parameter of is the name of the executable. The second parameter
878   --  contains the arguments to be passed to this program. Success is False
879   --  if the named program could not be spawned or its execution completed
880   --  unsuccessfully. Note that the caller will be blocked until the
881   --  execution of the spawned program is complete. For maximum portability,
882   --  use a full path name for the Program_Name argument. On some systems
883   --  (notably Unix systems) a simple file name may also work (if the
884   --  executable can be located in the path).
885   --
886   --  Spawning processes from tasking programs is not recommended. See
887   --  "NOTE: Spawn in tasking programs" below.
888   --
889   --  Note: Arguments in Args that contain spaces and/or quotes such as
890   --  "--GCC=gcc -v" or "--GCC=""gcc -v""" are not portable across all
891   --  operating systems, and would not have the desired effect if they were
892   --  passed directly to the operating system. To avoid this problem, Spawn
893   --  makes an internal call to Normalize_Arguments, which ensures that such
894   --  arguments are modified in a manner that ensures that the desired effect
895   --  is obtained on all operating systems. The caller may call
896   --  Normalize_Arguments explicitly before the call (e.g. to print out the
897   --  exact form of arguments passed to the operating system). In this case
898   --  the guarantee a second call to Normalize_Arguments has no effect
899   --  ensures that the internal call will not affect the result. Note that
900   --  the implicit call to Normalize_Arguments may free and reallocate some
901   --  of the individual arguments.
902   --
903   --  This function will always set Success to False under VxWorks and other
904   --  similar operating systems which have no notion of the concept of
905   --  dynamically executable file. Otherwise Success is set True if the exit
906   --  status of the spawned process is zero.
907
908   function Spawn
909     (Program_Name : String;
910      Args         : Argument_List) return Integer;
911   --  Similar to the above procedure, but returns the actual status returned
912   --  by the operating system, or -1 under VxWorks and any other similar
913   --  operating systems which have no notion of separately spawnable programs.
914   --
915   --  Spawning processes from tasking programs is not recommended. See
916   --  "NOTE: Spawn in tasking programs" below.
917
918   procedure Spawn
919     (Program_Name           : String;
920      Args                   : Argument_List;
921      Output_File_Descriptor : File_Descriptor;
922      Return_Code            : out Integer;
923      Err_To_Out             : Boolean := True);
924   --  Similar to the procedure above, but redirects the output to the file
925   --  designated by Output_File_Descriptor. If Err_To_Out is True, then the
926   --  Standard Error output is also redirected.
927   --  Return_Code is set to the status code returned by the operating system
928   --
929   --  Spawning processes from tasking programs is not recommended. See
930   --  "NOTE: Spawn in tasking programs" below.
931
932   procedure Spawn
933     (Program_Name : String;
934      Args         : Argument_List;
935      Output_File  : String;
936      Success      : out Boolean;
937      Return_Code  : out Integer;
938      Err_To_Out   : Boolean := True);
939   --  Similar to the procedure above, but saves the output of the command to
940   --  a file with the name Output_File.
941   --
942   --  Success is set to True if the command is executed and its output
943   --  successfully written to the file. If Success is True, then Return_Code
944   --  will be set to the status code returned by the operating system.
945   --  Otherwise, Return_Code is undefined.
946   --
947   --  Spawning processes from tasking programs is not recommended. See
948   --  "NOTE: Spawn in tasking programs" below.
949
950   procedure Wait_Process (Pid : out Process_Id; Success : out Boolean);
951   --  Wait for the completion of any of the processes created by previous
952   --  calls to Non_Blocking_Spawn. The caller will be suspended until one of
953   --  these processes terminates (normally or abnormally). If any of these
954   --  subprocesses terminates prior to the call to Wait_Process (and has not
955   --  been returned by a previous call to Wait_Process), then the call to
956   --  Wait_Process is immediate. Pid identifies the process that has
957   --  terminated (matching the value returned from Non_Blocking_Spawn).
958   --  Success is set to True if this sub-process terminated successfully. If
959   --  Pid = Invalid_Pid, there were no subprocesses left to wait on.
960   --
961   --  This function will always set success to False under VxWorks, since
962   --  there is no notion of executables under this OS.
963
964   procedure Non_Blocking_Wait_Process
965     (Pid : out Process_Id; Success : out Boolean);
966   --  Same as Wait_Process, except if there are no completed child processes,
967   --  return immediately without blocking, and return Invalid_Pid in Pid.
968   --  Not supported on all platforms; Success = False if not supported.
969
970   -------------------------------------
971   -- NOTE: Spawn in Tasking Programs --
972   -------------------------------------
973
974   --  Spawning processes in tasking programs using the above Spawn and
975   --  Non_Blocking_Spawn subprograms is not recommended, because there are
976   --  subtle interactions between creating a process and signals/locks that
977   --  can cause trouble. These issues are not specific to Ada; they depend
978   --  primarily on the operating system.
979
980   --  If you need to spawn processes in a tasking program, you will need to
981   --  understand the semantics of your operating system, and you are likely to
982   --  write non-portable code, because operating systems differ in this area.
983
984   --  The Spawn and Non_Blocking_Spawn subprograms call the following
985   --  operating system functions:
986
987   --     On Windows: spawnvp (blocking) or CreateProcess (non-blocking)
988
989   --     On Solaris: fork1, followed in the child process by execv
990
991   --     On other Unix-like systems: fork, followed in the child
992   --     process by execv.
993
994   --     On vxworks, spawning of processes is not supported
995
996   --  For details, look at the functions __gnat_portable_spawn and
997   --  __gnat_portable_no_block_spawn in adaint.c.
998
999   --  You should read the operating-system-specific documentation for the
1000   --  above functions, paying special attention to subtle interactions with
1001   --  threading, signals, locks, and file descriptors. Most of the issues are
1002   --  related to the fact that on Unix, there is a window of time between fork
1003   --  and execv; Windows does not have this problem, because spawning is done
1004   --  in a single operation.
1005
1006   --  On Posix-compliant systems, such as Linux, fork duplicates just the
1007   --  calling thread. (On Solaris, fork1 is the Posix-compliant version of
1008   --  fork.)
1009
1010   --  You should avoid using signals while spawning. This includes signals
1011   --  used internally by the Ada run-time system, such as timer signals used
1012   --  to implement delay statements.
1013
1014   --  It is best to spawn any subprocesses very early, before the parent
1015   --  process creates tasks, locks, or installs signal handlers. Certainly
1016   --  avoid doing simultaneous spawns from multiple threads of the same
1017   --  process.
1018
1019   --  There is no problem spawning a subprocess that uses tasking: the
1020   --  problems are caused only by tasking in the parent.
1021
1022   --  If the parent is using tasking, and needs to spawn subprocesses at
1023   --  arbitrary times, one technique is for the parent to spawn (very early)
1024   --  a particular spawn-manager subprocess whose job is to spawn other
1025   --  processes. The spawn-manager must avoid tasking. The parent sends
1026   --  messages to the spawn-manager requesting it to spawn processes, using
1027   --  whatever inter-process communication mechanism you like, such as
1028   --  sockets.
1029
1030   --  In short, mixing spawning of subprocesses with tasking is a tricky
1031   --  business, and should be avoided if possible, but if it is necessary,
1032   --  the above guidelines should be followed, and you should beware of
1033   --  portability problems.
1034
1035   -------------------
1036   -- Miscellaneous --
1037   -------------------
1038
1039   function Errno return Integer;
1040   pragma Import (C, Errno, "__get_errno");
1041   --  Return the task-safe last error number
1042
1043   function Errno_Message
1044     (Err     : Integer := Errno;
1045      Default : String  := "") return String;
1046   --  Return a message describing the given Errno value. If none is provided
1047   --  by the system, return Default if not empty, else return a generic
1048   --  message indicating the numeric errno value.
1049
1050   function Getenv (Name : String) return String_Access;
1051   --  Get the value of the environment variable. Returns an access to the
1052   --  empty string if the environment variable does not exist or has an
1053   --  explicit null value (in some operating systems these are distinct
1054   --  cases, in others they are not; this interface abstracts away that
1055   --  difference. The argument is allocated on the heap (even in the null
1056   --  case), and needs to be freed explicitly when no longer needed to avoid
1057   --  memory leaks.
1058
1059   procedure OS_Abort;
1060   pragma Import (C, OS_Abort, "abort");
1061   pragma No_Return (OS_Abort);
1062   --  Exit to OS signalling an abort (traceback or other appropriate
1063   --  diagnostic information should be given if possible, or entry made to
1064   --  the debugger if that is possible).
1065
1066   procedure OS_Exit (Status : Integer);
1067   pragma No_Return (OS_Exit);
1068   --  Exit to OS with given status code (program is terminated). Note that
1069   --  this is abrupt termination. All tasks are immediately terminated. There
1070   --  are no finalization or other Ada-specific cleanup actions performed. On
1071   --  systems with atexit handlers (such as Unix and Windows), atexit handlers
1072   --  are called.
1073
1074   type OS_Exit_Subprogram is access procedure (Status : Integer);
1075
1076   procedure OS_Exit_Default (Status : Integer);
1077   pragma No_Return (OS_Exit_Default);
1078   --  Default implementation of procedure OS_Exit
1079
1080   OS_Exit_Ptr : OS_Exit_Subprogram := OS_Exit_Default'Access;
1081   --  OS_Exit is implemented through this access value. It it then possible to
1082   --  change the implementation of OS_Exit by redirecting OS_Exit_Ptr to an
1083   --  other implementation.
1084
1085   procedure Set_Errno (Errno : Integer);
1086   pragma Import (C, Set_Errno, "__set_errno");
1087   --  Set the task-safe error number
1088
1089   procedure Setenv (Name : String; Value : String);
1090   --  Set the value of the environment variable Name to Value. This call
1091   --  modifies the current environment, but does not modify the parent
1092   --  process environment. After a call to Setenv, Getenv (Name) will always
1093   --  return a String_Access referencing the same String as Value. This is
1094   --  true also for the null string case (the actual effect may be to either
1095   --  set an explicit null as the value, or to remove the entry, this is
1096   --  operating system dependent). Note that any following calls to Spawn
1097   --  will pass an environment to the spawned process that includes the
1098   --  changes made by Setenv calls.
1099
1100   Directory_Separator : constant Character;
1101   --  The character that is used to separate parts of a pathname
1102
1103   Path_Separator : constant Character;
1104   --  The character to separate paths in an environment variable value
1105
1106private
1107   pragma Import (C, Path_Separator, "__gnat_path_separator");
1108   pragma Import (C, Directory_Separator, "__gnat_dir_separator");
1109   pragma Import (C, Current_Time, "__gnat_current_time");
1110   pragma Import (C, Current_Process_Id, "__gnat_current_process_id");
1111
1112   type OS_Time is
1113     range -(2 ** 63) ..  +(2 ** 63 - 1);
1114   --  Type used for timestamps in the compiler. This type is used to hold
1115   --  time stamps, but may have a different representation than C's time_t.
1116   --  This type needs to match the declaration of OS_Time in adaint.h.
1117
1118   Invalid_Time : constant OS_Time := -1;
1119   --  This value should match the return value from __gnat_file_time_*
1120
1121   pragma Import (Intrinsic, "<");
1122   pragma Import (Intrinsic, ">");
1123   pragma Import (Intrinsic, "<=");
1124   pragma Import (Intrinsic, ">=");
1125   pragma Inline (To_C);
1126   pragma Inline (To_Ada);
1127
1128   type Process_Id is new Integer;
1129   Invalid_Pid : constant Process_Id := -1;
1130
1131end System.OS_Lib;
1132