GCC Middle and Back End API Reference
collect2.c File Reference

Data Structures

struct  id
struct  head
struct  lto_object
struct  lto_object_list


typedef int scanfilter


enum  lto_mode_d {
enum  symkind {
  SYM_FINI = 4, SYM_DWEH = 5
enum  scanpass {
enum  scanfilter_masks {


static symkind is_ctor_dtor (const char *)
static void handler (int)
static void do_wait (const char *, struct pex_obj *)
static void fork_execute (const char *, char **)
static void maybe_unlink (const char *)
static void maybe_unlink_list (char **)
static void add_to_list (struct head *, const char *)
static int extract_init_priority (const char *)
static void sort_ids (struct head *)
static void write_list (FILE *, const char *, struct id *)
static void dump_list (FILE *, const char *, struct id *)
static void dump_prefix_list (FILE *, const char *, struct prefix_list *)
static void write_list_with_asm (FILE *, const char *, struct id *)
static void write_c_file (FILE *, const char *)
static void write_c_file_stat (FILE *, const char *)
static void write_c_file_glob (FILE *, const char *)
static void scan_libraries (const char *)
static int is_in_list (const char *, struct id *)
static void write_aix_file (FILE *, struct id *)
static char * resolve_lib_name (const char *)
static char * extract_string (const char **)
static void post_ld_pass (bool)
static void process_args (int *argcp, char **argv)
static void scan_prog_file (const char *, scanpass, scanfilter)
static void collect_atexit ()
void notice ()
void notice_translated ()
static void handler ()
int file_exists ()
static char * extract_string ()
void dump_ld_file ()
static symkind is_ctor_dtor ()
static void add_lto_object ()
static void maybe_run_lto_and_relink (char **lto_ld_argv, char **object_lst, const char **object, bool force)
int main ()
int collect_wait ()
static void do_wait ()
struct pex_obj * collect_execute (const char *prog, char **argv, const char *outname, const char *errname, int flags)
static void fork_execute ()
static void maybe_unlink ()
static void maybe_unlink_list ()
static void add_to_list ()
static int extract_init_priority ()
static void sort_ids ()
static void write_list ()
static int is_in_list ()
static void dump_list ()
static void dump_prefix_list ()
static void write_list_with_asm ()
static void write_c_file_stat ()
static void write_c_file_glob ()
static void write_c_file ()
static void write_aix_file ()
static bool maybe_lto_object_file ()
static void scan_libraries ()
static int ignore_library (const char *)
static int ignore_library ()
char * ldgetname (LDFILE *, GCC_SYMENT *)
static char * resolve_lib_name ()
static void do_dsymutil (const char *output_file)


int do_collecting = 1
int no_demangle
bool vflag
static int rflag
static int strip_flag
static int export_flag
static int aix64_flag
static int aixrtl_flag
static enum lto_mode_d lto_mode = LTO_MODE_NONE
bool debug
bool helpflag
static int shared_obj
static const char * c_file
static const char * o_file
static const char * export_file
static char ** lto_o_files
const char * ldout
const char * lderrout
static const char * output_file
static const char * nm_file_name
static const char * ldd_file_name
static const char * strip_file_name
const char * c_file_name
static char * initname
static char * fininame
static struct head constructors
static struct head destructors
static struct head exports
static struct head frame_tables
static bool at_file_supplied
static char * response_file
struct obstack temporary_obstack
char * temporary_firstobj
static const char * target_system_root = TARGET_SYSTEM_ROOT
bool may_unlink_output_file = false
static struct head libs
static struct path_prefix cmdline_lib_dirs
static struct path_prefix libpath_lib_dirs
static struct path_prefixlibpaths [3]
static struct lto_object_list lto_objects
static struct path_prefix cpath path
static const char *const target_machine = TARGET_MACHINE
static long sequence_number = 0
static const char *const aix_std_libs []
static int flag_dsym = false
static int flag_idsym = false

Typedef Documentation

typedef int scanfilter
   This type is used for parameters and variables which hold
   combinations of the flags in enum scanfilter_masks.  

Enumeration Type Documentation

enum lto_mode_d
   ... and which kinds of symbols are to be considered.  
enum scanpass
   Enumerations describing which pass this is for scanning the
   program file ...  
enum symkind
   Special kinds of symbols that a name may denote.  

Function Documentation

static void add_lto_object ( )
   Search for NAME using prefix list PPREFIX.  We only look for executable

