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