OSDN Git Service

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