   Return 0 if not found, otherwise return its name, allocated with malloc.  
   Add an entry for the object file NAME to object file list LIST.
   New entries are added at the end of the list. The original pointer
   value of NAME is preserved, i.e., no string copy is performed.  

References lto_object_list::first, getenv(), lto_objects, PASS_LTOINFO, SCAN_ALL, and scan_prog_file().

Referenced by maybe_lto_object_file().

static void add_to_list ( struct head ,
const char *   

Referenced by scan_prog_file().

static void add_to_list ( )
   Add a name to a linked list.  
     Check for duplicate symbols.  

References id::name, and id::next.

static void collect_atexit ( )
   Delete tempfiles and exit function.  
struct pex_obj* collect_execute ( const char *  prog,
char **  argv,
const char *  outname,
const char *  errname,
int  flags 
   Execute a program, and wait for the reply.  
         If using @file arguments, create a temporary file and put the
         contents of argv into it.  Then change argv to an array corresponding
         to a single argument @FILE, where FILE is the temporary filename.  
         Note: we assume argv contains at least one element; this is
         checked above.  
     If we cannot find a program we need, complain error.  Do this here
     since we might not end up needing something that we could not find.  
int collect_wait ( )
   Wait for a process to finish, and exit if a nonzero status is found.  

References errno.

static void do_dsymutil ( const char *  output_file)
static void do_wait ( const char *  ,
struct pex_obj *   
static void do_wait ( )
void dump_ld_file ( )
                         Make sure we output at least one space, or
                         the demangled symbol name will run into
                         whatever text follows.  
static void dump_list ( FILE *  ,
const char *  ,
struct id  
static void dump_list ( )
   Added for debugging purpose.  
static void dump_prefix_list ( FILE *  ,
const char *  ,
struct prefix_list  
static void dump_prefix_list ( )
static int extract_init_priority ( const char *  )
static int extract_init_priority ( )
   Grab the init priority number from an init function name that
   looks like "_GLOBAL_.I.12345.foo".  
     Extract init_p number from ctor/dtor name.  

References frame_tables, head::number, output_file, and strlen().

static char* extract_string ( const char **  )
static char* extract_string ( )
   Parse a reasonable subset of shell quoting syntax.  
int file_exists ( )
static void fork_execute ( const char *  ,
char **   
static void fork_execute ( )
static void handler ( int  )
static void handler ( )
static int ignore_library ( const char *  )
   This function checks the filename and returns 1
   if this name matches the location of a standard AIX library.  
static int ignore_library ( )
static symkind is_ctor_dtor ( const char *  )
static symkind is_ctor_dtor ( )
   Return the kind of symbol denoted by name S.  
static int is_in_list ( const char *  ,
struct id  
static int is_in_list ( )
   This function is really used only on AIX, but may be useful.  
char* ldgetname ( LDFILE ,
int main ( )
   Main program.  
     If we look for a program in the compiler directories, we just use
     the short name, since these directories are already system-specific.
     But it we look for a program in the system directories, we need to
     qualify the program name with the target machine.  
     The kinds of symbols we will have to consider when scanning the
     outcome of a first pass link.  This is ALL to start with, then might
     be adjusted before getting to the first pass link per se, typically on
     AIX where we perform an early scan of objects and libraries to fetch
     the list of global ctors/dtors and make sure they are not garbage
     Suppress demangling by the real linker, which may be broken.  
     Perform system dependent initialization, if necessary.  
     We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
     receive the signal.  A different setting is inheritable 
     Unlock the stdio streams.  
     Do not invoke xcalloc before this point, since locale needs to be
     set first, in case a diagnostic is issued.  
     Parse command line early for instances of -debug.  This allows
     the debug flag to be set before functions like find_a_file()
     are called.  We also look for the -flto or -flto-partition=none flag to know
     what LTO mode we are in.  
           These flags are position independent, although their order
           is important - subsequent flags override earlier ones. 
           -bexport:filename always needs the :filename 
     -fno-profile-arcs -fno-test-coverage -fno-branch-probabilities
     -fno-exceptions -w -fno-whole-program 
     Extract COMPILER_PATH and PATH into our prefix list.  
     Try to discover a valid linker/nm/strip to use.  
     Maybe we know the right file to use (if not cross).  
     Search the (target-specific) compiler dirs for ld'.  
     Likewise for `collect-ld'.  
     Search the compiler directories for `ld'.  We have protection against
     recursive calls in find_a_file.  
     Search the ordinary system bin directories
     for `ld' (if native linking) or `TARGET-ld' (if cross).  
     Determine the full path name of the C compiler to use.  
     Here it should be safe to use the system search path since we should have
     already qualified the name of the compiler when it is needed.  
     Make temp file names.  
     Generate a list of directories from LIBPATH.  
     Add to this list also two standard directories where
     AIX loader always searches for libraries.  
     Get any options that the upper GCC wants to pass to the sub-GCC.

     AIX support needs to know if -shared has been specified before
     parsing commandline arguments.  
     !!! When GCC calls collect2,
     it does not know whether it is calling collect2 or ld.
     So collect2 cannot meaningfully understand any options
     except those ld understands.
     If you propose to make GCC pass some other option,
     just imagine what will happen if ld is really ld!!!  
     Parse arguments.  Remember output file spec, pass the rest to ld.  
     After the first file, put in the c++ rt0.  
                     Already parsed.  
                     Do not pass LTO flag to the linker. 
                     Do not pass -fuse-ld={bfd|gold} to the linker. 
                     File containing a list of input files to process.  
                     Number of additionnal object files.  
                     Maximum of additionnal object files before vector
                     Accept -fFILENAME and -f FILENAME.  
                         Remove end of line.  
                         Put on object vector.
                         Note: we only expanse vector here, so we must keep
                         extra space for remaining arguments.  
                     place o_file BEFORE this argument! 
                   Resolving full library name.  
                   Saving a full library name.  
               Saving directories where to search for libraries.  
                     We must strip after the nm run, otherwise C++ linking
                     will not work.  Thus we strip in the second ld run, or
                     else with strip if there is no second ld run.  
                     place o_file BEFORE this argument! 
             libraries can be specified directly, i.e. without -l flag.  
                 Saving a full library name.  
     This is added only for debugging purposes.  
     The AIX linker will discard static constructors in object files if
     nothing else in the file is referenced, so look at them first.  Unless
     we are building a shared object, ignore the eh frame tables, as we
     would otherwise reference them all, hence drag all the corresponding
     objects even if nothing else is referenced.  
       Compute the filter to use from the current one, do scan, then adjust
       the "current" filter to remove what we just included here.  This will
       control whether we need a first pass link later on or not, and what
       will remain to be scanned there.  
     Load the program, searching all libraries and attempting to provide
     undefined symbols from repository information.

     If -r or they will be run via some other method, do not build the
     constructor or destructor list, just return now.  
       Perform the first pass link now, if we're about to exit or if we need
       to scan for things we haven't collected yet before pursuing further.

       On AIX, the latter typically includes nothing for shared objects or
       frame tables for an executable, out of what the required early scan on
       objects and libraries has performed above.  In the !shared_obj case, we
       expect the relevant tables to be dragged together with their associated
       functions from precise cross reference insertions by the compiler.  
           Make sure we delete the export file we may have created.  
     Unless we have done it all already, examine the namelist and search for
     static constructors and destructors to call.  Write the constructor and
     destructor tables to a .s file and reload.  
     If the scan exposed nothing of special interest, there's no need to
     generate the glue code and relink so return now.  
         If we will be running these functions ourselves, we want to emit
         stubs into the shared library so that we do not have to relink
         dependent programs when we add static objects.  
         Do tlink without additional code generation now if we didn't
         do it earlier for scanning purposes.  
         Strip now if it was requested on the command line.  
     Sort ctor and dtor lists by priority.  
     Tell the linker that we have initializer and finalizer functions.  
         If we did not add export flag to link arguments before, add it to
         second link phase now.  No new exports should have been added.  
     End of arguments to second link phase.  
     Assemble the constructor and destructor tables.
     Link the tables in with the rest of the program.  
     On AIX we must call tlink because of possible templates resolution.  
     Otherwise, simply call ld because tlink is already done.  
     Let scan_prog_file do any final mods (OSF/rose needs this for
     constructors/destructors in shared libraries.  
static bool maybe_lto_object_file ( )
   Check to make sure the file is an LTO object file.  

References add_lto_object(), and lto_objects.

static void maybe_run_lto_and_relink ( char **  lto_ld_argv,
char **  object_lst,
const char **  object,
bool  force 
   Perform a link-time recompilation and relink if any of the object
   files contain LTO info.  The linker command line LTO_LD_ARGV
   represents the linker command that would produce a final executable
   without the use of LTO. OBJECT_LST is a vector of object file names
   appearing in LTO_LD_ARGV that are to be considered for link-time
   recompilation, where OBJECT is a pointer to the last valid element.
   (This awkward convention avoids an impedance mismatch with the
   usage of similarly-named variables in main().)  The elements of
   OBJECT_LST must be identical, i.e., pointer equal, to the
   corresponding arguments in LTO_LD_ARGV.

   Upon entry, at least one linker run has been performed without the
   use of any LTO info that might be present.  Any recompilations
   necessary for template instantiations have been performed, and
   initializer/finalizer tables have been created if needed and
   included in the linker command line LTO_LD_ARGV. If any of the
   object files contain LTO info, we run the LTO back end on all such
   files, and perform the final link with the LTO back end output
   substituted for the LTO-optimized files.  In some cases, a final
   link with all link-time generated code has already been performed,
   so there is no need to relink if no LTO info is found.  In other
   cases, our caller has not produced the final executable, and is
   relying on us to perform the required link whether LTO info is
   present or not.  In that case, the FORCE argument should be true.
   Note that the linker command line argument LTO_LD_ARGV passed into
   this function may be modified in place.  
       If file contains LTO info, add it to the list of LTO objects.  
       Increment the argument count by the number of object file arguments
       we will add.  An upper bound suffices, so just count all of the
       object files regardless of whether they contain LTO info.  
         There is at least one object file containing LTO info,
         so we need to run the LTO back end and relink.

         To do so we build updated ld arguments with first
         LTO object replaced by all partitions and other LTO
         objects removed.  
         Add LTO objects to the wrapper command line.  
         Run the LTO back end.  
         Compute memory needed for new LD arguments.  At most number of original arguemtns
         plus number of partitions.  
         After running the LTO back end, we will relink, substituting
         the LTO output for the object files that we submitted to the
         LTO. Here, we modify the linker command line for the relink.  
         Copy all arguments until we find first LTO file.  
         Now insert all LTO partitions.  
         ... and copy the rest.  
         Run the linker again, this time replacing the object files
         optimized by the LTO with the temporary file generated by the LTO.  
         Our caller is relying on us to do the link
         even though there is no LTO back end work to be done.  
static void maybe_unlink ( const char *  )
static void maybe_unlink ( )
   Unlink FILE unless we are debugging or this is the output_file
   and we may not unlink it.  
static void maybe_unlink_list ( char **  )
static void maybe_unlink_list ( )
   Call maybe_unlink on the NULL-terminated list, FILE_LIST.  

References id::name, and id::next.

void notice ( )
   Notify user of a non-error.  
void notice_translated ( )
   Notify user of a non-error, without translating the format string.  
static void post_ld_pass ( bool  temp_file)
static void process_args ( int *  argcp,
char **  argv 

Remove the flag, as we handle all processing for it.

             Remove the flag, as we handle all processing for it.  
static char* resolve_lib_name ( const char *  )
static char* resolve_lib_name ( )
   Given a library name without "lib" prefix, this function
   returns a full library name including a path.  
     Library extensions for AIX dynamic linking.  
             The following lines are needed because path_prefix list
             may contain directories both with trailing DIR_SEPARATOR and
             without it.  
static void scan_libraries ( const char *  )
static void scan_libraries ( )
   Use the List Dynamic Dependencies program to find shared libraries that
   the output file depends upon and their initialization/finalization
   routines, if any.  
     If we do not have an `ldd', complain.  
     Trace if needed.  
     Read each line of ldd output.  
         Extract names of libraries and add to list.  
         Find the end of the symbol name.  
     Now iterate through the library list adding their symbols to
     the list.  
static void scan_prog_file ( const char *  prog_name,
scanpass  which_pass,
scanfilter  filter 
   Scan the name list of the loaded program for the symbols g++ uses for
   static constructors and destructors.

   The SCANPASS argument tells which collect processing pass this is for and
   the SCANFILTER argument tells which kinds of symbols to consider in this
   pass.  Symbols of a special kind not in the filter mask are considered as
   regular ones.

   The constructor table begins at __CTOR_LIST__ and contains a count of the
   number of pointers (or -1 if the constructors are built in a separate
   section by the linker), followed by the pointers to the constructor
   functions, terminated with a null pointer.  The destructor table has the
   same format, and begins at __DTOR_LIST__.  
   Generic version to scan the name list of the loaded program for
   the symbols g++ uses for static constructors and destructors.  
   COFF version to scan the name list of the loaded program for
   the symbols g++ uses for static constructors and destructors.  
     LTO objects must be in a known format.  This check prevents
     us from accepting an archive containing LTO objects, which
     gcc cannot currently handle.  
     If we do not have an `nm', complain.  
     Trace if needed.  
     Read each line of nm output.  
             Look for the LTO info marker symbol, and add filename to
             the LTO objects list if found.  
                   We need to read all the input, so we can't just
                   return here.  But we can avoid useless work.  
         If it contains a constructor or destructor name, add the name
         to the appropriate list unless this is a kind of symbol we're
         not supposed to even consider.  
         Find the end of the symbol name.
         Do not include `|', because Encore nm can tack that on the end.  
     We do not need scanning for some standard C libraries.  
     On AIX we have a loop, because there is not much difference
     between an object and an archive. This trick allows us to
     eliminate scan_libraries() function.  
         Some platforms (e.g. OSF4) declare ldopen as taking a
         non-const char * filename parameter, even though it will not
         modify that string.  So we must cast away const-ness here,
         using CONST_CAST to prevent complaints from -Wcast-qual.  
                 Is current archive member a shared object?  
                         All AIX function names have a duplicate entry
                         beginning with a dot.  
                             Explicitly export all global symbols when
                             building a shared object on AIX, but do not
                             re-export symbols from another shared object
                             and do not export symbols if the user
                             provides an explicit export list.  
                 If archive contains both 32-bit and 64-bit objects,
                 we want to skip objects in other mode so mismatch normal.  
         On AIX loop continues while there are more members in archive.  
     Otherwise we simply close ldptr.  

References add_to_list(), constructors, destructors, fatal_error(), frame_tables, PASS_LIB, SCAN_CTOR, SCAN_DTOR, SCAN_DWEH, SCAN_FINI, SCAN_INIT, SYM_CTOR, SYM_DTOR, SYM_DWEH, SYM_FINI, and SYM_INIT.

Referenced by add_lto_object().

static void sort_ids ( struct head )
static void sort_ids ( )
   Insertion sort the ids from ctor/dtor list HEAD_PTR in descending order.
   ctors will be run from right to left, dtors from left to right.  
     id holds the current element to insert.  id_next holds the next
     element to insert.  id_ptr iterates through the already sorted elements
     looking for the place to insert id.  
     We don't have any sorted elements yet.  
               If the sequence numbers are the same, we put the id from the
               file later on the command line later in the list.  
               Hack: do lexical compare, too.
            || (id->sequence == (*id_ptr)->sequence
                && strcmp (id->name, (*id_ptr)->name) > 0) 
     Now set the sequence numbers properly so write_c_file works.  
static void write_aix_file ( FILE *  ,
struct id  
static void write_aix_file ( )

References debug, and PASS_LTOINFO.

static void write_c_file ( FILE *  ,
const char *   
static void write_c_file ( )
static void write_c_file_glob ( FILE *  ,
const char *   
static void write_c_file_glob ( )
   Write the constructor/destructor tables.  
     Write the tables as C code.  
         This must match what's in frame.h.  
static void write_c_file_stat ( FILE *  ,
const char *   
static void write_c_file_stat ( )
   Write out the constructor and destructor tables statically (for a shared
   object), along with the functions to execute them.  
     Figure out name of output_file, stripping off .so version.  
     q points to null at end of the string (or . of the .so version) 
     Write the tables as C code.  
         This must match what's in frame.h.  
static void write_list ( FILE *  ,
const char *  ,
struct id  
static void write_list ( )
   Write: `prefix', the names on list LIST, `suffix'.  
static void write_list_with_asm ( FILE *  ,
const char *  ,
struct id  
static void write_list_with_asm ( )

Variable Documentation

int aix64_flag
const char* const aix_std_libs[]
Initial value:
   Array of standard AIX libraries which should not
   be scanned for ctors/dtors.  
int aixrtl_flag
bool at_file_supplied
const char* c_file
const char* c_file_name
struct path_prefix cmdline_lib_dirs
struct head constructors

Referenced by scan_prog_file().

   Dump expression REF.  
   Dump a rtx vector REF.  
   Unified dump function for a DATA_REFERENCE structure.  
   Generic dump for the above.  
     Print the slot this node is in, and its code, and address.  

Referenced by debug(), find_a_file(), find_file_set_debug(), prefix_from_string(), and write_aix_file().

struct head destructors

Referenced by scan_prog_file().

int do_collecting = 1
const char* export_file
int export_flag
struct head exports
char * fininame
int flag_dsym = false
int flag_idsym = false
struct head frame_tables
bool helpflag
char* initname
const char* ldd_file_name
const char* lderrout
const char* ldout
struct path_prefix libpath_lib_dirs
struct path_prefix* libpaths[3]
Initial value:
struct head libs
   Lists to keep libraries to be scanned for global constructors/destructors.  
enum lto_mode_d lto_mode = LTO_MODE_NONE
   Current LTO mode.  
char** lto_o_files
struct lto_object_list lto_objects
bool may_unlink_output_file = false
   Whether we may unlink the output file, which should be set as soon as we
   know we have successfully produced it.  This is typically useful to prevent
   blindly attempting to unlink a read-only output that the target linker
   would leave untouched.  
const char* nm_file_name
int no_demangle
   Nonzero if we should suppress the automatic demangling of identifiers
   in linker error messages.  Set from COLLECT_NO_DEMANGLE.  
const char* o_file
const char* output_file

Referenced by extract_init_priority().

struct path_prefix cpath path
   We maintain two prefix lists: one from COMPILER_PATH environment variable
   and one from the PATH variable.  

Referenced by add_pubtype(), create_block_for_threading(), and read_state_type().

char* response_file
int rflag
long sequence_number = 0
int shared_obj
const char* strip_file_name
int strip_flag
const char* const target_machine = TARGET_MACHINE
   This is the name of the target machine.  We use it to form the name
   of the files to execute.  
static const char * target_system_root = TARGET_SYSTEM_ROOT
   A string that must be prepended to a target OS path in order to find
   it on the host system.  
char* temporary_firstobj
struct obstack temporary_obstack

Referenced by obstack_fgets(), and tlink_execute().

bool vflag