OSDN Git Service

2007-10-15 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnatlink.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                             G N A T L I N K                              --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1996-2007, 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 --  Gnatlink usage: please consult the gnat documentation
27
28 with ALI;      use ALI;
29 with Csets;
30 with Gnatvsn;  use Gnatvsn;
31 with Hostparm;
32 with Indepsw;  use Indepsw;
33 with Namet;    use Namet;
34 with Opt;
35 with Osint;    use Osint;
36 with Output;   use Output;
37 with Snames;
38 with Switch;   use Switch;
39 with System;   use System;
40 with Table;
41 with Targparm; use Targparm;
42 with Types;
43
44 with Ada.Command_Line;     use Ada.Command_Line;
45 with Ada.Exceptions;       use Ada.Exceptions;
46
47 with System.OS_Lib;        use System.OS_Lib;
48 with System.CRTL;
49
50 with Interfaces.C_Streams; use Interfaces.C_Streams;
51 with Interfaces.C.Strings; use Interfaces.C.Strings;
52
53 procedure Gnatlink is
54    pragma Ident (Gnatvsn.Gnat_Static_Version_String);
55
56    Shared_Libgcc_String : constant String := "-shared-libgcc";
57    Shared_Libgcc        : constant String_Access :=
58                             new String'(Shared_Libgcc_String);
59    --  Used to invoke gcc when the binder is invoked with -shared
60
61    Static_Libgcc_String : constant String := "-static-libgcc";
62    Static_Libgcc        : constant String_Access :=
63                             new String'(Static_Libgcc_String);
64    --  Used to invoke gcc when shared libs are not used
65
66    package Gcc_Linker_Options is new Table.Table (
67      Table_Component_Type => String_Access,
68      Table_Index_Type     => Integer,
69      Table_Low_Bound      => 1,
70      Table_Initial        => 20,
71      Table_Increment      => 100,
72      Table_Name           => "Gnatlink.Gcc_Linker_Options");
73    --  Comments needed ???
74
75    package Libpath is new Table.Table (
76      Table_Component_Type => Character,
77      Table_Index_Type     => Integer,
78      Table_Low_Bound      => 1,
79      Table_Initial        => 4096,
80      Table_Increment      => 100,
81      Table_Name           => "Gnatlink.Libpath");
82    --  Comments needed ???
83
84    package Linker_Options is new Table.Table (
85      Table_Component_Type => String_Access,
86      Table_Index_Type     => Integer,
87      Table_Low_Bound      => 1,
88      Table_Initial        => 20,
89      Table_Increment      => 100,
90      Table_Name           => "Gnatlink.Linker_Options");
91    --  Comments needed ???
92
93    package Linker_Objects is new Table.Table (
94      Table_Component_Type => String_Access,
95      Table_Index_Type     => Integer,
96      Table_Low_Bound      => 1,
97      Table_Initial        => 20,
98      Table_Increment      => 100,
99      Table_Name           => "Gnatlink.Linker_Objects");
100    --  This table collects the objects file to be passed to the linker. In the
101    --  case where the linker command line is too long then programs objects
102    --  are put on the Response_File_Objects table. Note that the binder object
103    --  file and the user's objects remain in this table. This is very
104    --  important because on the GNU linker command line the -L switch is not
105    --  used to look for objects files but -L switch is used to look for
106    --  objects listed in the response file. This is not a problem with the
107    --  applications objects as they are specified with a fullname.
108
109    package Response_File_Objects is new Table.Table (
110      Table_Component_Type => String_Access,
111      Table_Index_Type     => Integer,
112      Table_Low_Bound      => 1,
113      Table_Initial        => 20,
114      Table_Increment      => 100,
115      Table_Name           => "Gnatlink.Response_File_Objects");
116    --  This table collects the objects file that are to be put in the response
117    --  file. Only application objects are collected there (see details in
118    --  Linker_Objects table comments)
119
120    package Binder_Options_From_ALI is new Table.Table (
121      Table_Component_Type => String_Access,
122      Table_Index_Type     => Integer,
123      Table_Low_Bound      => 1, -- equals low bound of Argument_List for Spawn
124      Table_Initial        => 20,
125      Table_Increment      => 100,
126      Table_Name           => "Gnatlink.Binder_Options_From_ALI");
127    --  This table collects the switches from the ALI file of the main
128    --  subprogram.
129
130    package Binder_Options is new Table.Table (
131      Table_Component_Type => String_Access,
132      Table_Index_Type     => Integer,
133      Table_Low_Bound      => 1, -- equals low bound of Argument_List for Spawn
134      Table_Initial        => 20,
135      Table_Increment      => 100,
136      Table_Name           => "Gnatlink.Binder_Options");
137    --  This table collects the arguments to be passed to compile the binder
138    --  generated file.
139
140    Gcc : String_Access := Program_Name ("gcc");
141
142    Read_Mode  : constant String := "r" & ASCII.Nul;
143
144    Begin_Info : String := "--  BEGIN Object file/option list";
145    End_Info   : String := "--  END Object file/option list   ";
146    --  Note: above lines are modified in C mode, see option processing
147
148    Gcc_Path             : String_Access;
149    Linker_Path          : String_Access;
150
151    Output_File_Name     : String_Access;
152    Ali_File_Name        : String_Access;
153    Binder_Spec_Src_File : String_Access;
154    Binder_Body_Src_File : String_Access;
155    Binder_Ali_File      : String_Access;
156    Binder_Obj_File      : String_Access;
157
158    Tname    : Temp_File_Name;
159    Tname_FD : File_Descriptor := Invalid_FD;
160    --  Temporary file used by linker to pass list of object files on
161    --  certain systems with limitations on size of arguments.
162
163    Debug_Flag_Present : Boolean := False;
164    Verbose_Mode       : Boolean := False;
165    Very_Verbose_Mode  : Boolean := False;
166
167    Ada_Bind_File : Boolean := True;
168    --  Set to True if bind file is generated in Ada
169
170    Standard_Gcc  : Boolean := True;
171
172    Compile_Bind_File : Boolean := True;
173    --  Set to False if bind file is not to be compiled
174
175    Create_Map_File : Boolean := False;
176    --  Set to True by switch -M. The map file name is derived from
177    --  the ALI file name (mainprog.ali => mainprog.map).
178
179    Object_List_File_Supported : Boolean;
180    for Object_List_File_Supported'Size use Character'Size;
181    pragma Import
182      (C, Object_List_File_Supported, "__gnat_objlist_file_supported");
183    --  Predicate indicating whether the linker has an option whereby the
184    --  names of object files can be passed to the linker in a file.
185
186    Object_List_File_Required : Boolean := False;
187    --  Set to True to force generation of a response file
188
189    function Base_Name (File_Name : String) return String;
190    --  Return just the file name part without the extension (if present)
191
192    procedure Delete (Name : String);
193    --  Wrapper to unlink as status is ignored by this application
194
195    procedure Error_Msg (Message : String);
196    --  Output the error or warning Message
197
198    procedure Exit_With_Error (Error : String);
199    --  Output Error and exit program with a fatal condition
200
201    procedure Process_Args;
202    --  Go through all the arguments and build option tables
203
204    procedure Process_Binder_File (Name : String);
205    --  Reads the binder file and extracts linker arguments
206
207    procedure Usage;
208    --  Display usage
209
210    procedure Write_Header;
211    --  Show user the program name, version and copyright
212
213    procedure Write_Usage;
214    --  Show user the program options
215
216    ---------------
217    -- Base_Name --
218    ---------------
219
220    function Base_Name (File_Name : String) return String is
221       Findex1 : Natural;
222       Findex2 : Natural;
223
224    begin
225       Findex1 := File_Name'First;
226
227       --  The file might be specified by a full path name. However,
228       --  we want the path to be stripped away.
229
230       for J in reverse File_Name'Range loop
231          if Is_Directory_Separator (File_Name (J)) then
232             Findex1 := J + 1;
233             exit;
234          end if;
235       end loop;
236
237       Findex2 := File_Name'Last;
238       while Findex2 > Findex1
239         and then File_Name (Findex2) /=  '.'
240       loop
241          Findex2 := Findex2 - 1;
242       end loop;
243
244       if Findex2 = Findex1 then
245          Findex2 := File_Name'Last + 1;
246       end if;
247
248       return File_Name (Findex1 .. Findex2 - 1);
249    end Base_Name;
250
251    ------------
252    -- Delete --
253    ------------
254
255    procedure Delete (Name : String) is
256       Status : int;
257       pragma Unreferenced (Status);
258    begin
259       Status := unlink (Name'Address);
260       --  Is it really right to ignore an error here ???
261    end Delete;
262
263    ---------------
264    -- Error_Msg --
265    ---------------
266
267    procedure Error_Msg (Message : String) is
268    begin
269       Write_Str (Base_Name (Command_Name));
270       Write_Str (": ");
271       Write_Str (Message);
272       Write_Eol;
273    end Error_Msg;
274
275    ---------------------
276    -- Exit_With_Error --
277    ---------------------
278
279    procedure Exit_With_Error (Error : String) is
280    begin
281       Error_Msg (Error);
282       Exit_Program (E_Fatal);
283    end Exit_With_Error;
284
285    ------------------
286    -- Process_Args --
287    ------------------
288
289    procedure Process_Args is
290       Next_Arg  : Integer;
291       Skip_Next : Boolean := False;
292       --  Set to true if the next argument is to be added into the list of
293       --  linker's argument without parsing it.
294
295    begin
296       --  First, check for --version and --help
297
298       Check_Version_And_Help ("GNATLINK", "1995", Usage'Unrestricted_Access);
299
300       --  Loop through arguments of gnatlink command
301
302       Next_Arg := 1;
303       loop
304          exit when Next_Arg > Argument_Count;
305
306          Process_One_Arg : declare
307             Arg : constant String := Argument (Next_Arg);
308
309          begin
310             --  Case of argument which is a switch
311
312             --  We definitely need section by section comments here ???
313
314             if Skip_Next then
315
316                --  This argument must not be parsed, just add it to the
317                --  list of linker's options.
318
319                Skip_Next := False;
320
321                Linker_Options.Increment_Last;
322                Linker_Options.Table (Linker_Options.Last) :=
323                  new String'(Arg);
324
325             elsif Arg'Length /= 0 and then Arg (1) = '-' then
326                if Arg'Length > 4 and then Arg (2 .. 5) =  "gnat" then
327                   Exit_With_Error
328                     ("invalid switch: """ & Arg & """ (gnat not needed here)");
329                end if;
330
331                if Arg = "-Xlinker" then
332
333                   --  Next argument should be sent directly to the linker.
334                   --  We do not want to parse it here.
335
336                   Skip_Next := True;
337
338                   Linker_Options.Increment_Last;
339                   Linker_Options.Table (Linker_Options.Last) :=
340                     new String'(Arg);
341
342                elsif Arg (2) = 'g'
343                  and then (Arg'Length < 5 or else Arg (2 .. 5) /= "gnat")
344                then
345                   Debug_Flag_Present := True;
346
347                   Linker_Options.Increment_Last;
348                   Linker_Options.Table (Linker_Options.Last) :=
349                    new String'(Arg);
350
351                   Binder_Options.Increment_Last;
352                   Binder_Options.Table (Binder_Options.Last) :=
353                     Linker_Options.Table (Linker_Options.Last);
354
355                elsif Arg'Length >= 3 and then Arg (2) = 'M' then
356                   declare
357                      Switches : String_List_Access;
358
359                   begin
360                      Convert (Map_File, Arg (3 .. Arg'Last), Switches);
361
362                      if Switches /= null then
363                         for J in Switches'Range loop
364                            Linker_Options.Increment_Last;
365                            Linker_Options.Table (Linker_Options.Last) :=
366                              Switches (J);
367                         end loop;
368                      end if;
369                   end;
370
371                elsif Arg'Length = 2 then
372                   case Arg (2) is
373                      when 'A' =>
374                         Ada_Bind_File := True;
375                         Begin_Info := "--  BEGIN Object file/option list";
376                         End_Info   := "--  END Object file/option list   ";
377
378                      when 'b' =>
379                         Linker_Options.Increment_Last;
380                         Linker_Options.Table (Linker_Options.Last) :=
381                           new String'(Arg);
382
383                         Binder_Options.Increment_Last;
384                         Binder_Options.Table (Binder_Options.Last) :=
385                           Linker_Options.Table (Linker_Options.Last);
386
387                         Next_Arg := Next_Arg + 1;
388
389                         if Next_Arg > Argument_Count then
390                            Exit_With_Error ("Missing argument for -b");
391                         end if;
392
393                         Get_Machine_Name : declare
394                            Name_Arg : constant String_Access :=
395                                         new String'(Argument (Next_Arg));
396
397                         begin
398                            Linker_Options.Increment_Last;
399                            Linker_Options.Table (Linker_Options.Last) :=
400                              Name_Arg;
401
402                            Binder_Options.Increment_Last;
403                            Binder_Options.Table (Binder_Options.Last) :=
404                              Name_Arg;
405
406                         end Get_Machine_Name;
407
408                      when 'C' =>
409                         Ada_Bind_File := False;
410                         Begin_Info := "/*  BEGIN Object file/option list";
411                         End_Info   := "    END Object file/option list */";
412
413                      when 'f' =>
414                         if Object_List_File_Supported then
415                            Object_List_File_Required := True;
416                         else
417                            Exit_With_Error
418                              ("Object list file not supported on this target");
419                         end if;
420
421                      when 'M' =>
422                         Create_Map_File := True;
423
424                      when 'n' =>
425                         Compile_Bind_File := False;
426
427                      when 'o' =>
428                         if VM_Target = CLI_Target then
429                            Linker_Options.Increment_Last;
430                            Linker_Options.Table (Linker_Options.Last) :=
431                               new String'("/QUIET");
432
433                         else
434                            Linker_Options.Increment_Last;
435                            Linker_Options.Table (Linker_Options.Last) :=
436                              new String'(Arg);
437                         end if;
438
439                         Next_Arg := Next_Arg + 1;
440
441                         if Next_Arg > Argument_Count then
442                            Exit_With_Error ("Missing argument for -o");
443                         end if;
444
445                         if VM_Target = CLI_Target then
446                            Output_File_Name :=
447                              new String'("/OUTPUT=" & Argument (Next_Arg));
448                         else
449                            Output_File_Name :=
450                              new String'(Argument (Next_Arg));
451                         end if;
452
453                         Linker_Options.Increment_Last;
454                         Linker_Options.Table (Linker_Options.Last) :=
455                           Output_File_Name;
456
457                      when 'R' =>
458                         Opt.Run_Path_Option := False;
459
460                      when 'v' =>
461
462                         --  Support "double" verbose mode.  Second -v
463                         --  gets sent to the linker and binder phases.
464
465                         if Verbose_Mode then
466                            Very_Verbose_Mode := True;
467
468                            Linker_Options.Increment_Last;
469                            Linker_Options.Table (Linker_Options.Last) :=
470                             new String'(Arg);
471
472                            Binder_Options.Increment_Last;
473                            Binder_Options.Table (Binder_Options.Last) :=
474                              Linker_Options.Table (Linker_Options.Last);
475
476                         else
477                            Verbose_Mode := True;
478
479                         end if;
480
481                      when others =>
482                         Linker_Options.Increment_Last;
483                         Linker_Options.Table (Linker_Options.Last) :=
484                          new String'(Arg);
485
486                   end case;
487
488                elsif Arg (2) = 'B' then
489                   Linker_Options.Increment_Last;
490                   Linker_Options.Table (Linker_Options.Last) :=
491                     new String'(Arg);
492
493                   Binder_Options.Increment_Last;
494                   Binder_Options.Table (Binder_Options.Last) :=
495                     Linker_Options.Table (Linker_Options.Last);
496
497                elsif Arg'Length >= 7 and then Arg (1 .. 7) = "--LINK=" then
498                   if Arg'Length = 7 then
499                      Exit_With_Error ("Missing argument for --LINK=");
500                   end if;
501
502                   Linker_Path :=
503                     System.OS_Lib.Locate_Exec_On_Path (Arg (8 .. Arg'Last));
504
505                   if Linker_Path = null then
506                      Exit_With_Error
507                        ("Could not locate linker: " & Arg (8 .. Arg'Last));
508                   end if;
509
510                elsif Arg'Length > 6 and then Arg (1 .. 6) = "--GCC=" then
511                   declare
512                      Program_Args : constant Argument_List_Access :=
513                                       Argument_String_To_List
514                                                  (Arg (7 .. Arg'Last));
515
516                   begin
517                      Gcc := new String'(Program_Args.all (1).all);
518                      Standard_Gcc := False;
519
520                      --  Set appropriate flags for switches passed
521
522                      for J in 2 .. Program_Args.all'Last loop
523                         declare
524                            Arg : constant String := Program_Args.all (J).all;
525                            AF  : constant Integer := Arg'First;
526
527                         begin
528                            if Arg'Length /= 0 and then Arg (AF) = '-' then
529                               if Arg (AF + 1) = 'g'
530                                 and then (Arg'Length = 2
531                                   or else Arg (AF + 2) in '0' .. '3'
532                                   or else Arg (AF + 2 .. Arg'Last) = "coff")
533                               then
534                                  Debug_Flag_Present := True;
535                               end if;
536                            end if;
537
538                            --  Add directory to source search dirs so that
539                            --  Get_Target_Parameters can find system.ads
540
541                            if Arg (AF .. AF + 1) = "-I"
542                              and then Arg'Length > 2
543                            then
544                               Add_Src_Search_Dir (Arg (AF + 2 .. Arg'Last));
545                            end if;
546
547                            --  Pass to gcc for compiling binder generated file
548                            --  No use passing libraries, it will just generate
549                            --  a warning
550
551                            if not (Arg (AF .. AF + 1) = "-l"
552                              or else Arg (AF .. AF + 1) = "-L")
553                            then
554                               Binder_Options.Increment_Last;
555                               Binder_Options.Table (Binder_Options.Last) :=
556                                 new String'(Arg);
557                            end if;
558
559                            --  Pass to gcc for linking program
560
561                            Gcc_Linker_Options.Increment_Last;
562                            Gcc_Linker_Options.Table
563                              (Gcc_Linker_Options.Last) := new String'(Arg);
564                         end;
565                      end loop;
566                   end;
567
568                --  Send all multi-character switches not recognized as
569                --  a special case by gnatlink to the linker/loader stage.
570
571                else
572                   Linker_Options.Increment_Last;
573                   Linker_Options.Table (Linker_Options.Last) :=
574                     new String'(Arg);
575                end if;
576
577             --  Here if argument is a file name rather than a switch
578
579             else
580                --  If explicit ali file, capture it
581
582                if Arg'Length > 4
583                  and then Arg (Arg'Last - 3 .. Arg'Last) = ".ali"
584                then
585                   if Ali_File_Name = null then
586                      Ali_File_Name := new String'(Arg);
587                   else
588                      Exit_With_Error ("cannot handle more than one ALI file");
589                   end if;
590
591                --  If target object file, record object file
592
593                elsif Arg'Length > Get_Target_Object_Suffix.all'Length
594                  and then Arg
595                    (Arg'Last -
596                     Get_Target_Object_Suffix.all'Length + 1 .. Arg'Last)
597                    = Get_Target_Object_Suffix.all
598                then
599                   Linker_Objects.Increment_Last;
600                   Linker_Objects.Table (Linker_Objects.Last) :=
601                     new String'(Arg);
602
603                --  If host object file, record object file
604                --  e.g. accept foo.o as well as foo.obj on VMS target
605
606                elsif Arg'Length > Get_Object_Suffix.all'Length
607                  and then Arg
608                    (Arg'Last - Get_Object_Suffix.all'Length + 1 .. Arg'Last)
609                                                 = Get_Object_Suffix.all
610                then
611                   Linker_Objects.Increment_Last;
612                   Linker_Objects.Table (Linker_Objects.Last) :=
613                     new String'(Arg);
614
615                --  If corresponding ali file exists, capture it
616
617                elsif Ali_File_Name = null
618                  and then Is_Regular_File (Arg & ".ali")
619                then
620                   Ali_File_Name := new String'(Arg & ".ali");
621
622                --  Otherwise assume this is a linker options entry, but
623                --  see below for interesting adjustment to this assumption.
624
625                else
626                   Linker_Options.Increment_Last;
627                   Linker_Options.Table (Linker_Options.Last) :=
628                     new String'(Arg);
629                end if;
630             end if;
631          end Process_One_Arg;
632
633          Next_Arg := Next_Arg + 1;
634       end loop;
635
636       --  If Ada bind file, then compile it with warnings suppressed, because
637       --  otherwise the with of the main program may cause junk warnings.
638
639       if Ada_Bind_File then
640          Binder_Options.Increment_Last;
641          Binder_Options.Table (Binder_Options.Last) := new String'("-gnatws");
642       end if;
643
644       --  If we did not get an ali file at all, and we had at least one
645       --  linker option, then assume that was the intended ali file after
646       --  all, so that we get a nicer message later on.
647
648       if Ali_File_Name = null
649         and then Linker_Options.Last >= Linker_Options.First
650       then
651          Ali_File_Name :=
652            new String'(Linker_Options.Table (Linker_Options.First).all &
653                                                                    ".ali");
654       end if;
655    end Process_Args;
656
657    -------------------------
658    -- Process_Binder_File --
659    -------------------------
660
661    procedure Process_Binder_File (Name : String) is
662       Fd : FILEs;
663       --  Binder file's descriptor
664
665       Link_Bytes : Integer := 0;
666       --  Projected number of bytes for the linker command line
667
668       Link_Max : Integer;
669       pragma Import (C, Link_Max, "__gnat_link_max");
670       --  Maximum number of bytes on the command line supported by the OS
671       --  linker. Passed this limit the response file mechanism must be used
672       --  if supported.
673
674       Next_Line : String (1 .. 1000);
675       --  Current line value
676
677       Nlast  : Integer;
678       Nfirst : Integer;
679       --  Current line slice (the slice does not contain line terminator)
680
681       Last : Integer;
682       --  Current line last character for shared libraries (without version)
683
684       Objs_Begin : Integer := 0;
685       --  First object file index in Linker_Objects table
686
687       Objs_End : Integer := 0;
688       --  Last object file index in Linker_Objects table
689
690       Status : int;
691       pragma Warnings (Off, Status);
692       --  Used for various Interfaces.C_Streams calls
693
694       Closing_Status : Boolean;
695       pragma Warnings (Off, Closing_Status);
696       --  For call to Close
697
698       GNAT_Static : Boolean := False;
699       --  Save state of -static option
700
701       GNAT_Shared : Boolean := False;
702       --  Save state of -shared option
703
704       Xlinker_Was_Previous : Boolean := False;
705       --  Indicate that "-Xlinker" was the option preceding the current
706       --  option. If True, then the current option is never suppressed.
707
708       --  Rollback data
709
710       --  These data items are used to store current binder file context.
711       --  The context is composed of the file descriptor position and the
712       --  current line together with the slice indexes (first and last
713       --  position) for this line. The rollback data are used by the
714       --  Store_File_Context and Rollback_File_Context routines below.
715       --  The file context mechanism interact only with the Get_Next_Line
716       --  call. For example:
717
718       --     Store_File_Context;
719       --     Get_Next_Line;
720       --     Rollback_File_Context;
721       --     Get_Next_Line;
722
723       --  Both Get_Next_Line calls above will read the exact same data from
724       --  the file. In other words, Next_Line, Nfirst and Nlast variables
725       --  will be set with the exact same values.
726
727       RB_File_Pos  : long;                -- File position
728       RB_Next_Line : String (1 .. 1000);  -- Current line content
729       RB_Nlast     : Integer;             -- Slice last index
730       RB_Nfirst    : Integer;             -- Slice first index
731
732       Run_Path_Option_Ptr : Interfaces.C.Strings.chars_ptr;
733       pragma Import (C, Run_Path_Option_Ptr, "__gnat_run_path_option");
734       --  Pointer to string representing the native linker option which
735       --  specifies the path where the dynamic loader should find shared
736       --  libraries. Equal to null string if this system doesn't support it.
737
738       Object_Library_Ext_Ptr : Interfaces.C.Strings.chars_ptr;
739       pragma Import
740         (C, Object_Library_Ext_Ptr, "__gnat_object_library_extension");
741       --  Pointer to string specifying the default extension for
742       --  object libraries, e.g. Unix uses ".a", VMS uses ".olb".
743
744       Object_File_Option_Ptr : Interfaces.C.Strings.chars_ptr;
745       pragma Import (C, Object_File_Option_Ptr, "__gnat_object_file_option");
746       --  Pointer to a string representing the linker option which specifies
747       --  the response file.
748
749       Using_GNU_Linker : Boolean;
750       for Using_GNU_Linker'Size use Character'Size;
751       pragma Import (C, Using_GNU_Linker, "__gnat_using_gnu_linker");
752       --  Predicate indicating whether this target uses the GNU linker. In
753       --  this case we must output a GNU linker compatible response file.
754
755       Opening : aliased constant String := """";
756       Closing : aliased constant String := '"' & ASCII.LF;
757       --  Needed to quote object paths in object list files when GNU linker
758       --  is used.
759
760       procedure Get_Next_Line;
761       --  Read the next line from the binder file without the line
762       --  terminator.
763
764       function Index (S, Pattern : String) return Natural;
765       --  Return the last occurrence of Pattern in S, or 0 if none
766
767       function Is_Option_Present (Opt : String) return Boolean;
768       --  Return true if the option Opt is already present in
769       --  Linker_Options table.
770
771       procedure Store_File_Context;
772       --  Store current file context, Fd position and current line data.
773       --  The file context is stored into the rollback data above (RB_*).
774       --  Store_File_Context can be called at any time, only the last call
775       --  will be used (i.e. this routine overwrites the file context).
776
777       procedure Rollback_File_Context;
778       --  Restore file context from rollback data. This routine must be called
779       --  after Store_File_Context. The binder file context will be restored
780       --  with the data stored by the last Store_File_Context call.
781
782       -------------------
783       -- Get_Next_Line --
784       -------------------
785
786       procedure Get_Next_Line is
787          Fchars : chars;
788
789       begin
790          Fchars := fgets (Next_Line'Address, Next_Line'Length, Fd);
791
792          if Fchars = System.Null_Address then
793             Exit_With_Error ("Error reading binder output");
794          end if;
795
796          Nfirst := Next_Line'First;
797          Nlast := Nfirst;
798          while Nlast <= Next_Line'Last
799            and then Next_Line (Nlast) /= ASCII.LF
800            and then Next_Line (Nlast) /= ASCII.CR
801          loop
802             Nlast := Nlast + 1;
803          end loop;
804
805          Nlast := Nlast - 1;
806       end Get_Next_Line;
807
808       -----------
809       -- Index --
810       -----------
811
812       function Index (S, Pattern : String) return Natural is
813          Len : constant Natural := Pattern'Length;
814
815       begin
816          for J in reverse S'First .. S'Last - Len + 1 loop
817             if Pattern = S (J .. J + Len - 1) then
818                return J;
819             end if;
820          end loop;
821
822          return 0;
823       end Index;
824
825       -----------------------
826       -- Is_Option_Present --
827       -----------------------
828
829       function Is_Option_Present (Opt : String) return Boolean is
830       begin
831          for I in 1 .. Linker_Options.Last loop
832
833             if Linker_Options.Table (I).all = Opt then
834                return True;
835             end if;
836
837          end loop;
838
839          return False;
840       end Is_Option_Present;
841
842       ---------------------------
843       -- Rollback_File_Context --
844       ---------------------------
845
846       procedure Rollback_File_Context is
847       begin
848          Next_Line := RB_Next_Line;
849          Nfirst    := RB_Nfirst;
850          Nlast     := RB_Nlast;
851          Status    := fseek (Fd, RB_File_Pos, Interfaces.C_Streams.SEEK_SET);
852
853          if Status = -1 then
854             Exit_With_Error ("Error setting file position");
855          end if;
856       end Rollback_File_Context;
857
858       ------------------------
859       -- Store_File_Context --
860       ------------------------
861
862       procedure Store_File_Context is
863          use type System.CRTL.long;
864       begin
865          RB_Next_Line := Next_Line;
866          RB_Nfirst    := Nfirst;
867          RB_Nlast     := Nlast;
868          RB_File_Pos  := ftell (Fd);
869
870          if RB_File_Pos = -1 then
871             Exit_With_Error ("Error getting file position");
872          end if;
873       end Store_File_Context;
874
875    --  Start of processing for Process_Binder_File
876
877    begin
878       Fd := fopen (Name'Address, Read_Mode'Address);
879
880       if Fd = NULL_Stream then
881          Exit_With_Error ("Failed to open binder output");
882       end if;
883
884       --  Skip up to the Begin Info line
885
886       loop
887          Get_Next_Line;
888          exit when Next_Line (Nfirst .. Nlast) = Begin_Info;
889       end loop;
890
891       loop
892          Get_Next_Line;
893
894          --  Go to end when end line is reached (this will happen in
895          --  High_Integrity_Mode where no -L switches are generated)
896
897          exit when Next_Line (Nfirst .. Nlast) = End_Info;
898
899          if Ada_Bind_File then
900             Next_Line (Nfirst .. Nlast - 8) :=
901               Next_Line (Nfirst + 8 .. Nlast);
902             Nlast := Nlast - 8;
903          end if;
904
905          --  Go to next section when switches are reached
906
907          exit when Next_Line (1) = '-';
908
909          --  Otherwise we have another object file to collect
910
911          Linker_Objects.Increment_Last;
912
913          --  Mark the positions of first and last object files in case
914          --  they need to be placed with a named file on systems having
915          --  linker line limitations.
916
917          if Objs_Begin = 0 then
918             Objs_Begin := Linker_Objects.Last;
919          end if;
920
921          Linker_Objects.Table (Linker_Objects.Last) :=
922            new String'(Next_Line (Nfirst .. Nlast));
923
924          Link_Bytes := Link_Bytes + Nlast - Nfirst + 2;
925          --  Nlast - Nfirst + 1, for the size, plus one for the space between
926          --  each arguments.
927       end loop;
928
929       Objs_End := Linker_Objects.Last;
930
931       --  Let's continue to compute the Link_Bytes, the linker options are
932       --  part of command line length.
933
934       Store_File_Context;
935
936       while Next_Line (Nfirst .. Nlast) /= End_Info loop
937          Link_Bytes := Link_Bytes + Nlast - Nfirst + 2;
938          --  See comment above
939          Get_Next_Line;
940       end loop;
941
942       Rollback_File_Context;
943
944       --  On systems that have limitations on handling very long linker lines
945       --  we make use of the system linker option which takes a list of object
946       --  file names from a file instead of the command line itself. What we do
947       --  is to replace the list of object files by the special linker option
948       --  which then reads the object file list from a file instead. The option
949       --  to read from a file instead of the command line is only triggered if
950       --  a conservative threshold is passed.
951
952       if Object_List_File_Required
953         or else (Object_List_File_Supported
954                    and then Link_Bytes > Link_Max)
955       then
956          --  Create a temporary file containing the Ada user object files
957          --  needed by the link. This list is taken from the bind file
958          --  and is output one object per line for maximal compatibility with
959          --  linkers supporting this option.
960
961          Create_Temp_File (Tname_FD, Tname);
962
963          --  ??? File descriptor should be checked to not be Invalid_FD.
964          --  ??? Status of Write and Close operations should be checked, and
965          --  failure should occur if a status is wrong.
966
967          --  If target is using the GNU linker we must add a special header
968          --  and footer in the response file.
969
970          --  The syntax is : INPUT (object1.o object2.o ... )
971
972          --  Because the GNU linker does not like name with characters such
973          --  as '!', we must put the object paths between double quotes.
974
975          if Using_GNU_Linker then
976             declare
977                GNU_Header : aliased constant String := "INPUT (";
978
979             begin
980                Status := Write (Tname_FD, GNU_Header'Address,
981                  GNU_Header'Length);
982             end;
983          end if;
984
985          for J in Objs_Begin .. Objs_End loop
986
987             --  Opening quote for GNU linker
988
989             if Using_GNU_Linker then
990                Status := Write (Tname_FD, Opening'Address, 1);
991             end if;
992
993             Status := Write (Tname_FD, Linker_Objects.Table (J).all'Address,
994                              Linker_Objects.Table (J).all'Length);
995
996             --  Closing quote for GNU linker
997
998             if Using_GNU_Linker then
999                Status := Write (Tname_FD, Closing'Address, 2);
1000
1001             else
1002                Status := Write (Tname_FD, ASCII.LF'Address, 1);
1003             end if;
1004
1005             Response_File_Objects.Increment_Last;
1006             Response_File_Objects.Table (Response_File_Objects.Last) :=
1007               Linker_Objects.Table (J);
1008          end loop;
1009
1010          --  Handle GNU linker response file footer
1011
1012          if Using_GNU_Linker then
1013             declare
1014                GNU_Footer : aliased constant String := ")";
1015
1016             begin
1017                Status := Write (Tname_FD, GNU_Footer'Address,
1018                  GNU_Footer'Length);
1019             end;
1020          end if;
1021
1022          Close (Tname_FD, Closing_Status);
1023
1024          --  Add the special objects list file option together with the name
1025          --  of the temporary file (removing the null character) to the objects
1026          --  file table.
1027
1028          Linker_Objects.Table (Objs_Begin) :=
1029            new String'(Value (Object_File_Option_Ptr) &
1030                        Tname (Tname'First .. Tname'Last - 1));
1031
1032          --  The slots containing these object file names are then removed
1033          --  from the objects table so they do not appear in the link. They
1034          --  are removed by moving up the linker options and non-Ada object
1035          --  files appearing after the Ada object list in the table.
1036
1037          declare
1038             N : Integer;
1039
1040          begin
1041             N := Objs_End - Objs_Begin + 1;
1042
1043             for J in Objs_End + 1 .. Linker_Objects.Last loop
1044                Linker_Objects.Table (J - N + 1) := Linker_Objects.Table (J);
1045             end loop;
1046
1047             Linker_Objects.Set_Last (Linker_Objects.Last - N + 1);
1048          end;
1049       end if;
1050
1051       --  Process switches and options
1052
1053       if Next_Line (Nfirst .. Nlast) /= End_Info then
1054          Xlinker_Was_Previous := False;
1055
1056          loop
1057             if Xlinker_Was_Previous
1058               or else Next_Line (Nfirst .. Nlast) = "-Xlinker"
1059             then
1060                Linker_Options.Increment_Last;
1061                Linker_Options.Table (Linker_Options.Last) :=
1062                  new String'(Next_Line (Nfirst .. Nlast));
1063
1064             elsif Next_Line (Nfirst .. Nlast) = "-static" then
1065                GNAT_Static := True;
1066
1067             elsif Next_Line (Nfirst .. Nlast) = "-shared" then
1068                GNAT_Shared := True;
1069
1070             --  Add binder options only if not already set on the command
1071             --  line. This rule is a way to control the linker options order.
1072
1073             --  The following test needs comments, why is it VMS specific.
1074             --  The above comment looks out of date ???
1075
1076             elsif not (OpenVMS_On_Target
1077                          and then
1078                        Is_Option_Present (Next_Line (Nfirst .. Nlast)))
1079             then
1080                if Nlast > Nfirst + 2 and then
1081                  Next_Line (Nfirst .. Nfirst + 1) = "-L"
1082                then
1083                   --  Construct a library search path for use later
1084                   --  to locate static gnatlib libraries.
1085
1086                   if Libpath.Last > 1 then
1087                      Libpath.Increment_Last;
1088                      Libpath.Table (Libpath.Last) := Path_Separator;
1089                   end if;
1090
1091                   for I in Nfirst + 2 .. Nlast loop
1092                      Libpath.Increment_Last;
1093                      Libpath.Table (Libpath.Last) := Next_Line (I);
1094                   end loop;
1095
1096                   Linker_Options.Increment_Last;
1097
1098                   Linker_Options.Table (Linker_Options.Last) :=
1099                     new String'(Next_Line (Nfirst .. Nlast));
1100
1101                elsif Next_Line (Nfirst .. Nlast) = "-ldecgnat"
1102                  or else Next_Line (Nfirst .. Nlast) = "-lgnarl"
1103                  or else Next_Line (Nfirst .. Nlast) = "-lgnat"
1104                  or else Next_Line
1105                      (1 .. Natural'Min (Nlast, 8 + Library_Version'Length)) =
1106                        Shared_Lib ("gnarl")
1107                  or else Next_Line
1108                      (1 .. Natural'Min (Nlast, 7 + Library_Version'Length)) =
1109                        Shared_Lib ("gnat")
1110                then
1111                   --  If it is a shared library, remove the library version.
1112                   --  We will be looking for the static version of the library
1113                   --  as it is in the same directory as the shared version.
1114
1115                   if Next_Line (Nlast - Library_Version'Length + 1 .. Nlast)
1116                        = Library_Version
1117                   then
1118                      --  Set Last to point to last character before the
1119                      --  library version.
1120
1121                      Last := Nlast - Library_Version'Length - 1;
1122                   else
1123                      Last := Nlast;
1124                   end if;
1125
1126                   --  Given a Gnat standard library, search the
1127                   --  library path to find the library location
1128
1129                   declare
1130                      File_Path : String_Access;
1131
1132                      Object_Lib_Extension : constant String :=
1133                                               Value (Object_Library_Ext_Ptr);
1134
1135                      File_Name : constant String := "lib" &
1136                                    Next_Line (Nfirst + 2 .. Last) &
1137                                    Object_Lib_Extension;
1138
1139                      Run_Path_Opt : constant String :=
1140                        Value (Run_Path_Option_Ptr);
1141
1142                      GCC_Index          : Natural;
1143                      Run_Path_Opt_Index : Natural := 0;
1144
1145                   begin
1146                      File_Path :=
1147                        Locate_Regular_File (File_Name,
1148                          String (Libpath.Table (1 .. Libpath.Last)));
1149
1150                      if File_Path /= null then
1151                         if GNAT_Static then
1152
1153                            --  If static gnatlib found, explicitly
1154                            --  specify to overcome possible linker
1155                            --  default usage of shared version.
1156
1157                            Linker_Options.Increment_Last;
1158
1159                            Linker_Options.Table (Linker_Options.Last) :=
1160                              new String'(File_Path.all);
1161
1162                         elsif GNAT_Shared then
1163                            if Opt.Run_Path_Option then
1164                               --  If shared gnatlib desired, add the
1165                               --  appropriate system specific switch
1166                               --  so that it can be located at runtime.
1167
1168                               if Run_Path_Opt'Length /= 0 then
1169                                  --  Output the system specific linker command
1170                                  --  that allows the image activator to find
1171                                  --  the shared library at runtime.
1172                                  --  Also add path to find libgcc_s.so, if
1173                                  --  relevant.
1174
1175                                  --  To find the location of the shared version
1176                                  --  of libgcc, we look for "gcc-lib" in the
1177                                  --  path of the library. However, this
1178                                  --  subdirectory is no longer present in
1179                                  --  in recent version of GCC. So, we look for
1180                                  --  the last subdirectory "lib" in the path.
1181
1182                                  GCC_Index :=
1183                                    Index (File_Path.all, "gcc-lib");
1184
1185                                  if GCC_Index /= 0 then
1186                                     --  The shared version of libgcc is
1187                                     --  located in the parent directory.
1188
1189                                     GCC_Index := GCC_Index - 1;
1190
1191                                  else
1192                                     GCC_Index :=
1193                                       Index (File_Path.all, "/lib/");
1194
1195                                     if GCC_Index = 0 then
1196                                        GCC_Index :=
1197                                          Index (File_Path.all,
1198                                                 Directory_Separator &
1199                                                 "lib" &
1200                                                 Directory_Separator);
1201                                     end if;
1202
1203                                     --  We have found a subdirectory "lib",
1204                                     --  this is where the shared version of
1205                                     --  libgcc should be located.
1206
1207                                     if GCC_Index /= 0 then
1208                                        GCC_Index := GCC_Index + 3;
1209                                     end if;
1210                                  end if;
1211
1212                                  --  Look for an eventual run_path_option in
1213                                  --  the linker switches.
1214
1215                                  for J in reverse 1 .. Linker_Options.Last loop
1216                                     if Linker_Options.Table (J) /= null
1217                                       and then
1218                                         Linker_Options.Table (J)'Length
1219                                                   > Run_Path_Opt'Length
1220                                       and then
1221                                         Linker_Options.Table (J)
1222                                           (1 .. Run_Path_Opt'Length) =
1223                                                                 Run_Path_Opt
1224                                     then
1225                                        --  We have found a already specified
1226                                        --  run_path_option: we will add to this
1227                                        --  switch, because only one
1228                                        --  run_path_option should be specified.
1229
1230                                        Run_Path_Opt_Index := J;
1231                                        exit;
1232                                     end if;
1233                                  end loop;
1234
1235                                  --  If there is no run_path_option, we need
1236                                  --  to add one.
1237
1238                                  if Run_Path_Opt_Index = 0 then
1239                                     Linker_Options.Increment_Last;
1240                                  end if;
1241
1242                                  if GCC_Index = 0 then
1243                                     if Run_Path_Opt_Index = 0 then
1244                                        Linker_Options.Table
1245                                          (Linker_Options.Last) :=
1246                                            new String'
1247                                               (Run_Path_Opt
1248                                                 & File_Path
1249                                                   (1 .. File_Path'Length
1250                                                          - File_Name'Length));
1251
1252                                     else
1253                                        Linker_Options.Table
1254                                          (Run_Path_Opt_Index) :=
1255                                            new String'
1256                                              (Linker_Options.Table
1257                                                  (Run_Path_Opt_Index).all
1258                                               & Path_Separator
1259                                               & File_Path
1260                                                  (1 .. File_Path'Length
1261                                                        - File_Name'Length));
1262                                     end if;
1263
1264                                  else
1265                                     if Run_Path_Opt_Index = 0 then
1266                                        Linker_Options.Table
1267                                          (Linker_Options.Last) :=
1268                                            new String'(Run_Path_Opt
1269                                              & File_Path
1270                                                  (1 .. File_Path'Length
1271                                                        - File_Name'Length)
1272                                              & Path_Separator
1273                                              & File_Path (1 .. GCC_Index));
1274
1275                                     else
1276                                        Linker_Options.Table
1277                                          (Run_Path_Opt_Index) :=
1278                                            new String'
1279                                             (Linker_Options.Table
1280                                                 (Run_Path_Opt_Index).all
1281                                              & Path_Separator
1282                                              & File_Path
1283                                                  (1 .. File_Path'Length
1284                                                        - File_Name'Length)
1285                                              & Path_Separator
1286                                              & File_Path (1 .. GCC_Index));
1287                                     end if;
1288                                  end if;
1289                               end if;
1290                            end if;
1291
1292                            --  Then we add the appropriate -l switch
1293
1294                            Linker_Options.Increment_Last;
1295                            Linker_Options.Table (Linker_Options.Last) :=
1296                              new String'(Next_Line (Nfirst .. Nlast));
1297                         end if;
1298
1299                      else
1300                         --  If gnatlib library not found, then
1301                         --  add it anyway in case some other
1302                         --  mechanimsm may find it.
1303
1304                         Linker_Options.Increment_Last;
1305                         Linker_Options.Table (Linker_Options.Last) :=
1306                           new String'(Next_Line (Nfirst .. Nlast));
1307                      end if;
1308                   end;
1309                else
1310                   Linker_Options.Increment_Last;
1311                   Linker_Options.Table (Linker_Options.Last) :=
1312                     new String'(Next_Line (Nfirst .. Nlast));
1313                end if;
1314             end if;
1315
1316             Xlinker_Was_Previous := Next_Line (Nfirst .. Nlast) = "-Xlinker";
1317
1318             Get_Next_Line;
1319             exit when Next_Line (Nfirst .. Nlast) = End_Info;
1320
1321             if Ada_Bind_File then
1322                Next_Line (Nfirst .. Nlast - 8) :=
1323                  Next_Line (Nfirst + 8 .. Nlast);
1324                Nlast := Nlast - 8;
1325             end if;
1326          end loop;
1327       end if;
1328
1329       --  If -shared was specified, invoke gcc with -shared-libgcc
1330
1331       if GNAT_Shared then
1332          Linker_Options.Increment_Last;
1333          Linker_Options.Table (Linker_Options.Last) := Shared_Libgcc;
1334       end if;
1335
1336       Status := fclose (Fd);
1337    end Process_Binder_File;
1338
1339    -----------
1340    -- Usage --
1341    -----------
1342
1343    procedure Usage is
1344    begin
1345       Write_Str ("Usage: ");
1346       Write_Str (Base_Name (Command_Name));
1347       Write_Str (" switches mainprog.ali [non-Ada-objects] [linker-options]");
1348       Write_Eol;
1349       Write_Eol;
1350       Write_Line ("  mainprog.ali   the ALI file of the main program");
1351       Write_Eol;
1352       Write_Line ("  -A    Binder generated source file is in Ada (default)");
1353       Write_Line ("  -C    Binder generated source file is in C");
1354       Write_Line ("  -f    force object file list to be generated");
1355       Write_Line ("  -g    Compile binder source file with debug information");
1356       Write_Line ("  -n    Do not compile the binder source file");
1357       Write_Line ("  -R    Do not use a run_path_option");
1358       Write_Line ("  -v    verbose mode");
1359       Write_Line ("  -v -v very verbose mode");
1360       Write_Eol;
1361       Write_Line ("  -o nam     Use 'nam' as the name of the executable");
1362       Write_Line ("  -b target  Compile the binder source to run on target");
1363       Write_Line ("  -Bdir      Load compiler executables from dir");
1364
1365       if Is_Supported (Map_File) then
1366          Write_Line ("  -Mmap      Create map file map");
1367          Write_Line ("  -M         Create map file mainprog.map");
1368       end if;
1369
1370       Write_Line ("  --GCC=comp Use comp as the compiler");
1371       Write_Line ("  --LINK=nam Use 'nam' for the linking rather than 'gcc'");
1372       Write_Eol;
1373       Write_Line ("  [non-Ada-objects]  list of non Ada object files");
1374       Write_Line ("  [linker-options]   other options for the linker");
1375    end Usage;
1376
1377    ------------------
1378    -- Write_Header --
1379    ------------------
1380
1381    procedure Write_Header is
1382    begin
1383       if Verbose_Mode then
1384          Write_Eol;
1385          Display_Version ("GNATLINK", "1995");
1386       end if;
1387    end Write_Header;
1388
1389    -----------------
1390    -- Write_Usage --
1391    -----------------
1392
1393    procedure Write_Usage is
1394    begin
1395       Write_Header;
1396       Usage;
1397    end Write_Usage;
1398
1399 --  Start of processing for Gnatlink
1400
1401 begin
1402    --  Add the directory where gnatlink is invoked in front of the
1403    --  path, if gnatlink is invoked with directory information.
1404    --  Only do this if the platform is not VMS, where the notion of path
1405    --  does not really exist.
1406
1407    if not Hostparm.OpenVMS then
1408       declare
1409          Command : constant String := Command_Name;
1410
1411       begin
1412          for Index in reverse Command'Range loop
1413             if Command (Index) = Directory_Separator then
1414                declare
1415                   Absolute_Dir : constant String :=
1416                                    Normalize_Pathname
1417                                      (Command (Command'First .. Index));
1418
1419                   PATH         : constant String :=
1420                                    Absolute_Dir &
1421                   Path_Separator &
1422                   Getenv ("PATH").all;
1423
1424                begin
1425                   Setenv ("PATH", PATH);
1426                end;
1427
1428                exit;
1429             end if;
1430          end loop;
1431       end;
1432    end if;
1433
1434    Process_Args;
1435
1436    if Argument_Count = 0
1437      or else
1438      (Verbose_Mode and then Argument_Count = 1)
1439    then
1440       Write_Usage;
1441       Exit_Program (E_Fatal);
1442    end if;
1443
1444    --  Get target parameters
1445
1446    Namet.Initialize;
1447    Csets.Initialize;
1448    Snames.Initialize;
1449    Osint.Add_Default_Search_Dirs;
1450    Targparm.Get_Target_Parameters;
1451
1452    if VM_Target /= No_VM then
1453       case VM_Target is
1454          when JVM_Target => Gcc := new String'("jgnat");
1455          when CLI_Target => Gcc := new String'("dotnet-gnatcompile");
1456          when No_VM      => raise Program_Error;
1457       end case;
1458
1459       Ada_Bind_File := True;
1460       Begin_Info := "--  BEGIN Object file/option list";
1461       End_Info   := "--  END Object file/option list   ";
1462    end if;
1463
1464    --  We always compile with -c
1465
1466    Binder_Options_From_ALI.Increment_Last;
1467    Binder_Options_From_ALI.Table (Binder_Options_From_ALI.Last) :=
1468      new String'("-c");
1469
1470    --  If the main program is in Ada it is compiled with the following
1471    --  switches:
1472
1473    --    -gnatA   stops reading gnat.adc, since we don't know what
1474    --             pagmas would work, and we do not need it anyway.
1475
1476    --    -gnatWb  allows brackets coding for wide characters
1477
1478    --    -gnatiw  allows wide characters in identifiers. This is needed
1479    --             because bindgen uses brackets encoding for all upper
1480    --             half and wide characters in identifier names.
1481
1482    if Ada_Bind_File then
1483       Binder_Options_From_ALI.Increment_Last;
1484       Binder_Options_From_ALI.Table (Binder_Options_From_ALI.Last) :=
1485         new String'("-gnatA");
1486       Binder_Options_From_ALI.Increment_Last;
1487       Binder_Options_From_ALI.Table (Binder_Options_From_ALI.Last) :=
1488         new String'("-gnatWb");
1489       Binder_Options_From_ALI.Increment_Last;
1490       Binder_Options_From_ALI.Table (Binder_Options_From_ALI.Last) :=
1491         new String'("-gnatiw");
1492    end if;
1493
1494    --  Locate all the necessary programs and verify required files are present
1495
1496    Gcc_Path := System.OS_Lib.Locate_Exec_On_Path (Gcc.all);
1497
1498    if Gcc_Path = null then
1499       Exit_With_Error ("Couldn't locate " & Gcc.all);
1500    end if;
1501
1502    if Linker_Path = null then
1503       if VM_Target = CLI_Target then
1504          Linker_Path := System.OS_Lib.Locate_Exec_On_Path ("ilasm");
1505
1506          if Linker_Path = null then
1507             Exit_With_Error ("Couldn't locate ilasm");
1508          end if;
1509       else
1510          Linker_Path := Gcc_Path;
1511       end if;
1512    end if;
1513
1514    if Ali_File_Name = null then
1515       Exit_With_Error ("no ali file given for link");
1516    end if;
1517
1518    if not Is_Regular_File (Ali_File_Name.all) then
1519       Exit_With_Error (Ali_File_Name.all & " not found");
1520    end if;
1521
1522    --  Read the ALI file of the main subprogram if the binder generated
1523    --  file needs to be compiled and no --GCC= switch has been specified.
1524    --  Fetch the back end switches from this ALI file and use these switches
1525    --  to compile the binder generated file
1526
1527    if Compile_Bind_File and then Standard_Gcc then
1528
1529       Initialize_ALI;
1530       Name_Len := Ali_File_Name'Length;
1531       Name_Buffer (1 .. Name_Len) := Ali_File_Name.all;
1532
1533       declare
1534          use Types;
1535          F : constant File_Name_Type := Name_Find;
1536          T : Text_Buffer_Ptr;
1537          A : ALI_Id;
1538
1539       begin
1540          --  Load the ALI file
1541
1542          T := Read_Library_Info (F, True);
1543
1544          --  Read it. Note that we ignore errors, since we only want very
1545          --  limited information from the ali file, and likely a slightly
1546          --  wrong version will be just fine, though in normal operation
1547          --  we don't expect this to happen!
1548
1549          A := Scan_ALI
1550                (F,
1551                 T,
1552                 Ignore_ED     => False,
1553                 Err           => False,
1554                 Ignore_Errors => True);
1555
1556          if A /= No_ALI_Id then
1557             for
1558               Index in Units.Table (ALIs.Table (A).First_Unit).First_Arg ..
1559                        Units.Table (ALIs.Table (A).First_Unit).Last_Arg
1560             loop
1561                --  Do not compile with the front end switches. However, --RTS
1562                --  is to be dealt with specially because it needs to be passed
1563                --  if the binder-generated file is in Ada and may also be used
1564                --  to drive the linker.
1565
1566                declare
1567                   Arg : String_Ptr renames Args.Table (Index);
1568                begin
1569                   if not Is_Front_End_Switch (Arg.all) then
1570                      Binder_Options_From_ALI.Increment_Last;
1571                      Binder_Options_From_ALI.Table
1572                        (Binder_Options_From_ALI.Last) := String_Access (Arg);
1573
1574                   elsif Arg'Length > 5
1575                     and then Arg (Arg'First + 2 .. Arg'First + 5) = "RTS="
1576                   then
1577                      if Ada_Bind_File then
1578                         Binder_Options_From_ALI.Increment_Last;
1579                         Binder_Options_From_ALI.Table
1580                           (Binder_Options_From_ALI.Last)
1581                             := String_Access (Arg);
1582                      end if;
1583
1584                      --  GNAT doesn't support the GCC multilib mechanism.
1585                      --  This means that, when a multilib switch is used
1586                      --  to request a particular compilation mode, the
1587                      --  corresponding runtime switch (--RTS) must also be
1588                      --  specified. The long-term goal is to fully support the
1589                      --  multilib mechanism; however, in the meantime, it is
1590                      --  convenient to eliminate the redundancy by keying the
1591                      --  compilation mode on a single switch, namely --RTS.
1592
1593                      --  Pass -mrtp to the linker if --RTS=rtp was passed
1594
1595                      if Linker_Path = Gcc_Path
1596                        and then Arg'Length > 8
1597                        and then Arg (Arg'First + 6 .. Arg'First + 8) = "rtp"
1598                      then
1599                         Linker_Options.Increment_Last;
1600                         Linker_Options.Table (Linker_Options.Last) :=
1601                           new String'("-mrtp");
1602
1603                      --  Pass -fsjlj to the linker if --RTS=sjlj was passed
1604
1605                      elsif Linker_Path = Gcc_Path
1606                        and then Arg'Length > 9
1607                        and then Arg (Arg'First + 6 .. Arg'First + 9) = "sjlj"
1608                      then
1609                         Linker_Options.Increment_Last;
1610                         Linker_Options.Table (Linker_Options.Last) :=
1611                           new String'("-fsjlj");
1612                      end if;
1613                   end if;
1614                end;
1615             end loop;
1616          end if;
1617       end;
1618    end if;
1619
1620    Write_Header;
1621
1622    --  If no output name specified, then use the base name of .ali file name
1623
1624    if Output_File_Name = null then
1625       Output_File_Name :=
1626         new String'(Base_Name (Ali_File_Name.all)
1627                       & Get_Target_Debuggable_Suffix.all);
1628
1629       if VM_Target = CLI_Target then
1630          Linker_Options.Increment_Last;
1631          Linker_Options.Table (Linker_Options.Last) := new String'("/QUIET");
1632
1633          Linker_Options.Increment_Last;
1634          Linker_Options.Table (Linker_Options.Last) := new String'("/DEBUG");
1635
1636          Linker_Options.Increment_Last;
1637          Linker_Options.Table (Linker_Options.Last) :=
1638            new String'("/OUTPUT=" & Output_File_Name.all);
1639
1640       else
1641          Linker_Options.Increment_Last;
1642          Linker_Options.Table (Linker_Options.Last) := new String'("-o");
1643
1644          Linker_Options.Increment_Last;
1645          Linker_Options.Table (Linker_Options.Last) :=
1646            new String'(Output_File_Name.all);
1647       end if;
1648    end if;
1649
1650    --  Warn if main program is called "test", as that may be a built-in command
1651    --  on Unix. On non-Unix systems executables have a suffix, so the warning
1652    --  will not appear. However, do not warn in the case of a cross compiler.
1653
1654    --  Assume this is a cross tool if the executable name is not gnatlink
1655
1656    if Base_Name (Command_Name) = "gnatlink"
1657      and then Output_File_Name.all = "test"
1658    then
1659       Error_Msg ("warning: executable name """ & Output_File_Name.all
1660                    & """ may conflict with shell command");
1661    end if;
1662
1663    --  If -M switch was specified, add the switches to create the map file
1664
1665    if Create_Map_File then
1666       declare
1667          Map_Name : constant String := Base_Name (Ali_File_Name.all) & ".map";
1668          Switches : String_List_Access;
1669
1670       begin
1671          Convert (Map_File, Map_Name, Switches);
1672
1673          if Switches /= null then
1674             for J in Switches'Range loop
1675                Linker_Options.Increment_Last;
1676                Linker_Options.Table (Linker_Options.Last) := Switches (J);
1677             end loop;
1678          end if;
1679       end;
1680    end if;
1681
1682    --  Perform consistency checks
1683
1684    --  Transform the .ali file name into the binder output file name
1685
1686    Make_Binder_File_Names : declare
1687       Fname     : constant String  := Base_Name (Ali_File_Name.all);
1688       Fname_Len : Integer := Fname'Length;
1689
1690       function Get_Maximum_File_Name_Length return Integer;
1691       pragma Import (C, Get_Maximum_File_Name_Length,
1692                         "__gnat_get_maximum_file_name_length");
1693
1694       Maximum_File_Name_Length : constant Integer :=
1695                                    Get_Maximum_File_Name_Length;
1696
1697       Bind_File_Prefix : Types.String_Ptr;
1698       --  Contains prefix used for bind files
1699
1700    begin
1701       --  Set prefix
1702
1703       if not Ada_Bind_File then
1704          Bind_File_Prefix := new String'("b_");
1705       elsif OpenVMS_On_Target then
1706          Bind_File_Prefix := new String'("b__");
1707       else
1708          Bind_File_Prefix := new String'("b~");
1709       end if;
1710
1711       --  If the length of the binder file becomes too long due to
1712       --  the addition of the "b?" prefix, then truncate it.
1713
1714       if Maximum_File_Name_Length > 0 then
1715          while Fname_Len >
1716                  Maximum_File_Name_Length - Bind_File_Prefix.all'Length
1717          loop
1718             Fname_Len := Fname_Len - 1;
1719          end loop;
1720       end if;
1721
1722       declare
1723          Fnam : constant String :=
1724                   Bind_File_Prefix.all &
1725                     Fname (Fname'First .. Fname'First + Fname_Len - 1);
1726
1727       begin
1728          if Ada_Bind_File then
1729             Binder_Spec_Src_File := new String'(Fnam & ".ads");
1730             Binder_Body_Src_File := new String'(Fnam & ".adb");
1731             Binder_Ali_File      := new String'(Fnam & ".ali");
1732          else
1733             Binder_Body_Src_File := new String'(Fnam & ".c");
1734          end if;
1735
1736          Binder_Obj_File := new String'(Fnam & Get_Target_Object_Suffix.all);
1737       end;
1738
1739       if Fname_Len /= Fname'Length then
1740          Binder_Options.Increment_Last;
1741          Binder_Options.Table (Binder_Options.Last) := new String'("-o");
1742          Binder_Options.Increment_Last;
1743          Binder_Options.Table (Binder_Options.Last) := Binder_Obj_File;
1744       end if;
1745    end Make_Binder_File_Names;
1746
1747    Process_Binder_File (Binder_Body_Src_File.all & ASCII.NUL);
1748
1749    --  Compile the binder file. This is fast, so we always do it, unless
1750    --  specifically told not to by the -n switch
1751
1752    if Compile_Bind_File then
1753       Bind_Step : declare
1754          Success : Boolean;
1755          Args    : Argument_List
1756            (1 .. Binder_Options_From_ALI.Last + Binder_Options.Last + 1);
1757
1758       begin
1759          for J in 1 .. Binder_Options_From_ALI.Last loop
1760             Args (J) := Binder_Options_From_ALI.Table (J);
1761          end loop;
1762
1763          for J in 1 .. Binder_Options.Last loop
1764             Args (Binder_Options_From_ALI.Last + J) :=
1765               Binder_Options.Table (J);
1766          end loop;
1767
1768          Args (Args'Last) := Binder_Body_Src_File;
1769
1770          if Verbose_Mode then
1771             Write_Str (Base_Name (Gcc_Path.all));
1772
1773             for J in Args'Range loop
1774                Write_Str (" ");
1775                Write_Str (Args (J).all);
1776             end loop;
1777
1778             Write_Eol;
1779          end if;
1780
1781          System.OS_Lib.Spawn (Gcc_Path.all, Args, Success);
1782
1783          if not Success then
1784             Exit_Program (E_Fatal);
1785          end if;
1786       end Bind_Step;
1787    end if;
1788
1789    --  Now, actually link the program
1790
1791    --  Skip this step for now on JVM since the Java interpreter will do
1792    --  the actual link at run time. We might consider packing all class files
1793    --  in a .zip file during this step.
1794
1795    if VM_Target /= JVM_Target then
1796       Link_Step : declare
1797          Num_Args : Natural :=
1798                      (Linker_Options.Last - Linker_Options.First + 1) +
1799                      (Gcc_Linker_Options.Last - Gcc_Linker_Options.First + 1) +
1800                      (Linker_Objects.Last - Linker_Objects.First + 1);
1801          Stack_Op : Boolean := False;
1802          IDENT_Op : Boolean := False;
1803
1804       begin
1805          if VM_Target = CLI_Target then
1806
1807             --  Remove extraneous flags not relevant for CIL. Also remove empty
1808             --  arguments, since ilasm chokes on them.
1809
1810             for J in reverse Linker_Options.First .. Linker_Options.Last loop
1811                if Linker_Options.Table (J)'Length = 0
1812                  or else Linker_Options.Table (J) (1 .. 2) = "-L"
1813                  or else Linker_Options.Table (J) (1 .. 2) = "-l"
1814                  or else Linker_Options.Table (J) (1 .. 3) = "-Wl"
1815                  or else Linker_Options.Table (J) (1 .. 3) = "-sh"
1816                  or else Linker_Options.Table (J) (1 .. 2) = "-g"
1817                then
1818                   Linker_Options.Table (J .. Linker_Options.Last - 1) :=
1819                     Linker_Options.Table (J + 1 .. Linker_Options.Last);
1820                   Linker_Options.Decrement_Last;
1821                   Num_Args := Num_Args - 1;
1822                end if;
1823             end loop;
1824          end if;
1825
1826          --  Remove duplicate stack size setting from the Linker_Options
1827          --  table. The stack setting option "-Xlinker --stack=R,C" can be
1828          --  found in one line when set by a pragma Linker_Options or in two
1829          --  lines ("-Xlinker" then "--stack=R,C") when set on the command
1830          --  line. We also check for the "-Wl,--stack=R" style option.
1831
1832          --  We must remove the second stack setting option instance
1833          --  because the one on the command line will always be the first
1834          --  one. And any subsequent stack setting option will overwrite the
1835          --  previous one. This is done especially for GNAT/NT where we set
1836          --  the stack size for tasking programs by a pragma in the NT
1837          --  specific tasking package System.Task_Primitives.Oparations.
1838
1839          --  Note: This is not a FOR loop that runs from Linker_Options.First
1840          --  to Linker_Options.Last, since operations within the loop can
1841          --  modify the length of the table.
1842
1843          Clean_Link_Option_Set : declare
1844             J : Natural := Linker_Options.First;
1845             Shared_Libgcc_Seen : Boolean := False;
1846
1847          begin
1848             while J <= Linker_Options.Last loop
1849
1850                if Linker_Options.Table (J).all = "-Xlinker"
1851                  and then J < Linker_Options.Last
1852                  and then Linker_Options.Table (J + 1)'Length > 8
1853                  and then Linker_Options.Table (J + 1) (1 .. 8) = "--stack="
1854                then
1855                   if Stack_Op then
1856                      Linker_Options.Table (J .. Linker_Options.Last - 2) :=
1857                        Linker_Options.Table (J + 2 .. Linker_Options.Last);
1858                      Linker_Options.Decrement_Last;
1859                      Linker_Options.Decrement_Last;
1860                      Num_Args := Num_Args - 2;
1861
1862                   else
1863                      Stack_Op := True;
1864                   end if;
1865                end if;
1866
1867                --  Remove duplicate -shared-libgcc switch
1868
1869                if Linker_Options.Table (J).all = Shared_Libgcc_String then
1870                   if Shared_Libgcc_Seen then
1871                      Linker_Options.Table (J .. Linker_Options.Last - 1) :=
1872                        Linker_Options.Table (J + 1 .. Linker_Options.Last);
1873                      Linker_Options.Decrement_Last;
1874                      Num_Args := Num_Args - 1;
1875
1876                   else
1877                      Shared_Libgcc_Seen := True;
1878                   end if;
1879                end if;
1880
1881                --  Here we just check for a canonical form that matches the
1882                --  pragma Linker_Options set in the NT runtime.
1883
1884                if (Linker_Options.Table (J)'Length > 17
1885                    and then Linker_Options.Table (J) (1 .. 17)
1886                            = "-Xlinker --stack=")
1887                  or else
1888                   (Linker_Options.Table (J)'Length > 12
1889                    and then Linker_Options.Table (J) (1 .. 12)
1890                             = "-Wl,--stack=")
1891                then
1892                   if Stack_Op then
1893                      Linker_Options.Table (J .. Linker_Options.Last - 1) :=
1894                        Linker_Options.Table (J + 1 .. Linker_Options.Last);
1895                      Linker_Options.Decrement_Last;
1896                      Num_Args := Num_Args - 1;
1897
1898                   else
1899                      Stack_Op := True;
1900                   end if;
1901                end if;
1902
1903                --  Remove duplicate IDENTIFICATION directives (VMS)
1904
1905                if Linker_Options.Table (J)'Length > 27
1906                  and then Linker_Options.Table (J) (1 .. 28)
1907                           = "--for-linker=IDENTIFICATION="
1908                then
1909                   if IDENT_Op then
1910                      Linker_Options.Table (J .. Linker_Options.Last - 1) :=
1911                        Linker_Options.Table (J + 1 .. Linker_Options.Last);
1912                      Linker_Options.Decrement_Last;
1913                      Num_Args := Num_Args - 1;
1914                   else
1915                      IDENT_Op := True;
1916                   end if;
1917                end if;
1918
1919                J := J + 1;
1920             end loop;
1921
1922             if Linker_Path = Gcc_Path and then VM_Target = No_VM then
1923
1924                --  If gcc is not called with -shared-libgcc, call it with
1925                --  -static-libgcc, as there are some platforms where one of
1926                --  these two switches is compulsory to link.
1927
1928                if not Shared_Libgcc_Seen then
1929                   Linker_Options.Increment_Last;
1930                   Linker_Options.Table (Linker_Options.Last) := Static_Libgcc;
1931                   Num_Args := Num_Args + 1;
1932                end if;
1933             end if;
1934
1935          end Clean_Link_Option_Set;
1936
1937          --  Prepare arguments for call to linker
1938
1939          Call_Linker : declare
1940             Success  : Boolean;
1941             Args     : Argument_List (1 .. Num_Args + 1);
1942             Index    : Integer := Args'First;
1943
1944          begin
1945             Args (Index) := Binder_Obj_File;
1946
1947             --  Add the object files and any -largs libraries
1948
1949             for J in Linker_Objects.First .. Linker_Objects.Last loop
1950                Index := Index + 1;
1951                Args (Index) := Linker_Objects.Table (J);
1952             end loop;
1953
1954             --  Add the linker options from the binder file
1955
1956             for J in Linker_Options.First .. Linker_Options.Last loop
1957                Index := Index + 1;
1958                Args (Index) := Linker_Options.Table (J);
1959             end loop;
1960
1961             --  Finally add the libraries from the --GCC= switch
1962
1963             for J in Gcc_Linker_Options.First .. Gcc_Linker_Options.Last loop
1964                Index := Index + 1;
1965                Args (Index) := Gcc_Linker_Options.Table (J);
1966             end loop;
1967
1968             if Verbose_Mode then
1969                Write_Str (Linker_Path.all);
1970
1971                for J in Args'Range loop
1972                   Write_Str (" ");
1973                   Write_Str (Args (J).all);
1974                end loop;
1975
1976                Write_Eol;
1977
1978                --  If we are on very verbose mode (-v -v) and a response file
1979                --  is used we display its content.
1980
1981                if Very_Verbose_Mode and then Tname_FD /= Invalid_FD then
1982                   Write_Eol;
1983                   Write_Str ("Response file (" &
1984                              Tname (Tname'First .. Tname'Last - 1) &
1985                              ") content : ");
1986                   Write_Eol;
1987
1988                   for J in
1989                     Response_File_Objects.First ..
1990                     Response_File_Objects.Last
1991                   loop
1992                      Write_Str (Response_File_Objects.Table (J).all);
1993                      Write_Eol;
1994                   end loop;
1995
1996                   Write_Eol;
1997                end if;
1998             end if;
1999
2000             System.OS_Lib.Spawn (Linker_Path.all, Args, Success);
2001
2002             --  Delete the temporary file used in conjuction with linking if
2003             --  one was created. See Process_Bind_File for details.
2004
2005             if Tname_FD /= Invalid_FD then
2006                Delete (Tname);
2007             end if;
2008
2009             if not Success then
2010                Error_Msg ("error when calling " & Linker_Path.all);
2011                Exit_Program (E_Fatal);
2012             end if;
2013          end Call_Linker;
2014       end Link_Step;
2015    end if;
2016
2017    --  Only keep the binder output file and it's associated object
2018    --  file if compiling with the -g option.  These files are only
2019    --  useful if debugging.
2020
2021    if not Debug_Flag_Present then
2022       if Binder_Ali_File /= null then
2023          Delete (Binder_Ali_File.all & ASCII.NUL);
2024       end if;
2025
2026       if Binder_Spec_Src_File /= null then
2027          Delete (Binder_Spec_Src_File.all & ASCII.NUL);
2028       end if;
2029
2030       Delete (Binder_Body_Src_File.all & ASCII.NUL);
2031
2032       if VM_Target = No_VM then
2033          Delete (Binder_Obj_File.all & ASCII.NUL);
2034       end if;
2035    end if;
2036
2037    Exit_Program (E_Success);
2038
2039 exception
2040    when X : others =>
2041       Write_Line (Exception_Information (X));
2042       Exit_With_Error ("INTERNAL ERROR. Please report");
2043 end Gnatlink;