OSDN Git Service

2010-12-09 Steven G. Kargl <kargl@gcc.gnu.org>
[pf3gnuchains/gcc-fork.git] / gcc / ada / make.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                                 M A K E                                  --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2010, 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.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with ALI;      use ALI;
27 with ALI.Util; use ALI.Util;
28 with Csets;
29 with Debug;
30 with Errutil;
31 with Fmap;
32 with Fname;    use Fname;
33 with Fname.SF; use Fname.SF;
34 with Fname.UF; use Fname.UF;
35 with Gnatvsn;  use Gnatvsn;
36 with Hostparm; use Hostparm;
37 with Makeusg;
38 with Makeutl;  use Makeutl;
39 with MLib;
40 with MLib.Prj;
41 with MLib.Tgt; use MLib.Tgt;
42 with MLib.Utl;
43 with Namet;    use Namet;
44 with Opt;      use Opt;
45 with Osint.M;  use Osint.M;
46 with Osint;    use Osint;
47 with Output;   use Output;
48 with Prj;      use Prj;
49 with Prj.Com;
50 with Prj.Env;
51 with Prj.Pars;
52 with Prj.Tree; use Prj.Tree;
53 with Prj.Util;
54 with SFN_Scan;
55 with Sinput.P;
56 with Snames;   use Snames;
57
58 pragma Warnings (Off);
59 with System.HTable;
60 pragma Warnings (On);
61
62 with Switch;   use Switch;
63 with Switch.M; use Switch.M;
64 with Targparm; use Targparm;
65 with Table;
66 with Tempdir;
67 with Types;    use Types;
68
69 with Ada.Exceptions;            use Ada.Exceptions;
70 with Ada.Command_Line;          use Ada.Command_Line;
71
72 with GNAT.Directory_Operations; use GNAT.Directory_Operations;
73 with GNAT.Dynamic_HTables;      use GNAT.Dynamic_HTables;
74 with GNAT.HTable;
75 with GNAT.Case_Util;            use GNAT.Case_Util;
76 with GNAT.OS_Lib;               use GNAT.OS_Lib;
77
78 package body Make is
79
80    use ASCII;
81    --  Make control characters visible
82
83    Standard_Library_Package_Body_Name : constant String := "s-stalib.adb";
84    --  Every program depends on this package, that must then be checked,
85    --  especially when -f and -a are used.
86
87    procedure Kill (Pid : Process_Id; Sig_Num : Integer; Close : Integer);
88    pragma Import (C, Kill, "__gnat_kill");
89    --  Called by Sigint_Intercepted to kill all spawned compilation processes
90
91    type Sigint_Handler is access procedure;
92    pragma Convention (C, Sigint_Handler);
93
94    procedure Install_Int_Handler (Handler : Sigint_Handler);
95    pragma Import (C, Install_Int_Handler, "__gnat_install_int_handler");
96    --  Called by Gnatmake to install the SIGINT handler below
97
98    procedure Sigint_Intercepted;
99    pragma Convention (C, Sigint_Intercepted);
100    --  Called when the program is interrupted by Ctrl-C to delete the
101    --  temporary mapping files and configuration pragmas files.
102
103    No_Mapping_File : constant Natural := 0;
104
105    type Compilation_Data is record
106       Pid              : Process_Id;
107       Full_Source_File : File_Name_Type;
108       Lib_File         : File_Name_Type;
109       Source_Unit      : Unit_Name_Type;
110       Full_Lib_File    : File_Name_Type;
111       Lib_File_Attr    : aliased File_Attributes;
112       Mapping_File     : Natural := No_Mapping_File;
113       Project          : Project_Id := No_Project;
114    end record;
115    --  Data recorded for each compilation process spawned
116
117    No_Compilation_Data : constant Compilation_Data :=
118      (Invalid_Pid, No_File, No_File, No_Unit_Name, No_File, Unknown_Attributes,
119       No_Mapping_File, No_Project);
120
121    type Comp_Data_Arr is array (Positive range <>) of Compilation_Data;
122    type Comp_Data_Ptr is access Comp_Data_Arr;
123    Running_Compile : Comp_Data_Ptr;
124    --  Used to save information about outstanding compilations
125
126    Outstanding_Compiles : Natural := 0;
127    --  Current number of outstanding compiles
128
129    -------------------------
130    -- Note on terminology --
131    -------------------------
132
133    --  In this program, we use the phrase "termination" of a file name to refer
134    --  to the suffix that appears after the unit name portion. Very often this
135    --  is simply the extension, but in some cases, the sequence may be more
136    --  complex, for example in main.1.ada, the termination in this name is
137    --  ".1.ada" and in main_.ada the termination is "_.ada".
138
139    procedure Insert_Project_Sources
140      (The_Project  : Project_Id;
141       All_Projects : Boolean;
142       Into_Q       : Boolean);
143    --  If Into_Q is True, insert all sources of the project file(s) that are
144    --  not already marked into the Q. If Into_Q is False, call Osint.Add_File
145    --  for the first source, then insert all other sources that are not already
146    --  marked into the Q. If All_Projects is True, all sources of all projects
147    --  are concerned; otherwise, only sources of The_Project are concerned,
148    --  including, if The_Project is an extending project, sources inherited
149    --  from projects being extended.
150
151    Unique_Compile : Boolean := False;
152    --  Set to True if -u or -U or a project file with no main is used
153
154    Unique_Compile_All_Projects : Boolean := False;
155    --  Set to True if -U is used
156
157    Must_Compile : Boolean := False;
158    --  True if gnatmake is invoked with -f -u and one or several mains on the
159    --  command line.
160
161    Main_On_Command_Line : Boolean := False;
162    --  True if gnatmake is invoked with one or several mains on the command
163    --  line.
164
165    RTS_Specified : String_Access := null;
166    --  Used to detect multiple --RTS= switches
167
168    N_M_Switch : Natural := 0;
169    --  Used to count -mxxx switches that can affect multilib
170
171    package Queue is
172       ---------------------------------
173       -- Queue Manipulation Routines --
174       ---------------------------------
175
176       procedure Initialize (Queue_Per_Obj_Dir : Boolean);
177       --  Initialize the queue
178
179       function Is_Empty return Boolean;
180       --  Returns True if the queue is empty
181
182       function Is_Virtually_Empty return Boolean;
183       --  Returns True if the queue is empty or if all object directories are
184       --  busy.
185
186       procedure Insert
187         (Source_File_Name : File_Name_Type;
188          Project          : Project_Id;
189          Source_Unit      : Unit_Name_Type := No_Unit_Name;
190          Index            : Int            := 0);
191       --  Insert source in the queue
192
193       procedure Extract
194         (Source_File_Name  : out File_Name_Type;
195          Source_Unit       : out Unit_Name_Type;
196          Source_Index      : out Int);
197       --  Get the first source that can be compiled from the queue. If no
198       --  source may be compiled, return No_File/No_Source.
199
200       function Size return Natural;
201       --  Return the total size of the queue, including the sources already
202       --  extracted.
203
204       function Processed return Natural;
205       --  Return the number of source in the queue that have aready been
206       --  processed.
207
208       procedure Set_Obj_Dir_Busy (Obj_Dir : Path_Name_Type);
209       --  Indicate that this object directory is busy, so that when
210       --  One_Compilation_Per_Obj_Dir is True no other compilation occurs in
211       --  this object directory.
212
213       procedure Set_Obj_Dir_Free (Obj_Dir : Path_Name_Type);
214       --  Indicate that there is no compilation for this object directory
215
216       function Element (Rank : Positive) return File_Name_Type;
217       --  Get the file name for element of index Rank in the queue
218
219    end Queue;
220
221    --  The 3 following packages are used to store gcc, gnatbind and gnatlink
222    --  switches found in the project files.
223
224    package Gcc_Switches is new Table.Table (
225      Table_Component_Type => String_Access,
226      Table_Index_Type     => Integer,
227      Table_Low_Bound      => 1,
228      Table_Initial        => 20,
229      Table_Increment      => 100,
230      Table_Name           => "Make.Gcc_Switches");
231
232    package Binder_Switches is new Table.Table (
233      Table_Component_Type => String_Access,
234      Table_Index_Type     => Integer,
235      Table_Low_Bound      => 1,
236      Table_Initial        => 20,
237      Table_Increment      => 100,
238      Table_Name           => "Make.Binder_Switches");
239
240    package Linker_Switches is new Table.Table (
241      Table_Component_Type => String_Access,
242      Table_Index_Type     => Integer,
243      Table_Low_Bound      => 1,
244      Table_Initial        => 20,
245      Table_Increment      => 100,
246      Table_Name           => "Make.Linker_Switches");
247
248    --  The following instantiations and variables are necessary to save what
249    --  is found on the command line, in case there is a project file specified.
250
251    package Saved_Gcc_Switches is new Table.Table (
252      Table_Component_Type => String_Access,
253      Table_Index_Type     => Integer,
254      Table_Low_Bound      => 1,
255      Table_Initial        => 20,
256      Table_Increment      => 100,
257      Table_Name           => "Make.Saved_Gcc_Switches");
258
259    package Saved_Binder_Switches is new Table.Table (
260      Table_Component_Type => String_Access,
261      Table_Index_Type     => Integer,
262      Table_Low_Bound      => 1,
263      Table_Initial        => 20,
264      Table_Increment      => 100,
265      Table_Name           => "Make.Saved_Binder_Switches");
266
267    package Saved_Linker_Switches is new Table.Table
268      (Table_Component_Type => String_Access,
269       Table_Index_Type     => Integer,
270       Table_Low_Bound      => 1,
271       Table_Initial        => 20,
272       Table_Increment      => 100,
273       Table_Name           => "Make.Saved_Linker_Switches");
274
275    package Switches_To_Check is new Table.Table (
276      Table_Component_Type => String_Access,
277      Table_Index_Type     => Integer,
278      Table_Low_Bound      => 1,
279      Table_Initial        => 20,
280      Table_Increment      => 100,
281      Table_Name           => "Make.Switches_To_Check");
282
283    package Library_Paths is new Table.Table (
284      Table_Component_Type => String_Access,
285      Table_Index_Type     => Integer,
286      Table_Low_Bound      => 1,
287      Table_Initial        => 20,
288      Table_Increment      => 100,
289      Table_Name           => "Make.Library_Paths");
290
291    package Failed_Links is new Table.Table (
292      Table_Component_Type => File_Name_Type,
293      Table_Index_Type     => Integer,
294      Table_Low_Bound      => 1,
295      Table_Initial        => 10,
296      Table_Increment      => 100,
297      Table_Name           => "Make.Failed_Links");
298
299    package Successful_Links is new Table.Table (
300      Table_Component_Type => File_Name_Type,
301      Table_Index_Type     => Integer,
302      Table_Low_Bound      => 1,
303      Table_Initial        => 10,
304      Table_Increment      => 100,
305      Table_Name           => "Make.Successful_Links");
306
307    package Library_Projs is new Table.Table (
308      Table_Component_Type => Project_Id,
309      Table_Index_Type     => Integer,
310      Table_Low_Bound      => 1,
311      Table_Initial        => 10,
312      Table_Increment      => 100,
313      Table_Name           => "Make.Library_Projs");
314
315    --  Two variables to keep the last binder and linker switch index in tables
316    --  Binder_Switches and Linker_Switches, before adding switches from the
317    --  project file (if any) and switches from the command line (if any).
318
319    Last_Binder_Switch : Integer := 0;
320    Last_Linker_Switch : Integer := 0;
321
322    Normalized_Switches : Argument_List_Access := new Argument_List (1 .. 10);
323    Last_Norm_Switch    : Natural := 0;
324
325    Saved_Maximum_Processes : Natural := 0;
326
327    Gnatmake_Switch_Found : Boolean;
328    --  Set by Scan_Make_Arg. True when the switch is a gnatmake switch.
329    --  Tested by Add_Switches when switches in package Builder must all be
330    --  gnatmake switches.
331
332    Switch_May_Be_Passed_To_The_Compiler : Boolean;
333    --  Set by Add_Switches and Switches_Of. True when unrecognized switches
334    --  are passed to the Ada compiler.
335
336    type Arg_List_Ref is access Argument_List;
337    The_Saved_Gcc_Switches : Arg_List_Ref;
338
339    Project_File_Name : String_Access  := null;
340    --  The path name of the main project file, if any
341
342    Project_File_Name_Present : Boolean := False;
343    --  True when -P is used with a space between -P and the project file name
344
345    Current_Verbosity : Prj.Verbosity  := Prj.Default;
346    --  Verbosity to parse the project files
347
348    Main_Project : Prj.Project_Id := No_Project;
349    --  The project id of the main project file, if any
350
351    Project_Of_Current_Object_Directory : Project_Id := No_Project;
352    --  The object directory of the project for the last compilation. Avoid
353    --  calling Change_Dir if the current working directory is already this
354    --  directory.
355
356    Map_File : String_Access := null;
357    --  Value of switch --create-map-file
358
359    --  Packages of project files where unknown attributes are errors
360
361    Naming_String   : aliased String := "naming";
362    Builder_String  : aliased String := "builder";
363    Compiler_String : aliased String := "compiler";
364    Binder_String   : aliased String := "binder";
365    Linker_String   : aliased String := "linker";
366
367    Gnatmake_Packages : aliased String_List :=
368      (Naming_String   'Access,
369       Builder_String  'Access,
370       Compiler_String 'Access,
371       Binder_String   'Access,
372       Linker_String   'Access);
373
374    Packages_To_Check_By_Gnatmake : constant String_List_Access :=
375      Gnatmake_Packages'Access;
376
377    procedure Add_Library_Search_Dir
378      (Path            : String;
379       On_Command_Line : Boolean);
380    --  Call Add_Lib_Search_Dir with an absolute directory path. If Path is
381    --  relative path, when On_Command_Line is True, it is relative to the
382    --  current working directory. When On_Command_Line is False, it is relative
383    --  to the project directory of the main project.
384
385    procedure Add_Source_Search_Dir
386      (Path            : String;
387       On_Command_Line : Boolean);
388    --  Call Add_Src_Search_Dir with an absolute directory path. If Path is a
389    --  relative path, when On_Command_Line is True, it is relative to the
390    --  current working directory. When On_Command_Line is False, it is relative
391    --  to the project directory of the main project.
392
393    procedure Add_Source_Dir (N : String);
394    --  Call Add_Src_Search_Dir (output one line when in verbose mode)
395
396    procedure Add_Source_Directories is
397      new Prj.Env.For_All_Source_Dirs (Action => Add_Source_Dir);
398
399    procedure Add_Object_Dir (N : String);
400    --  Call Add_Lib_Search_Dir (output one line when in verbose mode)
401
402    procedure Add_Object_Directories is
403      new Prj.Env.For_All_Object_Dirs (Action => Add_Object_Dir);
404
405    procedure Change_To_Object_Directory (Project : Project_Id);
406    --  Change to the object directory of project Project, if this is not
407    --  already the current working directory.
408
409    type Bad_Compilation_Info is record
410       File  : File_Name_Type;
411       Unit  : Unit_Name_Type;
412       Found : Boolean;
413    end record;
414    --  File is the name of the file for which a compilation failed. Unit is for
415    --  gnatdist use in order to easily get the unit name of a file when its
416    --  name is krunched or declared in gnat.adc. Found is False if the
417    --  compilation failed because the file could not be found.
418
419    package Bad_Compilation is new Table.Table (
420      Table_Component_Type => Bad_Compilation_Info,
421      Table_Index_Type     => Natural,
422      Table_Low_Bound      => 1,
423      Table_Initial        => 20,
424      Table_Increment      => 100,
425      Table_Name           => "Make.Bad_Compilation");
426    --  Full name of all the source files for which compilation fails
427
428    Do_Compile_Step : Boolean := True;
429    Do_Bind_Step    : Boolean := True;
430    Do_Link_Step    : Boolean := True;
431    --  Flags to indicate what step should be executed. Can be set to False
432    --  with the switches -c, -b and -l. These flags are reset to True for
433    --  each invocation of procedure Gnatmake.
434
435    Do_Codepeer_Globalize_Step : Boolean := False;
436    --  Flag to indicate whether the CodePeer globalizer should be called
437
438    Shared_String           : aliased String := "-shared";
439    Force_Elab_Flags_String : aliased String := "-F";
440
441    No_Shared_Switch : aliased Argument_List := (1 .. 0 => null);
442    Shared_Switch    : aliased Argument_List := (1 => Shared_String'Access);
443    Bind_Shared      : Argument_List_Access := No_Shared_Switch'Access;
444    --  Switch to added in front of gnatbind switches. By default no switch is
445    --  added. Switch "-shared" is added if there is a non-static Library
446    --  Project File.
447
448    Shared_Libgcc : aliased String := "-shared-libgcc";
449
450    No_Shared_Libgcc_Switch : aliased Argument_List := (1 .. 0 => null);
451    Shared_Libgcc_Switch    : aliased Argument_List :=
452                                (1 => Shared_Libgcc'Access);
453    Link_With_Shared_Libgcc : Argument_List_Access :=
454                                No_Shared_Libgcc_Switch'Access;
455
456    procedure Make_Failed (S : String);
457    --  Delete all temp files created by Gnatmake and call Osint.Fail, with the
458    --  parameter S (see osint.ads). This is called from the Prj hierarchy and
459    --  the MLib hierarchy.
460
461    --------------------------
462    -- Obsolete Executables --
463    --------------------------
464
465    Executable_Obsolete : Boolean := False;
466    --  Executable_Obsolete is initially set to False for each executable,
467    --  and is set to True whenever one of the source of the executable is
468    --  compiled, or has already been compiled for another executable.
469
470    Max_Header : constant := 200;
471    --  This needs a proper comment, it used to say "arbitrary"
472    --  that's not an adequate comment ???
473
474    type Header_Num is range 1 .. Max_Header;
475    --  Header_Num for the hash table Obsoleted below
476
477    function Hash (F : File_Name_Type) return Header_Num;
478    --  Hash function for the hash table Obsoleted below
479
480    package Obsoleted is new System.HTable.Simple_HTable
481      (Header_Num => Header_Num,
482       Element    => Boolean,
483       No_Element => False,
484       Key        => File_Name_Type,
485       Hash       => Hash,
486       Equal      => "=");
487    --  A hash table to keep all files that have been compiled, to detect
488    --  if an executable is up to date or not.
489
490    procedure Enter_Into_Obsoleted (F : File_Name_Type);
491    --  Enter a file name, without directory information, into the hash table
492    --  Obsoleted.
493
494    function Is_In_Obsoleted (F : File_Name_Type) return Boolean;
495    --  Check if a file name, without directory information, has already been
496    --  entered into the hash table Obsoleted.
497
498    type Dependency is record
499       This       : File_Name_Type;
500       Depends_On : File_Name_Type;
501    end record;
502    --  Components of table Dependencies below
503
504    package Dependencies is new Table.Table (
505      Table_Component_Type => Dependency,
506      Table_Index_Type     => Integer,
507      Table_Low_Bound      => 1,
508      Table_Initial        => 20,
509      Table_Increment      => 100,
510      Table_Name           => "Make.Dependencies");
511    --  A table to keep dependencies, to be able to decide if an executable
512    --  is obsolete. More explanation needed ???
513
514 --     procedure Add_Dependency (S : File_Name_Type; On : File_Name_Type);
515 --     --  Add one entry in table Dependencies
516
517    ----------------------------
518    -- Arguments and Switches --
519    ----------------------------
520
521    Arguments : Argument_List_Access;
522    --  Used to gather the arguments for invocation of the compiler
523
524    Last_Argument : Natural := 0;
525    --  Last index of arguments in Arguments above
526
527    Arguments_Project : Project_Id;
528    --  Project id, if any, of the source to be compiled
529
530    Arguments_Path_Name : Path_Name_Type;
531    --  Full path of the source to be compiled, when Arguments_Project is not
532    --  No_Project.
533
534    Dummy_Switch : constant String_Access := new String'("- ");
535    --  Used to initialized Prev_Switch in procedure Check
536
537    procedure Add_Arguments (Args : Argument_List);
538    --  Add arguments to global variable Arguments, increasing its size
539    --  if necessary and adjusting Last_Argument.
540
541    function Configuration_Pragmas_Switch
542      (For_Project : Project_Id) return Argument_List;
543    --  Return an argument list of one element, if there is a configuration
544    --  pragmas file to be specified for For_Project,
545    --  otherwise return an empty argument list.
546
547    -------------------
548    -- Misc Routines --
549    -------------------
550
551    procedure List_Depend;
552    --  Prints to standard output the list of object dependencies. This list
553    --  can be used directly in a Makefile. A call to Compile_Sources must
554    --  precede the call to List_Depend. Also because this routine uses the
555    --  ALI files that were originally loaded and scanned by Compile_Sources,
556    --  no additional ALI files should be scanned between the two calls (i.e.
557    --  between the call to Compile_Sources and List_Depend.)
558
559    procedure List_Bad_Compilations;
560    --  Prints out the list of all files for which the compilation failed
561
562    Usage_Needed : Boolean := True;
563    --  Flag used to make sure Makeusg is call at most once
564
565    procedure Usage;
566    --  Call Makeusg, if Usage_Needed is True.
567    --  Set Usage_Needed to False.
568
569    procedure Debug_Msg (S : String; N : Name_Id);
570    procedure Debug_Msg (S : String; N : File_Name_Type);
571    procedure Debug_Msg (S : String; N : Unit_Name_Type);
572    --  If Debug.Debug_Flag_W is set outputs string S followed by name N
573
574    procedure Recursive_Compute_Depth (Project : Project_Id);
575    --  Compute depth of Project and of the projects it depends on
576
577    -----------------------
578    -- Gnatmake Routines --
579    -----------------------
580
581    subtype Lib_Mark_Type is Byte;
582    --  Used in Mark_Directory
583
584    Ada_Lib_Dir : constant Lib_Mark_Type := 1;
585    --  Used to mark a directory as a GNAT lib dir
586
587    --  Note that the notion of GNAT lib dir is no longer used. The code related
588    --  to it has not been removed to give an idea on how to use the directory
589    --  prefix marking mechanism.
590
591    --  An Ada library directory is a directory containing ali and object files
592    --  but no source files for the bodies (the specs can be in the same or some
593    --  other directory). These directories are specified in the Gnatmake
594    --  command line with the switch "-Adir" (to specify the spec location -Idir
595    --  cab be used). Gnatmake skips the missing sources whose ali are in Ada
596    --  library directories. For an explanation of why Gnatmake behaves that
597    --  way, see the spec of Make.Compile_Sources. The directory lookup penalty
598    --  is incurred every single time this routine is called.
599
600    procedure Check_Steps;
601    --  Check what steps (Compile, Bind, Link) must be executed.
602    --  Set the step flags accordingly.
603
604    function In_Ada_Lib_Dir (File : File_Name_Type) return Boolean;
605    --  Get directory prefix of this file and get lib mark stored in name
606    --  table for this directory. Then check if an Ada lib mark has been set.
607
608    procedure Mark_Directory
609      (Dir             : String;
610       Mark            : Lib_Mark_Type;
611       On_Command_Line : Boolean);
612    --  Store the absolute path from Dir in name table and set lib mark as name
613    --  info to identify Ada libraries.
614    --
615    --  If Dir is a relative path, when On_Command_Line is True, it is relative
616    --  to the current working directory; when On_Command_Line is False, it is
617    --  relative to the project directory of the main project.
618
619    Output_Is_Object : Boolean := True;
620    --  Set to False when using a switch -S for the compiler
621
622    procedure Check_For_S_Switch;
623    --  Set Output_Is_Object to False when the -S switch is used for the
624    --  compiler.
625
626    function Switches_Of
627      (Source_File      : File_Name_Type;
628       Source_File_Name : String;
629       Source_Index     : Int;
630       Project          : Project_Id;
631       In_Package       : Package_Id;
632       Allow_ALI        : Boolean) return Variable_Value;
633    --  Return the switches for the source file in the specified package of a
634    --  project file. If the Source_File ends with a standard GNAT extension
635    --  (".ads" or ".adb"), try first the full name, then the name without the
636    --  extension, then, if Allow_ALI is True, the name with the extension
637    --  ".ali". If there is no switches for either names, try first Switches
638    --  (others) then the default switches for Ada. If all failed, return
639    --  No_Variable_Value.
640
641    function Is_In_Object_Directory
642      (Source_File   : File_Name_Type;
643       Full_Lib_File : File_Name_Type) return Boolean;
644    --  Check if, when using a project file, the ALI file is in the project
645    --  directory of the ultimate extending project. If it is not, we ignore
646    --  the fact that this ALI file is read-only.
647
648    procedure Process_Multilib (Project_Node_Tree : Project_Node_Tree_Ref);
649    --  Add appropriate --RTS argument to handle multilib
650
651    ----------------------------------------------------
652    -- Compiler, Binder & Linker Data and Subprograms --
653    ----------------------------------------------------
654
655    Gcc      : String_Access := Program_Name ("gcc", "gnatmake");
656    Gnatbind : String_Access := Program_Name ("gnatbind", "gnatmake");
657    Gnatlink : String_Access := Program_Name ("gnatlink", "gnatmake");
658    --  Default compiler, binder, linker programs
659
660    Globalizer : constant String := "codepeer_globalizer";
661    --  CodePeer globalizer executable name
662
663    Saved_Gcc      : String_Access := null;
664    Saved_Gnatbind : String_Access := null;
665    Saved_Gnatlink : String_Access := null;
666    --  Given by the command line. Will be used, if non null
667
668    Gcc_Path      : String_Access :=
669                      GNAT.OS_Lib.Locate_Exec_On_Path (Gcc.all);
670    Gnatbind_Path : String_Access :=
671                      GNAT.OS_Lib.Locate_Exec_On_Path (Gnatbind.all);
672    Gnatlink_Path : String_Access :=
673                      GNAT.OS_Lib.Locate_Exec_On_Path (Gnatlink.all);
674    --  Path for compiler, binder, linker programs, defaulted now for gnatdist.
675    --  Changed later if overridden on command line.
676
677    Globalizer_Path : constant String_Access :=
678                        GNAT.OS_Lib.Locate_Exec_On_Path (Globalizer);
679    --  Path for CodePeer globalizer
680
681    Comp_Flag         : constant String_Access := new String'("-c");
682    Output_Flag       : constant String_Access := new String'("-o");
683    Ada_Flag_1        : constant String_Access := new String'("-x");
684    Ada_Flag_2        : constant String_Access := new String'("ada");
685    No_gnat_adc       : constant String_Access := new String'("-gnatA");
686    GNAT_Flag         : constant String_Access := new String'("-gnatpg");
687    Do_Not_Check_Flag : constant String_Access := new String'("-x");
688
689    Object_Suffix : constant String := Get_Target_Object_Suffix.all;
690
691    Syntax_Only : Boolean := False;
692    --  Set to True when compiling with -gnats
693
694    Display_Executed_Programs : Boolean := True;
695    --  Set to True if name of commands should be output on stderr (or on stdout
696    --  if the Commands_To_Stdout flag was set by use of the -eS switch).
697
698    Output_File_Name_Seen : Boolean := False;
699    --  Set to True after having scanned the file_name for
700    --  switch "-o file_name"
701
702    Object_Directory_Seen : Boolean := False;
703    --  Set to True after having scanned the object directory for
704    --  switch "-D obj_dir".
705
706    Object_Directory_Path : String_Access := null;
707    --  The path name of the object directory, set with switch -D
708
709    type Make_Program_Type is (None, Compiler, Binder, Linker);
710
711    Program_Args : Make_Program_Type := None;
712    --  Used to indicate if we are scanning gnatmake, gcc, gnatbind, or gnatbind
713    --  options within the gnatmake command line. Used in Scan_Make_Arg only,
714    --  but must be global since value preserved from one call to another.
715
716    Temporary_Config_File : Boolean := False;
717    --  Set to True when there is a temporary config file used for a project
718    --  file, to avoid displaying the -gnatec switch for a temporary file.
719
720    procedure Add_Switches
721      (The_Package                      : Package_Id;
722       File_Name                        : String;
723       Index                            : Int;
724       Program                          : Make_Program_Type;
725       Unknown_Switches_To_The_Compiler : Boolean := True;
726       Project_Node_Tree                : Project_Node_Tree_Ref);
727    procedure Add_Switch
728      (S             : String_Access;
729       Program       : Make_Program_Type;
730       Append_Switch : Boolean := True;
731       And_Save      : Boolean := True);
732    procedure Add_Switch
733      (S             : String;
734       Program       : Make_Program_Type;
735       Append_Switch : Boolean := True;
736       And_Save      : Boolean := True);
737    --  Make invokes one of three programs (the compiler, the binder or the
738    --  linker). For the sake of convenience, some program specific switches
739    --  can be passed directly on the gnatmake command line. This procedure
740    --  records these switches so that gnatmake can pass them to the right
741    --  program.  S is the switch to be added at the end of the command line
742    --  for Program if Append_Switch is True. If Append_Switch is False S is
743    --  added at the beginning of the command line.
744
745    procedure Check
746      (Source_File    : File_Name_Type;
747       Source_Index   : Int;
748       Is_Main_Source : Boolean;
749       The_Args       : Argument_List;
750       Lib_File       : File_Name_Type;
751       Full_Lib_File  : File_Name_Type;
752       Lib_File_Attr  : access File_Attributes;
753       Read_Only      : Boolean;
754       ALI            : out ALI_Id;
755       O_File         : out File_Name_Type;
756       O_Stamp        : out Time_Stamp_Type);
757    --  Determines whether the library file Lib_File is up-to-date or not. The
758    --  full name (with path information) of the object file corresponding to
759    --  Lib_File is returned in O_File. Its time stamp is saved in O_Stamp.
760    --  ALI is the ALI_Id corresponding to Lib_File. If Lib_File in not
761    --  up-to-date, then the corresponding source file needs to be recompiled.
762    --  In this case ALI = No_ALI_Id.
763    --  Full_Lib_File must be the result of calling Osint.Full_Lib_File_Name on
764    --  Lib_File. Precomputing it saves system calls. Lib_File_Attr is the
765    --  initialized attributes of that file, which is also used to save on
766    --  system calls (it can safely be initialized to Unknown_Attributes).
767
768    procedure Check_Linker_Options
769      (E_Stamp : Time_Stamp_Type;
770       O_File  : out File_Name_Type;
771       O_Stamp : out Time_Stamp_Type);
772    --  Checks all linker options for linker files that are newer
773    --  than E_Stamp. If such objects are found, the youngest object
774    --  is returned in O_File and its stamp in O_Stamp.
775    --
776    --  If no obsolete linker files were found, the first missing
777    --  linker file is returned in O_File and O_Stamp is empty.
778    --  Otherwise O_File is No_File.
779
780    procedure Collect_Arguments
781      (Source_File    : File_Name_Type;
782       Source_Index   : Int;
783       Is_Main_Source : Boolean;
784       Args           : Argument_List);
785    --  Collect all arguments for a source to be compiled, including those
786    --  that come from a project file.
787
788    procedure Display (Program : String; Args : Argument_List);
789    --  Displays Program followed by the arguments in Args if variable
790    --  Display_Executed_Programs is set. The lower bound of Args must be 1.
791
792    procedure Report_Compilation_Failed;
793    --  Delete all temporary files and fail graciously
794
795    -----------------
796    --  Mapping files
797    -----------------
798
799    type Temp_Path_Names is array (Positive range <>) of Path_Name_Type;
800    type Temp_Path_Ptr is access Temp_Path_Names;
801
802    type Free_File_Indexes is array (Positive range <>) of Positive;
803    type Free_Indexes_Ptr is access Free_File_Indexes;
804
805    type Project_Compilation_Data is record
806       Mapping_File_Names : Temp_Path_Ptr;
807       --  The name ids of the temporary mapping files used. This is indexed
808       --  on the maximum number of compilation processes we will be spawning
809       --  (-j parameter)
810
811       Last_Mapping_File_Names : Natural;
812       --  Index of the last mapping file created for this project
813
814       Free_Mapping_File_Indexes : Free_Indexes_Ptr;
815       --  Indexes in Mapping_File_Names of the mapping file names that can be
816       --  reused for subsequent compilations.
817
818       Last_Free_Indexes : Natural;
819       --  Number of mapping files that can be reused
820    end record;
821    --  Information necessary when compiling a project
822
823    type Project_Compilation_Access is access Project_Compilation_Data;
824
825    package Project_Compilation_Htable is new Simple_HTable
826      (Header_Num => Prj.Header_Num,
827       Element    => Project_Compilation_Access,
828       No_Element => null,
829       Key        => Project_Id,
830       Hash       => Prj.Hash,
831       Equal      => "=");
832
833    Project_Compilation : Project_Compilation_Htable.Instance;
834
835    Gnatmake_Mapping_File : String_Access := null;
836    --  The path name of a mapping file specified by switch -C=
837
838    procedure Init_Mapping_File
839      (Project    : Project_Id;
840       Data       : in out Project_Compilation_Data;
841       File_Index : in out Natural);
842    --  Create a new temporary mapping file, and fill it with the project file
843    --  mappings, when using project file(s). The out parameter File_Index is
844    --  the index to the name of the file in the array The_Mapping_File_Names.
845
846    procedure Delete_Temp_Config_Files;
847    --  Delete all temporary config files. Must not be called if Debug_Flag_N
848    --  is False.
849
850    procedure Delete_All_Temp_Files;
851    --  Delete all temp files (config files, mapping files, path files), unless
852    --  Debug_Flag_N is True (in which case all temp files are left for user
853    --  examination).
854
855    -------------------------------------------------
856    -- Subprogram declarations moved from the spec --
857    -------------------------------------------------
858
859    procedure Bind (ALI_File : File_Name_Type; Args : Argument_List);
860    --  Binds ALI_File. Args are the arguments to pass to the binder.
861    --  Args must have a lower bound of 1.
862
863    procedure Display_Commands (Display : Boolean := True);
864    --  The default behavior of Make commands (Compile_Sources, Bind, Link)
865    --  is to display them on stderr. This behavior can be changed repeatedly
866    --  by invoking this procedure.
867
868    --  If a compilation, bind or link failed one of the following 3 exceptions
869    --  is raised. These need to be handled by the calling routines.
870
871    procedure Compile_Sources
872      (Main_Source           : File_Name_Type;
873       Args                  : Argument_List;
874       First_Compiled_File   : out File_Name_Type;
875       Most_Recent_Obj_File  : out File_Name_Type;
876       Most_Recent_Obj_Stamp : out Time_Stamp_Type;
877       Main_Unit             : out Boolean;
878       Compilation_Failures  : out Natural;
879       Main_Index            : Int      := 0;
880       Check_Readonly_Files  : Boolean  := False;
881       Do_Not_Execute        : Boolean  := False;
882       Force_Compilations    : Boolean  := False;
883       Keep_Going            : Boolean  := False;
884       In_Place_Mode         : Boolean  := False;
885       Initialize_ALI_Data   : Boolean  := True;
886       Max_Process           : Positive := 1);
887    --  Compile_Sources will recursively compile all the sources needed by
888    --  Main_Source. Before calling this routine make sure Namet has been
889    --  initialized. This routine can be called repeatedly with different
890    --  Main_Source file as long as all the source (-I flags), library
891    --  (-B flags) and ada library (-A flags) search paths between calls are
892    --  *exactly* the same. The default directory must also be the same.
893    --
894    --    Args contains the arguments to use during the compilations.
895    --    The lower bound of Args must be 1.
896    --
897    --    First_Compiled_File is set to the name of the first file that is
898    --    compiled or that needs to be compiled. This is set to No_Name if no
899    --    compilations were needed.
900    --
901    --    Most_Recent_Obj_File is set to the full name of the most recent
902    --    object file found when no compilations are needed, that is when
903    --    First_Compiled_File is set to No_Name. When First_Compiled_File
904    --    is set then Most_Recent_Obj_File is set to No_Name.
905    --
906    --    Most_Recent_Obj_Stamp is the time stamp of Most_Recent_Obj_File.
907    --
908    --    Main_Unit is set to True if Main_Source can be a main unit.
909    --    If Do_Not_Execute is False and First_Compiled_File /= No_Name
910    --    the value of Main_Unit is always False.
911    --    Is this used any more??? It is certainly not used by gnatmake???
912    --
913    --    Compilation_Failures is a count of compilation failures. This count
914    --    is used to extract compilation failure reports with Extract_Failure.
915    --
916    --    Main_Index, when not zero, is the index of the main unit in source
917    --    file Main_Source which is a multi-unit source.
918    --    Zero indicates that Main_Source is a single unit source file.
919    --
920    --    Check_Readonly_Files set it to True to compile source files
921    --    which library files are read-only. When compiling GNAT predefined
922    --    files the "-gnatg" flag is used.
923    --
924    --    Do_Not_Execute set it to True to find out the first source that
925    --    needs to be recompiled, but without recompiling it. This file is
926    --    saved in First_Compiled_File.
927    --
928    --    Force_Compilations forces all compilations no matter what but
929    --    recompiles read-only files only if Check_Readonly_Files
930    --    is set.
931    --
932    --    Keep_Going when True keep compiling even in the presence of
933    --    compilation errors.
934    --
935    --    In_Place_Mode when True save library/object files in their object
936    --    directory if they already exist; otherwise, in the source directory.
937    --
938    --    Initialize_ALI_Data set it to True when you want to initialize ALI
939    --    data-structures. This is what you should do most of the time.
940    --    (especially the first time around when you call this routine).
941    --    This parameter is set to False to preserve previously recorded
942    --    ALI file data.
943    --
944    --    Max_Process is the maximum number of processes that should be spawned
945    --    to carry out compilations.
946    --
947    --  Flags in Package Opt Affecting Compile_Sources
948    --  -----------------------------------------------
949    --
950    --    Check_Object_Consistency set it to False to omit all consistency
951    --      checks between an .ali file and its corresponding object file.
952    --      When this flag is set to true, every time an .ali is read,
953    --      package Osint checks that the corresponding object file
954    --      exists and is more recent than the .ali.
955    --
956    --  Use of Name Table Info
957    --  ----------------------
958    --
959    --  All file names manipulated by Compile_Sources are entered into the
960    --  Names table. The Byte field of a source file is used to mark it.
961    --
962    --  Calling Compile_Sources Several Times
963    --  -------------------------------------
964    --
965    --  Upon return from Compile_Sources all the ALI data structures are left
966    --  intact for further browsing. HOWEVER upon entry to this routine ALI
967    --  data structures are re-initialized if parameter Initialize_ALI_Data
968    --  above is set to true. Typically this is what you want the first time
969    --  you call Compile_Sources. You should not load an ali file, call this
970    --  routine with flag Initialize_ALI_Data set to True and then expect
971    --  that ALI information to be around after the call. Note that the first
972    --  time you call Compile_Sources you better set Initialize_ALI_Data to
973    --  True unless you have called Initialize_ALI yourself.
974    --
975    --  Compile_Sources ALGORITHM : Compile_Sources (Main_Source)
976    --  -------------------------
977    --
978    --  1. Insert Main_Source in a Queue (Q) and mark it.
979    --
980    --  2. Let unit.adb be the file at the head of the Q. If unit.adb is
981    --     missing but its corresponding ali file is in an Ada library directory
982    --     (see below) then, remove unit.adb from the Q and goto step 4.
983    --     Otherwise, look at the files under the D (dependency) section of
984    --     unit.ali. If unit.ali does not exist or some of the time stamps do
985    --     not match, (re)compile unit.adb.
986    --
987    --     An Ada library directory is a directory containing Ada specs, ali
988    --     and object files but no source files for the bodies. An Ada library
989    --     directory is communicated to gnatmake by means of some switch so that
990    --     gnatmake can skip the sources whole ali are in that directory.
991    --     There are two reasons for skipping the sources in this case. Firstly,
992    --     Ada libraries typically come without full sources but binding and
993    --     linking against those libraries is still possible. Secondly, it would
994    --     be very wasteful for gnatmake to systematically check the consistency
995    --     of every external Ada library used in a program. The binder is
996    --     already in charge of catching any potential inconsistencies.
997    --
998    --  3. Look into the W section of unit.ali and insert into the Q all
999    --     unmarked source files. Mark all files newly inserted in the Q.
1000    --     Specifically, assuming that the W section looks like
1001    --
1002    --     W types%s               types.adb               types.ali
1003    --     W unchecked_deallocation%s
1004    --     W xref_tab%s            xref_tab.adb            xref_tab.ali
1005    --
1006    --     Then xref_tab.adb and types.adb are inserted in the Q if they are not
1007    --     already marked.
1008    --     Note that there is no file listed under W unchecked_deallocation%s
1009    --     so no generic body should ever be explicitly compiled (unless the
1010    --     Main_Source at the start was a generic body).
1011    --
1012    --  4. Repeat steps 2 and 3 above until the Q is empty
1013    --
1014    --  Note that the above algorithm works because the units withed in
1015    --  subunits are transitively included in the W section (with section) of
1016    --  the main unit. Likewise the withed units in a generic body needed
1017    --  during a compilation are also transitively included in the W section
1018    --  of the originally compiled file.
1019
1020    procedure Globalize (Success : out Boolean);
1021    --  Call the CodePeer globalizer on all the project's object directories,
1022    --  or on the current directory if no projects.
1023
1024    procedure Initialize (Project_Node_Tree : out Project_Node_Tree_Ref);
1025    --  Performs default and package initialization. Therefore,
1026    --  Compile_Sources can be called by an external unit.
1027
1028    procedure Link
1029      (ALI_File : File_Name_Type;
1030       Args     : Argument_List;
1031       Success  : out Boolean);
1032    --  Links ALI_File. Args are the arguments to pass to the linker.
1033    --  Args must have a lower bound of 1. Success indicates if the link
1034    --  succeeded or not.
1035
1036    procedure Scan_Make_Arg
1037      (Project_Node_Tree : Project_Node_Tree_Ref;
1038       Argv              : String;
1039       And_Save          : Boolean);
1040    --  Scan make arguments. Argv is a single argument to be processed.
1041    --  Project_Node_Tree will be used to initialize external references. It
1042    --  must have been initialized.
1043
1044    -------------------
1045    -- Add_Arguments --
1046    -------------------
1047
1048    procedure Add_Arguments (Args : Argument_List) is
1049    begin
1050       if Arguments = null then
1051          Arguments := new Argument_List (1 .. Args'Length + 10);
1052
1053       else
1054          while Last_Argument + Args'Length > Arguments'Last loop
1055             declare
1056                New_Arguments : constant Argument_List_Access :=
1057                                  new Argument_List (1 .. Arguments'Last * 2);
1058             begin
1059                New_Arguments (1 .. Last_Argument) :=
1060                  Arguments (1 .. Last_Argument);
1061                Arguments := New_Arguments;
1062             end;
1063          end loop;
1064       end if;
1065
1066       Arguments (Last_Argument + 1 .. Last_Argument + Args'Length) := Args;
1067       Last_Argument := Last_Argument + Args'Length;
1068    end Add_Arguments;
1069
1070 --     --------------------
1071 --     -- Add_Dependency --
1072 --     --------------------
1073 --
1074 --     procedure Add_Dependency (S : File_Name_Type; On : File_Name_Type) is
1075 --     begin
1076 --        Dependencies.Increment_Last;
1077 --        Dependencies.Table (Dependencies.Last) := (S, On);
1078 --     end Add_Dependency;
1079
1080    ----------------------------
1081    -- Add_Library_Search_Dir --
1082    ----------------------------
1083
1084    procedure Add_Library_Search_Dir
1085      (Path            : String;
1086       On_Command_Line : Boolean)
1087    is
1088    begin
1089       if On_Command_Line then
1090          Add_Lib_Search_Dir (Normalize_Pathname (Path));
1091
1092       else
1093          Get_Name_String (Main_Project.Directory.Display_Name);
1094          Add_Lib_Search_Dir
1095            (Normalize_Pathname (Path, Name_Buffer (1 .. Name_Len)));
1096       end if;
1097    end Add_Library_Search_Dir;
1098
1099    --------------------
1100    -- Add_Object_Dir --
1101    --------------------
1102
1103    procedure Add_Object_Dir (N : String) is
1104    begin
1105       Add_Lib_Search_Dir (N);
1106
1107       if Verbose_Mode then
1108          Write_Str ("Adding object directory """);
1109          Write_Str (N);
1110          Write_Str (""".");
1111          Write_Eol;
1112       end if;
1113    end Add_Object_Dir;
1114
1115    --------------------
1116    -- Add_Source_Dir --
1117    --------------------
1118
1119    procedure Add_Source_Dir (N : String) is
1120    begin
1121       Add_Src_Search_Dir (N);
1122
1123       if Verbose_Mode then
1124          Write_Str ("Adding source directory """);
1125          Write_Str (N);
1126          Write_Str (""".");
1127          Write_Eol;
1128       end if;
1129    end Add_Source_Dir;
1130
1131    ---------------------------
1132    -- Add_Source_Search_Dir --
1133    ---------------------------
1134
1135    procedure Add_Source_Search_Dir
1136      (Path            : String;
1137       On_Command_Line : Boolean)
1138    is
1139    begin
1140       if On_Command_Line then
1141          Add_Src_Search_Dir (Normalize_Pathname (Path));
1142
1143       else
1144          Get_Name_String (Main_Project.Directory.Display_Name);
1145          Add_Src_Search_Dir
1146            (Normalize_Pathname (Path, Name_Buffer (1 .. Name_Len)));
1147       end if;
1148    end Add_Source_Search_Dir;
1149
1150    ----------------
1151    -- Add_Switch --
1152    ----------------
1153
1154    procedure Add_Switch
1155      (S             : String_Access;
1156       Program       : Make_Program_Type;
1157       Append_Switch : Boolean := True;
1158       And_Save      : Boolean := True)
1159    is
1160       generic
1161          with package T is new Table.Table (<>);
1162       procedure Generic_Position (New_Position : out Integer);
1163       --  Generic procedure that chooses a position for S in T at the
1164       --  beginning or the end, depending on the boolean Append_Switch.
1165       --  Calling this procedure may expand the table.
1166
1167       ----------------------
1168       -- Generic_Position --
1169       ----------------------
1170
1171       procedure Generic_Position (New_Position : out Integer) is
1172       begin
1173          T.Increment_Last;
1174
1175          if Append_Switch then
1176             New_Position := Integer (T.Last);
1177          else
1178             for J in reverse T.Table_Index_Type'Succ (T.First) .. T.Last loop
1179                T.Table (J) := T.Table (T.Table_Index_Type'Pred (J));
1180             end loop;
1181
1182             New_Position := Integer (T.First);
1183          end if;
1184       end Generic_Position;
1185
1186       procedure Gcc_Switches_Pos    is new Generic_Position (Gcc_Switches);
1187       procedure Binder_Switches_Pos is new Generic_Position (Binder_Switches);
1188       procedure Linker_Switches_Pos is new Generic_Position (Linker_Switches);
1189
1190       procedure Saved_Gcc_Switches_Pos is new
1191         Generic_Position (Saved_Gcc_Switches);
1192
1193       procedure Saved_Binder_Switches_Pos is new
1194         Generic_Position (Saved_Binder_Switches);
1195
1196       procedure Saved_Linker_Switches_Pos is new
1197         Generic_Position (Saved_Linker_Switches);
1198
1199       New_Position : Integer;
1200
1201    --  Start of processing for Add_Switch
1202
1203    begin
1204       if And_Save then
1205          case Program is
1206             when Compiler =>
1207                Saved_Gcc_Switches_Pos (New_Position);
1208                Saved_Gcc_Switches.Table (New_Position) := S;
1209
1210             when Binder   =>
1211                Saved_Binder_Switches_Pos (New_Position);
1212                Saved_Binder_Switches.Table (New_Position) := S;
1213
1214             when Linker   =>
1215                Saved_Linker_Switches_Pos (New_Position);
1216                Saved_Linker_Switches.Table (New_Position) := S;
1217
1218             when None =>
1219                raise Program_Error;
1220          end case;
1221
1222       else
1223          case Program is
1224             when Compiler =>
1225                Gcc_Switches_Pos (New_Position);
1226                Gcc_Switches.Table (New_Position) := S;
1227
1228             when Binder   =>
1229                Binder_Switches_Pos (New_Position);
1230                Binder_Switches.Table (New_Position) := S;
1231
1232             when Linker   =>
1233                Linker_Switches_Pos (New_Position);
1234                Linker_Switches.Table (New_Position) := S;
1235
1236             when None =>
1237                raise Program_Error;
1238          end case;
1239       end if;
1240    end Add_Switch;
1241
1242    procedure Add_Switch
1243      (S             : String;
1244       Program       : Make_Program_Type;
1245       Append_Switch : Boolean := True;
1246       And_Save      : Boolean := True)
1247    is
1248    begin
1249       Add_Switch (S             => new String'(S),
1250                   Program       => Program,
1251                   Append_Switch => Append_Switch,
1252                   And_Save      => And_Save);
1253    end Add_Switch;
1254
1255    ------------------
1256    -- Add_Switches --
1257    ------------------
1258
1259    procedure Add_Switches
1260      (The_Package                      : Package_Id;
1261       File_Name                        : String;
1262       Index                            : Int;
1263       Program                          : Make_Program_Type;
1264       Unknown_Switches_To_The_Compiler : Boolean := True;
1265       Project_Node_Tree                : Project_Node_Tree_Ref)
1266    is
1267       Switches    : Variable_Value;
1268       Switch_List : String_List_Id;
1269       Element     : String_Element;
1270
1271    begin
1272       Switch_May_Be_Passed_To_The_Compiler :=
1273         Unknown_Switches_To_The_Compiler;
1274
1275       if File_Name'Length > 0 then
1276          Name_Len := 0;
1277          Add_Str_To_Name_Buffer (File_Name);
1278          Switches :=
1279            Switches_Of
1280              (Source_File      => Name_Find,
1281               Source_File_Name => File_Name,
1282               Source_Index     => Index,
1283               Project          => Main_Project,
1284               In_Package       => The_Package,
1285               Allow_ALI        => Program = Binder or else Program = Linker);
1286
1287          if Switches.Kind = List then
1288             Program_Args := Program;
1289
1290             Switch_List := Switches.Values;
1291             while Switch_List /= Nil_String loop
1292                Element := Project_Tree.String_Elements.Table (Switch_List);
1293                Get_Name_String (Element.Value);
1294
1295                if Name_Len > 0 then
1296                   declare
1297                      Argv : constant String := Name_Buffer (1 .. Name_Len);
1298                      --  We need a copy, because Name_Buffer may be modified
1299
1300                   begin
1301                      if Verbose_Mode then
1302                         Write_Str ("   Adding ");
1303                         Write_Line (Argv);
1304                      end if;
1305
1306                      Scan_Make_Arg
1307                        (Project_Node_Tree, Argv, And_Save => False);
1308
1309                      if not Gnatmake_Switch_Found
1310                        and then not Switch_May_Be_Passed_To_The_Compiler
1311                      then
1312                         Errutil.Error_Msg
1313                           ('"' & Argv &
1314                            """ is not a gnatmake switch. Consider moving " &
1315                            "it to Global_Compilation_Switches.",
1316                            Element.Location);
1317                         Errutil.Finalize;
1318                         Make_Failed ("*** illegal switch """ & Argv & """");
1319                      end if;
1320                   end;
1321                end if;
1322
1323                Switch_List := Element.Next;
1324             end loop;
1325          end if;
1326       end if;
1327    end Add_Switches;
1328
1329    ----------
1330    -- Bind --
1331    ----------
1332
1333    procedure Bind (ALI_File : File_Name_Type; Args : Argument_List) is
1334       Bind_Args : Argument_List (1 .. Args'Last + 2);
1335       Bind_Last : Integer;
1336       Success   : Boolean;
1337
1338    begin
1339       pragma Assert (Args'First = 1);
1340
1341       --  Optimize the simple case where the gnatbind command line looks like
1342       --     gnatbind -aO. -I- file.ali   --into->   gnatbind file.adb
1343
1344       if Args'Length = 2
1345         and then Args (Args'First).all = "-aO" & Normalized_CWD
1346         and then Args (Args'Last).all = "-I-"
1347         and then ALI_File = Strip_Directory (ALI_File)
1348       then
1349          Bind_Last := Args'First - 1;
1350
1351       else
1352          Bind_Last := Args'Last;
1353          Bind_Args (Args'Range) := Args;
1354       end if;
1355
1356       --  It is completely pointless to re-check source file time stamps. This
1357       --  has been done already by gnatmake
1358
1359       Bind_Last := Bind_Last + 1;
1360       Bind_Args (Bind_Last) := Do_Not_Check_Flag;
1361
1362       Get_Name_String (ALI_File);
1363
1364       Bind_Last := Bind_Last + 1;
1365       Bind_Args (Bind_Last) := new String'(Name_Buffer (1 .. Name_Len));
1366
1367       GNAT.OS_Lib.Normalize_Arguments (Bind_Args (Args'First .. Bind_Last));
1368
1369       Display (Gnatbind.all, Bind_Args (Args'First .. Bind_Last));
1370
1371       if Gnatbind_Path = null then
1372          Make_Failed ("error, unable to locate " & Gnatbind.all);
1373       end if;
1374
1375       GNAT.OS_Lib.Spawn
1376         (Gnatbind_Path.all, Bind_Args (Args'First .. Bind_Last), Success);
1377
1378       if not Success then
1379          Make_Failed ("*** bind failed.");
1380       end if;
1381    end Bind;
1382
1383    --------------------------------
1384    -- Change_To_Object_Directory --
1385    --------------------------------
1386
1387    procedure Change_To_Object_Directory (Project : Project_Id) is
1388       Object_Directory : Path_Name_Type;
1389
1390    begin
1391       pragma Assert (Project /= No_Project);
1392
1393       --  Nothing to do if the current working directory is already the correct
1394       --  object directory.
1395
1396       if Project_Of_Current_Object_Directory /= Project then
1397          Project_Of_Current_Object_Directory := Project;
1398          Object_Directory := Project.Object_Directory.Display_Name;
1399
1400          --  Set the working directory to the object directory of the actual
1401          --  project.
1402
1403          if Verbose_Mode then
1404             Write_Str  ("Changing to object directory of """);
1405             Write_Name (Project.Display_Name);
1406             Write_Str  (""": """);
1407             Write_Name (Object_Directory);
1408             Write_Line ("""");
1409          end if;
1410
1411          Change_Dir (Get_Name_String (Object_Directory));
1412       end if;
1413
1414    exception
1415       --  Fail if unable to change to the object directory
1416
1417       when Directory_Error =>
1418          Make_Failed ("unable to change to object directory """ &
1419                       Path_Or_File_Name
1420                         (Project.Object_Directory.Display_Name) &
1421                       """ of project " &
1422                       Get_Name_String (Project.Display_Name));
1423    end Change_To_Object_Directory;
1424
1425    -----------
1426    -- Check --
1427    -----------
1428
1429    procedure Check
1430      (Source_File    : File_Name_Type;
1431       Source_Index   : Int;
1432       Is_Main_Source : Boolean;
1433       The_Args       : Argument_List;
1434       Lib_File       : File_Name_Type;
1435       Full_Lib_File  : File_Name_Type;
1436       Lib_File_Attr  : access File_Attributes;
1437       Read_Only      : Boolean;
1438       ALI            : out ALI_Id;
1439       O_File         : out File_Name_Type;
1440       O_Stamp        : out Time_Stamp_Type)
1441    is
1442       function First_New_Spec (A : ALI_Id) return File_Name_Type;
1443       --  Looks in the with table entries of A and returns the spec file name
1444       --  of the first withed unit (subprogram) for which no spec existed when
1445       --  A was generated but for which there exists one now, implying that A
1446       --  is now obsolete. If no such unit is found No_File is returned.
1447       --  Otherwise the spec file name of the unit is returned.
1448       --
1449       --  **WARNING** in the event of Uname format modifications, one *MUST*
1450       --  make sure this function is also updated.
1451       --
1452       --  Note: This function should really be in ali.adb and use Uname
1453       --  services, but this causes the whole compiler to be dragged along
1454       --  for gnatbind and gnatmake.
1455
1456       --------------------
1457       -- First_New_Spec --
1458       --------------------
1459
1460       function First_New_Spec (A : ALI_Id) return File_Name_Type is
1461          Spec_File_Name : File_Name_Type := No_File;
1462
1463          function New_Spec (Uname : Unit_Name_Type) return Boolean;
1464          --  Uname is the name of the spec or body of some ada unit. This
1465          --  function returns True if the Uname is the name of a body which has
1466          --  a spec not mentioned in ALI file A. If True is returned
1467          --  Spec_File_Name above is set to the name of this spec file.
1468
1469          --------------
1470          -- New_Spec --
1471          --------------
1472
1473          function New_Spec (Uname : Unit_Name_Type) return Boolean is
1474             Spec_Name : Unit_Name_Type;
1475             File_Name : File_Name_Type;
1476
1477          begin
1478             --  Test whether Uname is the name of a body unit (i.e. ends
1479             --  with %b)
1480
1481             Get_Name_String (Uname);
1482             pragma
1483               Assert (Name_Len > 2 and then Name_Buffer (Name_Len - 1) = '%');
1484
1485             if Name_Buffer (Name_Len) /= 'b' then
1486                return False;
1487             end if;
1488
1489             --  Convert unit name into spec name
1490
1491             --  ??? this code seems dubious in presence of pragma
1492             --  Source_File_Name since there is no more direct relationship
1493             --  between unit name and file name.
1494
1495             --  ??? Further, what about alternative subunit naming
1496
1497             Name_Buffer (Name_Len) := 's';
1498             Spec_Name := Name_Find;
1499             File_Name := Get_File_Name (Spec_Name, Subunit => False);
1500
1501             --  Look if File_Name is mentioned in A's sdep list.
1502             --  If not look if the file exists. If it does return True.
1503
1504             for D in
1505               ALIs.Table (A).First_Sdep .. ALIs.Table (A).Last_Sdep
1506             loop
1507                if Sdep.Table (D).Sfile = File_Name then
1508                   return False;
1509                end if;
1510             end loop;
1511
1512             if Full_Source_Name (File_Name) /= No_File then
1513                Spec_File_Name := File_Name;
1514                return True;
1515             end if;
1516
1517             return False;
1518          end New_Spec;
1519
1520       --  Start of processing for First_New_Spec
1521
1522       begin
1523          U_Chk : for U in
1524            ALIs.Table (A).First_Unit .. ALIs.Table (A).Last_Unit
1525          loop
1526             exit U_Chk when Units.Table (U).Utype = Is_Body_Only
1527                and then New_Spec (Units.Table (U).Uname);
1528
1529             for W in Units.Table (U).First_With
1530                        ..
1531                      Units.Table (U).Last_With
1532             loop
1533                exit U_Chk when
1534                  Withs.Table (W).Afile /= No_File
1535                  and then New_Spec (Withs.Table (W).Uname);
1536             end loop;
1537          end loop U_Chk;
1538
1539          return Spec_File_Name;
1540       end First_New_Spec;
1541
1542       ---------------------------------
1543       -- Data declarations for Check --
1544       ---------------------------------
1545
1546       Full_Obj_File : File_Name_Type;
1547       --  Full name of the object file corresponding to Lib_File
1548
1549       Lib_Stamp : Time_Stamp_Type;
1550       --  Time stamp of the current ada library file
1551
1552       Obj_Stamp : Time_Stamp_Type;
1553       --  Time stamp of the current object file
1554
1555       Modified_Source : File_Name_Type;
1556       --  The first source in Lib_File whose current time stamp differs
1557       --  from that stored in Lib_File.
1558
1559       New_Spec : File_Name_Type;
1560       --  If Lib_File contains in its W (with) section a body (for a
1561       --  subprogram) for which there exists a spec and the spec did not
1562       --  appear in the Sdep section of Lib_File, New_Spec contains the file
1563       --  name of this new spec.
1564
1565       Source_Name : File_Name_Type;
1566       Text        : Text_Buffer_Ptr;
1567
1568       Prev_Switch : String_Access;
1569       --  Previous switch processed
1570
1571       Arg : Arg_Id := Arg_Id'First;
1572       --  Current index in Args.Table for a given unit (init to stop warning)
1573
1574       Switch_Found : Boolean;
1575       --  True if a given switch has been found
1576
1577       ALI_Project : Project_Id;
1578       --  If the ALI file is in the object directory of a project, this is
1579       --  the project id.
1580
1581    --  Start of processing for Check
1582
1583    begin
1584       pragma Assert (Lib_File /= No_File);
1585
1586       --  If ALI file is read-only, temporarily set Check_Object_Consistency to
1587       --  False. We don't care if the object file is not there (presumably a
1588       --  library will be used for linking.)
1589
1590       if Read_Only then
1591          declare
1592             Saved_Check_Object_Consistency : constant Boolean :=
1593                                                Check_Object_Consistency;
1594          begin
1595             Check_Object_Consistency := False;
1596             Text := Read_Library_Info_From_Full (Full_Lib_File, Lib_File_Attr);
1597             Check_Object_Consistency := Saved_Check_Object_Consistency;
1598          end;
1599
1600       else
1601          Text := Read_Library_Info_From_Full (Full_Lib_File, Lib_File_Attr);
1602       end if;
1603
1604       Full_Obj_File := Full_Object_File_Name;
1605       Lib_Stamp     := Current_Library_File_Stamp;
1606       Obj_Stamp     := Current_Object_File_Stamp;
1607
1608       if Full_Lib_File = No_File then
1609          Verbose_Msg
1610            (Lib_File,
1611             "being checked ...",
1612             Prefix => "  ",
1613             Minimum_Verbosity => Opt.Medium);
1614       else
1615          Verbose_Msg
1616            (Full_Lib_File,
1617             "being checked ...",
1618             Prefix => "  ",
1619             Minimum_Verbosity => Opt.Medium);
1620       end if;
1621
1622       ALI     := No_ALI_Id;
1623       O_File  := Full_Obj_File;
1624       O_Stamp := Obj_Stamp;
1625
1626       if Text = null then
1627          if Full_Lib_File = No_File then
1628             Verbose_Msg (Lib_File, "missing.");
1629
1630          elsif Obj_Stamp (Obj_Stamp'First) = ' ' then
1631             Verbose_Msg (Full_Obj_File, "missing.");
1632
1633          else
1634             Verbose_Msg
1635               (Full_Lib_File, "(" & String (Lib_Stamp) & ") newer than",
1636                Full_Obj_File, "(" & String (Obj_Stamp) & ")");
1637          end if;
1638
1639       else
1640          ALI := Scan_ALI (Lib_File, Text, Ignore_ED => False, Err => True);
1641          Free (Text);
1642
1643          if ALI = No_ALI_Id then
1644             Verbose_Msg (Full_Lib_File, "incorrectly formatted ALI file");
1645             return;
1646
1647          elsif ALIs.Table (ALI).Ver (1 .. ALIs.Table (ALI).Ver_Len) /=
1648                  Verbose_Library_Version
1649          then
1650             Verbose_Msg (Full_Lib_File, "compiled with old GNAT version");
1651             ALI := No_ALI_Id;
1652             return;
1653          end if;
1654
1655          --  Don't take Ali file into account if it was generated with
1656          --  errors.
1657
1658          if ALIs.Table (ALI).Compile_Errors then
1659             Verbose_Msg (Full_Lib_File, "had errors, must be recompiled");
1660             ALI := No_ALI_Id;
1661             return;
1662          end if;
1663
1664          --  Don't take Ali file into account if it was generated without
1665          --  object.
1666
1667          if Operating_Mode /= Check_Semantics
1668            and then ALIs.Table (ALI).No_Object
1669          then
1670             Verbose_Msg (Full_Lib_File, "has no corresponding object");
1671             ALI := No_ALI_Id;
1672             return;
1673          end if;
1674
1675          --  When compiling with -gnatc, don't take ALI file into account if
1676          --  it has not been generated for the current source, for example if
1677          --  it has been generated for the spec, but we are compiling the body.
1678
1679          if Operating_Mode = Check_Semantics then
1680             declare
1681                File_Name : constant String := Get_Name_String (Source_File);
1682                OK        : Boolean := False;
1683
1684             begin
1685                for U in ALIs.Table (ALI).First_Unit ..
1686                  ALIs.Table (ALI).Last_Unit
1687                loop
1688                   OK := Get_Name_String (Units.Table (U).Sfile) = File_Name;
1689                   exit when OK;
1690                end loop;
1691
1692                if not OK then
1693                   Verbose_Msg
1694                     (Full_Lib_File, "not generated for the same source");
1695                   ALI := No_ALI_Id;
1696                   return;
1697                end if;
1698             end;
1699          end if;
1700
1701          --  Check for matching compiler switches if needed
1702
1703          if Check_Switches then
1704
1705             --  First, collect all the switches
1706
1707             Collect_Arguments
1708               (Source_File, Source_Index, Is_Main_Source, The_Args);
1709
1710             Prev_Switch := Dummy_Switch;
1711
1712             Get_Name_String (ALIs.Table (ALI).Sfile);
1713
1714             Switches_To_Check.Set_Last (0);
1715
1716             for J in 1 .. Last_Argument loop
1717
1718                --  Skip non switches -c, -I and -o switches
1719
1720                if Arguments (J) (1) = '-'
1721                  and then Arguments (J) (2) /= 'c'
1722                  and then Arguments (J) (2) /= 'o'
1723                  and then Arguments (J) (2) /= 'I'
1724                then
1725                   Normalize_Compiler_Switches
1726                     (Arguments (J).all,
1727                      Normalized_Switches,
1728                      Last_Norm_Switch);
1729
1730                   for K in 1 .. Last_Norm_Switch loop
1731                      Switches_To_Check.Increment_Last;
1732                      Switches_To_Check.Table (Switches_To_Check.Last) :=
1733                        Normalized_Switches (K);
1734                   end loop;
1735                end if;
1736             end loop;
1737
1738             for J in 1 .. Switches_To_Check.Last loop
1739
1740                --  Comparing switches is delicate because gcc reorders a number
1741                --  of switches, according to lang-specs.h, but gnatmake doesn't
1742                --  have sufficient knowledge to perform the same reordering.
1743                --  Instead, we ignore orders between different "first letter"
1744                --  switches, but keep orders between same switches, e.g -O -O2
1745                --  is different than -O2 -O, but -g -O is equivalent to -O -g.
1746
1747                if Switches_To_Check.Table (J) (2) /= Prev_Switch (2) or else
1748                    (Prev_Switch'Length >= 6 and then
1749                     Prev_Switch (2 .. 5) = "gnat" and then
1750                     Switches_To_Check.Table (J)'Length >= 6 and then
1751                     Switches_To_Check.Table (J) (2 .. 5) = "gnat" and then
1752                     Prev_Switch (6) /= Switches_To_Check.Table (J) (6))
1753                then
1754                   Prev_Switch := Switches_To_Check.Table (J);
1755                   Arg :=
1756                     Units.Table (ALIs.Table (ALI).First_Unit).First_Arg;
1757                end if;
1758
1759                Switch_Found := False;
1760
1761                for K in Arg ..
1762                  Units.Table (ALIs.Table (ALI).First_Unit).Last_Arg
1763                loop
1764                   if
1765                     Switches_To_Check.Table (J).all = Args.Table (K).all
1766                   then
1767                      Arg := K + 1;
1768                      Switch_Found := True;
1769                      exit;
1770                   end if;
1771                end loop;
1772
1773                if not Switch_Found then
1774                   if Verbose_Mode then
1775                      Verbose_Msg (ALIs.Table (ALI).Sfile,
1776                                   "switch mismatch """ &
1777                                   Switches_To_Check.Table (J).all & '"');
1778                   end if;
1779
1780                   ALI := No_ALI_Id;
1781                   return;
1782                end if;
1783             end loop;
1784
1785             if Switches_To_Check.Last /=
1786               Integer (Units.Table (ALIs.Table (ALI).First_Unit).Last_Arg -
1787                        Units.Table (ALIs.Table (ALI).First_Unit).First_Arg + 1)
1788             then
1789                if Verbose_Mode then
1790                   Verbose_Msg (ALIs.Table (ALI).Sfile,
1791                                "different number of switches");
1792
1793                   for K in Units.Table (ALIs.Table (ALI).First_Unit).First_Arg
1794                     .. Units.Table (ALIs.Table (ALI).First_Unit).Last_Arg
1795                   loop
1796                      Write_Str (Args.Table (K).all);
1797                      Write_Char (' ');
1798                   end loop;
1799
1800                   Write_Eol;
1801
1802                   for J in 1 .. Switches_To_Check.Last loop
1803                      Write_Str (Switches_To_Check.Table (J).all);
1804                      Write_Char (' ');
1805                   end loop;
1806
1807                   Write_Eol;
1808                end if;
1809
1810                ALI := No_ALI_Id;
1811                return;
1812             end if;
1813          end if;
1814
1815          --  Get the source files and their message digests. Note that some
1816          --  sources may be missing if ALI is out-of-date.
1817
1818          Set_Source_Table (ALI);
1819
1820          Modified_Source := Time_Stamp_Mismatch (ALI, Read_Only);
1821
1822          --  To avoid using too much memory when switch -m is used, free the
1823          --  memory allocated for the source file when computing the checksum.
1824
1825          if Minimal_Recompilation then
1826             Sinput.P.Clear_Source_File_Table;
1827          end if;
1828
1829          if Modified_Source /= No_File then
1830             ALI := No_ALI_Id;
1831
1832             if Verbose_Mode then
1833                Source_Name := Full_Source_Name (Modified_Source);
1834
1835                if Source_Name /= No_File then
1836                   Verbose_Msg (Source_Name, "time stamp mismatch");
1837                else
1838                   Verbose_Msg (Modified_Source, "missing");
1839                end if;
1840             end if;
1841
1842          else
1843             New_Spec := First_New_Spec (ALI);
1844
1845             if New_Spec /= No_File then
1846                ALI := No_ALI_Id;
1847
1848                if Verbose_Mode then
1849                   Source_Name := Full_Source_Name (New_Spec);
1850
1851                   if Source_Name /= No_File then
1852                      Verbose_Msg (Source_Name, "new spec");
1853                   else
1854                      Verbose_Msg (New_Spec, "old spec missing");
1855                   end if;
1856                end if;
1857
1858             elsif not Read_Only and then Main_Project /= No_Project then
1859                if not Check_Source_Info_In_ALI (ALI, Project_Tree) then
1860                   ALI := No_ALI_Id;
1861                   return;
1862                end if;
1863
1864                --  Check that the ALI file is in the correct object directory.
1865                --  If it is in the object directory of a project that is
1866                --  extended and it depends on a source that is in one of its
1867                --  extending projects, then the ALI file is not in the correct
1868                --  object directory.
1869
1870                --  First, find the project of this ALI file. As there may be
1871                --  several projects with the same object directory, we first
1872                --  need to find the project of the source.
1873
1874                ALI_Project := No_Project;
1875
1876                declare
1877                   Udata : Prj.Unit_Index;
1878
1879                begin
1880                   Udata := Units_Htable.Get_First (Project_Tree.Units_HT);
1881                   while Udata /= No_Unit_Index loop
1882                      if Udata.File_Names (Impl) /= null
1883                        and then Udata.File_Names (Impl).File = Source_File
1884                      then
1885                         ALI_Project := Udata.File_Names (Impl).Project;
1886                         exit;
1887
1888                      elsif Udata.File_Names (Spec) /= null
1889                        and then Udata.File_Names (Spec).File = Source_File
1890                      then
1891                         ALI_Project := Udata.File_Names (Spec).Project;
1892                         exit;
1893                      end if;
1894
1895                      Udata := Units_Htable.Get_Next (Project_Tree.Units_HT);
1896                   end loop;
1897                end;
1898
1899                if ALI_Project = No_Project then
1900                   return;
1901                end if;
1902
1903                declare
1904                   Obj_Dir : Path_Name_Type;
1905                   Res_Obj_Dir : constant String :=
1906                                   Normalize_Pathname
1907                                     (Dir_Name
1908                                       (Get_Name_String (Full_Lib_File)),
1909                                      Resolve_Links  =>
1910                                        Opt.Follow_Links_For_Dirs,
1911                                      Case_Sensitive => False);
1912
1913                begin
1914                   Name_Len := 0;
1915                   Add_Str_To_Name_Buffer (Res_Obj_Dir);
1916
1917                   if not Is_Directory_Separator (Name_Buffer (Name_Len)) then
1918                      Add_Char_To_Name_Buffer (Directory_Separator);
1919                   end if;
1920
1921                   Obj_Dir := Name_Find;
1922
1923                   while ALI_Project /= No_Project
1924                     and then Obj_Dir /= ALI_Project.Object_Directory.Name
1925                   loop
1926                      ALI_Project := ALI_Project.Extended_By;
1927                   end loop;
1928                end;
1929
1930                if ALI_Project = No_Project then
1931                   ALI := No_ALI_Id;
1932
1933                   Verbose_Msg (Lib_File, " wrong object directory");
1934                   return;
1935                end if;
1936
1937                --  If the ALI project is not extended, then it must be in
1938                --  the correct object directory.
1939
1940                if ALI_Project.Extended_By = No_Project then
1941                   return;
1942                end if;
1943
1944                --  Count the extending projects
1945
1946                declare
1947                   Num_Ext : Natural;
1948                   Proj    : Project_Id;
1949
1950                begin
1951                   Num_Ext := 0;
1952                   Proj := ALI_Project;
1953                   loop
1954                      Proj := Proj.Extended_By;
1955                      exit when Proj = No_Project;
1956                      Num_Ext := Num_Ext + 1;
1957                   end loop;
1958
1959                   --  Make a list of the extending projects
1960
1961                   declare
1962                      Projects : array (1 .. Num_Ext) of Project_Id;
1963                      Dep      : Sdep_Record;
1964                      OK       : Boolean := True;
1965                      UID      : Unit_Index;
1966
1967                   begin
1968                      Proj := ALI_Project;
1969                      for J in Projects'Range loop
1970                         Proj := Proj.Extended_By;
1971                         Projects (J) := Proj;
1972                      end loop;
1973
1974                      --  Now check if any of the dependant sources are in
1975                      --  any of these extending projects.
1976
1977                      D_Chk :
1978                      for D in ALIs.Table (ALI).First_Sdep ..
1979                        ALIs.Table (ALI).Last_Sdep
1980                      loop
1981                         Dep := Sdep.Table (D);
1982                         UID  := Units_Htable.Get_First (Project_Tree.Units_HT);
1983                         Proj := No_Project;
1984
1985                         Unit_Loop :
1986                         while UID /= null loop
1987                            if UID.File_Names (Impl) /= null
1988                              and then UID.File_Names (Impl).File = Dep.Sfile
1989                            then
1990                               Proj := UID.File_Names (Impl).Project;
1991
1992                            elsif UID.File_Names (Spec) /= null
1993                              and then UID.File_Names (Spec).File = Dep.Sfile
1994                            then
1995                               Proj := UID.File_Names (Spec).Project;
1996                            end if;
1997
1998                            --  If a source is in a project, check if it is one
1999                            --  in the list.
2000
2001                            if Proj /= No_Project then
2002                               for J in Projects'Range loop
2003                                  if Proj = Projects (J) then
2004                                     OK := False;
2005                                     exit D_Chk;
2006                                  end if;
2007                               end loop;
2008
2009                               exit Unit_Loop;
2010                            end if;
2011
2012                            UID :=
2013                              Units_Htable.Get_Next (Project_Tree.Units_HT);
2014                         end loop Unit_Loop;
2015                      end loop D_Chk;
2016
2017                      --  If one of the dependent sources is in one project of
2018                      --  the list, then we must recompile.
2019
2020                      if not OK then
2021                         ALI := No_ALI_Id;
2022                         Verbose_Msg (Lib_File, " wrong object directory");
2023                      end if;
2024                   end;
2025                end;
2026             end if;
2027          end if;
2028       end if;
2029    end Check;
2030
2031    ------------------------
2032    -- Check_For_S_Switch --
2033    ------------------------
2034
2035    procedure Check_For_S_Switch is
2036    begin
2037       --  By default, we generate an object file
2038
2039       Output_Is_Object := True;
2040
2041       for Arg in 1 .. Last_Argument loop
2042          if Arguments (Arg).all = "-S" then
2043             Output_Is_Object := False;
2044
2045          elsif Arguments (Arg).all = "-c" then
2046             Output_Is_Object := True;
2047          end if;
2048       end loop;
2049    end Check_For_S_Switch;
2050
2051    --------------------------
2052    -- Check_Linker_Options --
2053    --------------------------
2054
2055    procedure Check_Linker_Options
2056      (E_Stamp   : Time_Stamp_Type;
2057       O_File    : out File_Name_Type;
2058       O_Stamp   : out Time_Stamp_Type)
2059    is
2060       procedure Check_File (File : File_Name_Type);
2061       --  Update O_File and O_Stamp if the given file is younger than E_Stamp
2062       --  and O_Stamp, or if O_File is No_File and File does not exist.
2063
2064       function Get_Library_File (Name : String) return File_Name_Type;
2065       --  Return the full file name including path of a library based
2066       --  on the name specified with the -l linker option, using the
2067       --  Ada object path. Return No_File if no such file can be found.
2068
2069       type Char_Array is array (Natural) of Character;
2070       type Char_Array_Access is access constant Char_Array;
2071
2072       Template : Char_Array_Access;
2073       pragma Import (C, Template, "__gnat_library_template");
2074
2075       ----------------
2076       -- Check_File --
2077       ----------------
2078
2079       procedure Check_File (File : File_Name_Type) is
2080          Stamp : Time_Stamp_Type;
2081          Name  : File_Name_Type := File;
2082
2083       begin
2084          Get_Name_String (Name);
2085
2086          --  Remove any trailing NUL characters
2087
2088          while Name_Len >= Name_Buffer'First
2089            and then Name_Buffer (Name_Len) = NUL
2090          loop
2091             Name_Len := Name_Len - 1;
2092          end loop;
2093
2094          if Name_Len = 0 then
2095             return;
2096
2097          elsif Name_Buffer (1) = '-' then
2098
2099             --  Do not check if File is a switch other than "-l"
2100
2101             if Name_Buffer (2) /= 'l' then
2102                return;
2103             end if;
2104
2105             --  The argument is a library switch, get actual name. It
2106             --  is necessary to make a copy of the relevant part of
2107             --  Name_Buffer as Get_Library_Name uses Name_Buffer as well.
2108
2109             declare
2110                Base_Name : constant String := Name_Buffer (3 .. Name_Len);
2111
2112             begin
2113                Name := Get_Library_File (Base_Name);
2114             end;
2115
2116             if Name = No_File then
2117                return;
2118             end if;
2119          end if;
2120
2121          Stamp := File_Stamp (Name);
2122
2123          --  Find the youngest object file that is younger than the
2124          --  executable. If no such file exist, record the first object
2125          --  file that is not found.
2126
2127          if (O_Stamp < Stamp and then E_Stamp < Stamp)
2128            or else (O_File = No_File and then Stamp (Stamp'First) = ' ')
2129          then
2130             O_Stamp := Stamp;
2131             O_File := Name;
2132
2133             --  Strip the trailing NUL if present
2134
2135             Get_Name_String (O_File);
2136
2137             if Name_Buffer (Name_Len) = NUL then
2138                Name_Len := Name_Len - 1;
2139                O_File := Name_Find;
2140             end if;
2141          end if;
2142       end Check_File;
2143
2144       ----------------------
2145       -- Get_Library_Name --
2146       ----------------------
2147
2148       --  See comments in a-adaint.c about template syntax
2149
2150       function Get_Library_File (Name : String) return File_Name_Type is
2151          File : File_Name_Type := No_File;
2152
2153       begin
2154          Name_Len := 0;
2155
2156          for Ptr in Template'Range loop
2157             case Template (Ptr) is
2158                when '*'    =>
2159                   Add_Str_To_Name_Buffer (Name);
2160
2161                when ';'    =>
2162                   File := Full_Lib_File_Name (Name_Find);
2163                   exit when File /= No_File;
2164                   Name_Len := 0;
2165
2166                when NUL    =>
2167                   exit;
2168
2169                when others =>
2170                   Add_Char_To_Name_Buffer (Template (Ptr));
2171             end case;
2172          end loop;
2173
2174          --  The for loop exited because the end of the template
2175          --  was reached. File contains the last possible file name
2176          --  for the library.
2177
2178          if File = No_File and then Name_Len > 0 then
2179             File := Full_Lib_File_Name (Name_Find);
2180          end if;
2181
2182          return File;
2183       end Get_Library_File;
2184
2185    --  Start of processing for Check_Linker_Options
2186
2187    begin
2188       O_File  := No_File;
2189       O_Stamp := (others => ' ');
2190
2191       --  Process linker options from the ALI files
2192
2193       for Opt in 1 .. Linker_Options.Last loop
2194          Check_File (File_Name_Type (Linker_Options.Table (Opt).Name));
2195       end loop;
2196
2197       --  Process options given on the command line
2198
2199       for Opt in Linker_Switches.First .. Linker_Switches.Last loop
2200
2201          --  Check if the previous Opt has one of the two switches
2202          --  that take an extra parameter. (See GCC manual.)
2203
2204          if Opt = Linker_Switches.First
2205            or else (Linker_Switches.Table (Opt - 1).all /= "-u"
2206                       and then
2207                     Linker_Switches.Table (Opt - 1).all /= "-Xlinker"
2208                       and then
2209                     Linker_Switches.Table (Opt - 1).all /= "-L")
2210          then
2211             Name_Len := 0;
2212             Add_Str_To_Name_Buffer (Linker_Switches.Table (Opt).all);
2213             Check_File (Name_Find);
2214          end if;
2215       end loop;
2216
2217    end Check_Linker_Options;
2218
2219    -----------------
2220    -- Check_Steps --
2221    -----------------
2222
2223    procedure Check_Steps is
2224    begin
2225       --  If either -c, -b or -l has been specified, we will not necessarily
2226       --  execute all steps.
2227
2228       if Make_Steps then
2229          Do_Compile_Step := Do_Compile_Step and Compile_Only;
2230          Do_Bind_Step    := Do_Bind_Step    and Bind_Only;
2231          Do_Link_Step    := Do_Link_Step    and Link_Only;
2232
2233          --  If -c has been specified, but not -b, ignore any potential -l
2234
2235          if Do_Compile_Step and then not Do_Bind_Step then
2236             Do_Link_Step := False;
2237          end if;
2238       end if;
2239    end Check_Steps;
2240
2241    -----------------------
2242    -- Collect_Arguments --
2243    -----------------------
2244
2245    procedure Collect_Arguments
2246      (Source_File    : File_Name_Type;
2247       Source_Index   : Int;
2248       Is_Main_Source : Boolean;
2249       Args           : Argument_List)
2250    is
2251    begin
2252       Arguments_Project := No_Project;
2253       Last_Argument := 0;
2254       Add_Arguments (Args);
2255
2256       if Main_Project /= No_Project then
2257          declare
2258             Source_File_Name : constant String :=
2259                                  Get_Name_String (Source_File);
2260             Compiler_Package : Prj.Package_Id;
2261             Switches         : Prj.Variable_Value;
2262
2263          begin
2264             Prj.Env.
2265               Get_Reference
2266               (Source_File_Name => Source_File_Name,
2267                Project          => Arguments_Project,
2268                Path             => Arguments_Path_Name,
2269                In_Tree          => Project_Tree);
2270
2271             --  If the source is not a source of a project file, add the
2272             --  recorded arguments. Check will be done later if the source
2273             --  need to be compiled that the switch -x has been used.
2274
2275             if Arguments_Project = No_Project then
2276                Add_Arguments (The_Saved_Gcc_Switches.all);
2277
2278             elsif not Arguments_Project.Externally_Built
2279               or else Must_Compile
2280             then
2281                --  We get the project directory for the relative path
2282                --  switches and arguments.
2283
2284                Arguments_Project :=
2285                  Ultimate_Extending_Project_Of (Arguments_Project);
2286
2287                --  If building a dynamic or relocatable library, compile with
2288                --  PIC option, if it exists.
2289
2290                if Arguments_Project.Library
2291                  and then Arguments_Project.Library_Kind /= Static
2292                then
2293                   declare
2294                      PIC : constant String := MLib.Tgt.PIC_Option;
2295                   begin
2296                      if PIC /= "" then
2297                         Add_Arguments ((1 => new String'(PIC)));
2298                      end if;
2299                   end;
2300                end if;
2301
2302                --  We now look for package Compiler and get the switches from
2303                --  this package.
2304
2305                Compiler_Package :=
2306                  Prj.Util.Value_Of
2307                    (Name        => Name_Compiler,
2308                     In_Packages => Arguments_Project.Decl.Packages,
2309                     In_Tree     => Project_Tree);
2310
2311                if Compiler_Package /= No_Package then
2312
2313                   --  If package Gnatmake.Compiler exists, we get the specific
2314                   --  switches for the current source, or the global switches,
2315                   --  if any.
2316
2317                   Switches :=
2318                     Switches_Of
2319                       (Source_File      => Source_File,
2320                        Source_File_Name => Source_File_Name,
2321                        Source_Index     => Source_Index,
2322                        Project          => Arguments_Project,
2323                        In_Package       => Compiler_Package,
2324                        Allow_ALI        => False);
2325
2326                end if;
2327
2328                case Switches.Kind is
2329
2330                   --  We have a list of switches. We add these switches,
2331                   --  plus the saved gcc switches.
2332
2333                   when List =>
2334
2335                      declare
2336                         Current : String_List_Id := Switches.Values;
2337                         Element : String_Element;
2338                         Number  : Natural := 0;
2339
2340                      begin
2341                         while Current /= Nil_String loop
2342                            Element := Project_Tree.String_Elements.
2343                                         Table (Current);
2344                            Number  := Number + 1;
2345                            Current := Element.Next;
2346                         end loop;
2347
2348                         declare
2349                            New_Args : Argument_List (1 .. Number);
2350                            Last_New : Natural := 0;
2351                            Dir_Path : constant String := Get_Name_String
2352                              (Arguments_Project.Directory.Display_Name);
2353
2354                         begin
2355                            Current := Switches.Values;
2356
2357                            for Index in New_Args'Range loop
2358                               Element := Project_Tree.String_Elements.
2359                                            Table (Current);
2360                               Get_Name_String (Element.Value);
2361
2362                               if Name_Len > 0 then
2363                                  Last_New := Last_New + 1;
2364                                  New_Args (Last_New) :=
2365                                    new String'(Name_Buffer (1 .. Name_Len));
2366                                  Test_If_Relative_Path
2367                                    (New_Args (Last_New),
2368                                     Parent => Dir_Path,
2369                                     Including_Non_Switch => False);
2370                               end if;
2371
2372                               Current := Element.Next;
2373                            end loop;
2374
2375                            Add_Arguments
2376                              (Configuration_Pragmas_Switch
2377                                 (Arguments_Project) &
2378                               New_Args (1 .. Last_New) &
2379                               The_Saved_Gcc_Switches.all);
2380                         end;
2381                      end;
2382
2383                      --  We have a single switch. We add this switch,
2384                      --  plus the saved gcc switches.
2385
2386                   when Single =>
2387                      Get_Name_String (Switches.Value);
2388
2389                      declare
2390                         New_Args : Argument_List :=
2391                                      (1 => new String'
2392                                             (Name_Buffer (1 .. Name_Len)));
2393                         Dir_Path : constant String :=
2394                                      Get_Name_String
2395                                       (Arguments_Project.
2396                                        Directory.Display_Name);
2397
2398                      begin
2399                         Test_If_Relative_Path
2400                           (New_Args (1),
2401                            Parent               => Dir_Path,
2402                            Including_Non_Switch => False);
2403                         Add_Arguments
2404                           (Configuration_Pragmas_Switch (Arguments_Project) &
2405                            New_Args & The_Saved_Gcc_Switches.all);
2406                      end;
2407
2408                      --  We have no switches from Gnatmake.Compiler.
2409                      --  We add the saved gcc switches.
2410
2411                   when Undefined =>
2412                      Add_Arguments
2413                        (Configuration_Pragmas_Switch (Arguments_Project) &
2414                         The_Saved_Gcc_Switches.all);
2415                end case;
2416             end if;
2417          end;
2418       end if;
2419
2420       --  For VMS, when compiling the main source, add switch
2421       --  -mdebug-main=_ada_ so that the executable can be debugged
2422       --  by the standard VMS debugger.
2423
2424       if not No_Main_Subprogram
2425         and then Targparm.OpenVMS_On_Target
2426         and then Is_Main_Source
2427       then
2428          --  First, check if compilation will be invoked with -g
2429
2430          for J in 1 .. Last_Argument loop
2431             if Arguments (J)'Length >= 2
2432               and then Arguments (J) (1 .. 2) = "-g"
2433               and then (Arguments (J)'Length < 5
2434                         or else Arguments (J) (1 .. 5) /= "-gnat")
2435             then
2436                Add_Arguments
2437                  ((1 => new String'("-mdebug-main=_ada_")));
2438                exit;
2439             end if;
2440          end loop;
2441       end if;
2442
2443       --  Set Output_Is_Object, depending if there is a -S switch.
2444       --  If the bind step is not performed, and there is a -S switch,
2445       --  then we will not check for a valid object file.
2446
2447       Check_For_S_Switch;
2448    end Collect_Arguments;
2449
2450    ---------------------
2451    -- Compile_Sources --
2452    ---------------------
2453
2454    procedure Compile_Sources
2455      (Main_Source           : File_Name_Type;
2456       Args                  : Argument_List;
2457       First_Compiled_File   : out File_Name_Type;
2458       Most_Recent_Obj_File  : out File_Name_Type;
2459       Most_Recent_Obj_Stamp : out Time_Stamp_Type;
2460       Main_Unit             : out Boolean;
2461       Compilation_Failures  : out Natural;
2462       Main_Index            : Int      := 0;
2463       Check_Readonly_Files  : Boolean  := False;
2464       Do_Not_Execute        : Boolean  := False;
2465       Force_Compilations    : Boolean  := False;
2466       Keep_Going            : Boolean  := False;
2467       In_Place_Mode         : Boolean  := False;
2468       Initialize_ALI_Data   : Boolean  := True;
2469       Max_Process           : Positive := 1)
2470    is
2471       Mfile            : Natural := No_Mapping_File;
2472       Mapping_File_Arg : String_Access;
2473       --  Info on the mapping file
2474
2475       Need_To_Check_Standard_Library : Boolean :=
2476                                          (Check_Readonly_Files or Must_Compile)
2477                                            and not Unique_Compile;
2478
2479       procedure Add_Process
2480         (Pid           : Process_Id;
2481          Sfile         : File_Name_Type;
2482          Afile         : File_Name_Type;
2483          Uname         : Unit_Name_Type;
2484          Full_Lib_File : File_Name_Type;
2485          Lib_File_Attr : File_Attributes;
2486          Mfile         : Natural := No_Mapping_File);
2487       --  Adds process Pid to the current list of outstanding compilation
2488       --  processes and record the full name of the source file Sfile that
2489       --  we are compiling, the name of its library file Afile and the
2490       --  name of its unit Uname. If Mfile is not equal to No_Mapping_File,
2491       --  it is the index of the mapping file used during compilation in the
2492       --  array The_Mapping_File_Names.
2493
2494       procedure Await_Compile
2495         (Data  : out Compilation_Data;
2496          OK    : out Boolean);
2497       --  Awaits that an outstanding compilation process terminates. When it
2498       --  does set Data to the information registered for the corresponding
2499       --  call to Add_Process. Note that this time stamp can be used to check
2500       --  whether the compilation did generate an object file. OK is set to
2501       --  True if the compilation succeeded. Data could be No_Compilation_Data
2502       --  if there was no compilation to wait for.
2503
2504       function Bad_Compilation_Count return Natural;
2505       --  Returns the number of compilation failures
2506
2507       procedure Check_Standard_Library;
2508       --  Check if s-stalib.adb needs to be compiled
2509
2510       procedure Collect_Arguments_And_Compile
2511         (Full_Source_File : File_Name_Type;
2512          Lib_File         : File_Name_Type;
2513          Source_Index     : Int;
2514          Pid              : out Process_Id;
2515          Process_Created  : out Boolean);
2516       --  Collect arguments from project file (if any) and compile. If no
2517       --  compilation was attempted, Processed_Created is set to False, and the
2518       --  value of Pid is unknown.
2519
2520       function Compile
2521         (Project      : Project_Id;
2522          S            : File_Name_Type;
2523          L            : File_Name_Type;
2524          Source_Index : Int;
2525          Args         : Argument_List) return Process_Id;
2526       --  Compiles S using Args. If S is a GNAT predefined source "-gnatpg" is
2527       --  added to Args. Non blocking call. L corresponds to the expected
2528       --  library file name. Process_Id of the process spawned to execute the
2529       --  compilation.
2530
2531       type ALI_Project is record
2532          ALI      : ALI_Id;
2533          Project : Project_Id;
2534       end record;
2535
2536       package Good_ALI is new Table.Table (
2537         Table_Component_Type => ALI_Project,
2538         Table_Index_Type     => Natural,
2539         Table_Low_Bound      => 1,
2540         Table_Initial        => 50,
2541         Table_Increment      => 100,
2542         Table_Name           => "Make.Good_ALI");
2543       --  Contains the set of valid ALI files that have not yet been scanned
2544
2545       function Good_ALI_Present return Boolean;
2546       --  Returns True if any ALI file was recorded in the previous set
2547
2548       procedure Get_Mapping_File (Project : Project_Id);
2549       --  Get a mapping file name. If there is one to be reused, reuse it.
2550       --  Otherwise, create a new mapping file.
2551
2552       function Get_Next_Good_ALI return ALI_Project;
2553       --  Returns the next good ALI_Id record
2554
2555       procedure Record_Failure
2556         (File  : File_Name_Type;
2557          Unit  : Unit_Name_Type;
2558          Found : Boolean := True);
2559       --  Records in the previous table that the compilation for File failed.
2560       --  If Found is False then the compilation of File failed because we
2561       --  could not find it. Records also Unit when possible.
2562
2563       procedure Record_Good_ALI (A : ALI_Id; Project : Project_Id);
2564       --  Records in the previous set the Id of an ALI file
2565
2566       function Must_Exit_Because_Of_Error return Boolean;
2567       --  Return True if there were errors and the user decided to exit in such
2568       --  a case. This waits for any outstanding compilation.
2569
2570       function Start_Compile_If_Possible (Args : Argument_List) return Boolean;
2571       --  Check if there is more work that we can do (i.e. the Queue is non
2572       --  empty). If there is, do it only if we have not yet used up all the
2573       --  available processes.
2574       --  Returns True if we should exit the main loop
2575
2576       procedure Wait_For_Available_Slot;
2577       --  Check if we should wait for a compilation to finish. This is the case
2578       --  if all the available processes are busy compiling sources or there is
2579       --  nothing else to do (that is the Q is empty and there are no good ALIs
2580       --  to process).
2581
2582       procedure Fill_Queue_From_ALI_Files;
2583       --  Check if we recorded good ALI files. If yes process them now in the
2584       --  order in which they have been recorded. There are two occasions in
2585       --  which we record good ali files. The first is in phase 1 when, after
2586       --  scanning an existing ALI file we realize it is up-to-date, the second
2587       --  instance is after a successful compilation.
2588
2589       -----------------
2590       -- Add_Process --
2591       -----------------
2592
2593       procedure Add_Process
2594         (Pid           : Process_Id;
2595          Sfile         : File_Name_Type;
2596          Afile         : File_Name_Type;
2597          Uname         : Unit_Name_Type;
2598          Full_Lib_File : File_Name_Type;
2599          Lib_File_Attr : File_Attributes;
2600          Mfile         : Natural := No_Mapping_File)
2601       is
2602          OC1 : constant Positive := Outstanding_Compiles + 1;
2603
2604       begin
2605          pragma Assert (OC1 <= Max_Process);
2606          pragma Assert (Pid /= Invalid_Pid);
2607
2608          Running_Compile (OC1) :=
2609            (Pid              => Pid,
2610             Full_Source_File => Sfile,
2611             Lib_File         => Afile,
2612             Full_Lib_File    => Full_Lib_File,
2613             Lib_File_Attr    => Lib_File_Attr,
2614             Source_Unit      => Uname,
2615             Mapping_File     => Mfile,
2616             Project          => Arguments_Project);
2617
2618          Outstanding_Compiles := OC1;
2619
2620          if Arguments_Project /= No_Project then
2621             Queue.Set_Obj_Dir_Busy (Arguments_Project.Object_Directory.Name);
2622          end if;
2623       end Add_Process;
2624
2625       --------------------
2626       -- Await_Compile --
2627       -------------------
2628
2629       procedure Await_Compile
2630         (Data : out Compilation_Data;
2631          OK   : out Boolean)
2632       is
2633          Pid       : Process_Id;
2634          Project   : Project_Id;
2635          Comp_Data : Project_Compilation_Access;
2636
2637       begin
2638          pragma Assert (Outstanding_Compiles > 0);
2639
2640          Data := No_Compilation_Data;
2641          OK   := False;
2642
2643          --  The loop here is a work-around for a problem on VMS; in some
2644          --  circumstances (shared library and several executables, for
2645          --  example), there are child processes other than compilation
2646          --  processes that are received. Until this problem is resolved,
2647          --  we will ignore such processes.
2648
2649          loop
2650             Wait_Process (Pid, OK);
2651
2652             if Pid = Invalid_Pid then
2653                return;
2654             end if;
2655
2656             for J in Running_Compile'First .. Outstanding_Compiles loop
2657                if Pid = Running_Compile (J).Pid then
2658                   Data    := Running_Compile (J);
2659                   Project := Running_Compile (J).Project;
2660
2661                   if Project /= No_Project then
2662                      Queue.Set_Obj_Dir_Free (Project.Object_Directory.Name);
2663                   end if;
2664
2665                   --  If a mapping file was used by this compilation, get its
2666                   --  file name for reuse by a subsequent compilation.
2667
2668                   if Running_Compile (J).Mapping_File /= No_Mapping_File then
2669                      Comp_Data :=
2670                        Project_Compilation_Htable.Get
2671                          (Project_Compilation, Project);
2672                      Comp_Data.Last_Free_Indexes :=
2673                        Comp_Data.Last_Free_Indexes + 1;
2674                      Comp_Data.Free_Mapping_File_Indexes
2675                        (Comp_Data.Last_Free_Indexes) :=
2676                          Running_Compile (J).Mapping_File;
2677                   end if;
2678
2679                   --  To actually remove this Pid and related info from
2680                   --  Running_Compile replace its entry with the last valid
2681                   --  entry in Running_Compile.
2682
2683                   if J = Outstanding_Compiles then
2684                      null;
2685                   else
2686                      Running_Compile (J) :=
2687                        Running_Compile (Outstanding_Compiles);
2688                   end if;
2689
2690                   Outstanding_Compiles := Outstanding_Compiles - 1;
2691                   return;
2692                end if;
2693             end loop;
2694
2695             --  This child process was not one of our compilation processes;
2696             --  just ignore it for now.
2697
2698             --  Why is this commented out code sitting here???
2699
2700             --  raise Program_Error;
2701          end loop;
2702       end Await_Compile;
2703
2704       ---------------------------
2705       -- Bad_Compilation_Count --
2706       ---------------------------
2707
2708       function Bad_Compilation_Count return Natural is
2709       begin
2710          return Bad_Compilation.Last - Bad_Compilation.First + 1;
2711       end Bad_Compilation_Count;
2712
2713       ----------------------------
2714       -- Check_Standard_Library --
2715       ----------------------------
2716
2717       procedure Check_Standard_Library is
2718       begin
2719          Need_To_Check_Standard_Library := False;
2720
2721          if not Targparm.Suppress_Standard_Library_On_Target then
2722             declare
2723                Sfile  : File_Name_Type;
2724                Add_It : Boolean := True;
2725
2726             begin
2727                Name_Len := 0;
2728                Add_Str_To_Name_Buffer (Standard_Library_Package_Body_Name);
2729                Sfile := Name_Enter;
2730
2731                --  If we have a special runtime, we add the standard
2732                --  library only if we can find it.
2733
2734                if RTS_Switch then
2735                   Add_It := Full_Source_Name (Sfile) /= No_File;
2736                end if;
2737
2738                if Add_It then
2739                   if Is_Marked (Sfile) then
2740                      if Is_In_Obsoleted (Sfile) then
2741                         Executable_Obsolete := True;
2742                      end if;
2743
2744                   else
2745                      Queue.Insert (Sfile, Project => No_Project, Index => 0);
2746                      Mark (Sfile, Index => 0);
2747                   end if;
2748                end if;
2749             end;
2750          end if;
2751       end Check_Standard_Library;
2752
2753       -----------------------------------
2754       -- Collect_Arguments_And_Compile --
2755       -----------------------------------
2756
2757       procedure Collect_Arguments_And_Compile
2758         (Full_Source_File : File_Name_Type;
2759          Lib_File         : File_Name_Type;
2760          Source_Index     : Int;
2761          Pid              : out Process_Id;
2762          Process_Created  : out Boolean) is
2763       begin
2764          Process_Created := False;
2765
2766          --  If we use mapping file (-P or -C switches), then get one
2767
2768          if Create_Mapping_File then
2769             Get_Mapping_File (Arguments_Project);
2770          end if;
2771
2772          --  If the source is part of a project file, we set the ADA_*_PATHs,
2773          --  check for an eventual library project, and use the full path.
2774
2775          if Arguments_Project /= No_Project then
2776             if not Arguments_Project.Externally_Built
2777               or else Must_Compile
2778             then
2779                Prj.Env.Set_Ada_Paths
2780                  (Arguments_Project,
2781                   Project_Tree,
2782                   Including_Libraries => True,
2783                   Include_Path        => Use_Include_Path_File);
2784
2785                if not Unique_Compile
2786                  and then MLib.Tgt.Support_For_Libraries /= Prj.None
2787                then
2788                   declare
2789                      Prj : constant Project_Id :=
2790                              Ultimate_Extending_Project_Of (Arguments_Project);
2791
2792                   begin
2793                      if Prj.Library
2794                        and then (not Prj.Externally_Built or else Must_Compile)
2795                        and then not Prj.Need_To_Build_Lib
2796                      then
2797                         --  Add to the Q all sources of the project that have
2798                         --  not been marked.
2799
2800                         Insert_Project_Sources
2801                           (The_Project  => Prj,
2802                            All_Projects => False,
2803                            Into_Q       => True);
2804
2805                         --  Now mark the project as processed
2806
2807                         Prj.Need_To_Build_Lib := True;
2808                      end if;
2809                   end;
2810                end if;
2811
2812                Pid :=
2813                  Compile
2814                    (Project       => Arguments_Project,
2815                     S             => File_Name_Type (Arguments_Path_Name),
2816                     L             => Lib_File,
2817                     Source_Index  => Source_Index,
2818                     Args          => Arguments (1 .. Last_Argument));
2819                Process_Created := True;
2820             end if;
2821
2822          else
2823             --  If this is a source outside of any project file, make sure it
2824             --  will be compiled in object directory of the main project file.
2825
2826             Pid :=
2827               Compile
2828                 (Project        => Main_Project,
2829                  S              => Full_Source_File,
2830                  L              => Lib_File,
2831                  Source_Index   => Source_Index,
2832                  Args           => Arguments (1 .. Last_Argument));
2833             Process_Created := True;
2834          end if;
2835       end Collect_Arguments_And_Compile;
2836
2837       -------------
2838       -- Compile --
2839       -------------
2840
2841       function Compile
2842         (Project      : Project_Id;
2843          S            : File_Name_Type;
2844          L            : File_Name_Type;
2845          Source_Index : Int;
2846          Args         : Argument_List) return Process_Id
2847       is
2848          Comp_Args : Argument_List (Args'First .. Args'Last + 10);
2849          Comp_Next : Integer := Args'First;
2850          Comp_Last : Integer;
2851          Arg_Index : Integer;
2852
2853          function Ada_File_Name (Name : File_Name_Type) return Boolean;
2854          --  Returns True if Name is the name of an ada source file
2855          --  (i.e. suffix is .ads or .adb)
2856
2857          -------------------
2858          -- Ada_File_Name --
2859          -------------------
2860
2861          function Ada_File_Name (Name : File_Name_Type) return Boolean is
2862          begin
2863             Get_Name_String (Name);
2864             return
2865               Name_Len > 4
2866                 and then Name_Buffer (Name_Len - 3 .. Name_Len - 1) = ".ad"
2867                 and then (Name_Buffer (Name_Len) = 'b'
2868                             or else
2869                           Name_Buffer (Name_Len) = 's');
2870          end Ada_File_Name;
2871
2872       --  Start of processing for Compile
2873
2874       begin
2875          Enter_Into_Obsoleted (S);
2876
2877          --  By default, Syntax_Only is False
2878
2879          Syntax_Only := False;
2880
2881          for J in Args'Range loop
2882             if Args (J).all = "-gnats" then
2883
2884                --  If we compile with -gnats, the bind step and the link step
2885                --  are inhibited. Also, we set Syntax_Only to True, so that
2886                --  we don't fail when we don't find the ALI file, after
2887                --  compilation.
2888
2889                Do_Bind_Step := False;
2890                Do_Link_Step := False;
2891                Syntax_Only  := True;
2892
2893             elsif Args (J).all = "-gnatc" then
2894
2895                --  If we compile with -gnatc, the bind step and the link step
2896                --  are inhibited. We set Syntax_Only to False for the case when
2897                --  -gnats was previously specified.
2898
2899                Do_Bind_Step := False;
2900                Do_Link_Step := False;
2901                Syntax_Only  := False;
2902
2903             elsif Args (J).all = "-gnatC"
2904               or else Args (J).all = "-gnatcC"
2905             then
2906                --  If we compile with -gnatC, enable CodePeer globalize step
2907
2908                Do_Codepeer_Globalize_Step := True;
2909             end if;
2910          end loop;
2911
2912          Comp_Args (Comp_Next) := new String'("-gnatea");
2913          Comp_Next := Comp_Next + 1;
2914
2915          Comp_Args (Comp_Next) := Comp_Flag;
2916          Comp_Next := Comp_Next + 1;
2917
2918          --  Optimize the simple case where the gcc command line looks like
2919          --     gcc -c -I. ... -I- file.adb
2920          --  into
2921          --     gcc -c ... file.adb
2922
2923          if Args (Args'First).all = "-I" & Normalized_CWD
2924            and then Args (Args'Last).all = "-I-"
2925            and then S = Strip_Directory (S)
2926          then
2927             Comp_Last := Comp_Next + Args'Length - 3;
2928             Arg_Index := Args'First + 1;
2929
2930          else
2931             Comp_Last := Comp_Next + Args'Length - 1;
2932             Arg_Index := Args'First;
2933          end if;
2934
2935          --  Make a deep copy of the arguments, because Normalize_Arguments
2936          --  may deallocate some arguments.
2937
2938          for J in Comp_Next .. Comp_Last loop
2939             Comp_Args (J) := new String'(Args (Arg_Index).all);
2940             Arg_Index := Arg_Index + 1;
2941          end loop;
2942
2943          --  Set -gnatpg for predefined files (for this purpose the renamings
2944          --  such as Text_IO do not count as predefined). Note that we strip
2945          --  the directory name from the source file name because the call to
2946          --  Fname.Is_Predefined_File_Name cannot deal with directory prefixes.
2947
2948          declare
2949             Fname : constant File_Name_Type := Strip_Directory (S);
2950
2951          begin
2952             if Is_Predefined_File_Name (Fname, False) then
2953                if Check_Readonly_Files or else Must_Compile then
2954                   Comp_Args (Comp_Args'First + 2 .. Comp_Last + 1) :=
2955                     Comp_Args (Comp_Args'First + 1 .. Comp_Last);
2956                   Comp_Last := Comp_Last + 1;
2957                   Comp_Args (Comp_Args'First + 1) := GNAT_Flag;
2958
2959                else
2960                   Make_Failed
2961                     ("not allowed to compile """ &
2962                      Get_Name_String (Fname) &
2963                      """; use -a switch, or compile file with " &
2964                      """-gnatg"" switch");
2965                end if;
2966             end if;
2967          end;
2968
2969          --  Now check if the file name has one of the suffixes familiar to
2970          --  the gcc driver. If this is not the case then add the ada flag
2971          --  "-x ada".
2972
2973          if not Ada_File_Name (S) and then not Targparm.AAMP_On_Target then
2974             Comp_Last := Comp_Last + 1;
2975             Comp_Args (Comp_Last) := Ada_Flag_1;
2976             Comp_Last := Comp_Last + 1;
2977             Comp_Args (Comp_Last) := Ada_Flag_2;
2978          end if;
2979
2980          if Source_Index /= 0 then
2981             declare
2982                Num : constant String := Source_Index'Img;
2983             begin
2984                Comp_Last := Comp_Last + 1;
2985                Comp_Args (Comp_Last) :=
2986                  new String'("-gnateI" & Num (Num'First + 1 .. Num'Last));
2987             end;
2988          end if;
2989
2990          if Source_Index /= 0
2991            or else L /= Strip_Directory (L)
2992            or else Object_Directory_Path /= null
2993          then
2994             --  Build -o argument
2995
2996             Get_Name_String (L);
2997
2998             for J in reverse 1 .. Name_Len loop
2999                if Name_Buffer (J) = '.' then
3000                   Name_Len := J + Object_Suffix'Length - 1;
3001                   Name_Buffer (J .. Name_Len) := Object_Suffix;
3002                   exit;
3003                end if;
3004             end loop;
3005
3006             Comp_Last := Comp_Last + 1;
3007             Comp_Args (Comp_Last) := Output_Flag;
3008             Comp_Last := Comp_Last + 1;
3009
3010             --  If an object directory was specified, prepend the object file
3011             --  name with this object directory.
3012
3013             if Object_Directory_Path /= null then
3014                Comp_Args (Comp_Last) :=
3015                  new String'(Object_Directory_Path.all &
3016                                Name_Buffer (1 .. Name_Len));
3017
3018             else
3019                Comp_Args (Comp_Last) :=
3020                  new String'(Name_Buffer (1 .. Name_Len));
3021             end if;
3022          end if;
3023
3024          if Create_Mapping_File and then Mapping_File_Arg /= null then
3025             Comp_Last := Comp_Last + 1;
3026             Comp_Args (Comp_Last) := new String'(Mapping_File_Arg.all);
3027          end if;
3028
3029          Get_Name_String (S);
3030
3031          Comp_Last := Comp_Last + 1;
3032          Comp_Args (Comp_Last) := new String'(Name_Buffer (1 .. Name_Len));
3033
3034          --  Change to object directory of the project file, if necessary
3035
3036          if Project /= No_Project then
3037             Change_To_Object_Directory (Project);
3038          end if;
3039
3040          GNAT.OS_Lib.Normalize_Arguments (Comp_Args (Args'First .. Comp_Last));
3041
3042          Comp_Last := Comp_Last + 1;
3043          Comp_Args (Comp_Last) := new String'("-gnatez");
3044
3045          Display (Gcc.all, Comp_Args (Args'First .. Comp_Last));
3046
3047          if Gcc_Path = null then
3048             Make_Failed ("error, unable to locate " & Gcc.all);
3049          end if;
3050
3051          return
3052            GNAT.OS_Lib.Non_Blocking_Spawn
3053              (Gcc_Path.all, Comp_Args (Args'First .. Comp_Last));
3054       end Compile;
3055
3056       -------------------------------
3057       -- Fill_Queue_From_ALI_Files --
3058       -------------------------------
3059
3060       procedure Fill_Queue_From_ALI_Files is
3061          ALI_P        : ALI_Project;
3062          ALI          : ALI_Id;
3063          Source_Index : Int;
3064          Sfile        : File_Name_Type;
3065          Uname        : Unit_Name_Type;
3066          Unit_Name    : Name_Id;
3067          Uid          : Prj.Unit_Index;
3068
3069       begin
3070          while Good_ALI_Present loop
3071             ALI_P        := Get_Next_Good_ALI;
3072             ALI          := ALI_P.ALI;
3073             Source_Index := Unit_Index_Of (ALIs.Table (ALI_P.ALI).Afile);
3074
3075             --  If we are processing the library file corresponding to the
3076             --  main source file check if this source can be a main unit.
3077
3078             if ALIs.Table (ALI).Sfile = Main_Source
3079               and then Source_Index = Main_Index
3080             then
3081                Main_Unit := ALIs.Table (ALI).Main_Program /= None;
3082             end if;
3083
3084             --  The following adds the standard library (s-stalib) to the list
3085             --  of files to be handled by gnatmake: this file and any files it
3086             --  depends on are always included in every bind, even if they are
3087             --  not in the explicit dependency list. Of course, it is not added
3088             --  if Suppress_Standard_Library is True.
3089
3090             --  However, to avoid annoying output about s-stalib.ali being read
3091             --  only, when "-v" is used, we add the standard library only when
3092             --  "-a" is used.
3093
3094             if Need_To_Check_Standard_Library then
3095                Check_Standard_Library;
3096             end if;
3097
3098             --  Now insert in the Q the unmarked source files (i.e. those which
3099             --  have never been inserted in the Q and hence never considered).
3100             --  Only do that if Unique_Compile is False.
3101
3102             if not Unique_Compile then
3103                for J in
3104                  ALIs.Table (ALI).First_Unit .. ALIs.Table (ALI).Last_Unit
3105                loop
3106                   for K in
3107                     Units.Table (J).First_With .. Units.Table (J).Last_With
3108                   loop
3109                      Sfile := Withs.Table (K).Sfile;
3110                      Uname := Withs.Table (K).Uname;
3111
3112                      --  If project files are used, find the proper source to
3113                      --  compile in case Sfile is the spec but there is a body.
3114
3115                      if Main_Project /= No_Project then
3116                         Get_Name_String (Uname);
3117                         Name_Len  := Name_Len - 2;
3118                         Unit_Name := Name_Find;
3119                         Uid :=
3120                           Units_Htable.Get (Project_Tree.Units_HT, Unit_Name);
3121
3122                         if Uid /= Prj.No_Unit_Index then
3123                            if Uid.File_Names (Impl) /= null
3124                              and then not Uid.File_Names (Impl).Locally_Removed
3125                            then
3126                               Sfile        := Uid.File_Names (Impl).File;
3127                               Source_Index := Uid.File_Names (Impl).Index;
3128
3129                            elsif Uid.File_Names (Spec) /= null
3130                              and then not Uid.File_Names (Spec).Locally_Removed
3131                            then
3132                               Sfile        := Uid.File_Names (Spec).File;
3133                               Source_Index := Uid.File_Names (Spec).Index;
3134                            end if;
3135                         end if;
3136                      end if;
3137
3138                      Dependencies.Append ((ALIs.Table (ALI).Sfile, Sfile));
3139
3140                      if Is_In_Obsoleted (Sfile) then
3141                         Executable_Obsolete := True;
3142                      end if;
3143
3144                      if Sfile = No_File then
3145                         Debug_Msg ("Skipping generic:", Withs.Table (K).Uname);
3146
3147                      else
3148                         Source_Index := Unit_Index_Of (Withs.Table (K).Afile);
3149
3150                         if Is_Marked (Sfile, Source_Index) then
3151                            Debug_Msg ("Skipping marked file:", Sfile);
3152
3153                         elsif not (Check_Readonly_Files or Must_Compile)
3154                           and then Is_Internal_File_Name (Sfile, False)
3155                         then
3156                            Debug_Msg ("Skipping internal file:", Sfile);
3157
3158                         else
3159                            Queue.Insert
3160                              (Sfile,
3161                               ALI_P.Project,
3162                               Withs.Table (K).Uname,
3163                               Source_Index);
3164                            Mark (Sfile, Source_Index);
3165                         end if;
3166                      end if;
3167                   end loop;
3168                end loop;
3169             end if;
3170          end loop;
3171       end Fill_Queue_From_ALI_Files;
3172
3173       ----------------------
3174       -- Get_Mapping_File --
3175       ----------------------
3176
3177       procedure Get_Mapping_File (Project : Project_Id) is
3178          Data : Project_Compilation_Access;
3179
3180       begin
3181          Data := Project_Compilation_Htable.Get (Project_Compilation, Project);
3182
3183          --  If there is a mapping file ready to be reused, reuse it
3184
3185          if Data.Last_Free_Indexes > 0 then
3186             Mfile := Data.Free_Mapping_File_Indexes (Data.Last_Free_Indexes);
3187             Data.Last_Free_Indexes := Data.Last_Free_Indexes - 1;
3188
3189          --  Otherwise, create and initialize a new one
3190
3191          else
3192             Init_Mapping_File
3193               (Project => Project, Data => Data.all, File_Index => Mfile);
3194          end if;
3195
3196          --  Put the name in the mapping file argument for the invocation
3197          --  of the compiler.
3198
3199          Free (Mapping_File_Arg);
3200          Mapping_File_Arg :=
3201            new String'("-gnatem=" &
3202                        Get_Name_String (Data.Mapping_File_Names (Mfile)));
3203       end Get_Mapping_File;
3204
3205       -----------------------
3206       -- Get_Next_Good_ALI --
3207       -----------------------
3208
3209       function Get_Next_Good_ALI return ALI_Project is
3210          ALIP : ALI_Project;
3211
3212       begin
3213          pragma Assert (Good_ALI_Present);
3214          ALIP := Good_ALI.Table (Good_ALI.Last);
3215          Good_ALI.Decrement_Last;
3216          return ALIP;
3217       end Get_Next_Good_ALI;
3218
3219       ----------------------
3220       -- Good_ALI_Present --
3221       ----------------------
3222
3223       function Good_ALI_Present return Boolean is
3224       begin
3225          return Good_ALI.First <= Good_ALI.Last;
3226       end Good_ALI_Present;
3227
3228       --------------------------------
3229       -- Must_Exit_Because_Of_Error --
3230       --------------------------------
3231
3232       function Must_Exit_Because_Of_Error return Boolean is
3233          Data    : Compilation_Data;
3234          Success : Boolean;
3235
3236       begin
3237          if Bad_Compilation_Count > 0 and then not Keep_Going then
3238             while Outstanding_Compiles > 0 loop
3239                Await_Compile (Data, Success);
3240
3241                if not Success then
3242                   Record_Failure (Data.Full_Source_File, Data.Source_Unit);
3243                end if;
3244             end loop;
3245
3246             return True;
3247          end if;
3248
3249          return False;
3250       end Must_Exit_Because_Of_Error;
3251
3252       --------------------
3253       -- Record_Failure --
3254       --------------------
3255
3256       procedure Record_Failure
3257         (File  : File_Name_Type;
3258          Unit  : Unit_Name_Type;
3259          Found : Boolean := True)
3260       is
3261       begin
3262          Bad_Compilation.Increment_Last;
3263          Bad_Compilation.Table (Bad_Compilation.Last) := (File, Unit, Found);
3264       end Record_Failure;
3265
3266       ---------------------
3267       -- Record_Good_ALI --
3268       ---------------------
3269
3270       procedure Record_Good_ALI (A : ALI_Id; Project : Project_Id) is
3271       begin
3272          Good_ALI.Increment_Last;
3273          Good_ALI.Table (Good_ALI.Last) := (A, Project);
3274       end Record_Good_ALI;
3275
3276       -------------------------------
3277       -- Start_Compile_If_Possible --
3278       -------------------------------
3279
3280       function Start_Compile_If_Possible
3281         (Args : Argument_List) return Boolean
3282       is
3283          In_Lib_Dir      : Boolean;
3284          Need_To_Compile : Boolean;
3285          Pid             : Process_Id;
3286          Process_Created : Boolean;
3287
3288          Source_File      : File_Name_Type;
3289          Full_Source_File : File_Name_Type;
3290          Source_File_Attr : aliased File_Attributes;
3291          --  The full name of the source file and its attributes (size, ...)
3292
3293          Source_Unit  : Unit_Name_Type;
3294          Source_Index : Int;
3295          --  Index of the current unit in the current source file
3296
3297          Lib_File      : File_Name_Type;
3298          Full_Lib_File : File_Name_Type;
3299          Lib_File_Attr : aliased File_Attributes;
3300          Read_Only     : Boolean := False;
3301          ALI           : ALI_Id;
3302          --  The ALI file and its attributes (size, stamp, ...)
3303
3304          Obj_File  : File_Name_Type;
3305          Obj_Stamp : Time_Stamp_Type;
3306          --  The object file
3307
3308       begin
3309          if not Queue.Is_Virtually_Empty and then
3310             Outstanding_Compiles < Max_Process
3311          then
3312             Queue.Extract (Source_File, Source_Unit, Source_Index);
3313
3314             Osint.Full_Source_Name
3315               (Source_File,
3316                Full_File => Full_Source_File,
3317                Attr      => Source_File_Attr'Access);
3318
3319             Lib_File := Osint.Lib_File_Name (Source_File, Source_Index);
3320
3321             --  ??? This call could be avoided when using projects, since we
3322             --  know where the ALI file is supposed to be. That would avoid
3323             --  searches in the object directories, including in the runtime
3324             --  dir. However, that would require getting access to the
3325             --  Source_Id.
3326
3327             Osint.Full_Lib_File_Name
3328               (Lib_File,
3329                Lib_File => Full_Lib_File,
3330                Attr     => Lib_File_Attr);
3331
3332             --  If source has already been compiled, executable is obsolete
3333
3334             if Is_In_Obsoleted (Source_File) then
3335                Executable_Obsolete := True;
3336             end if;
3337
3338             In_Lib_Dir := Full_Lib_File /= No_File
3339                           and then In_Ada_Lib_Dir (Full_Lib_File);
3340
3341             --  Since the following requires a system call, we precompute it
3342             --  when needed.
3343
3344             if not In_Lib_Dir then
3345                if Full_Lib_File /= No_File
3346                  and then not (Check_Readonly_Files or else Must_Compile)
3347                then
3348                   Get_Name_String (Full_Lib_File);
3349                   Name_Buffer (Name_Len + 1) := ASCII.NUL;
3350                   Read_Only := not Is_Writable_File
3351                     (Name_Buffer'Address, Lib_File_Attr'Access);
3352                else
3353                   Read_Only := False;
3354                end if;
3355             end if;
3356
3357             --  If the library file is an Ada library skip it
3358
3359             if In_Lib_Dir then
3360                Verbose_Msg
3361                  (Lib_File,
3362                   "is in an Ada library",
3363                   Prefix => "  ",
3364                   Minimum_Verbosity => Opt.High);
3365
3366                --  If the library file is a read-only library skip it, but only
3367                --  if, when using project files, this library file is in the
3368                --  right object directory (a read-only ALI file in the object
3369                --  directory of a project being extended must not be skipped).
3370
3371             elsif Read_Only
3372               and then Is_In_Object_Directory (Source_File, Full_Lib_File)
3373             then
3374                Verbose_Msg
3375                  (Lib_File,
3376                   "is a read-only library",
3377                   Prefix => "  ",
3378                   Minimum_Verbosity => Opt.High);
3379
3380                --  The source file that we are checking cannot be located
3381
3382             elsif Full_Source_File = No_File then
3383                Record_Failure (Source_File, Source_Unit, False);
3384
3385                --  Source and library files can be located but are internal
3386                --  files.
3387
3388             elsif not (Check_Readonly_Files or else Must_Compile)
3389               and then Full_Lib_File /= No_File
3390               and then Is_Internal_File_Name (Source_File, False)
3391             then
3392                if Force_Compilations then
3393                   Fail
3394                     ("not allowed to compile """ &
3395                      Get_Name_String (Source_File) &
3396                      """; use -a switch, or compile file with " &
3397                      """-gnatg"" switch");
3398                end if;
3399
3400                Verbose_Msg
3401                  (Lib_File,
3402                   "is an internal library",
3403                   Prefix => "  ",
3404                   Minimum_Verbosity => Opt.High);
3405
3406                --  The source file that we are checking can be located
3407
3408             else
3409                Collect_Arguments (Source_File, Source_Index,
3410                                   Source_File = Main_Source, Args);
3411
3412                --  Do nothing if project of source is externally built
3413
3414                if Arguments_Project = No_Project
3415                  or else not Arguments_Project.Externally_Built
3416                  or else Must_Compile
3417                then
3418                   --  Don't waste any time if we have to recompile anyway
3419
3420                   Obj_Stamp       := Empty_Time_Stamp;
3421                   Need_To_Compile := Force_Compilations;
3422
3423                   if not Force_Compilations then
3424                      Check (Source_File    => Source_File,
3425                             Source_Index   => Source_Index,
3426                             Is_Main_Source => Source_File = Main_Source,
3427                             The_Args       => Args,
3428                             Lib_File       => Lib_File,
3429                             Full_Lib_File  => Full_Lib_File,
3430                             Lib_File_Attr  => Lib_File_Attr'Access,
3431                             Read_Only      => Read_Only,
3432                             ALI            => ALI,
3433                             O_File         => Obj_File,
3434                             O_Stamp        => Obj_Stamp);
3435                      Need_To_Compile := (ALI = No_ALI_Id);
3436                   end if;
3437
3438                   if not Need_To_Compile then
3439
3440                      --  The ALI file is up-to-date; record its Id
3441
3442                      Record_Good_ALI (ALI, Arguments_Project);
3443
3444                      --  Record the time stamp of the most recent object
3445                      --  file as long as no (re)compilations are needed.
3446
3447                      if First_Compiled_File = No_File
3448                        and then (Most_Recent_Obj_File = No_File
3449                                   or else Obj_Stamp > Most_Recent_Obj_Stamp)
3450                      then
3451                         Most_Recent_Obj_File  := Obj_File;
3452                         Most_Recent_Obj_Stamp := Obj_Stamp;
3453                      end if;
3454
3455                   else
3456                      --  Check that switch -x has been used if a source outside
3457                      --  of project files need to be compiled.
3458
3459                      if Main_Project /= No_Project
3460                        and then Arguments_Project = No_Project
3461                        and then not External_Unit_Compilation_Allowed
3462                      then
3463                         Make_Failed ("external source ("
3464                                      & Get_Name_String (Source_File)
3465                                      & ") is not part of any project;"
3466                                      & " cannot be compiled without"
3467                                      & " gnatmake switch -x");
3468                      end if;
3469
3470                      --  Is this the first file we have to compile?
3471
3472                      if First_Compiled_File = No_File then
3473                         First_Compiled_File  := Full_Source_File;
3474                         Most_Recent_Obj_File := No_File;
3475
3476                         if Do_Not_Execute then
3477
3478                            --  Exit the main loop
3479
3480                            return True;
3481                         end if;
3482                      end if;
3483
3484                      --  Compute where the ALI file must be generated in
3485                      --  In_Place_Mode (this does not require to know the
3486                      --  location of the object directory).
3487
3488                      if In_Place_Mode then
3489                         if Full_Lib_File = No_File then
3490
3491                            --  If the library file was not found, then save
3492                            --  the library file near the source file.
3493
3494                            Lib_File :=
3495                              Osint.Lib_File_Name
3496                                (Full_Source_File, Source_Index);
3497                            Full_Lib_File := Lib_File;
3498
3499                         else
3500                            --  If the library file was found, then save the
3501                            --  library file in the same place.
3502
3503                            Lib_File := Full_Lib_File;
3504                         end if;
3505                      end if;
3506
3507                      --  Start the compilation and record it. We can do this
3508                      --  because there is at least one free process. This might
3509                      --  change the current directory.
3510
3511                      Collect_Arguments_And_Compile
3512                        (Full_Source_File => Full_Source_File,
3513                         Lib_File         => Lib_File,
3514                         Source_Index     => Source_Index,
3515                         Pid              => Pid,
3516                         Process_Created  => Process_Created);
3517
3518                      --  Compute where the ALI file will be generated (for
3519                      --  cases that might require to know the current
3520                      --  directory). The current directory might be changed
3521                      --  when compiling other files so we cannot rely on it
3522                      --  being the same to find the resulting ALI file.
3523
3524                      if not In_Place_Mode then
3525
3526                         --  Compute the expected location of the ALI file. This
3527                         --  can be from several places:
3528                         --    -i => in place mode. In such a case,
3529                         --          Full_Lib_File has already been set above
3530                         --    -D => if specified
3531                         --    or defaults in current dir
3532                         --  We could simply use a call similar to
3533                         --     Osint.Full_Lib_File_Name (Lib_File)
3534                         --  but that involves system calls and is thus slower
3535
3536                         if Object_Directory_Path /= null then
3537                            Name_Len := 0;
3538                            Add_Str_To_Name_Buffer (Object_Directory_Path.all);
3539                            Add_Str_To_Name_Buffer (Get_Name_String (Lib_File));
3540                            Full_Lib_File := Name_Find;
3541
3542                         else
3543                            if Project_Of_Current_Object_Directory /=
3544                              No_Project
3545                            then
3546                               Get_Name_String
3547                                 (Project_Of_Current_Object_Directory
3548                                  .Object_Directory.Display_Name);
3549                               Add_Str_To_Name_Buffer
3550                                 (Get_Name_String (Lib_File));
3551                               Full_Lib_File := Name_Find;
3552
3553                            else
3554                               Full_Lib_File := Lib_File;
3555                            end if;
3556                         end if;
3557
3558                      end if;
3559
3560                      Lib_File_Attr := Unknown_Attributes;
3561
3562                      --  Make sure we could successfully start the compilation
3563
3564                      if Process_Created then
3565                         if Pid = Invalid_Pid then
3566                            Record_Failure (Full_Source_File, Source_Unit);
3567                         else
3568                            Add_Process
3569                              (Pid           => Pid,
3570                               Sfile         => Full_Source_File,
3571                               Afile         => Lib_File,
3572                               Uname         => Source_Unit,
3573                               Mfile         => Mfile,
3574                               Full_Lib_File => Full_Lib_File,
3575                               Lib_File_Attr => Lib_File_Attr);
3576                         end if;
3577                      end if;
3578                   end if;
3579                end if;
3580             end if;
3581          end if;
3582          return False;
3583       end Start_Compile_If_Possible;
3584
3585       -----------------------------
3586       -- Wait_For_Available_Slot --
3587       -----------------------------
3588
3589       procedure Wait_For_Available_Slot is
3590          Compilation_OK : Boolean;
3591          Text           : Text_Buffer_Ptr;
3592          ALI            : ALI_Id;
3593          Data           : Compilation_Data;
3594
3595       begin
3596          if Outstanding_Compiles = Max_Process
3597            or else (Queue.Is_Virtually_Empty
3598                      and then not Good_ALI_Present
3599                      and then Outstanding_Compiles > 0)
3600          then
3601             Await_Compile (Data, Compilation_OK);
3602
3603             if not Compilation_OK then
3604                Record_Failure (Data.Full_Source_File, Data.Source_Unit);
3605             end if;
3606
3607             if Compilation_OK or else Keep_Going then
3608
3609                --  Re-read the updated library file
3610
3611                declare
3612                   Saved_Object_Consistency : constant Boolean :=
3613                                                Check_Object_Consistency;
3614
3615                begin
3616                   --  If compilation was not OK, or if output is not an object
3617                   --  file and we don't do the bind step, don't check for
3618                   --  object consistency.
3619
3620                   Check_Object_Consistency :=
3621                     Check_Object_Consistency
3622                       and Compilation_OK
3623                       and (Output_Is_Object or Do_Bind_Step);
3624
3625                   Text :=
3626                     Read_Library_Info_From_Full
3627                       (Data.Full_Lib_File, Data.Lib_File_Attr'Access);
3628
3629                   --  Restore Check_Object_Consistency to its initial value
3630
3631                   Check_Object_Consistency := Saved_Object_Consistency;
3632                end;
3633
3634                --  If an ALI file was generated by this compilation, scan the
3635                --  ALI file and record it.
3636
3637                --  If the scan fails, a previous ali file is inconsistent with
3638                --  the unit just compiled.
3639
3640                if Text /= null then
3641                   ALI :=
3642                     Scan_ALI
3643                       (Data.Lib_File, Text, Ignore_ED => False, Err => True);
3644
3645                   if ALI = No_ALI_Id then
3646
3647                      --  Record a failure only if not already done
3648
3649                      if Compilation_OK then
3650                         Inform
3651                           (Data.Lib_File,
3652                            "incompatible ALI file, please recompile");
3653                         Record_Failure
3654                           (Data.Full_Source_File, Data.Source_Unit);
3655                      end if;
3656
3657                   else
3658                      Record_Good_ALI (ALI, Data.Project);
3659                   end if;
3660
3661                   Free (Text);
3662
3663                --  If we could not read the ALI file that was just generated
3664                --  then there could be a problem reading either the ALI or the
3665                --  corresponding object file (if Check_Object_Consistency is
3666                --  set Read_Library_Info checks that the time stamp of the
3667                --  object file is more recent than that of the ALI). However,
3668                --  we record a failure only if not already done.
3669
3670                else
3671                   if Compilation_OK and not Syntax_Only then
3672                      Inform
3673                        (Data.Lib_File,
3674                         "WARNING: ALI or object file not found after compile");
3675                      Record_Failure (Data.Full_Source_File, Data.Source_Unit);
3676                   end if;
3677                end if;
3678             end if;
3679          end if;
3680       end Wait_For_Available_Slot;
3681
3682    --  Start of processing for Compile_Sources
3683
3684    begin
3685       pragma Assert (Args'First = 1);
3686
3687       Outstanding_Compiles := 0;
3688       Running_Compile := new Comp_Data_Arr (1 .. Max_Process);
3689
3690       --  Package and Queue initializations
3691
3692       Good_ALI.Init;
3693
3694       if Initialize_ALI_Data then
3695          Initialize_ALI;
3696          Initialize_ALI_Source;
3697       end if;
3698
3699       --  The following two flags affect the behavior of ALI.Set_Source_Table.
3700       --  We set Check_Source_Files to True to ensure that source file time
3701       --  stamps are checked, and we set All_Sources to False to avoid checking
3702       --  the presence of the source files listed in the source dependency
3703       --  section of an ali file (which would be a mistake since the ali file
3704       --  may be obsolete).
3705
3706       Check_Source_Files := True;
3707       All_Sources        := False;
3708
3709       --  Only insert in the Q if it is not already done, to avoid simultaneous
3710       --  compilations if -jnnn is used.
3711
3712       if not Is_Marked (Main_Source, Main_Index) then
3713          Queue.Insert (Main_Source, Main_Project, Index => Main_Index);
3714          Mark (Main_Source, Main_Index);
3715       end if;
3716
3717       First_Compiled_File   := No_File;
3718       Most_Recent_Obj_File  := No_File;
3719       Most_Recent_Obj_Stamp := Empty_Time_Stamp;
3720       Main_Unit             := False;
3721
3722       --  Keep looping until there is no more work to do (the Q is empty)
3723       --  and all the outstanding compilations have terminated.
3724
3725       Make_Loop :
3726       while not Queue.Is_Empty or else Outstanding_Compiles > 0 loop
3727          exit Make_Loop when Must_Exit_Because_Of_Error;
3728          exit Make_Loop when Start_Compile_If_Possible (Args);
3729
3730          Wait_For_Available_Slot;
3731
3732          --  ??? Should be done as soon as we add a Good_ALI, wouldn't it avoid
3733          --  the need for a list of good ALI?
3734
3735          Fill_Queue_From_ALI_Files;
3736
3737          if Display_Compilation_Progress then
3738             Write_Str ("completed ");
3739             Write_Int (Int (Queue.Processed));
3740             Write_Str (" out of ");
3741             Write_Int (Int (Queue.Size));
3742             Write_Str (" (");
3743             Write_Int (Int ((Queue.Processed * 100) / Queue.Size));
3744             Write_Str ("%)...");
3745             Write_Eol;
3746          end if;
3747       end loop Make_Loop;
3748
3749       Compilation_Failures := Bad_Compilation_Count;
3750
3751       --  Compilation is finished
3752
3753       --  Delete any temporary configuration pragma file
3754
3755       if not Debug.Debug_Flag_N then
3756          Delete_Temp_Config_Files;
3757       end if;
3758    end Compile_Sources;
3759
3760    ----------------------------------
3761    -- Configuration_Pragmas_Switch --
3762    ----------------------------------
3763
3764    function Configuration_Pragmas_Switch
3765      (For_Project : Project_Id) return Argument_List
3766    is
3767       The_Packages : Package_Id;
3768       Gnatmake     : Package_Id;
3769       Compiler     : Package_Id;
3770
3771       Global_Attribute : Variable_Value := Nil_Variable_Value;
3772       Local_Attribute  : Variable_Value := Nil_Variable_Value;
3773
3774       Global_Attribute_Present : Boolean := False;
3775       Local_Attribute_Present  : Boolean := False;
3776
3777       Result : Argument_List (1 .. 3);
3778       Last   : Natural := 0;
3779
3780       function Absolute_Path
3781         (Path    : Path_Name_Type;
3782          Project : Project_Id) return String;
3783       --  Returns an absolute path for a configuration pragmas file
3784
3785       -------------------
3786       -- Absolute_Path --
3787       -------------------
3788
3789       function Absolute_Path
3790         (Path    : Path_Name_Type;
3791          Project : Project_Id) return String
3792       is
3793       begin
3794          Get_Name_String (Path);
3795
3796          declare
3797             Path_Name : constant String := Name_Buffer (1 .. Name_Len);
3798
3799          begin
3800             if Is_Absolute_Path (Path_Name) then
3801                return Path_Name;
3802
3803             else
3804                declare
3805                   Parent_Directory : constant String :=
3806                     Get_Name_String (Project.Directory.Display_Name);
3807
3808                begin
3809                   if Parent_Directory (Parent_Directory'Last) =
3810                                                  Directory_Separator
3811                   then
3812                      return Parent_Directory & Path_Name;
3813
3814                   else
3815                      return Parent_Directory & Directory_Separator & Path_Name;
3816                   end if;
3817                end;
3818             end if;
3819          end;
3820       end Absolute_Path;
3821
3822    --  Start of processing for Configuration_Pragmas_Switch
3823
3824    begin
3825       Prj.Env.Create_Config_Pragmas_File
3826         (For_Project, Project_Tree);
3827
3828       if For_Project.Config_File_Name /= No_Path then
3829          Temporary_Config_File := For_Project.Config_File_Temp;
3830          Last := 1;
3831          Result (1) :=
3832            new String'
3833                  ("-gnatec=" & Get_Name_String (For_Project.Config_File_Name));
3834
3835       else
3836          Temporary_Config_File := False;
3837       end if;
3838
3839       --  Check for attribute Builder'Global_Configuration_Pragmas
3840
3841       The_Packages := Main_Project.Decl.Packages;
3842       Gnatmake :=
3843         Prj.Util.Value_Of
3844           (Name        => Name_Builder,
3845            In_Packages => The_Packages,
3846            In_Tree     => Project_Tree);
3847
3848       if Gnatmake /= No_Package then
3849          Global_Attribute := Prj.Util.Value_Of
3850            (Variable_Name => Name_Global_Configuration_Pragmas,
3851             In_Variables  => Project_Tree.Packages.Table
3852                                (Gnatmake).Decl.Attributes,
3853             In_Tree       => Project_Tree);
3854          Global_Attribute_Present :=
3855            Global_Attribute /= Nil_Variable_Value
3856            and then Get_Name_String (Global_Attribute.Value) /= "";
3857
3858          if Global_Attribute_Present then
3859             declare
3860                Path : constant String :=
3861                         Absolute_Path
3862                           (Path_Name_Type (Global_Attribute.Value),
3863                            Global_Attribute.Project);
3864             begin
3865                if not Is_Regular_File (Path) then
3866                   if Debug.Debug_Flag_F then
3867                      Make_Failed
3868                        ("cannot find configuration pragmas file "
3869                         & File_Name (Path));
3870                   else
3871                      Make_Failed
3872                        ("cannot find configuration pragmas file " & Path);
3873                   end if;
3874                end if;
3875
3876                Last := Last + 1;
3877                Result (Last) := new String'("-gnatec=" &  Path);
3878             end;
3879          end if;
3880       end if;
3881
3882       --  Check for attribute Compiler'Local_Configuration_Pragmas
3883
3884       The_Packages := For_Project.Decl.Packages;
3885       Compiler :=
3886         Prj.Util.Value_Of
3887           (Name        => Name_Compiler,
3888            In_Packages => The_Packages,
3889            In_Tree     => Project_Tree);
3890
3891       if Compiler /= No_Package then
3892          Local_Attribute := Prj.Util.Value_Of
3893            (Variable_Name => Name_Local_Configuration_Pragmas,
3894             In_Variables  => Project_Tree.Packages.Table
3895                                (Compiler).Decl.Attributes,
3896             In_Tree       => Project_Tree);
3897          Local_Attribute_Present :=
3898            Local_Attribute /= Nil_Variable_Value
3899            and then Get_Name_String (Local_Attribute.Value) /= "";
3900
3901          if Local_Attribute_Present then
3902             declare
3903                Path : constant String :=
3904                         Absolute_Path
3905                           (Path_Name_Type (Local_Attribute.Value),
3906                            Local_Attribute.Project);
3907             begin
3908                if not Is_Regular_File (Path) then
3909                   if Debug.Debug_Flag_F then
3910                      Make_Failed
3911                        ("cannot find configuration pragmas file "
3912                         & File_Name (Path));
3913
3914                   else
3915                      Make_Failed
3916                        ("cannot find configuration pragmas file " & Path);
3917                   end if;
3918                end if;
3919
3920                Last := Last + 1;
3921                Result (Last) := new String'("-gnatec=" & Path);
3922             end;
3923          end if;
3924       end if;
3925
3926       return Result (1 .. Last);
3927    end Configuration_Pragmas_Switch;
3928
3929    ---------------
3930    -- Debug_Msg --
3931    ---------------
3932
3933    procedure Debug_Msg (S : String; N : Name_Id) is
3934    begin
3935       if Debug.Debug_Flag_W then
3936          Write_Str ("   ... ");
3937          Write_Str (S);
3938          Write_Str (" ");
3939          Write_Name (N);
3940          Write_Eol;
3941       end if;
3942    end Debug_Msg;
3943
3944    procedure Debug_Msg (S : String; N : File_Name_Type) is
3945    begin
3946       Debug_Msg (S, Name_Id (N));
3947    end Debug_Msg;
3948
3949    procedure Debug_Msg (S : String; N : Unit_Name_Type) is
3950    begin
3951       Debug_Msg (S, Name_Id (N));
3952    end Debug_Msg;
3953
3954    ---------------------------
3955    -- Delete_All_Temp_Files --
3956    ---------------------------
3957
3958    procedure Delete_All_Temp_Files is
3959    begin
3960       if not Debug.Debug_Flag_N then
3961          Delete_Temp_Config_Files;
3962          Prj.Delete_All_Temp_Files (Project_Tree);
3963       end if;
3964    end Delete_All_Temp_Files;
3965
3966    ------------------------------
3967    -- Delete_Temp_Config_Files --
3968    ------------------------------
3969
3970    procedure Delete_Temp_Config_Files is
3971       Success : Boolean;
3972       Proj    : Project_List;
3973       pragma Warnings (Off, Success);
3974
3975    begin
3976       --  The caller is responsible for ensuring that Debug_Flag_N is False
3977
3978       pragma Assert (not Debug.Debug_Flag_N);
3979
3980       if Main_Project /= No_Project then
3981          Proj := Project_Tree.Projects;
3982          while Proj /= null loop
3983             if Proj.Project.Config_File_Temp then
3984                Delete_Temporary_File
3985                  (Project_Tree, Proj.Project.Config_File_Name);
3986
3987                --  Make sure that we don't have a config file for this project,
3988                --  in case there are several mains. In this case, we will
3989                --  recreate another config file: we cannot reuse the one that
3990                --  we just deleted!
3991
3992                Proj.Project.Config_Checked   := False;
3993                Proj.Project.Config_File_Name := No_Path;
3994                Proj.Project.Config_File_Temp := False;
3995             end if;
3996             Proj := Proj.Next;
3997          end loop;
3998       end if;
3999    end Delete_Temp_Config_Files;
4000
4001    -------------
4002    -- Display --
4003    -------------
4004
4005    procedure Display (Program : String; Args : Argument_List) is
4006    begin
4007       pragma Assert (Args'First = 1);
4008
4009       if Display_Executed_Programs then
4010          Write_Str (Program);
4011
4012          for J in Args'Range loop
4013
4014             --  Never display -gnatea nor -gnatez
4015
4016             if Args (J).all /= "-gnatea"
4017                  and then
4018                Args (J).all /= "-gnatez"
4019             then
4020                --  Do not display the mapping file argument automatically
4021                --  created when using a project file.
4022
4023                if Main_Project = No_Project
4024                  or else Debug.Debug_Flag_N
4025                  or else Args (J)'Length < 8
4026                  or else
4027                    Args (J) (Args (J)'First .. Args (J)'First + 6) /= "-gnatem"
4028                then
4029                   --  When -dn is not specified, do not display the config
4030                   --  pragmas switch (-gnatec) for the temporary file created
4031                   --  by the project manager (always the first -gnatec switch).
4032                   --  Reset Temporary_Config_File to False so that the eventual
4033                   --  other -gnatec switches will be displayed.
4034
4035                   if (not Debug.Debug_Flag_N)
4036                     and then Temporary_Config_File
4037                     and then Args (J)'Length > 7
4038                     and then Args (J) (Args (J)'First .. Args (J)'First + 6)
4039                     = "-gnatec"
4040                   then
4041                      Temporary_Config_File := False;
4042
4043                      --  Do not display the -F=mapping_file switch for gnatbind
4044                      --  if -dn is not specified.
4045
4046                   elsif Debug.Debug_Flag_N
4047                     or else Args (J)'Length < 4
4048                     or else
4049                       Args (J) (Args (J)'First .. Args (J)'First + 2) /= "-F="
4050                   then
4051                      Write_Str (" ");
4052
4053                      --  If -df is used, only display file names, not path
4054                      --  names.
4055
4056                      if Debug.Debug_Flag_F then
4057                         declare
4058                            Equal_Pos : Natural;
4059                         begin
4060                            Equal_Pos := Args (J)'First - 1;
4061                            for K in Args (J)'Range loop
4062                               if Args (J) (K) = '=' then
4063                                  Equal_Pos := K;
4064                                  exit;
4065                               end if;
4066                            end loop;
4067
4068                            if Is_Absolute_Path
4069                              (Args (J) (Equal_Pos + 1 .. Args (J)'Last))
4070                            then
4071                               Write_Str
4072                                 (Args (J) (Args (J)'First .. Equal_Pos));
4073                               Write_Str
4074                                 (File_Name
4075                                    (Args (J)
4076                                     (Equal_Pos + 1 .. Args (J)'Last)));
4077
4078                            else
4079                               Write_Str (Args (J).all);
4080                            end if;
4081                         end;
4082
4083                      else
4084                         Write_Str (Args (J).all);
4085                      end if;
4086                   end if;
4087                end if;
4088             end if;
4089          end loop;
4090
4091          Write_Eol;
4092       end if;
4093    end Display;
4094
4095    ----------------------
4096    -- Display_Commands --
4097    ----------------------
4098
4099    procedure Display_Commands (Display : Boolean := True) is
4100    begin
4101       Display_Executed_Programs := Display;
4102    end Display_Commands;
4103
4104    --------------------------
4105    -- Enter_Into_Obsoleted --
4106    --------------------------
4107
4108    procedure Enter_Into_Obsoleted (F : File_Name_Type) is
4109       Name  : constant String := Get_Name_String (F);
4110       First : Natural;
4111       F2    : File_Name_Type;
4112
4113    begin
4114       First := Name'Last;
4115       while First > Name'First
4116         and then Name (First - 1) /= Directory_Separator
4117         and then Name (First - 1) /= '/'
4118       loop
4119          First := First - 1;
4120       end loop;
4121
4122       if First /= Name'First then
4123          Name_Len := 0;
4124          Add_Str_To_Name_Buffer (Name (First .. Name'Last));
4125          F2 := Name_Find;
4126
4127       else
4128          F2 := F;
4129       end if;
4130
4131       Debug_Msg ("New entry in Obsoleted table:", F2);
4132       Obsoleted.Set (F2, True);
4133    end Enter_Into_Obsoleted;
4134
4135    ---------------
4136    -- Globalize --
4137    ---------------
4138
4139    procedure Globalize (Success : out Boolean) is
4140       Quiet_Str       : aliased String := "-quiet";
4141       Globalizer_Args : constant Argument_List :=
4142                           (1 => Quiet_Str'Unchecked_Access);
4143       Previous_Dir    : String_Access;
4144
4145       procedure Globalize_Dir (Dir : String);
4146       --  Call CodePeer globalizer on Dir
4147
4148       -------------------
4149       -- Globalize_Dir --
4150       -------------------
4151
4152       procedure Globalize_Dir (Dir : String) is
4153          Result : Boolean;
4154       begin
4155          if Previous_Dir = null or else Dir /= Previous_Dir.all then
4156             Free (Previous_Dir);
4157             Previous_Dir := new String'(Dir);
4158             Change_Dir (Dir);
4159             GNAT.OS_Lib.Spawn (Globalizer_Path.all, Globalizer_Args, Result);
4160             Success := Success and Result;
4161          end if;
4162       end Globalize_Dir;
4163
4164       procedure Globalize_Dirs is new
4165         Prj.Env.For_All_Object_Dirs (Globalize_Dir);
4166
4167    begin
4168       Success := True;
4169       Display (Globalizer, Globalizer_Args);
4170
4171       if Globalizer_Path = null then
4172          Make_Failed ("error, unable to locate " & Globalizer);
4173       end if;
4174
4175       if Main_Project = No_Project then
4176          GNAT.OS_Lib.Spawn (Globalizer_Path.all, Globalizer_Args, Success);
4177       else
4178          Globalize_Dirs (Main_Project);
4179       end if;
4180    end Globalize;
4181
4182    --------------
4183    -- Gnatmake --
4184    --------------
4185
4186    procedure Gnatmake is
4187       Main_Source_File : File_Name_Type;
4188       --  The source file containing the main compilation unit
4189
4190       Compilation_Failures : Natural;
4191
4192       Total_Compilation_Failures : Natural := 0;
4193
4194       Is_Main_Unit : Boolean;
4195       --  Set True by Compile_Sources if Main_Source_File can be a main unit
4196
4197       Main_ALI_File : File_Name_Type;
4198       --  The ali file corresponding to Main_Source_File
4199
4200       Executable : File_Name_Type := No_File;
4201       --  The file name of an executable
4202
4203       Non_Std_Executable : Boolean := False;
4204       --  Non_Std_Executable is set to True when there is a possibility that
4205       --  the linker will not choose the correct executable file name.
4206
4207       Current_Work_Dir : constant String_Access :=
4208                                     new String'(Get_Current_Dir);
4209       --  The current working directory, used to modify some relative path
4210       --  switches on the command line when a project file is used.
4211
4212       Current_Main_Index : Int := 0;
4213       --  If not zero, the index of the current main unit in its source file
4214
4215       Stand_Alone_Libraries : Boolean := False;
4216       --  Set to True when there are Stand-Alone Libraries, so that gnatbind
4217       --  is invoked with the -F switch to force checking of elaboration flags.
4218
4219       Mapping_Path : Path_Name_Type := No_Path;
4220       --  The path name of the mapping file
4221
4222       Project_Node_Tree : Project_Node_Tree_Ref;
4223
4224       Discard : Boolean;
4225       pragma Warnings (Off, Discard);
4226
4227       procedure Check_Mains;
4228       --  Check that the main subprograms do exist and that they all
4229       --  belong to the same project file.
4230
4231       -----------------
4232       -- Check_Mains --
4233       -----------------
4234
4235       procedure Check_Mains is
4236          Real_Main_Project : Project_Id := No_Project;
4237          --  The project of the first main
4238
4239          Proj              : Project_Id := No_Project;
4240          --  The project of the current main
4241
4242          Real_Path         : String_Access;
4243
4244       begin
4245          Mains.Reset;
4246
4247          --  Check each main
4248
4249          loop
4250             declare
4251                Main      : constant String := Mains.Next_Main;
4252                --  The name specified on the command line may include directory
4253                --  information.
4254
4255                File_Name : constant String := Base_Name (Main);
4256                --  The simple file name of the current main
4257
4258                Lang : Language_Ptr;
4259
4260             begin
4261                exit when Main = "";
4262
4263                --  Get the project of the current main
4264
4265                Proj := Prj.Env.Project_Of
4266                          (File_Name, Main_Project, Project_Tree);
4267
4268                --  Fail if the current main is not a source of a project
4269
4270                if Proj = No_Project then
4271                   Make_Failed
4272                     ("""" & Main & """ is not a source of any project");
4273
4274                else
4275                   --  If there is directory information, check that the source
4276                   --  exists and, if it does, that the path is the actual path
4277                   --  of a source of a project.
4278
4279                   if Main /= File_Name then
4280                      Lang := Get_Language_From_Name (Main_Project, "ada");
4281
4282                      Real_Path :=
4283                        Locate_Regular_File
4284                          (Main & Get_Name_String
4285                               (Lang.Config.Naming_Data.Body_Suffix),
4286                           "");
4287                      if Real_Path = null then
4288                         Real_Path :=
4289                           Locate_Regular_File
4290                             (Main & Get_Name_String
4291                                  (Lang.Config.Naming_Data.Spec_Suffix),
4292                              "");
4293                      end if;
4294
4295                      if Real_Path = null then
4296                         Real_Path := Locate_Regular_File (Main, "");
4297                      end if;
4298
4299                      --  Fail if the file cannot be found
4300
4301                      if Real_Path = null then
4302                         Make_Failed ("file """ & Main & """ does not exist");
4303                      end if;
4304
4305                      declare
4306                         Project_Path : constant String :=
4307                                          Prj.Env.File_Name_Of_Library_Unit_Body
4308                                            (Name              => File_Name,
4309                                             Project           => Main_Project,
4310                                             In_Tree           => Project_Tree,
4311                                             Main_Project_Only => False,
4312                                             Full_Path         => True);
4313                         Normed_Path  : constant String :=
4314                                          Normalize_Pathname
4315                                            (Real_Path.all,
4316                                             Case_Sensitive => False);
4317                         Proj_Path    : constant String :=
4318                                          Normalize_Pathname
4319                                            (Project_Path,
4320                                             Case_Sensitive => False);
4321
4322                      begin
4323                         Free (Real_Path);
4324
4325                         --  Fail if it is not the correct path
4326
4327                         if Normed_Path /= Proj_Path then
4328                            if Verbose_Mode then
4329                               Set_Standard_Error;
4330                               Write_Str (Normed_Path);
4331                               Write_Str (" /= ");
4332                               Write_Line (Proj_Path);
4333                            end if;
4334
4335                            Make_Failed
4336                              ("""" & Main &
4337                               """ is not a source of any project");
4338                         end if;
4339                      end;
4340                   end if;
4341
4342                   if not Unique_Compile then
4343
4344                      --  Record the project, if it is the first main
4345
4346                      if Real_Main_Project = No_Project then
4347                         Real_Main_Project := Proj;
4348
4349                      elsif Proj /= Real_Main_Project then
4350
4351                         --  Fail, as the current main is not a source of the
4352                         --  same project as the first main.
4353
4354                         Make_Failed
4355                           ("""" & Main &
4356                            """ is not a source of project " &
4357                            Get_Name_String (Real_Main_Project.Name));
4358                      end if;
4359                   end if;
4360                end if;
4361
4362                --  If -u and -U are not used, we may have mains that are
4363                --  sources of a project that is not the one specified with
4364                --  switch -P.
4365
4366                if not Unique_Compile then
4367                   Main_Project := Real_Main_Project;
4368                end if;
4369             end;
4370          end loop;
4371       end Check_Mains;
4372
4373    --  Start of processing for Gnatmake
4374
4375    --  This body is very long, should be broken down???
4376
4377    begin
4378       Install_Int_Handler (Sigint_Intercepted'Access);
4379
4380       Do_Compile_Step := True;
4381       Do_Bind_Step    := True;
4382       Do_Link_Step    := True;
4383
4384       Obsoleted.Reset;
4385
4386       Make.Initialize (Project_Node_Tree);
4387
4388       Bind_Shared := No_Shared_Switch'Access;
4389       Link_With_Shared_Libgcc := No_Shared_Libgcc_Switch'Access;
4390
4391       Failed_Links.Set_Last (0);
4392       Successful_Links.Set_Last (0);
4393
4394       --  Special case when switch -B was specified
4395
4396       if Build_Bind_And_Link_Full_Project then
4397
4398          --  When switch -B is specified, there must be a project file
4399
4400          if Main_Project = No_Project then
4401             Make_Failed ("-B cannot be used without a project file");
4402
4403          --  No main program may be specified on the command line
4404
4405          elsif Osint.Number_Of_Files /= 0 then
4406             Make_Failed ("-B cannot be used with a main specified on " &
4407                          "the command line");
4408
4409          --  And the project file cannot be a library project file
4410
4411          elsif Main_Project.Library then
4412             Make_Failed ("-B cannot be used for a library project file");
4413
4414          else
4415             No_Main_Subprogram := True;
4416             Insert_Project_Sources
4417               (The_Project  => Main_Project,
4418                All_Projects => Unique_Compile_All_Projects,
4419                Into_Q       => False);
4420
4421             --  If there are no sources to compile, we fail
4422
4423             if Osint.Number_Of_Files = 0 then
4424                Make_Failed ("no sources to compile");
4425             end if;
4426
4427             --  Specify -n for gnatbind and add the ALI files of all the
4428             --  sources, except the one which is a fake main subprogram: this
4429             --  is the one for the binder generated file and it will be
4430             --  transmitted to gnatlink. These sources are those that are in
4431             --  the queue.
4432
4433             Add_Switch ("-n", Binder, And_Save => True);
4434
4435             for J in 1 .. Queue.Size loop
4436                Add_Switch
4437                  (Get_Name_String
4438                     (Lib_File_Name (Queue.Element (J))),
4439                   Binder, And_Save => True);
4440             end loop;
4441          end if;
4442
4443       elsif Main_Index /= 0 and then Osint.Number_Of_Files > 1 then
4444          Make_Failed ("cannot specify several mains with a multi-unit index");
4445
4446       elsif Main_Project /= No_Project then
4447
4448          --  If the main project file is a library project file, main(s) cannot
4449          --  be specified on the command line.
4450
4451          if Osint.Number_Of_Files /= 0 then
4452             if Main_Project.Library
4453               and then not Unique_Compile
4454               and then ((not Make_Steps) or else Bind_Only or else Link_Only)
4455             then
4456                Make_Failed ("cannot specify a main program " &
4457                             "on the command line for a library project file");
4458
4459             else
4460                --  Check that each main on the command line is a source of a
4461                --  project file and, if there are several mains, each of them
4462                --  is a source of the same project file.
4463
4464                Check_Mains;
4465             end if;
4466
4467          --  If no mains have been specified on the command line, and we are
4468          --  using a project file, we either find the main(s) in attribute Main
4469          --  of the main project, or we put all the sources of the project file
4470          --  as mains.
4471
4472          else
4473             if Main_Index /= 0 then
4474                Make_Failed ("cannot specify a multi-unit index but no main " &
4475                             "on the command line");
4476             end if;
4477
4478             declare
4479                Value : String_List_Id := Main_Project.Mains;
4480
4481             begin
4482                --  The attribute Main is an empty list or not specified, or
4483                --  else gnatmake was invoked with the switch "-u".
4484
4485                if Value = Prj.Nil_String or else Unique_Compile then
4486
4487                   if (not Make_Steps) or else Compile_Only
4488                     or else not Main_Project.Library
4489                   then
4490                      --  First make sure that the binder and the linker will
4491                      --  not be invoked.
4492
4493                      Do_Bind_Step := False;
4494                      Do_Link_Step := False;
4495
4496                      --  Put all the sources in the queue
4497
4498                      No_Main_Subprogram := True;
4499                      Insert_Project_Sources
4500                        (The_Project  => Main_Project,
4501                         All_Projects => Unique_Compile_All_Projects,
4502                         Into_Q       => False);
4503
4504                      --  If no sources to compile, then there is nothing to do
4505
4506                      if Osint.Number_Of_Files = 0 then
4507                         if not Quiet_Output then
4508                            Osint.Write_Program_Name;
4509                            Write_Line (": no sources to compile");
4510                         end if;
4511
4512                         Delete_All_Temp_Files;
4513                         Exit_Program (E_Success);
4514                      end if;
4515                   end if;
4516
4517                else
4518                   --  The attribute Main is not an empty list. Put all the main
4519                   --  subprograms in the list as if they were specified on the
4520                   --  command line. However, if attribute Languages includes a
4521                   --  language other than Ada, only include the Ada mains; if
4522                   --  there is no Ada main, compile all sources of the project.
4523
4524                   declare
4525                      Languages : constant Variable_Value :=
4526                                    Prj.Util.Value_Of
4527                                      (Name_Languages,
4528                                       Main_Project.Decl.Attributes,
4529                                       Project_Tree);
4530
4531                      Current : String_List_Id;
4532                      Element : String_Element;
4533
4534                      Foreign_Language  : Boolean := False;
4535                      At_Least_One_Main : Boolean := False;
4536
4537                   begin
4538                      --  First, determine if there is a foreign language in
4539                      --  attribute Languages.
4540
4541                      if not Languages.Default then
4542                         Current := Languages.Values;
4543                         Look_For_Foreign :
4544                         while Current /= Nil_String loop
4545                            Element := Project_Tree.String_Elements.
4546                                         Table (Current);
4547                            Get_Name_String (Element.Value);
4548                            To_Lower (Name_Buffer (1 .. Name_Len));
4549
4550                            if Name_Buffer (1 .. Name_Len) /= "ada" then
4551                               Foreign_Language := True;
4552                               exit Look_For_Foreign;
4553                            end if;
4554
4555                            Current := Element.Next;
4556                         end loop Look_For_Foreign;
4557                      end if;
4558
4559                      --  Then, find all mains, or if there is a foreign
4560                      --  language, all the Ada mains.
4561
4562                      while Value /= Prj.Nil_String loop
4563                         --  To know if a main is an Ada main, get its project.
4564                         --  It should be the project specified on the command
4565                         --  line.
4566
4567                         Get_Name_String
4568                           (Project_Tree.String_Elements.Table (Value).Value);
4569
4570                         declare
4571                            Main_Name : constant String :=
4572                               Get_Name_String
4573                                (Project_Tree.String_Elements.Table
4574                                     (Value).Value);
4575                            Proj : constant Project_Id :=
4576                              Prj.Env.Project_Of
4577                               (Main_Name, Main_Project, Project_Tree);
4578                         begin
4579
4580                            if Proj = Main_Project then
4581
4582                               At_Least_One_Main := True;
4583                               Osint.Add_File
4584                                 (Get_Name_String
4585                                    (Project_Tree.String_Elements.Table
4586                                       (Value).Value),
4587                                  Index =>
4588                                    Project_Tree.String_Elements.Table
4589                                      (Value).Index);
4590
4591                            elsif not Foreign_Language then
4592                               Make_Failed
4593                                 ("""" & Main_Name &
4594                                  """ is not a source of project " &
4595                                  Get_Name_String (Main_Project.Display_Name));
4596                            end if;
4597                         end;
4598
4599                         Value := Project_Tree.String_Elements.Table
4600                                    (Value).Next;
4601                      end loop;
4602
4603                      --  If we did not get any main, it means that all mains
4604                      --  in attribute Mains are in a foreign language and -B
4605                      --  was not specified to gnatmake; so, we fail.
4606
4607                      if not At_Least_One_Main then
4608                         Make_Failed
4609                           ("no Ada mains, use -B to build foreign main");
4610                      end if;
4611                   end;
4612
4613                end if;
4614             end;
4615          end if;
4616       end if;
4617
4618       if Verbose_Mode then
4619          Write_Eol;
4620          Display_Version ("GNATMAKE", "1995");
4621       end if;
4622
4623       if Osint.Number_Of_Files = 0 then
4624          if Main_Project /= No_Project
4625            and then Main_Project.Library
4626          then
4627             if Do_Bind_Step
4628               and then not Main_Project.Standalone_Library
4629             then
4630                Make_Failed ("only stand-alone libraries may be bound");
4631             end if;
4632
4633             --  Add the default search directories to be able to find libgnat
4634
4635             Osint.Add_Default_Search_Dirs;
4636
4637             --  Get the target parameters, so that the correct binder generated
4638             --  files are generated if OpenVMS is the target.
4639
4640             begin
4641                Targparm.Get_Target_Parameters;
4642
4643             exception
4644                when Unrecoverable_Error =>
4645                   Make_Failed ("*** make failed.");
4646             end;
4647
4648             --  And bind and or link the library
4649
4650             MLib.Prj.Build_Library
4651               (For_Project   => Main_Project,
4652                In_Tree       => Project_Tree,
4653                Gnatbind      => Gnatbind.all,
4654                Gnatbind_Path => Gnatbind_Path,
4655                Gcc           => Gcc.all,
4656                Gcc_Path      => Gcc_Path,
4657                Bind          => Bind_Only,
4658                Link          => Link_Only);
4659
4660             Delete_All_Temp_Files;
4661             Exit_Program (E_Success);
4662
4663          else
4664             --  Call Get_Target_Parameters to ensure that VM_Target and
4665             --  AAMP_On_Target get set before calling Usage.
4666
4667             Targparm.Get_Target_Parameters;
4668
4669             --  Output usage information if no files to compile
4670
4671             Usage;
4672             Exit_Program (E_Fatal);
4673          end if;
4674       end if;
4675
4676       --  If -M was specified, behave as if -n was specified
4677
4678       if List_Dependencies then
4679          Do_Not_Execute := True;
4680       end if;
4681
4682       --  Note that Osint.M.Next_Main_Source will always return the (possibly
4683       --  abbreviated file) without any directory information.
4684
4685       Main_Source_File := Next_Main_Source;
4686
4687       if Current_File_Index /= No_Index then
4688          Main_Index := Current_File_Index;
4689       end if;
4690
4691       Add_Switch ("-I-", Compiler, And_Save => True);
4692
4693       if Main_Project = No_Project then
4694          if Look_In_Primary_Dir then
4695
4696             Add_Switch
4697               ("-I" &
4698                Normalize_Directory_Name
4699                (Get_Primary_Src_Search_Directory.all).all,
4700                Compiler, Append_Switch => False,
4701                And_Save => False);
4702
4703          end if;
4704
4705       else
4706          --  If we use a project file, we have already checked that a main
4707          --  specified on the command line with directory information has the
4708          --  path name corresponding to a correct source in the project tree.
4709          --  So, we don't need the directory information to be taken into
4710          --  account by Find_File, and in fact it may lead to take the wrong
4711          --  sources for other compilation units, when there are extending
4712          --  projects.
4713
4714          Look_In_Primary_Dir := False;
4715          Add_Switch ("-I-", Binder, And_Save => True);
4716       end if;
4717
4718       --  If the user wants a program without a main subprogram, add the
4719       --  appropriate switch to the binder.
4720
4721       if No_Main_Subprogram then
4722          Add_Switch ("-z", Binder, And_Save => True);
4723       end if;
4724
4725       if Main_Project /= No_Project then
4726
4727          if Main_Project.Object_Directory /= No_Path_Information then
4728             --  Change current directory to object directory of main project
4729
4730             Project_Of_Current_Object_Directory := No_Project;
4731             Change_To_Object_Directory (Main_Project);
4732          end if;
4733
4734          --  Source file lookups should be cached for efficiency.
4735          --  Source files are not supposed to change.
4736
4737          Osint.Source_File_Data (Cache => True);
4738
4739          --  Find the file name of the (first) main unit
4740
4741          declare
4742             Main_Source_File_Name : constant String :=
4743                                       Get_Name_String (Main_Source_File);
4744             Main_Unit_File_Name   : constant String :=
4745                                       Prj.Env.File_Name_Of_Library_Unit_Body
4746                                         (Name    => Main_Source_File_Name,
4747                                          Project => Main_Project,
4748                                          In_Tree => Project_Tree,
4749                                          Main_Project_Only =>
4750                                            not Unique_Compile);
4751
4752             The_Packages : constant Package_Id :=
4753                              Main_Project.Decl.Packages;
4754
4755             Builder_Package : constant Prj.Package_Id :=
4756                                 Prj.Util.Value_Of
4757                                   (Name        => Name_Builder,
4758                                    In_Packages => The_Packages,
4759                                    In_Tree     => Project_Tree);
4760
4761             Binder_Package : constant Prj.Package_Id :=
4762                                Prj.Util.Value_Of
4763                                  (Name        => Name_Binder,
4764                                   In_Packages => The_Packages,
4765                                   In_Tree     => Project_Tree);
4766
4767             Linker_Package : constant Prj.Package_Id :=
4768                                Prj.Util.Value_Of
4769                                  (Name        => Name_Linker,
4770                                   In_Packages => The_Packages,
4771                                   In_Tree     => Project_Tree);
4772
4773             Default_Switches_Array : Array_Id;
4774
4775             Global_Compilation_Array    : Array_Element_Id;
4776             Global_Compilation_Elem     : Array_Element;
4777             Global_Compilation_Switches : Variable_Value;
4778
4779          begin
4780             --  We fail if we cannot find the main source file
4781
4782             if Main_Unit_File_Name = "" then
4783                Make_Failed ('"' & Main_Source_File_Name
4784                             & """ is not a unit of project "
4785                             & Project_File_Name.all & ".");
4786             else
4787                --  Remove any directory information from the main source file
4788                --  file name.
4789
4790                declare
4791                   Pos : Natural := Main_Unit_File_Name'Last;
4792
4793                begin
4794                   loop
4795                      exit when Pos < Main_Unit_File_Name'First or else
4796                        Main_Unit_File_Name (Pos) = Directory_Separator;
4797                      Pos := Pos - 1;
4798                   end loop;
4799
4800                   Name_Len := Main_Unit_File_Name'Last - Pos;
4801
4802                   Name_Buffer (1 .. Name_Len) :=
4803                     Main_Unit_File_Name
4804                     (Pos + 1 .. Main_Unit_File_Name'Last);
4805
4806                   Main_Source_File := Name_Find;
4807
4808                   --  We only output the main source file if there is only one
4809
4810                   if Verbose_Mode and then Osint.Number_Of_Files = 1 then
4811                      Write_Str ("Main source file: """);
4812                      Write_Str (Main_Unit_File_Name
4813                                 (Pos + 1 .. Main_Unit_File_Name'Last));
4814                      Write_Line (""".");
4815                   end if;
4816                end;
4817             end if;
4818
4819             --  If there is a package Builder in the main project file, add
4820             --  the switches from it.
4821
4822             if Builder_Package /= No_Package then
4823
4824                Global_Compilation_Array := Prj.Util.Value_Of
4825                  (Name      => Name_Global_Compilation_Switches,
4826                   In_Arrays => Project_Tree.Packages.Table
4827                     (Builder_Package).Decl.Arrays,
4828                   In_Tree   => Project_Tree);
4829
4830                Default_Switches_Array :=
4831                  Project_Tree.Packages.Table
4832                    (Builder_Package).Decl.Arrays;
4833
4834                while Default_Switches_Array /= No_Array and then
4835                Project_Tree.Arrays.Table (Default_Switches_Array).Name /=
4836                  Name_Default_Switches
4837                loop
4838                   Default_Switches_Array :=
4839                     Project_Tree.Arrays.Table (Default_Switches_Array).Next;
4840                end loop;
4841
4842                if Global_Compilation_Array /= No_Array_Element and then
4843                   Default_Switches_Array /= No_Array
4844                then
4845                   Errutil.Error_Msg
4846                     ("Default_Switches forbidden in presence of " &
4847                      "Global_Compilation_Switches. Use Switches instead.",
4848                      Project_Tree.Arrays.Table
4849                        (Default_Switches_Array).Location);
4850                   Errutil.Finalize;
4851                   Make_Failed
4852                     ("*** illegal combination of Builder attributes");
4853                end if;
4854
4855                --  If there is only one main, we attempt to get the gnatmake
4856                --  switches for this main (if any). If there are no specific
4857                --  switch for this particular main, get the general gnatmake
4858                --  switches (if any).
4859
4860                if Osint.Number_Of_Files = 1 then
4861                   if Verbose_Mode then
4862                      Write_Str ("Adding gnatmake switches for """);
4863                      Write_Str (Main_Unit_File_Name);
4864                      Write_Line (""".");
4865                   end if;
4866
4867                   Add_Switches
4868                     (Project_Node_Tree                => Project_Node_Tree,
4869                      File_Name                        => Main_Unit_File_Name,
4870                      Index                            => Main_Index,
4871                      The_Package                      => Builder_Package,
4872                      Program                          => None,
4873                      Unknown_Switches_To_The_Compiler =>
4874                        Global_Compilation_Array = No_Array_Element);
4875
4876                else
4877                   --  If there are several mains, we always get the general
4878                   --  gnatmake switches (if any).
4879
4880                   --  Warn the user, if necessary, so that he is not surprised
4881                   --  that specific switches are not taken into account.
4882
4883                   declare
4884                      Defaults : constant Variable_Value :=
4885                                   Prj.Util.Value_Of
4886                                     (Name                    => Name_Ada,
4887                                      Index                   => 0,
4888                                      Attribute_Or_Array_Name =>
4889                                        Name_Default_Switches,
4890                                      In_Package              =>
4891                                        Builder_Package,
4892                                      In_Tree                 => Project_Tree);
4893
4894                      Switches : constant Array_Element_Id :=
4895                                   Prj.Util.Value_Of
4896                                     (Name      => Name_Switches,
4897                                      In_Arrays =>
4898                                        Project_Tree.Packages.Table
4899                                          (Builder_Package).Decl.Arrays,
4900                                      In_Tree   => Project_Tree);
4901
4902                      Other_Switches : constant Variable_Value :=
4903                                         Prj.Util.Value_Of
4904                                           (Name        => All_Other_Names,
4905                                            Index       => 0,
4906                                            Attribute_Or_Array_Name
4907                                                        => Name_Switches,
4908                                            In_Package  => Builder_Package,
4909                                            In_Tree     => Project_Tree);
4910
4911                   begin
4912                      if Other_Switches /= Nil_Variable_Value then
4913                         if not Quiet_Output
4914                           and then Switches /= No_Array_Element
4915                           and then Project_Tree.Array_Elements.Table
4916                                      (Switches).Next /= No_Array_Element
4917                         then
4918                            Write_Line
4919                              ("Warning: using Builder'Switches(others), "
4920                               & "as there are several mains");
4921                         end if;
4922
4923                         Add_Switches
4924                           (Project_Node_Tree              => Project_Node_Tree,
4925                            File_Name                        => " ",
4926                            Index                            => 0,
4927                            The_Package                      => Builder_Package,
4928                            Program                          => None,
4929                            Unknown_Switches_To_The_Compiler => False);
4930
4931                      elsif Defaults /= Nil_Variable_Value then
4932                         if not Quiet_Output
4933                           and then Switches /= No_Array_Element
4934                         then
4935                            Write_Line
4936                              ("Warning: using Builder'Default_Switches"
4937                               & "(""Ada""), as there are several mains");
4938                         end if;
4939
4940                         Add_Switches
4941                           (Project_Node_Tree => Project_Node_Tree,
4942                            File_Name   => " ",
4943                            Index       => 0,
4944                            The_Package => Builder_Package,
4945                            Program     => None);
4946
4947                      elsif not Quiet_Output
4948                        and then Switches /= No_Array_Element
4949                      then
4950                         Write_Line
4951                           ("Warning: using no switches from package "
4952                            & "Builder, as there are several mains");
4953                      end if;
4954                   end;
4955                end if;
4956
4957                --  Take into account attribute Global_Compilation_Switches
4958                --  ("Ada").
4959
4960                declare
4961                   Index : Name_Id;
4962                   List  : String_List_Id;
4963                   Elem  : String_Element;
4964
4965                begin
4966                   while Global_Compilation_Array /= No_Array_Element loop
4967                      Global_Compilation_Elem :=
4968                        Project_Tree.Array_Elements.Table
4969                          (Global_Compilation_Array);
4970
4971                      Get_Name_String (Global_Compilation_Elem.Index);
4972                      To_Lower (Name_Buffer (1 .. Name_Len));
4973                      Index := Name_Find;
4974
4975                      if Index = Name_Ada then
4976                         Global_Compilation_Switches :=
4977                           Global_Compilation_Elem.Value;
4978
4979                         if Global_Compilation_Switches /= Nil_Variable_Value
4980                           and then not Global_Compilation_Switches.Default
4981                         then
4982                            --  We have found attribute
4983                            --  Global_Compilation_Switches ("Ada"): put the
4984                            --  switches in the appropriate table.
4985
4986                            List := Global_Compilation_Switches.Values;
4987
4988                            while List /= Nil_String loop
4989                               Elem :=
4990                                 Project_Tree.String_Elements.Table (List);
4991
4992                               if Elem.Value /= No_Name then
4993                                  Add_Switch
4994                                    (Get_Name_String (Elem.Value),
4995                                     Compiler,
4996                                     And_Save => False);
4997                               end if;
4998
4999                               List := Elem.Next;
5000                            end loop;
5001
5002                            exit;
5003                         end if;
5004                      end if;
5005
5006                      Global_Compilation_Array := Global_Compilation_Elem.Next;
5007                   end loop;
5008                end;
5009             end if;
5010
5011             Osint.Add_Default_Search_Dirs;
5012
5013             --  Record the current last switch index for table Binder_Switches
5014             --  and Linker_Switches, so that these tables may be reset before
5015             --  for each main, before adding switches from the project file
5016             --  and from the command line.
5017
5018             Last_Binder_Switch := Binder_Switches.Last;
5019             Last_Linker_Switch := Linker_Switches.Last;
5020
5021             Check_Steps;
5022
5023             --  Add binder switches from the project file for the first main
5024
5025             if Do_Bind_Step and then Binder_Package /= No_Package then
5026                if Verbose_Mode then
5027                   Write_Str ("Adding binder switches for """);
5028                   Write_Str (Main_Unit_File_Name);
5029                   Write_Line (""".");
5030                end if;
5031
5032                Add_Switches
5033                  (Project_Node_Tree => Project_Node_Tree,
5034                   File_Name         => Main_Unit_File_Name,
5035                   Index             => Main_Index,
5036                   The_Package       => Binder_Package,
5037                   Program           => Binder);
5038             end if;
5039
5040             --  Add linker switches from the project file for the first main
5041
5042             if Do_Link_Step and then Linker_Package /= No_Package then
5043                if Verbose_Mode then
5044                   Write_Str ("Adding linker switches for""");
5045                   Write_Str (Main_Unit_File_Name);
5046                   Write_Line (""".");
5047                end if;
5048
5049                Add_Switches
5050                  (Project_Node_Tree => Project_Node_Tree,
5051                   File_Name         => Main_Unit_File_Name,
5052                   Index             => Main_Index,
5053                   The_Package       => Linker_Package,
5054                   Program           => Linker);
5055             end if;
5056          end;
5057       end if;
5058
5059       --  The combination of -f -u and one or several mains on the command line
5060       --  implies -a.
5061
5062       if Force_Compilations
5063         and then Unique_Compile
5064         and then not Unique_Compile_All_Projects
5065         and then Main_On_Command_Line
5066       then
5067          Must_Compile := True;
5068       end if;
5069
5070       if Main_Project /= No_Project
5071         and then not Must_Compile
5072         and then Main_Project.Externally_Built
5073       then
5074          Make_Failed
5075            ("nothing to do for a main project that is externally built");
5076       end if;
5077
5078       --  Get the target parameters, which are only needed for a couple of
5079       --  cases in gnatmake. Protect against an exception, such as the case of
5080       --  system.ads missing from the library, and fail gracefully.
5081
5082       begin
5083          Targparm.Get_Target_Parameters;
5084       exception
5085          when Unrecoverable_Error =>
5086             Make_Failed ("*** make failed.");
5087       end;
5088
5089       --  Special processing for VM targets
5090
5091       if Targparm.VM_Target /= No_VM then
5092
5093          --  Set proper processing commands
5094
5095          case Targparm.VM_Target is
5096             when Targparm.JVM_Target =>
5097
5098                --  Do not check for an object file (".o") when compiling to
5099                --  JVM machine since ".class" files are generated instead.
5100
5101                Check_Object_Consistency := False;
5102                Gcc := new String'("jvm-gnatcompile");
5103
5104             when Targparm.CLI_Target =>
5105                Gcc := new String'("dotnet-gnatcompile");
5106
5107             when Targparm.No_VM =>
5108                raise Program_Error;
5109          end case;
5110       end if;
5111
5112       Display_Commands (not Quiet_Output);
5113
5114       Check_Steps;
5115
5116       if Main_Project /= No_Project then
5117
5118          --  For all library project, if the library file does not exist, put
5119          --  all the project sources in the queue, and flag the project so that
5120          --  the library is generated.
5121
5122          if not Unique_Compile
5123            and then MLib.Tgt.Support_For_Libraries /= Prj.None
5124          then
5125             declare
5126                Proj : Project_List;
5127
5128             begin
5129                Proj := Project_Tree.Projects;
5130                while Proj /= null loop
5131                   if Proj.Project.Library then
5132                      Proj.Project.Need_To_Build_Lib :=
5133                        not MLib.Tgt.Library_Exists_For
5134                          (Proj.Project, Project_Tree)
5135                        and then not Proj.Project.Externally_Built;
5136
5137                      if Proj.Project.Need_To_Build_Lib then
5138
5139                         --  If there is no object directory, then it will be
5140                         --  impossible to build the library. So fail
5141                         --  immediately.
5142
5143                         if
5144                           Proj.Project.Object_Directory = No_Path_Information
5145                         then
5146                            Make_Failed
5147                              ("no object files to build library for project """
5148                               & Get_Name_String (Proj.Project.Name)
5149                               & """");
5150                            Proj.Project.Need_To_Build_Lib := False;
5151
5152                         else
5153                            if Verbose_Mode then
5154                               Write_Str
5155                                 ("Library file does not exist for project """);
5156                               Write_Str (Get_Name_String (Proj.Project.Name));
5157                               Write_Line ("""");
5158                            end if;
5159
5160                            Insert_Project_Sources
5161                              (The_Project  => Proj.Project,
5162                               All_Projects => False,
5163                               Into_Q       => True);
5164                         end if;
5165                      end if;
5166                   end if;
5167
5168                   Proj := Proj.Next;
5169                end loop;
5170             end;
5171          end if;
5172
5173          --  If a relative path output file has been specified, we add the
5174          --  exec directory.
5175
5176          for J in reverse 1 .. Saved_Linker_Switches.Last - 1 loop
5177             if Saved_Linker_Switches.Table (J).all = Output_Flag.all then
5178                declare
5179                   Exec_File_Name : constant String :=
5180                                      Saved_Linker_Switches.Table (J + 1).all;
5181
5182                begin
5183                   if not Is_Absolute_Path (Exec_File_Name) then
5184                      Get_Name_String
5185                        (Main_Project.Exec_Directory.Display_Name);
5186
5187                      if not
5188                        Is_Directory_Separator (Name_Buffer (Name_Len))
5189                      then
5190                         Add_Char_To_Name_Buffer (Directory_Separator);
5191                      end if;
5192
5193                      Add_Str_To_Name_Buffer (Exec_File_Name);
5194                      Saved_Linker_Switches.Table (J + 1) :=
5195                        new String'(Name_Buffer (1 .. Name_Len));
5196                   end if;
5197                end;
5198
5199                exit;
5200             end if;
5201          end loop;
5202
5203          --  If we are using a project file, for relative paths we add the
5204          --  current working directory for any relative path on the command
5205          --  line and the project directory, for any relative path in the
5206          --  project file.
5207
5208          declare
5209             Dir_Path : constant String :=
5210                          Get_Name_String (Main_Project.Directory.Display_Name);
5211          begin
5212             for J in 1 .. Binder_Switches.Last loop
5213                Test_If_Relative_Path
5214                  (Binder_Switches.Table (J),
5215                   Parent => Dir_Path, Including_L_Switch => False);
5216             end loop;
5217
5218             for J in 1 .. Saved_Binder_Switches.Last loop
5219                Test_If_Relative_Path
5220                  (Saved_Binder_Switches.Table (J),
5221                   Parent => Current_Work_Dir.all, Including_L_Switch => False);
5222             end loop;
5223
5224             for J in 1 .. Linker_Switches.Last loop
5225                Test_If_Relative_Path
5226                  (Linker_Switches.Table (J), Parent => Dir_Path);
5227             end loop;
5228
5229             for J in 1 .. Saved_Linker_Switches.Last loop
5230                Test_If_Relative_Path
5231                  (Saved_Linker_Switches.Table (J),
5232                   Parent => Current_Work_Dir.all);
5233             end loop;
5234
5235             for J in 1 .. Gcc_Switches.Last loop
5236                Test_If_Relative_Path
5237                  (Gcc_Switches.Table (J),
5238                   Parent               => Dir_Path,
5239                   Including_Non_Switch => False);
5240             end loop;
5241
5242             for J in 1 .. Saved_Gcc_Switches.Last loop
5243                Test_If_Relative_Path
5244                  (Saved_Gcc_Switches.Table (J),
5245                   Parent               => Current_Work_Dir.all,
5246                   Including_Non_Switch => False);
5247             end loop;
5248          end;
5249       end if;
5250
5251       --  We now put in the Binder_Switches and Linker_Switches tables, the
5252       --  binder and linker switches of the command line that have been put in
5253       --  the Saved_ tables. If a project file was used, then the command line
5254       --  switches will follow the project file switches.
5255
5256       for J in 1 .. Saved_Binder_Switches.Last loop
5257          Add_Switch
5258            (Saved_Binder_Switches.Table (J),
5259             Binder,
5260             And_Save => False);
5261       end loop;
5262
5263       for J in 1 .. Saved_Linker_Switches.Last loop
5264          Add_Switch
5265            (Saved_Linker_Switches.Table (J),
5266             Linker,
5267             And_Save => False);
5268       end loop;
5269
5270       --  If no project file is used, we just put the gcc switches
5271       --  from the command line in the Gcc_Switches table.
5272
5273       if Main_Project = No_Project then
5274          for J in 1 .. Saved_Gcc_Switches.Last loop
5275             Add_Switch
5276               (Saved_Gcc_Switches.Table (J), Compiler, And_Save => False);
5277          end loop;
5278
5279       else
5280          --  If there is a project, put the command line gcc switches in the
5281          --  variable The_Saved_Gcc_Switches. They are going to be used later
5282          --  in procedure Compile_Sources.
5283
5284          The_Saved_Gcc_Switches :=
5285            new Argument_List (1 .. Saved_Gcc_Switches.Last + 1);
5286
5287          for J in 1 .. Saved_Gcc_Switches.Last loop
5288             The_Saved_Gcc_Switches (J) := Saved_Gcc_Switches.Table (J);
5289          end loop;
5290
5291          --  We never use gnat.adc when a project file is used
5292
5293          The_Saved_Gcc_Switches (The_Saved_Gcc_Switches'Last) := No_gnat_adc;
5294       end if;
5295
5296       --  If there was a --GCC, --GNATBIND or --GNATLINK switch on the command
5297       --  line, then we have to use it, even if there was another switch in
5298       --  the project file.
5299
5300       if Saved_Gcc /= null then
5301          Gcc := Saved_Gcc;
5302       end if;
5303
5304       if Saved_Gnatbind /= null then
5305          Gnatbind := Saved_Gnatbind;
5306       end if;
5307
5308       if Saved_Gnatlink /= null then
5309          Gnatlink := Saved_Gnatlink;
5310       end if;
5311
5312       Gcc_Path       := GNAT.OS_Lib.Locate_Exec_On_Path (Gcc.all);
5313       Gnatbind_Path  := GNAT.OS_Lib.Locate_Exec_On_Path (Gnatbind.all);
5314       Gnatlink_Path  := GNAT.OS_Lib.Locate_Exec_On_Path (Gnatlink.all);
5315
5316       --  If we have specified -j switch both from the project file
5317       --  and on the command line, the one from the command line takes
5318       --  precedence.
5319
5320       if Saved_Maximum_Processes = 0 then
5321          Saved_Maximum_Processes := Maximum_Processes;
5322       end if;
5323
5324       if Debug.Debug_Flag_M then
5325          Write_Line ("Maximum number of simultaneous compilations =" &
5326                      Saved_Maximum_Processes'Img);
5327       end if;
5328
5329       --  Allocate as many temporary mapping file names as the maximum number
5330       --  of compilations processed, for each possible project.
5331
5332       declare
5333          Data : Project_Compilation_Access;
5334          Proj : Project_List := Project_Tree.Projects;
5335       begin
5336          while Proj /= null loop
5337             Data := new Project_Compilation_Data'
5338               (Mapping_File_Names        => new Temp_Path_Names
5339                                               (1 .. Saved_Maximum_Processes),
5340                Last_Mapping_File_Names   => 0,
5341                Free_Mapping_File_Indexes => new Free_File_Indexes
5342                                               (1 .. Saved_Maximum_Processes),
5343                Last_Free_Indexes         => 0);
5344
5345             Project_Compilation_Htable.Set
5346               (Project_Compilation, Proj.Project, Data);
5347             Proj := Proj.Next;
5348          end loop;
5349
5350          Data := new Project_Compilation_Data'
5351            (Mapping_File_Names        => new Temp_Path_Names
5352                                            (1 .. Saved_Maximum_Processes),
5353             Last_Mapping_File_Names   => 0,
5354             Free_Mapping_File_Indexes => new Free_File_Indexes
5355                                            (1 .. Saved_Maximum_Processes),
5356             Last_Free_Indexes         => 0);
5357
5358          Project_Compilation_Htable.Set
5359            (Project_Compilation, No_Project, Data);
5360       end;
5361
5362       Bad_Compilation.Init;
5363
5364       --  If project files are used, create the mapping of all the sources, so
5365       --  that the correct paths will be found. Otherwise, if there is a file
5366       --  which is not a source with the same name in a source directory this
5367       --  file may be incorrectly found.
5368
5369       if Main_Project /= No_Project then
5370          Prj.Env.Create_Mapping (Project_Tree);
5371       end if;
5372
5373       Current_Main_Index := Main_Index;
5374
5375       --  Here is where the make process is started
5376
5377       --  We do the same process for each main
5378
5379       Multiple_Main_Loop : for N_File in 1 .. Osint.Number_Of_Files loop
5380
5381          --  First, find the executable name and path
5382
5383          Executable          := No_File;
5384          Executable_Obsolete := False;
5385          Non_Std_Executable  :=
5386            Targparm.Executable_Extension_On_Target /= No_Name;
5387
5388          --  Look inside the linker switches to see if the name of the final
5389          --  executable program was specified.
5390
5391          for J in reverse Linker_Switches.First .. Linker_Switches.Last loop
5392             if Linker_Switches.Table (J).all = Output_Flag.all then
5393                pragma Assert (J < Linker_Switches.Last);
5394
5395                --  We cannot specify a single executable for several main
5396                --  subprograms
5397
5398                if Osint.Number_Of_Files > 1 then
5399                   Fail
5400                     ("cannot specify a single executable for several mains");
5401                end if;
5402
5403                Name_Len := 0;
5404                Add_Str_To_Name_Buffer (Linker_Switches.Table (J + 1).all);
5405                Executable := Name_Enter;
5406
5407                Verbose_Msg (Executable, "final executable");
5408             end if;
5409          end loop;
5410
5411          --  If the name of the final executable program was not specified then
5412          --  construct it from the main input file.
5413
5414          if Executable = No_File then
5415             if Main_Project = No_Project then
5416                Executable := Executable_Name (Strip_Suffix (Main_Source_File));
5417
5418             else
5419                --  If we are using a project file, we attempt to remove the
5420                --  body (or spec) termination of the main subprogram. We find
5421                --  it the naming scheme of the project file. This avoids
5422                --  generating an executable "main.2" for a main subprogram
5423                --  "main.2.ada", when the body termination is ".2.ada".
5424
5425                Executable :=
5426                  Prj.Util.Executable_Of
5427                    (Main_Project, Project_Tree, Main_Source_File, Main_Index);
5428             end if;
5429          end if;
5430
5431          if Main_Project /= No_Project
5432            and then Main_Project.Exec_Directory /= No_Path_Information
5433          then
5434             declare
5435                Exec_File_Name : constant String :=
5436                                   Get_Name_String (Executable);
5437
5438             begin
5439                if not Is_Absolute_Path (Exec_File_Name) then
5440                   Get_Name_String (Main_Project.Exec_Directory.Display_Name);
5441
5442                   if Name_Buffer (Name_Len) /= Directory_Separator then
5443                      Add_Char_To_Name_Buffer (Directory_Separator);
5444                   end if;
5445
5446                   Add_Str_To_Name_Buffer (Exec_File_Name);
5447                   Executable := Name_Find;
5448                end if;
5449
5450                Non_Std_Executable := True;
5451             end;
5452          end if;
5453
5454          if Do_Compile_Step then
5455             Recursive_Compilation_Step : declare
5456                Args                : Argument_List (1 .. Gcc_Switches.Last);
5457
5458                First_Compiled_File : File_Name_Type;
5459                Youngest_Obj_File   : File_Name_Type;
5460                Youngest_Obj_Stamp  : Time_Stamp_Type;
5461
5462                Executable_Stamp : Time_Stamp_Type;
5463                --  Executable is the final executable program
5464                --  ??? comment seems unrelated to declaration
5465
5466                Library_Rebuilt : Boolean := False;
5467
5468             begin
5469                for J in 1 .. Gcc_Switches.Last loop
5470                   Args (J) := Gcc_Switches.Table (J);
5471                end loop;
5472
5473                Queue.Initialize
5474                        (Main_Project /= No_Project and then
5475                         One_Compilation_Per_Obj_Dir);
5476
5477                --  Now we invoke Compile_Sources for the current main
5478
5479                Compile_Sources
5480                  (Main_Source           => Main_Source_File,
5481                   Args                  => Args,
5482                   First_Compiled_File   => First_Compiled_File,
5483                   Most_Recent_Obj_File  => Youngest_Obj_File,
5484                   Most_Recent_Obj_Stamp => Youngest_Obj_Stamp,
5485                   Main_Unit             => Is_Main_Unit,
5486                   Main_Index            => Current_Main_Index,
5487                   Compilation_Failures  => Compilation_Failures,
5488                   Check_Readonly_Files  => Check_Readonly_Files,
5489                   Do_Not_Execute        => Do_Not_Execute,
5490                   Force_Compilations    => Force_Compilations,
5491                   In_Place_Mode         => In_Place_Mode,
5492                   Keep_Going            => Keep_Going,
5493                   Initialize_ALI_Data   => True,
5494                   Max_Process           => Saved_Maximum_Processes);
5495
5496                if Verbose_Mode then
5497                   Write_Str ("End of compilation");
5498                   Write_Eol;
5499                end if;
5500
5501                Total_Compilation_Failures :=
5502                  Total_Compilation_Failures + Compilation_Failures;
5503
5504                if Total_Compilation_Failures /= 0 then
5505                   if Keep_Going then
5506                      goto Next_Main;
5507
5508                   else
5509                      List_Bad_Compilations;
5510                      Report_Compilation_Failed;
5511                   end if;
5512                end if;
5513
5514                --  Regenerate libraries, if there are any and if object files
5515                --  have been regenerated.
5516
5517                if Main_Project /= No_Project
5518                  and then MLib.Tgt.Support_For_Libraries /= Prj.None
5519                  and then (Do_Bind_Step
5520                              or Unique_Compile_All_Projects
5521                              or not Compile_Only)
5522                  and then (Do_Link_Step or else N_File = Osint.Number_Of_Files)
5523                then
5524                   Library_Projs.Init;
5525
5526                   declare
5527                      Depth   : Natural;
5528                      Current : Natural;
5529                      Proj1   : Project_List;
5530
5531                      procedure Add_To_Library_Projs (Proj : Project_Id);
5532                      --  Add project Project to table Library_Projs in
5533                      --  decreasing depth order.
5534
5535                      --------------------------
5536                      -- Add_To_Library_Projs --
5537                      --------------------------
5538
5539                      procedure Add_To_Library_Projs (Proj : Project_Id) is
5540                         Prj : Project_Id;
5541
5542                      begin
5543                         Library_Projs.Increment_Last;
5544                         Depth := Proj.Depth;
5545
5546                         --  Put the projects in decreasing depth order, so that
5547                         --  if libA depends on libB, libB is first in order.
5548
5549                         Current := Library_Projs.Last;
5550                         while Current > 1 loop
5551                            Prj := Library_Projs.Table (Current - 1);
5552                            exit when Prj.Depth >= Depth;
5553                            Library_Projs.Table (Current) := Prj;
5554                            Current := Current - 1;
5555                         end loop;
5556
5557                         Library_Projs.Table (Current) := Proj;
5558                      end Add_To_Library_Projs;
5559
5560                   --  Start of processing for ??? (should name declare block
5561                   --  or probably better, break this out as a nested proc).
5562
5563                   begin
5564                      --  Put in Library_Projs table all library project file
5565                      --  ids when the library need to be rebuilt.
5566
5567                      Proj1 := Project_Tree.Projects;
5568                      while Proj1 /= null loop
5569                         if Proj1.Project.Standalone_Library then
5570                            Stand_Alone_Libraries := True;
5571                         end if;
5572
5573                         if Proj1.Project.Library then
5574                            MLib.Prj.Check_Library
5575                              (Proj1.Project, Project_Tree);
5576                         end if;
5577
5578                         if Proj1.Project.Need_To_Build_Lib then
5579                            Add_To_Library_Projs (Proj1.Project);
5580                         end if;
5581
5582                         Proj1 := Proj1.Next;
5583                      end loop;
5584
5585                      --  Check if importing libraries should be regenerated
5586                      --  because at least an imported library will be
5587                      --  regenerated or is more recent.
5588
5589                      Proj1 := Project_Tree.Projects;
5590                      while Proj1 /= null loop
5591                         if Proj1.Project.Library
5592                           and then Proj1.Project.Library_Kind /= Static
5593                           and then not Proj1.Project.Need_To_Build_Lib
5594                           and then not Proj1.Project.Externally_Built
5595                         then
5596                            declare
5597                               List    : Project_List;
5598                               Proj2   : Project_Id;
5599                               Rebuild : Boolean := False;
5600
5601                               Lib_Timestamp1 : constant Time_Stamp_Type :=
5602                                                  Proj1.Project.Library_TS;
5603
5604                            begin
5605                               List := Proj1.Project.All_Imported_Projects;
5606                               while List /= null loop
5607                                  Proj2 := List.Project;
5608
5609                                  if Proj2.Library then
5610                                     if Proj2.Need_To_Build_Lib
5611                                       or else
5612                                         (Lib_Timestamp1 < Proj2.Library_TS)
5613                                     then
5614                                        Rebuild := True;
5615                                        exit;
5616                                     end if;
5617                                  end if;
5618
5619                                  List := List.Next;
5620                               end loop;
5621
5622                               if Rebuild then
5623                                  Proj1.Project.Need_To_Build_Lib := True;
5624                                  Add_To_Library_Projs (Proj1.Project);
5625                               end if;
5626                            end;
5627                         end if;
5628
5629                         Proj1 := Proj1.Next;
5630                      end loop;
5631
5632                      --  Reset the flags Need_To_Build_Lib for the next main,
5633                      --  to avoid rebuilding libraries uselessly.
5634
5635                      Proj1 := Project_Tree.Projects;
5636                      while Proj1 /= null loop
5637                         Proj1.Project.Need_To_Build_Lib := False;
5638                         Proj1 := Proj1.Next;
5639                      end loop;
5640                   end;
5641
5642                   --  Build the libraries, if any need to be built
5643
5644                   for J in 1 .. Library_Projs.Last loop
5645                      Library_Rebuilt := True;
5646
5647                      --  If a library is rebuilt, then executables are obsolete
5648
5649                      Executable_Obsolete := True;
5650
5651                      MLib.Prj.Build_Library
5652                        (For_Project   => Library_Projs.Table (J),
5653                         In_Tree       => Project_Tree,
5654                         Gnatbind      => Gnatbind.all,
5655                         Gnatbind_Path => Gnatbind_Path,
5656                         Gcc           => Gcc.all,
5657                         Gcc_Path      => Gcc_Path);
5658                   end loop;
5659                end if;
5660
5661                if List_Dependencies then
5662                   if First_Compiled_File /= No_File then
5663                      Inform
5664                        (First_Compiled_File,
5665                         "must be recompiled. Can't generate dependence list.");
5666                   else
5667                      List_Depend;
5668                   end if;
5669
5670                elsif First_Compiled_File = No_File
5671                  and then not Do_Bind_Step
5672                  and then not Quiet_Output
5673                  and then not Library_Rebuilt
5674                  and then Osint.Number_Of_Files = 1
5675                then
5676                   Inform (Msg => "objects up to date.");
5677
5678                elsif Do_Not_Execute
5679                  and then First_Compiled_File /= No_File
5680                then
5681                   Write_Name (First_Compiled_File);
5682                   Write_Eol;
5683                end if;
5684
5685                --  Stop after compile step if any of:
5686
5687                --    1) -n (Do_Not_Execute) specified
5688
5689                --    2) -M (List_Dependencies) specified (also sets
5690                --       Do_Not_Execute above, so this is probably superfluous).
5691
5692                --    3) -c (Compile_Only) specified, but not -b (Bind_Only)
5693
5694                --    4) Made unit cannot be a main unit
5695
5696                if ((Do_Not_Execute
5697                     or List_Dependencies
5698                     or not Do_Bind_Step
5699                     or not Is_Main_Unit)
5700                   and then not No_Main_Subprogram
5701                   and then not Build_Bind_And_Link_Full_Project)
5702                  or else Unique_Compile
5703                then
5704                   if Osint.Number_Of_Files = 1 then
5705                      exit Multiple_Main_Loop;
5706
5707                   else
5708                      goto Next_Main;
5709                   end if;
5710                end if;
5711
5712                --  If the objects were up-to-date check if the executable file
5713                --  is also up-to-date. For now always bind and link on the JVM
5714                --  since there is currently no simple way to check whether
5715                --  objects are up-to-date.
5716
5717                if Targparm.VM_Target /= JVM_Target
5718                  and then First_Compiled_File = No_File
5719                then
5720                   Executable_Stamp := File_Stamp (Executable);
5721
5722                   if not Executable_Obsolete then
5723                      Executable_Obsolete :=
5724                        Youngest_Obj_Stamp > Executable_Stamp;
5725                   end if;
5726
5727                   if not Executable_Obsolete then
5728                      for Index in reverse 1 .. Dependencies.Last loop
5729                         if Is_In_Obsoleted
5730                              (Dependencies.Table (Index).Depends_On)
5731                         then
5732                            Enter_Into_Obsoleted
5733                              (Dependencies.Table (Index).This);
5734                         end if;
5735                      end loop;
5736
5737                      Executable_Obsolete := Is_In_Obsoleted (Main_Source_File);
5738                      Dependencies.Init;
5739                   end if;
5740
5741                   if not Executable_Obsolete then
5742
5743                      --  If no Ada object files obsolete the executable, check
5744                      --  for younger or missing linker files.
5745
5746                      Check_Linker_Options
5747                        (Executable_Stamp,
5748                         Youngest_Obj_File,
5749                         Youngest_Obj_Stamp);
5750
5751                      Executable_Obsolete := Youngest_Obj_File /= No_File;
5752                   end if;
5753
5754                   --  Check if any library file is more recent than the
5755                   --  executable: there may be an externally built library
5756                   --  file that has been modified.
5757
5758                   if not Executable_Obsolete
5759                     and then Main_Project /= No_Project
5760                   then
5761                      declare
5762                         Proj1 : Project_List;
5763
5764                      begin
5765                         Proj1 := Project_Tree.Projects;
5766                         while Proj1 /= null loop
5767                            if Proj1.Project.Library
5768                              and then
5769                                Proj1.Project.Library_TS > Executable_Stamp
5770                            then
5771                               Executable_Obsolete := True;
5772                               Youngest_Obj_Stamp := Proj1.Project.Library_TS;
5773                               Name_Len := 0;
5774                               Add_Str_To_Name_Buffer ("library ");
5775                               Add_Str_To_Name_Buffer
5776                                 (Get_Name_String (Proj1.Project.Library_Name));
5777                               Youngest_Obj_File := Name_Find;
5778                               exit;
5779                            end if;
5780
5781                            Proj1 := Proj1.Next;
5782                         end loop;
5783                      end;
5784                   end if;
5785
5786                   --  Return if the executable is up to date and otherwise
5787                   --  motivate the relink/rebind.
5788
5789                   if not Executable_Obsolete then
5790                      if not Quiet_Output then
5791                         Inform (Executable, "up to date.");
5792                      end if;
5793
5794                      if Osint.Number_Of_Files = 1 then
5795                         exit Multiple_Main_Loop;
5796
5797                      else
5798                         goto Next_Main;
5799                      end if;
5800                   end if;
5801
5802                   if Executable_Stamp (1) = ' ' then
5803                      if not No_Main_Subprogram then
5804                         Verbose_Msg (Executable, "missing.", Prefix => "  ");
5805                      end if;
5806
5807                   elsif Youngest_Obj_Stamp (1) = ' ' then
5808                      Verbose_Msg
5809                        (Youngest_Obj_File, "missing.",  Prefix => "  ");
5810
5811                   elsif Youngest_Obj_Stamp > Executable_Stamp then
5812                      Verbose_Msg
5813                        (Youngest_Obj_File,
5814                         "(" & String (Youngest_Obj_Stamp) & ") newer than",
5815                         Executable,
5816                         "(" & String (Executable_Stamp) & ")");
5817
5818                   else
5819                      Verbose_Msg
5820                        (Executable, "needs to be rebuilt", Prefix => "  ");
5821
5822                   end if;
5823                end if;
5824             end Recursive_Compilation_Step;
5825          end if;
5826
5827          --  For binding and linking, we need to be in the object directory of
5828          --  the main project.
5829
5830          if Main_Project /= No_Project then
5831             Change_To_Object_Directory (Main_Project);
5832          end if;
5833
5834          --  If we are here, it means that we need to rebuilt the current main,
5835          --  so we set Executable_Obsolete to True to make sure that subsequent
5836          --  mains will be rebuilt.
5837
5838          Main_ALI_In_Place_Mode_Step : declare
5839             ALI_File : File_Name_Type;
5840             Src_File : File_Name_Type;
5841
5842          begin
5843             Src_File      := Strip_Directory (Main_Source_File);
5844             ALI_File      := Lib_File_Name (Src_File, Current_Main_Index);
5845             Main_ALI_File := Full_Lib_File_Name (ALI_File);
5846
5847             --  When In_Place_Mode, the library file can be located in the
5848             --  Main_Source_File directory which may not be present in the
5849             --  library path. If it is not present then use the corresponding
5850             --  library file name.
5851
5852             if Main_ALI_File = No_File and then In_Place_Mode then
5853                Get_Name_String (Get_Directory (Full_Source_Name (Src_File)));
5854                Get_Name_String_And_Append (ALI_File);
5855                Main_ALI_File := Name_Find;
5856                Main_ALI_File := Full_Lib_File_Name (Main_ALI_File);
5857             end if;
5858
5859             if Main_ALI_File = No_File then
5860                Make_Failed ("could not find the main ALI file");
5861             end if;
5862          end Main_ALI_In_Place_Mode_Step;
5863
5864          if Do_Bind_Step then
5865             Bind_Step : declare
5866                Args : Argument_List
5867                         (Binder_Switches.First .. Binder_Switches.Last + 2);
5868                --  The arguments for the invocation of gnatbind
5869
5870                Last_Arg : Natural := Binder_Switches.Last;
5871                --  Index of the last argument in Args
5872
5873                Shared_Libs : Boolean := False;
5874                --  Set to True when there are shared library project files or
5875                --  when gnatbind is invoked with -shared.
5876
5877                Proj : Project_List;
5878
5879             begin
5880                --  Check if there are shared libraries, so that gnatbind is
5881                --  called with -shared. Check also if gnatbind is called with
5882                --  -shared, so that gnatlink is called with -shared-libgcc
5883                --  ensuring that the shared version of libgcc will be used.
5884
5885                if Main_Project /= No_Project
5886                  and then MLib.Tgt.Support_For_Libraries /= Prj.None
5887                then
5888                   Proj := Project_Tree.Projects;
5889                   while Proj /= null loop
5890                      if Proj.Project.Library
5891                        and then Proj.Project.Library_Kind /= Static
5892                      then
5893                         Shared_Libs := True;
5894                         Bind_Shared := Shared_Switch'Access;
5895                         exit;
5896                      end if;
5897                      Proj := Proj.Next;
5898                   end loop;
5899                end if;
5900
5901                --  Check now for switch -shared
5902
5903                if not Shared_Libs then
5904                   for J in Binder_Switches.First .. Last_Arg loop
5905                      if Binder_Switches.Table (J).all = "-shared" then
5906                         Shared_Libs := True;
5907                         exit;
5908                      end if;
5909                   end loop;
5910                end if;
5911
5912                --  If shared libraries present, invoke gnatlink with
5913                --  -shared-libgcc.
5914
5915                if Shared_Libs then
5916                   Link_With_Shared_Libgcc := Shared_Libgcc_Switch'Access;
5917                end if;
5918
5919                --  Get all the binder switches
5920
5921                for J in Binder_Switches.First .. Last_Arg loop
5922                   Args (J) := Binder_Switches.Table (J);
5923                end loop;
5924
5925                if Stand_Alone_Libraries then
5926                   Last_Arg := Last_Arg + 1;
5927                   Args (Last_Arg) := Force_Elab_Flags_String'Access;
5928                end if;
5929
5930                if Main_Project /= No_Project then
5931
5932                   --  Put all the source directories in ADA_INCLUDE_PATH,
5933                   --  and all the object directories in ADA_OBJECTS_PATH,
5934                   --  except those of library projects.
5935
5936                   Prj.Env.Set_Ada_Paths
5937                     (Main_Project, Project_Tree, Use_Include_Path_File);
5938
5939                   --  If switch -C was specified, create a binder mapping file
5940
5941                   if Create_Mapping_File then
5942                      Mapping_Path := Create_Binder_Mapping_File;
5943
5944                      if Mapping_Path /= No_Path then
5945                         Last_Arg := Last_Arg + 1;
5946                         Args (Last_Arg) :=
5947                           new String'("-F=" & Get_Name_String (Mapping_Path));
5948                      end if;
5949                   end if;
5950
5951                end if;
5952
5953                begin
5954                   Bind (Main_ALI_File,
5955                         Bind_Shared.all & Args (Args'First .. Last_Arg));
5956
5957                exception
5958                   when others =>
5959
5960                      --  Delete the temporary mapping file if one was created
5961
5962                      if Mapping_Path /= No_Path then
5963                         Delete_Temporary_File (Project_Tree, Mapping_Path);
5964                      end if;
5965
5966                      --  And reraise the exception
5967
5968                      raise;
5969                end;
5970
5971                --  If -dn was not specified, delete the temporary mapping file
5972                --  if one was created.
5973
5974                if Mapping_Path /= No_Path then
5975                   Delete_Temporary_File (Project_Tree, Mapping_Path);
5976                end if;
5977             end Bind_Step;
5978          end if;
5979
5980          if Do_Link_Step then
5981             Link_Step : declare
5982                Linker_Switches_Last : constant Integer := Linker_Switches.Last;
5983                Path_Option          : constant String_Access :=
5984                                         MLib.Linker_Library_Path_Option;
5985                Libraries_Present    : Boolean := False;
5986                Current              : Natural;
5987                Proj2                : Project_Id;
5988                Depth                : Natural;
5989                Proj1                : Project_List;
5990
5991             begin
5992                if not Run_Path_Option then
5993                   Linker_Switches.Increment_Last;
5994                   Linker_Switches.Table (Linker_Switches.Last) :=
5995                     new String'("-R");
5996                end if;
5997
5998                if Main_Project /= No_Project then
5999                   Library_Paths.Set_Last (0);
6000                   Library_Projs.Init;
6001
6002                   if MLib.Tgt.Support_For_Libraries /= Prj.None then
6003
6004                      --  Check for library projects
6005
6006                      Proj1 := Project_Tree.Projects;
6007                      while Proj1 /= null loop
6008                         if Proj1.Project /= Main_Project
6009                           and then Proj1.Project.Library
6010                         then
6011                            --  Add this project to table Library_Projs
6012
6013                            Libraries_Present := True;
6014                            Depth := Proj1.Project.Depth;
6015                            Library_Projs.Increment_Last;
6016                            Current := Library_Projs.Last;
6017
6018                            --  Any project with a greater depth should be
6019                            --  after this project in the list.
6020
6021                            while Current > 1 loop
6022                               Proj2 := Library_Projs.Table (Current - 1);
6023                               exit when Proj2.Depth <= Depth;
6024                               Library_Projs.Table (Current) := Proj2;
6025                               Current := Current - 1;
6026                            end loop;
6027
6028                            Library_Projs.Table (Current) := Proj1.Project;
6029
6030                            --  If it is not a static library and path option
6031                            --  is set, add it to the Library_Paths table.
6032
6033                            if Proj1.Project.Library_Kind /= Static
6034                              and then Path_Option /= null
6035                            then
6036                               Library_Paths.Increment_Last;
6037                               Library_Paths.Table (Library_Paths.Last) :=
6038                                 new String'
6039                                   (Get_Name_String
6040                                      (Proj1.Project.Library_Dir.Display_Name));
6041                            end if;
6042                         end if;
6043
6044                         Proj1 := Proj1.Next;
6045                      end loop;
6046
6047                      for Index in 1 .. Library_Projs.Last loop
6048
6049                         --  Add the -L switch
6050
6051                         Linker_Switches.Increment_Last;
6052                         Linker_Switches.Table (Linker_Switches.Last) :=
6053                           new String'("-L" &
6054                                       Get_Name_String
6055                                         (Library_Projs.Table (Index).
6056                                             Library_Dir.Display_Name));
6057
6058                         --  Add the -l switch
6059
6060                         Linker_Switches.Increment_Last;
6061                         Linker_Switches.Table (Linker_Switches.Last) :=
6062                           new String'("-l" &
6063                                       Get_Name_String
6064                                         (Library_Projs.Table (Index).
6065                                            Library_Name));
6066                      end loop;
6067                   end if;
6068
6069                   if Libraries_Present then
6070
6071                      --  If Path_Option is not null, create the switch
6072                      --  ("-Wl,-rpath," or equivalent) with all the non static
6073                      --  library dirs plus the standard GNAT library dir.
6074                      --  We do that only if Run_Path_Option is True
6075                      --  (not disabled by -R switch).
6076
6077                      if Run_Path_Option and then Path_Option /= null then
6078                         declare
6079                            Option  : String_Access;
6080                            Length  : Natural := Path_Option'Length;
6081                            Current : Natural;
6082
6083                         begin
6084                            if MLib.Separate_Run_Path_Options then
6085
6086                               --  We are going to create one switch of the form
6087                               --  "-Wl,-rpath,dir_N" for each directory to
6088                               --  consider.
6089
6090                               --  One switch for each library directory
6091
6092                               for Index in
6093                                 Library_Paths.First .. Library_Paths.Last
6094                               loop
6095                                  Linker_Switches.Increment_Last;
6096                                  Linker_Switches.Table
6097                                    (Linker_Switches.Last) := new String'
6098                                    (Path_Option.all &
6099                                     Library_Paths.Table (Index).all);
6100                               end loop;
6101
6102                               --  One switch for the standard GNAT library dir
6103
6104                               Linker_Switches.Increment_Last;
6105                               Linker_Switches.Table
6106                                 (Linker_Switches.Last) := new String'
6107                                 (Path_Option.all & MLib.Utl.Lib_Directory);
6108
6109                            else
6110                               --  We are going to create one switch of the form
6111                               --  "-Wl,-rpath,dir_1:dir_2:dir_3"
6112
6113                               for Index in
6114                                 Library_Paths.First .. Library_Paths.Last
6115                               loop
6116                                  --  Add the length of the library dir plus one
6117                                  --  for the directory separator.
6118
6119                                  Length :=
6120                                    Length +
6121                                      Library_Paths.Table (Index)'Length + 1;
6122                               end loop;
6123
6124                               --  Finally, add the length of the standard GNAT
6125                               --  library dir.
6126
6127                               Length := Length + MLib.Utl.Lib_Directory'Length;
6128                               Option := new String (1 .. Length);
6129                               Option (1 .. Path_Option'Length) :=
6130                                 Path_Option.all;
6131                               Current := Path_Option'Length;
6132
6133                               --  Put each library dir followed by a dir
6134                               --  separator.
6135
6136                               for Index in
6137                                 Library_Paths.First .. Library_Paths.Last
6138                               loop
6139                                  Option
6140                                    (Current + 1 ..
6141                                       Current +
6142                                         Library_Paths.Table (Index)'Length) :=
6143                                    Library_Paths.Table (Index).all;
6144                                  Current :=
6145                                    Current +
6146                                      Library_Paths.Table (Index)'Length + 1;
6147                                  Option (Current) := Path_Separator;
6148                               end loop;
6149
6150                               --  Finally put the standard GNAT library dir
6151
6152                               Option
6153                                 (Current + 1 ..
6154                                    Current + MLib.Utl.Lib_Directory'Length) :=
6155                                   MLib.Utl.Lib_Directory;
6156
6157                               --  And add the switch to the linker switches
6158
6159                               Linker_Switches.Increment_Last;
6160                               Linker_Switches.Table (Linker_Switches.Last) :=
6161                                 Option;
6162                            end if;
6163                         end;
6164                      end if;
6165
6166                   end if;
6167
6168                   --  Put the object directories in ADA_OBJECTS_PATH
6169
6170                   Prj.Env.Set_Ada_Paths
6171                     (Main_Project,
6172                      Project_Tree,
6173                      Including_Libraries => False,
6174                      Include_Path        => False);
6175
6176                   --  Check for attributes Linker'Linker_Options in projects
6177                   --  other than the main project
6178
6179                   declare
6180                      Linker_Options : constant String_List :=
6181                                         Linker_Options_Switches
6182                                           (Main_Project, Project_Tree);
6183                   begin
6184                      for Option in Linker_Options'Range loop
6185                         Linker_Switches.Increment_Last;
6186                         Linker_Switches.Table (Linker_Switches.Last) :=
6187                           Linker_Options (Option);
6188                      end loop;
6189                   end;
6190                end if;
6191
6192                --  Add switch -M to gnatlink if buider switch --create-map-file
6193                --  has been specified.
6194
6195                if Map_File /= null then
6196                   Linker_Switches.Increment_Last;
6197                   Linker_Switches.Table (Linker_Switches.Last) :=
6198                     new String'("-M" & Map_File.all);
6199                end if;
6200
6201                declare
6202                   Args : Argument_List
6203                            (Linker_Switches.First .. Linker_Switches.Last + 2);
6204
6205                   Last_Arg : Integer := Linker_Switches.First - 1;
6206                   Skip     : Boolean := False;
6207
6208                begin
6209                   --  Get all the linker switches
6210
6211                   for J in Linker_Switches.First .. Linker_Switches.Last loop
6212                      if Skip then
6213                         Skip := False;
6214
6215                      elsif Non_Std_Executable
6216                        and then Linker_Switches.Table (J).all = "-o"
6217                      then
6218                         Skip := True;
6219
6220                      --  Here we capture and duplicate the linker argument. We
6221                      --  need to do the duplication since the arguments will
6222                      --  get normalized. Not doing so will result in calling
6223                      --  normalized two times for the same set of arguments if
6224                      --  gnatmake is passed multiple mains. This can result in
6225                      --  the wrong argument being passed to the linker.
6226
6227                      else
6228                         Last_Arg := Last_Arg + 1;
6229                         Args (Last_Arg) :=
6230                           new String'(Linker_Switches.Table (J).all);
6231                      end if;
6232                   end loop;
6233
6234                   --  If need be, add the -o switch
6235
6236                   if Non_Std_Executable then
6237                      Last_Arg := Last_Arg + 1;
6238                      Args (Last_Arg) := new String'("-o");
6239                      Last_Arg := Last_Arg + 1;
6240                      Args (Last_Arg) :=
6241                        new String'(Get_Name_String (Executable));
6242                   end if;
6243
6244                   --  And invoke the linker
6245
6246                   declare
6247                      Success : Boolean := False;
6248                   begin
6249                      Link (Main_ALI_File,
6250                            Link_With_Shared_Libgcc.all &
6251                            Args (Args'First .. Last_Arg),
6252                            Success);
6253
6254                      if Success then
6255                         Successful_Links.Increment_Last;
6256                         Successful_Links.Table (Successful_Links.Last) :=
6257                           Main_ALI_File;
6258
6259                      elsif Osint.Number_Of_Files = 1
6260                        or else not Keep_Going
6261                      then
6262                         Make_Failed ("*** link failed.");
6263
6264                      else
6265                         Set_Standard_Error;
6266                         Write_Line ("*** link failed");
6267
6268                         if Commands_To_Stdout then
6269                            Set_Standard_Output;
6270                         end if;
6271
6272                         Failed_Links.Increment_Last;
6273                         Failed_Links.Table (Failed_Links.Last) :=
6274                           Main_ALI_File;
6275                      end if;
6276                   end;
6277                end;
6278
6279                Linker_Switches.Set_Last (Linker_Switches_Last);
6280             end Link_Step;
6281          end if;
6282
6283          --  We go to here when we skip the bind and link steps
6284
6285          <<Next_Main>>
6286
6287          --  We go to the next main, if we did not process the last one
6288
6289          if N_File < Osint.Number_Of_Files then
6290             Main_Source_File := Next_Main_Source;
6291
6292             if Current_File_Index /= No_Index then
6293                Main_Index := Current_File_Index;
6294             end if;
6295
6296             if Main_Project /= No_Project then
6297
6298                --  Find the file name of the main unit
6299
6300                declare
6301                   Main_Source_File_Name : constant String :=
6302                                             Get_Name_String (Main_Source_File);
6303
6304                   Main_Unit_File_Name : constant String :=
6305                                           Prj.Env.
6306                                             File_Name_Of_Library_Unit_Body
6307                                               (Name => Main_Source_File_Name,
6308                                                Project => Main_Project,
6309                                                In_Tree => Project_Tree,
6310                                                Main_Project_Only =>
6311                                                  not Unique_Compile);
6312
6313                   The_Packages : constant Package_Id :=
6314                     Main_Project.Decl.Packages;
6315
6316                   Binder_Package : constant Prj.Package_Id :=
6317                                Prj.Util.Value_Of
6318                                  (Name        => Name_Binder,
6319                                   In_Packages => The_Packages,
6320                                   In_Tree     => Project_Tree);
6321
6322                   Linker_Package : constant Prj.Package_Id :=
6323                                Prj.Util.Value_Of
6324                                  (Name        => Name_Linker,
6325                                   In_Packages => The_Packages,
6326                                   In_Tree     => Project_Tree);
6327
6328                begin
6329                   --  We fail if we cannot find the main source file
6330                   --  as an immediate source of the main project file.
6331
6332                   if Main_Unit_File_Name = "" then
6333                      Make_Failed ('"' & Main_Source_File_Name
6334                                   & """ is not a unit of project "
6335                                   & Project_File_Name.all & ".");
6336
6337                   else
6338                      --  Remove any directory information from the main
6339                      --  source file name.
6340
6341                      declare
6342                         Pos : Natural := Main_Unit_File_Name'Last;
6343
6344                      begin
6345                         loop
6346                            exit when Pos < Main_Unit_File_Name'First
6347                              or else
6348                              Main_Unit_File_Name (Pos) = Directory_Separator;
6349                            Pos := Pos - 1;
6350                         end loop;
6351
6352                         Name_Len := Main_Unit_File_Name'Last - Pos;
6353
6354                         Name_Buffer (1 .. Name_Len) :=
6355                           Main_Unit_File_Name
6356                           (Pos + 1 .. Main_Unit_File_Name'Last);
6357
6358                         Main_Source_File := Name_Find;
6359                      end;
6360                   end if;
6361
6362                   --  We now deal with the binder and linker switches.
6363                   --  If no project file is used, there is nothing to do
6364                   --  because the binder and linker switches are the same
6365                   --  for all mains.
6366
6367                   --  Reset the tables Binder_Switches and Linker_Switches
6368
6369                   Binder_Switches.Set_Last (Last_Binder_Switch);
6370                   Linker_Switches.Set_Last (Last_Linker_Switch);
6371
6372                   --  Add binder switches from the project file for this main,
6373                   --  if any.
6374
6375                   if Do_Bind_Step and then Binder_Package /= No_Package then
6376                      if Verbose_Mode then
6377                         Write_Str ("Adding binder switches for """);
6378                         Write_Str (Main_Unit_File_Name);
6379                         Write_Line (""".");
6380                      end if;
6381
6382                      Add_Switches
6383                        (Project_Node_Tree => Project_Node_Tree,
6384                         File_Name         => Main_Unit_File_Name,
6385                         Index             => Main_Index,
6386                         The_Package       => Binder_Package,
6387                         Program           => Binder);
6388                   end if;
6389
6390                   --  Add linker switches from the project file for this main,
6391                   --  if any.
6392
6393                   if Do_Link_Step and then Linker_Package /= No_Package then
6394                      if Verbose_Mode then
6395                         Write_Str ("Adding linker switches for""");
6396                         Write_Str (Main_Unit_File_Name);
6397                         Write_Line (""".");
6398                      end if;
6399
6400                      Add_Switches
6401                        (Project_Node_Tree => Project_Node_Tree,
6402                         File_Name         => Main_Unit_File_Name,
6403                         Index             => Main_Index,
6404                         The_Package       => Linker_Package,
6405                         Program           => Linker);
6406                   end if;
6407
6408                   --  As we are using a project file, for relative paths we add
6409                   --  the current working directory for any relative path on
6410                   --  the command line and the project directory, for any
6411                   --  relative path in the project file.
6412
6413                   declare
6414                      Dir_Path : constant String :=
6415                                   Get_Name_String
6416                                     (Main_Project.Directory.Display_Name);
6417
6418                   begin
6419                      for
6420                        J in Last_Binder_Switch + 1 .. Binder_Switches.Last
6421                      loop
6422                         Test_If_Relative_Path
6423                           (Binder_Switches.Table (J),
6424                            Parent => Dir_Path, Including_L_Switch => False);
6425                      end loop;
6426
6427                      for
6428                        J in Last_Linker_Switch + 1 .. Linker_Switches.Last
6429                      loop
6430                         Test_If_Relative_Path
6431                           (Linker_Switches.Table (J), Parent => Dir_Path);
6432                      end loop;
6433                   end;
6434
6435                   --  We now put in the Binder_Switches and Linker_Switches
6436                   --  tables, the binder and linker switches of the command
6437                   --  line that have been put in the Saved_ tables.
6438                   --  These switches will follow the project file switches.
6439
6440                   for J in 1 .. Saved_Binder_Switches.Last loop
6441                      Add_Switch
6442                        (Saved_Binder_Switches.Table (J),
6443                         Binder,
6444                         And_Save => False);
6445                   end loop;
6446
6447                   for J in 1 .. Saved_Linker_Switches.Last loop
6448                      Add_Switch
6449                        (Saved_Linker_Switches.Table (J),
6450                         Linker,
6451                         And_Save => False);
6452                   end loop;
6453                end;
6454             end if;
6455          end if;
6456
6457          --  Remove all marks to be sure to check sources for all executables,
6458          --  as the switches may be different and -s may be in use.
6459
6460          Delete_All_Marks;
6461       end loop Multiple_Main_Loop;
6462
6463       if Do_Codepeer_Globalize_Step then
6464          declare
6465             Success : Boolean := False;
6466          begin
6467             Globalize (Success);
6468
6469             if not Success then
6470                Set_Standard_Error;
6471                Write_Str ("*** globalize failed.");
6472
6473                if Commands_To_Stdout then
6474                   Set_Standard_Output;
6475                end if;
6476             end if;
6477          end;
6478       end if;
6479
6480       if Failed_Links.Last > 0 then
6481          for Index in 1 .. Successful_Links.Last loop
6482             Write_Str ("Linking of """);
6483             Write_Str (Get_Name_String (Successful_Links.Table (Index)));
6484             Write_Line (""" succeeded.");
6485          end loop;
6486
6487          Set_Standard_Error;
6488
6489          for Index in 1 .. Failed_Links.Last loop
6490             Write_Str ("Linking of """);
6491             Write_Str (Get_Name_String (Failed_Links.Table (Index)));
6492             Write_Line (""" failed.");
6493          end loop;
6494
6495          if Commands_To_Stdout then
6496             Set_Standard_Output;
6497          end if;
6498
6499          if Total_Compilation_Failures = 0 then
6500             Report_Compilation_Failed;
6501          end if;
6502       end if;
6503
6504       if Total_Compilation_Failures /= 0 then
6505          List_Bad_Compilations;
6506          Report_Compilation_Failed;
6507       end if;
6508
6509       --  Delete the temporary mapping file that was created if we are
6510       --  using project files.
6511
6512       Delete_All_Temp_Files;
6513
6514       --  Output Namet statistics
6515
6516       Namet.Finalize;
6517
6518    exception
6519       when X : others =>
6520          Set_Standard_Error;
6521          Write_Line (Exception_Information (X));
6522          Make_Failed ("INTERNAL ERROR. Please report.");
6523    end Gnatmake;
6524
6525    ----------
6526    -- Hash --
6527    ----------
6528
6529    function Hash (F : File_Name_Type) return Header_Num is
6530    begin
6531       return Header_Num (1 + F mod Max_Header);
6532    end Hash;
6533
6534    --------------------
6535    -- In_Ada_Lib_Dir --
6536    --------------------
6537
6538    function In_Ada_Lib_Dir (File : File_Name_Type) return Boolean is
6539       D : constant File_Name_Type := Get_Directory (File);
6540       B : constant Byte           := Get_Name_Table_Byte (D);
6541    begin
6542       return (B and Ada_Lib_Dir) /= 0;
6543    end In_Ada_Lib_Dir;
6544
6545    -----------------------
6546    -- Init_Mapping_File --
6547    -----------------------
6548
6549    procedure Init_Mapping_File
6550      (Project    : Project_Id;
6551       Data       : in out Project_Compilation_Data;
6552       File_Index : in out Natural)
6553    is
6554       FD     : File_Descriptor;
6555       Status : Boolean;
6556       --  For call to Close
6557
6558    begin
6559       --  Increase the index of the last mapping file for this project
6560
6561       Data.Last_Mapping_File_Names := Data.Last_Mapping_File_Names + 1;
6562
6563       --  If there is a project file, call Create_Mapping_File with
6564       --  the project id.
6565
6566       if Project /= No_Project then
6567          Prj.Env.Create_Mapping_File
6568            (Project,
6569             In_Tree  => Project_Tree,
6570             Language => Name_Ada,
6571             Name     => Data.Mapping_File_Names
6572                           (Data.Last_Mapping_File_Names));
6573
6574       --  Otherwise, just create an empty file
6575
6576       else
6577          Tempdir.Create_Temp_File
6578            (FD,
6579             Data.Mapping_File_Names (Data.Last_Mapping_File_Names));
6580
6581          if FD = Invalid_FD then
6582             Make_Failed ("disk full");
6583
6584          else
6585             Record_Temp_File
6586               (Project_Tree,
6587                Data.Mapping_File_Names (Data.Last_Mapping_File_Names));
6588          end if;
6589
6590          Close (FD, Status);
6591
6592          if not Status then
6593             Make_Failed ("disk full");
6594          end if;
6595       end if;
6596
6597       --  And return the index of the newly created file
6598
6599       File_Index := Data.Last_Mapping_File_Names;
6600    end Init_Mapping_File;
6601
6602    ----------------
6603    -- Initialize --
6604    ----------------
6605
6606    procedure Initialize (Project_Node_Tree : out Project_Node_Tree_Ref) is
6607
6608       procedure Check_Version_And_Help is
6609          new Check_Version_And_Help_G (Makeusg);
6610
6611       --  Start of processing for Initialize
6612
6613    begin
6614       --  Prepare the project's tree, since this is used to hold external
6615       --  references, project path and other attributes that can be impacted by
6616       --  the command line switches
6617
6618       Project_Node_Tree := new Project_Node_Tree_Data;
6619       Prj.Tree.Initialize (Project_Node_Tree);
6620
6621       --  Override default initialization of Check_Object_Consistency since
6622       --  this is normally False for GNATBIND, but is True for GNATMAKE since
6623       --  we do not need to check source consistency again once GNATMAKE has
6624       --  looked at the sources to check.
6625
6626       Check_Object_Consistency := True;
6627
6628       --  Package initializations (the order of calls is important here)
6629
6630       Output.Set_Standard_Error;
6631
6632       Gcc_Switches.Init;
6633       Binder_Switches.Init;
6634       Linker_Switches.Init;
6635
6636       Csets.Initialize;
6637       Snames.Initialize;
6638
6639       Prj.Initialize (Project_Tree);
6640
6641       Dependencies.Init;
6642
6643       RTS_Specified := null;
6644       N_M_Switch := 0;
6645
6646       Mains.Delete;
6647
6648       --  Add the directory where gnatmake is invoked in front of the path,
6649       --  if gnatmake is invoked from a bin directory or with directory
6650       --  information. Only do this if the platform is not VMS, where the
6651       --  notion of path does not really exist.
6652
6653       if not OpenVMS then
6654          declare
6655             Prefix  : constant String := Executable_Prefix_Path;
6656             Command : constant String := Command_Name;
6657
6658          begin
6659             if Prefix'Length > 0 then
6660                declare
6661                   PATH : constant String :=
6662                            Prefix & Directory_Separator & "bin" &
6663                            Path_Separator &
6664                            Getenv ("PATH").all;
6665                begin
6666                   Setenv ("PATH", PATH);
6667                end;
6668
6669             else
6670                for Index in reverse Command'Range loop
6671                   if Command (Index) = Directory_Separator then
6672                      declare
6673                         Absolute_Dir : constant String :=
6674                                          Normalize_Pathname
6675                                            (Command (Command'First .. Index));
6676                         PATH         : constant String :=
6677                                          Absolute_Dir &
6678                                          Path_Separator &
6679                                          Getenv ("PATH").all;
6680                      begin
6681                         Setenv ("PATH", PATH);
6682                      end;
6683
6684                      exit;
6685                   end if;
6686                end loop;
6687             end if;
6688          end;
6689       end if;
6690
6691       --  Scan the switches and arguments
6692
6693       --  First, scan to detect --version and/or --help
6694
6695       Check_Version_And_Help ("GNATMAKE", "1995");
6696
6697       --  Scan again the switch and arguments, now that we are sure that they
6698       --  do not include --version or --help.
6699
6700       Scan_Args : for Next_Arg in 1 .. Argument_Count loop
6701          Scan_Make_Arg
6702            (Project_Node_Tree, Argument (Next_Arg), And_Save => True);
6703       end loop Scan_Args;
6704
6705       if N_M_Switch > 0 and RTS_Specified = null then
6706          Process_Multilib (Project_Node_Tree);
6707       end if;
6708
6709       if Commands_To_Stdout then
6710          Set_Standard_Output;
6711       end if;
6712
6713       if Usage_Requested then
6714          Usage;
6715       end if;
6716
6717       --  Test for trailing -P switch
6718
6719       if Project_File_Name_Present and then Project_File_Name = null then
6720          Make_Failed ("project file name missing after -P");
6721
6722       --  Test for trailing -o switch
6723
6724       elsif Output_File_Name_Present
6725         and then not Output_File_Name_Seen
6726       then
6727          Make_Failed ("output file name missing after -o");
6728
6729       --  Test for trailing -D switch
6730
6731       elsif Object_Directory_Present
6732         and then not Object_Directory_Seen then
6733          Make_Failed ("object directory missing after -D");
6734       end if;
6735
6736       --  Test for simultaneity of -i and -D
6737
6738       if Object_Directory_Path /= null and then In_Place_Mode then
6739          Make_Failed ("-i and -D cannot be used simultaneously");
6740       end if;
6741
6742       --  Deal with -C= switch
6743
6744       if Gnatmake_Mapping_File /= null then
6745
6746          --  First, check compatibility with other switches
6747
6748          if Project_File_Name /= null then
6749             Make_Failed ("-C= switch is not compatible with -P switch");
6750
6751          elsif Saved_Maximum_Processes > 1 then
6752             Make_Failed ("-C= switch is not compatible with -jnnn switch");
6753          end if;
6754
6755          Fmap.Initialize (Gnatmake_Mapping_File.all);
6756          Add_Switch
6757            ("-gnatem=" & Gnatmake_Mapping_File.all,
6758             Compiler,
6759             And_Save => True);
6760       end if;
6761
6762       if Project_File_Name /= null then
6763
6764          --  A project file was specified by a -P switch
6765
6766          if Verbose_Mode then
6767             Write_Eol;
6768             Write_Str ("Parsing project file """);
6769             Write_Str (Project_File_Name.all);
6770             Write_Str (""".");
6771             Write_Eol;
6772          end if;
6773
6774          --  Avoid looking in the current directory for ALI files
6775
6776          --  Look_In_Primary_Dir := False;
6777
6778          --  Set the project parsing verbosity to whatever was specified
6779          --  by a possible -vP switch.
6780
6781          Prj.Pars.Set_Verbosity (To => Current_Verbosity);
6782
6783          --  Parse the project file.
6784          --  If there is an error, Main_Project will still be No_Project.
6785
6786          Prj.Pars.Parse
6787            (Project           => Main_Project,
6788             In_Tree           => Project_Tree,
6789             Project_File_Name => Project_File_Name.all,
6790             Packages_To_Check => Packages_To_Check_By_Gnatmake,
6791             Flags             => Gnatmake_Flags,
6792             In_Node_Tree      => Project_Node_Tree);
6793
6794          --  The parsing of project files may have changed the current output
6795
6796          if Commands_To_Stdout then
6797             Set_Standard_Output;
6798          else
6799             Set_Standard_Error;
6800          end if;
6801
6802          if Main_Project = No_Project then
6803             Make_Failed
6804               ("""" & Project_File_Name.all & """ processing failed");
6805          end if;
6806
6807          Create_Mapping_File := True;
6808
6809          if Verbose_Mode then
6810             Write_Eol;
6811             Write_Str ("Parsing of project file """);
6812             Write_Str (Project_File_Name.all);
6813             Write_Str (""" is finished.");
6814             Write_Eol;
6815          end if;
6816
6817          --  We add the source directories and the object directories to the
6818          --  search paths.
6819          --  ??? Why do we need these search directories, we already know the
6820          --  locations from parsing the project, except for the runtime which
6821          --  has its own directories anyway
6822
6823          Add_Source_Directories (Main_Project, Project_Tree);
6824          Add_Object_Directories (Main_Project);
6825
6826          Recursive_Compute_Depth (Main_Project);
6827          Compute_All_Imported_Projects (Project_Tree);
6828
6829       else
6830
6831          Osint.Add_Default_Search_Dirs;
6832
6833          --  Source file lookups should be cached for efficiency. Source files
6834          --  are not supposed to change. However, we do that now only if no
6835          --  project file is used; if a project file is used, we do it just
6836          --  after changing the directory to the object directory.
6837
6838          Osint.Source_File_Data (Cache => True);
6839
6840          --  Read gnat.adc file to initialize Fname.UF
6841
6842          Fname.UF.Initialize;
6843
6844          begin
6845             Fname.SF.Read_Source_File_Name_Pragmas;
6846
6847          exception
6848             when Err : SFN_Scan.Syntax_Error_In_GNAT_ADC =>
6849                Make_Failed (Exception_Message (Err));
6850          end;
6851       end if;
6852
6853       --  Make sure no project object directory is recorded
6854
6855       Project_Of_Current_Object_Directory := No_Project;
6856
6857    end Initialize;
6858
6859    ----------------------------
6860    -- Insert_Project_Sources --
6861    ----------------------------
6862
6863    procedure Insert_Project_Sources
6864      (The_Project  : Project_Id;
6865       All_Projects : Boolean;
6866       Into_Q       : Boolean)
6867    is
6868       Put_In_Q : Boolean := Into_Q;
6869       Unit     : Unit_Index;
6870       Sfile    : File_Name_Type;
6871       Index    : Int;
6872       Project  : Project_Id;
6873
6874       Extending : constant Boolean := The_Project.Extends /= No_Project;
6875
6876       function Check_Project (P : Project_Id) return Boolean;
6877       --  Returns True if P is The_Project or a project extended by The_Project
6878
6879       -------------------
6880       -- Check_Project --
6881       -------------------
6882
6883       function Check_Project (P : Project_Id) return Boolean is
6884       begin
6885          if All_Projects or else P = The_Project then
6886             return True;
6887
6888          elsif Extending then
6889             declare
6890                Proj : Project_Id;
6891
6892             begin
6893                Proj := The_Project;
6894                while Proj /= null loop
6895                   if P = Proj.Extends then
6896                      return True;
6897                   end if;
6898
6899                   Proj := Proj.Extends;
6900                end loop;
6901             end;
6902          end if;
6903
6904          return False;
6905       end Check_Project;
6906
6907    --  Start of processing for Insert_Project_Sources
6908
6909    begin
6910       --  For all the sources in the project files,
6911
6912       Unit := Units_Htable.Get_First (Project_Tree.Units_HT);
6913       while Unit /= null loop
6914          Sfile   := No_File;
6915          Index   := 0;
6916          Project := No_Project;
6917
6918          --  If there is a source for the body, and the body has not been
6919          --  locally removed.
6920
6921          if Unit.File_Names (Impl) /= null
6922            and then not Unit.File_Names (Impl).Locally_Removed
6923          then
6924             --  And it is a source for the specified project
6925
6926             if Check_Project (Unit.File_Names (Impl).Project) then
6927                Project := Unit.File_Names (Impl).Project;
6928
6929                --  If we don't have a spec, we cannot consider the source
6930                --  if it is a subunit.
6931
6932                if Unit.File_Names (Spec) = null then
6933                   declare
6934                      Src_Ind : Source_File_Index;
6935
6936                      --  Here we are cheating a little bit: we don't want to
6937                      --  use Sinput.L, because it depends on the GNAT tree
6938                      --  (Atree, Sinfo, ...). So, we pretend that it is a
6939                      --  project file, and we use Sinput.P.
6940
6941                      --  Source_File_Is_Subunit is just scanning through the
6942                      --  file until it finds one of the reserved words
6943                      --  separate, procedure, function, generic or package.
6944                      --  Fortunately, these Ada reserved words are also
6945                      --  reserved for project files.
6946
6947                   begin
6948                      Src_Ind := Sinput.P.Load_Project_File
6949                                   (Get_Name_String
6950                                    (Unit.File_Names (Impl).Path.Display_Name));
6951
6952                      --  If it is a subunit, discard it
6953
6954                      if Sinput.P.Source_File_Is_Subunit (Src_Ind) then
6955                         Sfile := No_File;
6956                         Index := 0;
6957                      else
6958                         Sfile := Unit.File_Names (Impl).Display_File;
6959                         Index := Unit.File_Names (Impl).Index;
6960                      end if;
6961                   end;
6962
6963                else
6964                   Sfile := Unit.File_Names (Impl).Display_File;
6965                   Index := Unit.File_Names (Impl).Index;
6966                end if;
6967             end if;
6968
6969          elsif Unit.File_Names (Spec) /= null
6970            and then not Unit.File_Names (Spec).Locally_Removed
6971            and then Check_Project (Unit.File_Names (Spec).Project)
6972          then
6973             --  If there is no source for the body, but there is one for the
6974             --  spec which has not been locally removed, then we take this one.
6975
6976             Sfile := Unit.File_Names (Spec).Display_File;
6977             Index := Unit.File_Names (Spec).Index;
6978             Project := Unit.File_Names (Spec).Project;
6979          end if;
6980
6981          --  For the first source inserted into the Q, we need to initialize
6982          --  the Q, but not for the subsequent sources.
6983
6984          Queue.Initialize
6985                  (Main_Project /= No_Project and then
6986                   One_Compilation_Per_Obj_Dir);
6987
6988          --  And of course, only insert in the Q if the source is not marked
6989
6990          if Sfile /= No_File and then not Is_Marked (Sfile, Index) then
6991             if Verbose_Mode then
6992                Write_Str ("Adding """);
6993                Write_Str (Get_Name_String (Sfile));
6994                Write_Line (""" to the queue");
6995             end if;
6996
6997             Queue.Insert (Sfile, Project, Index => Index);
6998             Mark (Sfile, Index);
6999          end if;
7000
7001          if not Put_In_Q and then Sfile /= No_File then
7002
7003             --  If Put_In_Q is False, we add the source as if it were specified
7004             --  on the command line, and we set Put_In_Q to True, so that the
7005             --  following sources will only be put in the queue. The source is
7006             --  aready in the Q, but we need at least one fake main to call
7007             --  Compile_Sources.
7008
7009             if Verbose_Mode then
7010                Write_Str ("Adding """);
7011                Write_Str (Get_Name_String (Sfile));
7012                Write_Line (""" as if on the command line");
7013             end if;
7014
7015             Osint.Add_File (Get_Name_String (Sfile), Index);
7016             Put_In_Q := True;
7017          end if;
7018
7019          Unit := Units_Htable.Get_Next (Project_Tree.Units_HT);
7020       end loop;
7021    end Insert_Project_Sources;
7022
7023    ---------------------
7024    -- Is_In_Obsoleted --
7025    ---------------------
7026
7027    function Is_In_Obsoleted (F : File_Name_Type) return Boolean is
7028    begin
7029       if F = No_File then
7030          return False;
7031
7032       else
7033          declare
7034             Name  : constant String := Get_Name_String (F);
7035             First : Natural;
7036             F2    : File_Name_Type;
7037
7038          begin
7039             First := Name'Last;
7040             while First > Name'First
7041               and then Name (First - 1) /= Directory_Separator
7042               and then Name (First - 1) /= '/'
7043             loop
7044                First := First - 1;
7045             end loop;
7046
7047             if First /= Name'First then
7048                Name_Len := 0;
7049                Add_Str_To_Name_Buffer (Name (First .. Name'Last));
7050                F2 := Name_Find;
7051
7052             else
7053                F2 := F;
7054             end if;
7055
7056             return Obsoleted.Get (F2);
7057          end;
7058       end if;
7059    end Is_In_Obsoleted;
7060
7061    ----------------------------
7062    -- Is_In_Object_Directory --
7063    ----------------------------
7064
7065    function Is_In_Object_Directory
7066      (Source_File   : File_Name_Type;
7067       Full_Lib_File : File_Name_Type) return Boolean
7068    is
7069    begin
7070       --  There is something to check only when using project files. Otherwise,
7071       --  this function returns True (last line of the function).
7072
7073       if Main_Project /= No_Project then
7074          declare
7075             Source_File_Name : constant String :=
7076                                  Get_Name_String (Source_File);
7077             Saved_Verbosity  : constant Verbosity := Current_Verbosity;
7078             Project          : Project_Id         := No_Project;
7079
7080             Path_Name : Path_Name_Type := No_Path;
7081             pragma Warnings (Off, Path_Name);
7082
7083          begin
7084             --  Call Get_Reference to know the ultimate extending project of
7085             --  the source. Call it with verbosity default to avoid verbose
7086             --  messages.
7087
7088             Current_Verbosity := Default;
7089             Prj.Env.Get_Reference
7090               (Source_File_Name => Source_File_Name,
7091                Project          => Project,
7092                In_Tree          => Project_Tree,
7093                Path             => Path_Name);
7094             Current_Verbosity := Saved_Verbosity;
7095
7096             --  If this source is in a project, check that the ALI file is in
7097             --  its object directory. If it is not, return False, so that the
7098             --  ALI file will not be skipped.
7099
7100             if Project /= No_Project then
7101                declare
7102                   Object_Directory : constant String :=
7103                                        Normalize_Pathname
7104                                         (Get_Name_String
7105                                          (Project.
7106                                             Object_Directory.Display_Name));
7107
7108                   Olast : Natural := Object_Directory'Last;
7109
7110                   Lib_File_Directory : constant String :=
7111                                          Normalize_Pathname (Dir_Name
7112                                            (Get_Name_String (Full_Lib_File)));
7113
7114                   Llast : Natural := Lib_File_Directory'Last;
7115
7116                begin
7117                   --  For directories, Normalize_Pathname may or may not put
7118                   --  a directory separator at the end, depending on its input.
7119                   --  Remove any last directory separator before comparison.
7120                   --  Returns True only if the two directories are the same.
7121
7122                   if Object_Directory (Olast) = Directory_Separator then
7123                      Olast := Olast - 1;
7124                   end if;
7125
7126                   if Lib_File_Directory (Llast) = Directory_Separator then
7127                      Llast := Llast - 1;
7128                   end if;
7129
7130                   return Object_Directory (Object_Directory'First .. Olast) =
7131                         Lib_File_Directory (Lib_File_Directory'First .. Llast);
7132                end;
7133             end if;
7134          end;
7135       end if;
7136
7137       --  When the source is not in a project file, always return True
7138
7139       return True;
7140    end Is_In_Object_Directory;
7141
7142    ----------
7143    -- Link --
7144    ----------
7145
7146    procedure Link
7147      (ALI_File : File_Name_Type;
7148       Args     : Argument_List;
7149       Success  : out Boolean)
7150    is
7151       Link_Args : Argument_List (1 .. Args'Length + 1);
7152
7153    begin
7154       Get_Name_String (ALI_File);
7155       Link_Args (1) := new String'(Name_Buffer (1 .. Name_Len));
7156
7157       Link_Args (2 .. Args'Length + 1) :=  Args;
7158
7159       GNAT.OS_Lib.Normalize_Arguments (Link_Args);
7160
7161       Display (Gnatlink.all, Link_Args);
7162
7163       if Gnatlink_Path = null then
7164          Make_Failed ("error, unable to locate " & Gnatlink.all);
7165       end if;
7166
7167       GNAT.OS_Lib.Spawn (Gnatlink_Path.all, Link_Args, Success);
7168    end Link;
7169
7170    ---------------------------
7171    -- List_Bad_Compilations --
7172    ---------------------------
7173
7174    procedure List_Bad_Compilations is
7175    begin
7176       for J in Bad_Compilation.First .. Bad_Compilation.Last loop
7177          if Bad_Compilation.Table (J).File = No_File then
7178             null;
7179          elsif not Bad_Compilation.Table (J).Found then
7180             Inform (Bad_Compilation.Table (J).File, "not found");
7181          else
7182             Inform (Bad_Compilation.Table (J).File, "compilation error");
7183          end if;
7184       end loop;
7185    end List_Bad_Compilations;
7186
7187    -----------------
7188    -- List_Depend --
7189    -----------------
7190
7191    procedure List_Depend is
7192       Lib_Name  : File_Name_Type;
7193       Obj_Name  : File_Name_Type;
7194       Src_Name  : File_Name_Type;
7195
7196       Len       : Natural;
7197       Line_Pos  : Natural;
7198       Line_Size : constant := 77;
7199
7200    begin
7201       Set_Standard_Output;
7202
7203       for A in ALIs.First .. ALIs.Last loop
7204          Lib_Name := ALIs.Table (A).Afile;
7205
7206          --  We have to provide the full library file name in In_Place_Mode
7207
7208          if In_Place_Mode then
7209             Lib_Name := Full_Lib_File_Name (Lib_Name);
7210          end if;
7211
7212          Obj_Name := Object_File_Name (Lib_Name);
7213          Write_Name (Obj_Name);
7214          Write_Str (" :");
7215
7216          Get_Name_String (Obj_Name);
7217          Len := Name_Len;
7218          Line_Pos := Len + 2;
7219
7220          for D in ALIs.Table (A).First_Sdep .. ALIs.Table (A).Last_Sdep loop
7221             Src_Name := Sdep.Table (D).Sfile;
7222
7223             if Is_Internal_File_Name (Src_Name)
7224               and then not Check_Readonly_Files
7225             then
7226                null;
7227             else
7228                if not Quiet_Output then
7229                   Src_Name := Full_Source_Name (Src_Name);
7230                end if;
7231
7232                Get_Name_String (Src_Name);
7233                Len := Name_Len;
7234
7235                if Line_Pos + Len + 1 > Line_Size then
7236                   Write_Str (" \");
7237                   Write_Eol;
7238                   Line_Pos := 0;
7239                end if;
7240
7241                Line_Pos := Line_Pos + Len + 1;
7242
7243                Write_Str (" ");
7244                Write_Name (Src_Name);
7245             end if;
7246          end loop;
7247
7248          Write_Eol;
7249       end loop;
7250
7251       if not Commands_To_Stdout then
7252          Set_Standard_Error;
7253       end if;
7254    end List_Depend;
7255
7256    -----------------
7257    -- Make_Failed --
7258    -----------------
7259
7260    procedure Make_Failed (S : String) is
7261    begin
7262       Delete_All_Temp_Files;
7263       Osint.Fail (S);
7264    end Make_Failed;
7265
7266    --------------------
7267    -- Mark_Directory --
7268    --------------------
7269
7270    procedure Mark_Directory
7271      (Dir             : String;
7272       Mark            : Lib_Mark_Type;
7273       On_Command_Line : Boolean)
7274    is
7275       N : Name_Id;
7276       B : Byte;
7277
7278       function Base_Directory return String;
7279       --  If Dir comes from the command line, empty string (relative paths are
7280       --  resolved with respect to the current directory), else return the main
7281       --  project's directory.
7282
7283       --------------------
7284       -- Base_Directory --
7285       --------------------
7286
7287       function Base_Directory return String is
7288       begin
7289          if On_Command_Line then
7290             return "";
7291          else
7292             return Get_Name_String (Main_Project.Directory.Display_Name);
7293          end if;
7294       end Base_Directory;
7295
7296       Real_Path : constant String := Normalize_Pathname (Dir, Base_Directory);
7297
7298    --  Start of processing for Mark_Directory
7299
7300    begin
7301       Name_Len := 0;
7302
7303       if Real_Path'Length = 0 then
7304          Add_Str_To_Name_Buffer (Dir);
7305
7306       else
7307          Add_Str_To_Name_Buffer (Real_Path);
7308       end if;
7309
7310       --  Last character is supposed to be a directory separator
7311
7312       if not Is_Directory_Separator (Name_Buffer (Name_Len)) then
7313          Add_Char_To_Name_Buffer (Directory_Separator);
7314       end if;
7315
7316       --  Add flags to the already existing flags
7317
7318       N := Name_Find;
7319       B := Get_Name_Table_Byte (N);
7320       Set_Name_Table_Byte (N, B or Mark);
7321    end Mark_Directory;
7322
7323    ----------------------
7324    -- Process_Multilib --
7325    ----------------------
7326
7327    procedure Process_Multilib
7328      (Project_Node_Tree : Project_Node_Tree_Ref)
7329    is
7330       Output_FD         : File_Descriptor;
7331       Output_Name       : String_Access;
7332       Arg_Index         : Natural := 0;
7333       Success           : Boolean := False;
7334       Return_Code       : Integer := 0;
7335       Multilib_Gcc_Path : String_Access;
7336       Multilib_Gcc      : String_Access;
7337       N_Read            : Integer := 0;
7338       Line              : String (1 .. 1000);
7339       Args              : Argument_List (1 .. N_M_Switch + 1);
7340
7341    begin
7342       pragma Assert (N_M_Switch > 0 and RTS_Specified = null);
7343
7344       --  In case we detected a multilib switch and the user has not
7345       --  manually specified a specific RTS we emulate the following command:
7346       --  gnatmake $FLAGS --RTS=$(gcc -print-multi-directory $FLAGS)
7347
7348       --  First select the flags which might have an impact on multilib
7349       --  processing. Note that this is an heuristic selection and it
7350       --  will need to be maintained over time. The condition has to
7351       --  be kept synchronized with N_M_Switch counting in Scan_Make_Arg.
7352
7353       for Next_Arg in 1 .. Argument_Count loop
7354          declare
7355             Argv : constant String := Argument (Next_Arg);
7356          begin
7357             if Argv'Length > 2
7358               and then Argv (1) = '-'
7359               and then Argv (2) = 'm'
7360               and then Argv /= "-margs"
7361
7362               --  Ignore -mieee to avoid spawning an extra gcc in this case
7363
7364               and then Argv /= "-mieee"
7365             then
7366                Arg_Index := Arg_Index + 1;
7367                Args (Arg_Index) := new String'(Argv);
7368             end if;
7369          end;
7370       end loop;
7371
7372       pragma Assert (Arg_Index = N_M_Switch);
7373
7374       Args (Args'Last) := new String'("-print-multi-directory");
7375
7376       --  Call the GCC driver with the collected flags and save its
7377       --  output. Alternate design would be to link in gnatmake the
7378       --  relevant part of the GCC driver.
7379
7380       if Saved_Gcc /= null then
7381          Multilib_Gcc := Saved_Gcc;
7382       else
7383          Multilib_Gcc := Gcc;
7384       end if;
7385
7386       Multilib_Gcc_Path := GNAT.OS_Lib.Locate_Exec_On_Path (Multilib_Gcc.all);
7387
7388       Create_Temp_Output_File (Output_FD, Output_Name);
7389
7390       if Output_FD = Invalid_FD then
7391          return;
7392       end if;
7393
7394       GNAT.OS_Lib.Spawn
7395         (Multilib_Gcc_Path.all, Args, Output_FD, Return_Code, False);
7396       Close (Output_FD);
7397
7398       if Return_Code /= 0 then
7399          return;
7400       end if;
7401
7402       --  Parse the GCC driver output which is a single line, removing CR/LF
7403
7404       Output_FD := Open_Read (Output_Name.all, Binary);
7405
7406       if Output_FD = Invalid_FD then
7407          return;
7408       end if;
7409
7410       N_Read := Read (Output_FD, Line (1)'Address, Line'Length);
7411       Close (Output_FD);
7412       Delete_File (Output_Name.all, Success);
7413
7414       for J in reverse 1 .. N_Read loop
7415          if Line (J) = ASCII.CR or else Line (J) = ASCII.LF then
7416             N_Read := N_Read - 1;
7417          else
7418             exit;
7419          end if;
7420       end loop;
7421
7422       --  In case the standard RTS is selected do nothing
7423
7424       if N_Read = 0 or else Line (1 .. N_Read) = "." then
7425          return;
7426       end if;
7427
7428       --  Otherwise add -margs --RTS=output
7429
7430       Scan_Make_Arg (Project_Node_Tree, "-margs", And_Save => True);
7431       Scan_Make_Arg
7432         (Project_Node_Tree, "--RTS=" & Line (1 .. N_Read), And_Save => True);
7433    end Process_Multilib;
7434
7435    -----------
7436    -- Queue --
7437    -----------
7438
7439    package body Queue is
7440
7441       type Q_Record is record
7442          File      : File_Name_Type;
7443          Unit      : Unit_Name_Type;
7444          Index     : Int;
7445          Project   : Project_Id;
7446          Processed : Boolean;
7447       end record;
7448       --  File is the name of the file to compile. Unit is for gnatdist use in
7449       --  order to easily get the unit name of a file to compile when its name
7450       --  is krunched or declared in gnat.adc. Index, when not 0, is the index
7451       --  of the unit in a multi-unit source.
7452
7453       package Q is new Table.Table
7454         (Table_Component_Type => Q_Record,
7455          Table_Index_Type     => Positive,
7456          Table_Low_Bound      => 1,
7457          Table_Initial        => 4000,
7458          Table_Increment      => 100,
7459          Table_Name           => "Make.Queue.Q");
7460       --  This is the actual Q
7461
7462       package Busy_Obj_Dirs is new GNAT.HTable.Simple_HTable
7463         (Header_Num => Prj.Header_Num,
7464          Element    => Boolean,
7465          No_Element => False,
7466          Key        => Path_Name_Type,
7467          Hash       => Hash,
7468          Equal      => "=");
7469
7470       Q_First : Natural := 1;
7471       --  Points to the first valid element in the queue
7472
7473       Q_Processed           : Natural := 0;
7474       One_Queue_Per_Obj_Dir : Boolean := False;
7475       Q_Initialized         : Boolean := False;
7476
7477       -------------
7478       -- Element --
7479       -------------
7480
7481       function Element (Rank : Positive) return File_Name_Type is
7482       begin
7483          if Rank <= Q.Last then
7484             return Q.Table (Rank).File;
7485          else
7486             return No_File;
7487          end if;
7488       end Element;
7489
7490       -------------
7491       -- Extract --
7492       -------------
7493
7494       --  This body needs commenting ???
7495
7496       procedure Extract
7497         (Source_File_Name : out File_Name_Type;
7498          Source_Unit      : out Unit_Name_Type;
7499          Source_Index     : out Int)
7500       is
7501          Found : Boolean := False;
7502
7503       begin
7504          if One_Queue_Per_Obj_Dir then
7505             for J in Q_First .. Q.Last loop
7506                if not Q.Table (J).Processed
7507                  and then (Q.Table (J).Project = No_Project
7508                             or else not
7509                               Busy_Obj_Dirs.Get
7510                                 (Q.Table (J).Project.Object_Directory.Name))
7511                then
7512                   Found := True;
7513                   Source_File_Name := Q.Table (J).File;
7514                   Source_Unit      := Q.Table (J).Unit;
7515                   Source_Index     := Q.Table (J).Index;
7516                   Q.Table (J).Processed := True;
7517
7518                   if J = Q_First then
7519                      while Q_First <= Q.Last
7520                        and then Q.Table (Q_First).Processed
7521                      loop
7522                         Q_First := Q_First + 1;
7523                      end loop;
7524                   end if;
7525
7526                   exit;
7527                end if;
7528             end loop;
7529
7530          elsif Q_First <= Q.Last then
7531             Source_File_Name := Q.Table (Q_First).File;
7532             Source_Unit      := Q.Table (Q_First).Unit;
7533             Source_Index     := Q.Table (Q_First).Index;
7534             Q.Table (Q_First).Processed := True;
7535             Q_First := Q_First + 1;
7536             Found := True;
7537          end if;
7538
7539          if Found then
7540             Q_Processed := Q_Processed + 1;
7541          else
7542             Source_File_Name := No_File;
7543             Source_Unit      := No_Unit_Name;
7544             Source_Index     := 0;
7545          end if;
7546
7547          if Found and then Debug.Debug_Flag_Q then
7548             Write_Str ("   Q := Q - [ ");
7549             Write_Name (Source_File_Name);
7550
7551             if Source_Index /= 0 then
7552                Write_Str (", ");
7553                Write_Int (Source_Index);
7554             end if;
7555
7556             Write_Str (" ]");
7557             Write_Eol;
7558
7559             Write_Str ("   Q_First =");
7560             Write_Int (Int (Q_First));
7561             Write_Eol;
7562
7563             Write_Str ("   Q.Last =");
7564             Write_Int (Int (Q.Last));
7565             Write_Eol;
7566          end if;
7567       end Extract;
7568
7569       ----------------
7570       -- Initialize --
7571       ----------------
7572
7573       procedure Initialize (Queue_Per_Obj_Dir : Boolean) is
7574       begin
7575          if not Q_Initialized then
7576             One_Queue_Per_Obj_Dir := Queue_Per_Obj_Dir;
7577             Q.Init;
7578             Q_Initialized := True;
7579             Q_Processed   := 0;
7580             Q_First       := 1;
7581          end if;
7582       end Initialize;
7583
7584       ------------
7585       -- Insert --
7586       ------------
7587
7588       --  This body needs commenting ???
7589
7590       procedure Insert
7591         (Source_File_Name : File_Name_Type;
7592          Project          : Project_Id;
7593          Source_Unit      : Unit_Name_Type := No_Unit_Name;
7594          Index            : Int            := 0)
7595       is
7596       begin
7597          Q.Append
7598            ((File      => Source_File_Name,
7599              Project   => Project,
7600              Unit      => Source_Unit,
7601              Index     => Index,
7602              Processed => False));
7603
7604          if Debug.Debug_Flag_Q then
7605             Write_Str ("   Q := Q + [ ");
7606             Write_Name (Source_File_Name);
7607
7608             if Index /= 0 then
7609                Write_Str (", ");
7610                Write_Int (Index);
7611             end if;
7612
7613             Write_Str (" ] ");
7614             Write_Eol;
7615
7616             Write_Str ("   Q_First =");
7617             Write_Int (Int (Q_First));
7618             Write_Eol;
7619
7620             Write_Str ("   Q.Last =");
7621             Write_Int (Int (Q.Last));
7622             Write_Eol;
7623          end if;
7624       end Insert;
7625
7626       --------------
7627       -- Is_Empty --
7628       --------------
7629
7630       function Is_Empty return Boolean is
7631       begin
7632          if Debug.Debug_Flag_P then
7633             Write_Str ("   Q := [");
7634
7635             for J in Q_First .. Q.Last loop
7636                if not Q.Table (J).Processed then
7637                   Write_Str (" ");
7638                   Write_Name (Q.Table (J).File);
7639                   Write_Eol;
7640                   Write_Str ("         ");
7641                end if;
7642             end loop;
7643
7644             Write_Str ("]");
7645             Write_Eol;
7646          end if;
7647
7648          return Q_First > Q.Last;
7649       end Is_Empty;
7650
7651       ------------------------
7652       -- Is_Virtually_Empty --
7653       ------------------------
7654
7655       function Is_Virtually_Empty return Boolean is
7656       begin
7657          if One_Queue_Per_Obj_Dir then
7658             for J in Q_First .. Q.Last loop
7659                if not Q.Table (J).Processed
7660                  and then
7661                    (Q.Table (J).Project = No_Project
7662                      or else not
7663                        Busy_Obj_Dirs.Get
7664                          (Q.Table (J).Project.Object_Directory.Name))
7665                then
7666                   return False;
7667                end if;
7668             end loop;
7669
7670             return True;
7671
7672          else
7673             return Is_Empty;
7674          end if;
7675       end Is_Virtually_Empty;
7676
7677       ---------------
7678       -- Processed --
7679       ---------------
7680
7681       function Processed return Natural is
7682       begin
7683          return Q_Processed;
7684       end Processed;
7685
7686       ----------------------
7687       -- Set_Obj_Dir_Busy --
7688       ----------------------
7689
7690       procedure Set_Obj_Dir_Busy (Obj_Dir : Path_Name_Type) is
7691       begin
7692          if One_Queue_Per_Obj_Dir then
7693             Busy_Obj_Dirs.Set (Obj_Dir, True);
7694          end if;
7695       end Set_Obj_Dir_Busy;
7696
7697       ----------------------
7698       -- Set_Obj_Dir_Free --
7699       ----------------------
7700
7701       procedure Set_Obj_Dir_Free (Obj_Dir : Path_Name_Type) is
7702       begin
7703          if One_Queue_Per_Obj_Dir then
7704             Busy_Obj_Dirs.Set (Obj_Dir, False);
7705          end if;
7706       end Set_Obj_Dir_Free;
7707
7708       ----------
7709       -- Size --
7710       ----------
7711
7712       function Size return Natural is
7713       begin
7714          return Q.Last;
7715       end Size;
7716
7717    end Queue;
7718
7719    -----------------------------
7720    -- Recursive_Compute_Depth --
7721    -----------------------------
7722
7723    procedure Recursive_Compute_Depth (Project : Project_Id) is
7724       use Project_Boolean_Htable;
7725       Seen : Project_Boolean_Htable.Instance := Project_Boolean_Htable.Nil;
7726
7727       procedure Recurse (Prj : Project_Id; Depth : Natural);
7728       --  Recursive procedure that does the work, keeping track of the depth
7729
7730       -------------
7731       -- Recurse --
7732       -------------
7733
7734       procedure Recurse (Prj : Project_Id; Depth : Natural) is
7735          List : Project_List;
7736          Proj : Project_Id;
7737
7738       begin
7739          if Prj.Depth >= Depth or else Get (Seen, Prj) then
7740             return;
7741          end if;
7742
7743          --  We need a test to avoid infinite recursions with limited withs:
7744          --  If we have A -> B -> A, then when set level of A to n, we try and
7745          --  set level of B to n+1, and then level of A to n + 2, ...
7746
7747          Set (Seen, Prj, True);
7748
7749          Prj.Depth := Depth;
7750
7751          --  Visit each imported project
7752
7753          List := Prj.Imported_Projects;
7754          while List /= null loop
7755             Proj := List.Project;
7756             List := List.Next;
7757             Recurse (Prj => Proj, Depth => Depth + 1);
7758          end loop;
7759
7760          --  We again allow changing the depth of this project later on if it
7761          --  is in fact imported by a lower-level project.
7762
7763          Set (Seen, Prj, False);
7764       end Recurse;
7765
7766       Proj : Project_List;
7767
7768    --  Start of processing for Recursive_Compute_Depth
7769
7770    begin
7771       Proj := Project_Tree.Projects;
7772       while Proj /= null loop
7773          Proj.Project.Depth := 0;
7774          Proj := Proj.Next;
7775       end loop;
7776
7777       Recurse (Project, Depth => 1);
7778       Reset (Seen);
7779    end Recursive_Compute_Depth;
7780
7781    -------------------------------
7782    -- Report_Compilation_Failed --
7783    -------------------------------
7784
7785    procedure Report_Compilation_Failed is
7786    begin
7787       Delete_All_Temp_Files;
7788       Exit_Program (E_Fatal);
7789    end Report_Compilation_Failed;
7790
7791    ------------------------
7792    -- Sigint_Intercepted --
7793    ------------------------
7794
7795    procedure Sigint_Intercepted is
7796       SIGINT  : constant := 2;
7797
7798    begin
7799       Set_Standard_Error;
7800       Write_Line ("*** Interrupted ***");
7801
7802       --  Send SIGINT to all outstanding compilation processes spawned
7803
7804       for J in 1 .. Outstanding_Compiles loop
7805          Kill (Running_Compile (J).Pid, SIGINT, 1);
7806       end loop;
7807
7808       Delete_All_Temp_Files;
7809       OS_Exit (1);
7810       --  ??? OS_Exit (1) is equivalent to Exit_Program (E_No_Compile),
7811       --  shouldn't that be Exit_Program (E_Abort) instead?
7812    end Sigint_Intercepted;
7813
7814    -------------------
7815    -- Scan_Make_Arg --
7816    -------------------
7817
7818    procedure Scan_Make_Arg
7819      (Project_Node_Tree : Project_Node_Tree_Ref;
7820       Argv              : String;
7821       And_Save          : Boolean)
7822    is
7823       Success : Boolean;
7824
7825    begin
7826       Gnatmake_Switch_Found := True;
7827
7828       pragma Assert (Argv'First = 1);
7829
7830       if Argv'Length = 0 then
7831          return;
7832       end if;
7833
7834       --  If the previous switch has set the Project_File_Name_Present flag
7835       --  (that is we have seen a -P alone), then the next argument is the name
7836       --  of the project file.
7837
7838       if Project_File_Name_Present and then Project_File_Name = null then
7839          if Argv (1) = '-' then
7840             Make_Failed ("project file name missing after -P");
7841
7842          else
7843             Project_File_Name_Present := False;
7844             Project_File_Name := new String'(Argv);
7845          end if;
7846
7847       --  If the previous switch has set the Output_File_Name_Present flag
7848       --  (that is we have seen a -o), then the next argument is the name of
7849       --  the output executable.
7850
7851       elsif Output_File_Name_Present
7852         and then not Output_File_Name_Seen
7853       then
7854          Output_File_Name_Seen := True;
7855
7856          if Argv (1) = '-' then
7857             Make_Failed ("output file name missing after -o");
7858
7859          else
7860             Add_Switch ("-o", Linker, And_Save => And_Save);
7861             Add_Switch (Executable_Name (Argv), Linker, And_Save => And_Save);
7862          end if;
7863
7864       --  If the previous switch has set the Object_Directory_Present flag
7865       --  (that is we have seen a -D), then the next argument is the path name
7866       --  of the object directory.
7867
7868       elsif Object_Directory_Present
7869         and then not Object_Directory_Seen
7870       then
7871          Object_Directory_Seen := True;
7872
7873          if Argv (1) = '-' then
7874             Make_Failed ("object directory path name missing after -D");
7875
7876          elsif not Is_Directory (Argv) then
7877             Make_Failed ("cannot find object directory """ & Argv & """");
7878
7879          else
7880             --  Record the object directory. Make sure it ends with a directory
7881             --  separator.
7882
7883             declare
7884                Norm : constant String := Normalize_Pathname (Argv);
7885
7886             begin
7887                if Norm (Norm'Last) = Directory_Separator then
7888                   Object_Directory_Path := new String'(Norm);
7889                else
7890                   Object_Directory_Path :=
7891                     new String'(Norm & Directory_Separator);
7892                end if;
7893
7894                Add_Lib_Search_Dir (Norm);
7895
7896                --  Specify the object directory to the binder
7897
7898                Add_Switch ("-aO" & Norm, Binder, And_Save => And_Save);
7899             end;
7900
7901          end if;
7902
7903       --  Then check if we are dealing with -cargs/-bargs/-largs/-margs
7904
7905       elsif Argv = "-bargs"
7906               or else
7907             Argv = "-cargs"
7908               or else
7909             Argv = "-largs"
7910               or else
7911             Argv = "-margs"
7912       then
7913          case Argv (2) is
7914             when 'c' => Program_Args := Compiler;
7915             when 'b' => Program_Args := Binder;
7916             when 'l' => Program_Args := Linker;
7917             when 'm' => Program_Args := None;
7918
7919             when others =>
7920                raise Program_Error;
7921          end case;
7922
7923       --  A special test is needed for the -o switch within a -largs since that
7924       --  is another way to specify the name of the final executable.
7925
7926       elsif Program_Args = Linker
7927         and then Argv = "-o"
7928       then
7929          Make_Failed ("switch -o not allowed within a -largs. " &
7930                       "Use -o directly.");
7931
7932       --  Check to see if we are reading switches after a -cargs, -bargs or
7933       --  -largs switch. If so, save it.
7934
7935       elsif Program_Args /= None then
7936
7937          --  Check to see if we are reading -I switches in order
7938          --  to take into account in the src & lib search directories.
7939
7940          if Argv'Length > 2 and then Argv (1 .. 2) = "-I" then
7941             if Argv (3 .. Argv'Last) = "-" then
7942                Look_In_Primary_Dir := False;
7943
7944             elsif Program_Args = Compiler then
7945                if Argv (3 .. Argv'Last) /= "-" then
7946                   Add_Source_Search_Dir (Argv (3 .. Argv'Last), And_Save);
7947                end if;
7948
7949             elsif Program_Args = Binder then
7950                Add_Library_Search_Dir (Argv (3 .. Argv'Last), And_Save);
7951             end if;
7952          end if;
7953
7954          Add_Switch (Argv, Program_Args, And_Save => And_Save);
7955
7956       --  Handle non-default compiler, binder, linker, and handle --RTS switch
7957
7958       elsif Argv'Length > 2 and then Argv (1 .. 2) = "--" then
7959          if Argv'Length > 6
7960            and then Argv (1 .. 6) = "--GCC="
7961          then
7962             declare
7963                Program_Args : constant Argument_List_Access :=
7964                                 Argument_String_To_List
7965                                   (Argv (7 .. Argv'Last));
7966
7967             begin
7968                if And_Save then
7969                   Saved_Gcc := new String'(Program_Args.all (1).all);
7970                else
7971                   Gcc := new String'(Program_Args.all (1).all);
7972                end if;
7973
7974                for J in 2 .. Program_Args.all'Last loop
7975                   Add_Switch
7976                     (Program_Args.all (J).all, Compiler, And_Save => And_Save);
7977                end loop;
7978             end;
7979
7980          elsif Argv'Length > 11
7981            and then Argv (1 .. 11) = "--GNATBIND="
7982          then
7983             declare
7984                Program_Args : constant Argument_List_Access :=
7985                                 Argument_String_To_List
7986                                   (Argv (12 .. Argv'Last));
7987
7988             begin
7989                if And_Save then
7990                   Saved_Gnatbind := new String'(Program_Args.all (1).all);
7991                else
7992                   Gnatbind := new String'(Program_Args.all (1).all);
7993                end if;
7994
7995                for J in 2 .. Program_Args.all'Last loop
7996                   Add_Switch
7997                     (Program_Args.all (J).all, Binder, And_Save => And_Save);
7998                end loop;
7999             end;
8000
8001          elsif Argv'Length > 11
8002            and then Argv (1 .. 11) = "--GNATLINK="
8003          then
8004             declare
8005                Program_Args : constant Argument_List_Access :=
8006                                 Argument_String_To_List
8007                                   (Argv (12 .. Argv'Last));
8008             begin
8009                if And_Save then
8010                   Saved_Gnatlink := new String'(Program_Args.all (1).all);
8011                else
8012                   Gnatlink := new String'(Program_Args.all (1).all);
8013                end if;
8014
8015                for J in 2 .. Program_Args.all'Last loop
8016                   Add_Switch (Program_Args.all (J).all, Linker);
8017                end loop;
8018             end;
8019
8020          elsif Argv'Length >= 5 and then
8021            Argv (1 .. 5) = "--RTS"
8022          then
8023             Add_Switch (Argv, Compiler, And_Save => And_Save);
8024             Add_Switch (Argv, Binder,   And_Save => And_Save);
8025
8026             if Argv'Length <= 6 or else Argv (6) /= '=' then
8027                Make_Failed ("missing path for --RTS");
8028
8029             else
8030                --  Check that this is the first time we see this switch or
8031                --  if it is not the first time, the same path is specified.
8032
8033                if RTS_Specified = null then
8034                   RTS_Specified := new String'(Argv (7 .. Argv'Last));
8035
8036                elsif RTS_Specified.all /= Argv (7 .. Argv'Last) then
8037                   Make_Failed ("--RTS cannot be specified multiple times");
8038                end if;
8039
8040                --  Valid --RTS switch
8041
8042                No_Stdinc := True;
8043                No_Stdlib := True;
8044                RTS_Switch := True;
8045
8046                declare
8047                   Src_Path_Name : constant String_Ptr :=
8048                                     Get_RTS_Search_Dir
8049                                       (Argv (7 .. Argv'Last), Include);
8050
8051                   Lib_Path_Name : constant String_Ptr :=
8052                                     Get_RTS_Search_Dir
8053                                       (Argv (7 .. Argv'Last), Objects);
8054
8055                begin
8056                   if Src_Path_Name /= null
8057                     and then Lib_Path_Name /= null
8058                   then
8059                      --  Set RTS_*_Path_Name variables, so that correct direct-
8060                      --  ories will be set when Osint.Add_Default_Search_Dirs
8061                      --  is called later.
8062
8063                      RTS_Src_Path_Name := Src_Path_Name;
8064                      RTS_Lib_Path_Name := Lib_Path_Name;
8065
8066                   elsif Src_Path_Name = null
8067                     and then Lib_Path_Name = null
8068                   then
8069                      Make_Failed ("RTS path not valid: missing " &
8070                                   "adainclude and adalib directories");
8071
8072                   elsif Src_Path_Name = null then
8073                      Make_Failed ("RTS path not valid: missing adainclude " &
8074                                   "directory");
8075
8076                   elsif  Lib_Path_Name = null then
8077                      Make_Failed ("RTS path not valid: missing adalib " &
8078                                   "directory");
8079                   end if;
8080                end;
8081             end if;
8082
8083          elsif Argv'Length > Source_Info_Option'Length and then
8084            Argv (1 .. Source_Info_Option'Length) = Source_Info_Option
8085          then
8086             Project_Tree.Source_Info_File_Name :=
8087               new String'(Argv (Source_Info_Option'Length + 1 .. Argv'Last));
8088
8089          elsif Argv'Length >= 8 and then
8090            Argv (1 .. 8) = "--param="
8091          then
8092             Add_Switch (Argv, Compiler, And_Save => And_Save);
8093             Add_Switch (Argv, Linker,   And_Save => And_Save);
8094
8095          elsif Argv = Create_Map_File_Switch then
8096             Map_File := new String'("");
8097
8098          elsif Argv'Length > Create_Map_File_Switch'Length + 1
8099            and then
8100              Argv (1 .. Create_Map_File_Switch'Length) = Create_Map_File_Switch
8101            and then
8102              Argv (Create_Map_File_Switch'Length + 1) = '='
8103          then
8104             Map_File :=
8105               new String'
8106                 (Argv (Create_Map_File_Switch'Length + 2 .. Argv'Last));
8107
8108          else
8109             Scan_Make_Switches (Project_Node_Tree, Argv, Success);
8110          end if;
8111
8112       --  If we have seen a regular switch process it
8113
8114       elsif Argv (1) = '-' then
8115          if Argv'Length = 1 then
8116             Make_Failed ("switch character cannot be followed by a blank");
8117
8118          --  Incorrect switches that should start with "--"
8119
8120          elsif     (Argv'Length > 5  and then Argv (1 .. 5) = "-RTS=")
8121            or else (Argv'Length > 5  and then Argv (1 .. 5) = "-GCC=")
8122            or else (Argv'Length > 8  and then Argv (1 .. 7) = "-param=")
8123            or else (Argv'Length > 10 and then Argv (1 .. 10) = "-GNATLINK=")
8124            or else (Argv'Length > 10 and then Argv (1 .. 10) = "-GNATBIND=")
8125          then
8126             Make_Failed ("option " & Argv & " should start with '--'");
8127
8128          --  -I-
8129
8130          elsif Argv (2 .. Argv'Last) = "I-" then
8131             Look_In_Primary_Dir := False;
8132
8133          --  Forbid  -?-  or  -??-  where ? is any character
8134
8135          elsif (Argv'Length = 3 and then Argv (3) = '-')
8136            or else (Argv'Length = 4 and then Argv (4) = '-')
8137          then
8138             Make_Failed
8139               ("trailing ""-"" at the end of " & Argv & " forbidden.");
8140
8141          --  -Idir
8142
8143          elsif Argv (2) = 'I' then
8144             Add_Source_Search_Dir  (Argv (3 .. Argv'Last), And_Save);
8145             Add_Library_Search_Dir (Argv (3 .. Argv'Last), And_Save);
8146             Add_Switch (Argv, Compiler, And_Save => And_Save);
8147             Add_Switch (Argv, Binder,   And_Save => And_Save);
8148
8149          --  -aIdir (to gcc this is like a -I switch)
8150
8151          elsif Argv'Length >= 3 and then Argv (2 .. 3) = "aI" then
8152             Add_Source_Search_Dir (Argv (4 .. Argv'Last), And_Save);
8153             Add_Switch
8154               ("-I" & Argv (4 .. Argv'Last), Compiler, And_Save => And_Save);
8155             Add_Switch (Argv, Binder, And_Save => And_Save);
8156
8157          --  -aOdir
8158
8159          elsif Argv'Length >= 3 and then Argv (2 .. 3) = "aO" then
8160             Add_Library_Search_Dir (Argv (4 .. Argv'Last), And_Save);
8161             Add_Switch (Argv, Binder, And_Save => And_Save);
8162
8163          --  -aLdir (to gnatbind this is like a -aO switch)
8164
8165          elsif Argv'Length >= 3 and then Argv (2 .. 3) = "aL" then
8166             Mark_Directory (Argv (4 .. Argv'Last), Ada_Lib_Dir, And_Save);
8167             Add_Library_Search_Dir (Argv (4 .. Argv'Last), And_Save);
8168             Add_Switch
8169               ("-aO" & Argv (4 .. Argv'Last), Binder, And_Save => And_Save);
8170
8171          --  -aamp_target=...
8172
8173          elsif Argv'Length >= 13 and then Argv (2 .. 13) = "aamp_target=" then
8174             Add_Switch (Argv, Compiler, And_Save => And_Save);
8175
8176             --  Set the aamp_target environment variable so that the binder and
8177             --  linker will use the proper target library. This is consistent
8178             --  with how things work when -aamp_target is passed on the command
8179             --  line to gnaampmake.
8180
8181             Setenv ("aamp_target", Argv (14 .. Argv'Last));
8182
8183          --  -Adir (to gnatbind this is like a -aO switch, to gcc like a -I)
8184
8185          elsif Argv (2) = 'A' then
8186             Mark_Directory (Argv (3 .. Argv'Last), Ada_Lib_Dir, And_Save);
8187             Add_Source_Search_Dir  (Argv (3 .. Argv'Last), And_Save);
8188             Add_Library_Search_Dir (Argv (3 .. Argv'Last), And_Save);
8189             Add_Switch
8190               ("-I"  & Argv (3 .. Argv'Last), Compiler, And_Save => And_Save);
8191             Add_Switch
8192               ("-aO" & Argv (3 .. Argv'Last), Binder,   And_Save => And_Save);
8193
8194          --  -Ldir
8195
8196          elsif Argv (2) = 'L' then
8197             Add_Switch (Argv, Linker, And_Save => And_Save);
8198
8199          --  For -gxxx, -pg, -mxxx, -fxxx, -Oxxx, pass the switch to both the
8200          --  compiler and the linker (except for -gnatxxx which is only for the
8201          --  compiler). Some of the -mxxx (for example -m64) and -fxxx (for
8202          --  example -ftest-coverage for gcov) need to be used when compiling
8203          --  the binder generated files, and using all these gcc switches for
8204          --  them should not be a problem. Pass -Oxxx to the linker for LTO.
8205
8206          elsif
8207            (Argv (2) = 'g' and then (Argv'Last < 5
8208                                        or else Argv (2 .. 5) /= "gnat"))
8209              or else Argv (2 .. Argv'Last) = "pg"
8210              or else (Argv (2) = 'm' and then Argv'Last > 2)
8211              or else (Argv (2) = 'f' and then Argv'Last > 2)
8212              or else Argv (2) = 'O'
8213          then
8214             Add_Switch (Argv, Compiler, And_Save => And_Save);
8215             Add_Switch (Argv, Linker,   And_Save => And_Save);
8216
8217             --  The following condition has to be kept synchronized with
8218             --  the Process_Multilib one.
8219
8220             if Argv (2) = 'm'
8221               and then Argv /= "-mieee"
8222             then
8223                N_M_Switch := N_M_Switch + 1;
8224             end if;
8225
8226          --  -C=<mapping file>
8227
8228          elsif Argv'Last > 2 and then Argv (2) = 'C' then
8229             if And_Save then
8230                if Argv (3) /= '=' or else Argv'Last <= 3 then
8231                   Make_Failed ("illegal switch " & Argv);
8232                end if;
8233
8234                Gnatmake_Mapping_File := new String'(Argv (4 .. Argv'Last));
8235             end if;
8236
8237          --  -D
8238
8239          elsif Argv'Last = 2 and then Argv (2) = 'D' then
8240             if Project_File_Name /= null then
8241                Make_Failed
8242                  ("-D cannot be used in conjunction with a project file");
8243
8244             else
8245                Scan_Make_Switches (Project_Node_Tree, Argv, Success);
8246             end if;
8247
8248          --  -d
8249
8250          elsif Argv (2) = 'd' and then Argv'Last = 2 then
8251             Display_Compilation_Progress := True;
8252
8253          --  -i
8254
8255          elsif Argv'Last = 2 and then Argv (2) = 'i' then
8256             if Project_File_Name /= null then
8257                Make_Failed
8258                  ("-i cannot be used in conjunction with a project file");
8259             else
8260                Scan_Make_Switches (Project_Node_Tree, Argv, Success);
8261             end if;
8262
8263          --  -j (need to save the result)
8264
8265          elsif Argv (2) = 'j' then
8266             Scan_Make_Switches (Project_Node_Tree, Argv, Success);
8267
8268             if And_Save then
8269                Saved_Maximum_Processes := Maximum_Processes;
8270             end if;
8271
8272          --  -m
8273
8274          elsif Argv (2) = 'm' and then Argv'Last = 2 then
8275             Minimal_Recompilation := True;
8276
8277          --  -u
8278
8279          elsif Argv (2) = 'u' and then Argv'Last = 2 then
8280             Unique_Compile := True;
8281             Compile_Only   := True;
8282             Do_Bind_Step   := False;
8283             Do_Link_Step   := False;
8284
8285          --  -U
8286
8287          elsif Argv (2) = 'U'
8288            and then Argv'Last = 2
8289          then
8290             Unique_Compile_All_Projects := True;
8291             Unique_Compile := True;
8292             Compile_Only   := True;
8293             Do_Bind_Step   := False;
8294             Do_Link_Step   := False;
8295
8296          --  -Pprj or -P prj (only once, and only on the command line)
8297
8298          elsif Argv (2) = 'P' then
8299             if Project_File_Name /= null then
8300                Make_Failed ("cannot have several project files specified");
8301
8302             elsif Object_Directory_Path /= null then
8303                Make_Failed
8304                  ("-D cannot be used in conjunction with a project file");
8305
8306             elsif In_Place_Mode then
8307                Make_Failed
8308                  ("-i cannot be used in conjunction with a project file");
8309
8310             elsif not And_Save then
8311
8312                --  It could be a tool other than gnatmake (e.g. gnatdist)
8313                --  or a -P switch inside a project file.
8314
8315                Fail
8316                  ("either the tool is not ""project-aware"" or " &
8317                   "a project file is specified inside a project file");
8318
8319             elsif Argv'Last = 2 then
8320
8321                --  -P is used alone: the project file name is the next option
8322
8323                Project_File_Name_Present := True;
8324
8325             else
8326                Project_File_Name := new String'(Argv (3 .. Argv'Last));
8327             end if;
8328
8329          --  -vPx  (verbosity of the parsing of the project files)
8330
8331          elsif Argv'Last = 4
8332            and then Argv (2 .. 3) = "vP"
8333            and then Argv (4) in '0' .. '2'
8334          then
8335             if And_Save then
8336                case Argv (4) is
8337                   when '0' =>
8338                      Current_Verbosity := Prj.Default;
8339                   when '1' =>
8340                      Current_Verbosity := Prj.Medium;
8341                   when '2' =>
8342                      Current_Verbosity := Prj.High;
8343                   when others =>
8344                      null;
8345                end case;
8346             end if;
8347
8348          --  -Xext=val  (External assignment)
8349
8350          elsif Argv (2) = 'X'
8351            and then Is_External_Assignment (Project_Node_Tree, Argv)
8352          then
8353             --  Is_External_Assignment has side effects when it returns True
8354
8355             null;
8356
8357          --  If -gnath is present, then generate the usage information right
8358          --  now and do not pass this option on to the compiler calls.
8359
8360          elsif Argv = "-gnath" then
8361             Usage;
8362
8363          --  If -gnatc is specified, make sure the bind and link steps are not
8364          --  executed.
8365
8366          elsif Argv'Length >= 6 and then Argv (2 .. 6) = "gnatc" then
8367
8368             --  If -gnatc is specified, make sure the bind and link steps are
8369             --  not executed.
8370
8371             Add_Switch (Argv, Compiler, And_Save => And_Save);
8372             Operating_Mode           := Check_Semantics;
8373             Check_Object_Consistency := False;
8374             Compile_Only             := True;
8375             Do_Bind_Step             := False;
8376             Do_Link_Step             := False;
8377
8378          elsif Argv (2 .. Argv'Last) = "nostdlib" then
8379
8380             --  Pass -nstdlib to gnatbind and gnatlink
8381
8382             No_Stdlib := True;
8383             Add_Switch (Argv, Binder, And_Save => And_Save);
8384             Add_Switch (Argv, Linker, And_Save => And_Save);
8385
8386          elsif Argv (2 .. Argv'Last) = "nostdinc" then
8387
8388             --  Pass -nostdinc to the Compiler and to gnatbind
8389
8390             No_Stdinc := True;
8391             Add_Switch (Argv, Compiler, And_Save => And_Save);
8392             Add_Switch (Argv, Binder,   And_Save => And_Save);
8393
8394          --  All other switches are processed by Scan_Make_Switches. If the
8395          --  call returns with Gnatmake_Switch_Found = False, then the switch
8396          --  is passed to the compiler.
8397
8398          else
8399             Scan_Make_Switches
8400               (Project_Node_Tree, Argv, Gnatmake_Switch_Found);
8401
8402             if not Gnatmake_Switch_Found then
8403                Add_Switch (Argv, Compiler, And_Save => And_Save);
8404             end if;
8405          end if;
8406
8407       --  If not a switch it must be a file name
8408
8409       else
8410          if And_Save then
8411             Main_On_Command_Line := True;
8412          end if;
8413
8414          Add_File (Argv);
8415          Mains.Add_Main (Argv);
8416       end if;
8417    end Scan_Make_Arg;
8418
8419    -----------------
8420    -- Switches_Of --
8421    -----------------
8422
8423    function Switches_Of
8424      (Source_File      : File_Name_Type;
8425       Source_File_Name : String;
8426       Source_Index     : Int;
8427       Project          : Project_Id;
8428       In_Package       : Package_Id;
8429       Allow_ALI        : Boolean) return Variable_Value
8430    is
8431       Lang : constant Language_Ptr := Get_Language_From_Name (Project, "ada");
8432
8433       Switches : Variable_Value;
8434
8435       Defaults : constant Array_Element_Id :=
8436                    Prj.Util.Value_Of
8437                      (Name      => Name_Default_Switches,
8438                       In_Arrays =>
8439                         Project_Tree.Packages.Table
8440                           (In_Package).Decl.Arrays,
8441                       In_Tree   => Project_Tree);
8442
8443       Switches_Array : constant Array_Element_Id :=
8444                          Prj.Util.Value_Of
8445                            (Name      => Name_Switches,
8446                             In_Arrays =>
8447                               Project_Tree.Packages.Table
8448                                 (In_Package).Decl.Arrays,
8449                             In_Tree   => Project_Tree);
8450
8451    begin
8452       --  First, try Switches (<file name>)
8453
8454       Switches :=
8455         Prj.Util.Value_Of
8456           (Index           => Name_Id (Source_File),
8457            Src_Index       => Source_Index,
8458            In_Array        => Switches_Array,
8459            In_Tree         => Project_Tree,
8460            Allow_Wildcards => True);
8461
8462       --  Check also without the suffix
8463
8464       if Switches = Nil_Variable_Value
8465         and then Lang /= null
8466       then
8467          declare
8468             Naming      : Lang_Naming_Data renames Lang.Config.Naming_Data;
8469             Name        : String (1 .. Source_File_Name'Length + 3);
8470             Last        : Positive := Source_File_Name'Length;
8471             Spec_Suffix : String   := Get_Name_String (Naming.Spec_Suffix);
8472             Body_Suffix : String   := Get_Name_String (Naming.Body_Suffix);
8473             Truncated   : Boolean  := False;
8474
8475          begin
8476             Canonical_Case_File_Name (Spec_Suffix);
8477             Canonical_Case_File_Name (Body_Suffix);
8478             Name (1 .. Last) := Source_File_Name;
8479
8480             if Last > Body_Suffix'Length
8481                and then Name (Last - Body_Suffix'Length + 1 .. Last) =
8482                                                                   Body_Suffix
8483             then
8484                Truncated := True;
8485                Last := Last - Body_Suffix'Length;
8486             end if;
8487
8488             if not Truncated
8489               and then Last > Spec_Suffix'Length
8490               and then Name (Last - Spec_Suffix'Length + 1 .. Last) =
8491                                                                  Spec_Suffix
8492             then
8493                Truncated := True;
8494                Last := Last - Spec_Suffix'Length;
8495             end if;
8496
8497             if Truncated then
8498                Name_Len := 0;
8499                Add_Str_To_Name_Buffer (Name (1 .. Last));
8500                Switches :=
8501                  Prj.Util.Value_Of
8502                    (Index           => Name_Find,
8503                     Src_Index       => 0,
8504                     In_Array        => Switches_Array,
8505                     In_Tree         => Project_Tree,
8506                     Allow_Wildcards => True);
8507
8508                if Switches = Nil_Variable_Value and then Allow_ALI then
8509                   Last := Source_File_Name'Length;
8510
8511                   while Name (Last) /= '.' loop
8512                      Last := Last - 1;
8513                   end loop;
8514
8515                   Name_Len := 0;
8516                   Add_Str_To_Name_Buffer (Name (1 .. Last));
8517                   Add_Str_To_Name_Buffer ("ali");
8518
8519                   Switches :=
8520                     Prj.Util.Value_Of
8521                       (Index     => Name_Find,
8522                        Src_Index => 0,
8523                        In_Array  => Switches_Array,
8524                        In_Tree   => Project_Tree);
8525                end if;
8526             end if;
8527          end;
8528       end if;
8529
8530       --  Next, try Switches ("Ada")
8531
8532       if Switches = Nil_Variable_Value then
8533          Switches :=
8534            Prj.Util.Value_Of
8535              (Index                  => Name_Ada,
8536               Src_Index              => 0,
8537               In_Array               => Switches_Array,
8538               In_Tree                => Project_Tree,
8539               Force_Lower_Case_Index => True);
8540
8541          if Switches /= Nil_Variable_Value then
8542             Switch_May_Be_Passed_To_The_Compiler := False;
8543          end if;
8544       end if;
8545
8546       --  Next, try Switches (others)
8547
8548       if Switches = Nil_Variable_Value then
8549          Switches :=
8550            Prj.Util.Value_Of
8551              (Index     => All_Other_Names,
8552               Src_Index => 0,
8553               In_Array  => Switches_Array,
8554               In_Tree   => Project_Tree);
8555
8556          if Switches /= Nil_Variable_Value then
8557             Switch_May_Be_Passed_To_The_Compiler := False;
8558          end if;
8559       end if;
8560
8561       --  And finally, Default_Switches ("Ada")
8562
8563       if Switches = Nil_Variable_Value then
8564          Switches :=
8565            Prj.Util.Value_Of
8566              (Index     => Name_Ada,
8567               Src_Index => 0,
8568               In_Array  => Defaults,
8569               In_Tree   => Project_Tree);
8570       end if;
8571
8572       return Switches;
8573    end Switches_Of;
8574
8575    -----------
8576    -- Usage --
8577    -----------
8578
8579    procedure Usage is
8580    begin
8581       if Usage_Needed then
8582          Usage_Needed := False;
8583          Makeusg;
8584       end if;
8585    end Usage;
8586
8587 begin
8588    --  Make sure that in case of failure, the temp files will be deleted
8589
8590    Prj.Com.Fail    := Make_Failed'Access;
8591    MLib.Fail       := Make_Failed'Access;
8592    Makeutl.Do_Fail := Make_Failed'Access;
8593 end Make;