(root)/
gcc-13.2.0/
lto-plugin/
lto-plugin.c
       1  /* LTO plugin for linkers like gold, GNU ld or mold.
       2     Copyright (C) 2009-2023 Free Software Foundation, Inc.
       3     Contributed by Rafael Avila de Espindola (espindola@google.com).
       4  
       5  This program is free software; you can redistribute it and/or modify
       6  it under the terms of the GNU General Public License as published by
       7  the Free Software Foundation; either version 3, or (at your option)
       8  any later version.
       9  
      10  This program is distributed in the hope that it will be useful, but
      11  WITHOUT ANY WARRANTY; without even the implied warranty of
      12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      13  General Public License for more details.
      14  
      15  You should have received a copy of the GNU General Public License
      16  along with this program; see the file COPYING3.  If not see
      17  <http://www.gnu.org/licenses/>.  */
      18  
      19  /* The plugin has only one external function: onload. A linker passes it an array of
      20     function that the plugin uses to communicate back to the linker.
      21  
      22     With the functions provided by the linker, the plugin can be notified when
      23     the linker first analyzes a file and pass a symbol table back to the linker. The plugin
      24     is also notified when all symbols have been read and it is time to generate
      25     machine code for the necessary symbols.
      26  
      27     More information at http://gcc.gnu.org/wiki/whopr/driver.
      28  
      29     This plugin should be passed the lto-wrapper options and will forward them.
      30     It also has options at his own:
      31     -debug: Print the command line used to run lto-wrapper.
      32     -nop: Instead of running lto-wrapper, pass the original to the plugin. This
      33     only works if the input files are hybrid. 
      34     -linker-output-known: Do not determine linker output
      35     -linker-output-auto-nolto-rel: Switch from rel to nolto-rel mode without
      36     warning.  This is used on systems like VxWorks (kernel) where the link is
      37     always partial and repeated incremental linking is generally not used.
      38     -sym-style={none,win32,underscore|uscore}
      39     -pass-through  */
      40  
      41  #ifdef HAVE_CONFIG_H
      42  #include "config.h"
      43  #endif
      44  #if HAVE_STDINT_H
      45  #include <stdint.h>
      46  #endif
      47  #include <stdbool.h>
      48  #include <assert.h>
      49  #include <errno.h>
      50  #include <string.h>
      51  #include <stdlib.h>
      52  #include <stdio.h>
      53  #include <inttypes.h>
      54  #include <sys/stat.h>
      55  #include <unistd.h>
      56  #include <fcntl.h>
      57  #include <sys/types.h>
      58  #if HAVE_PTHREAD_LOCKING
      59  #include <pthread.h>
      60  #endif
      61  #ifdef HAVE_SYS_WAIT_H
      62  #include <sys/wait.h>
      63  #endif
      64  #ifndef WIFEXITED
      65  #define WIFEXITED(S) (((S) & 0xff) == 0)
      66  #endif
      67  #ifndef WEXITSTATUS
      68  #define WEXITSTATUS(S) (((S) & 0xff00) >> 8)
      69  #endif
      70  #include <libiberty.h>
      71  #include <hashtab.h>
      72  #include "../gcc/lto/common.h"
      73  #include "simple-object.h"
      74  #include "plugin-api.h"
      75  
      76  /* We need to use I64 instead of ll width-specifier on native Windows.
      77     The reason for this is that older MS-runtimes don't support the ll.  */
      78  #ifdef __MINGW32__
      79  #define PRI_LL "I64"
      80  #else
      81  #define PRI_LL "ll"
      82  #endif
      83  
      84  /* Handle opening elf files on hosts, such as Windows, that may use
      85     text file handling that will break binary access.  */
      86  #ifndef O_BINARY
      87  # define O_BINARY 0
      88  #endif
      89  
      90  /* Segment name for LTO sections.  This is only used for Mach-O.
      91     FIXME: This needs to be kept in sync with darwin.c.  */
      92  
      93  #define LTO_SEGMENT_NAME "__GNU_LTO"
      94  
      95  /* Return true if STR string starts with PREFIX.  */
      96  
      97  static inline bool
      98  startswith (const char *str, const char *prefix)
      99  {
     100    return strncmp (str, prefix, strlen (prefix)) == 0;
     101  }
     102  
     103  /* The part of the symbol table the plugin has to keep track of. Note that we
     104     must keep SYMS until all_symbols_read is called to give the linker time to
     105     copy the symbol information. 
     106     The id must be 64bit to minimze collisions. */
     107  
     108  struct sym_aux
     109  {
     110    uint32_t slot;
     111    unsigned long long id;
     112    unsigned next_conflict;
     113  };
     114  
     115  struct plugin_symtab
     116  {
     117    int nsyms;
     118    int last_sym;
     119    struct sym_aux *aux;
     120    struct ld_plugin_symbol *syms;
     121    unsigned long long id;
     122  };
     123  
     124  /* Encapsulates object file data during symbol scan.  */
     125  struct plugin_objfile
     126  {
     127    int found;
     128    bool offload;
     129    simple_object_read *objfile;
     130    struct plugin_symtab *out;
     131    const struct ld_plugin_input_file *file;
     132  };
     133  
     134  /* All that we have to remember about a file. */
     135  
     136  struct plugin_file_info
     137  {
     138    char *name;
     139    void *handle;
     140    struct plugin_symtab symtab;
     141    struct plugin_symtab conflicts;
     142    bool skip_file;
     143  };
     144  
     145  /* List item with name of the file with offloading.  */
     146  
     147  struct plugin_offload_file
     148  {
     149    char *name;
     150    struct plugin_offload_file *next;
     151  };
     152  
     153  /* Until ASM_OUTPUT_LABELREF can be hookized and decoupled from
     154     stdio file streams, we do simple label translation here.  */
     155  
     156  enum symbol_style
     157  {
     158    ss_none,	/* No underscore prefix. */
     159    ss_win32,	/* Underscore prefix any symbol not beginning with '@'.  */
     160    ss_uscore,	/* Underscore prefix all symbols.  */
     161  };
     162  
     163  #if HAVE_PTHREAD_LOCKING
     164  /* Plug-in mutex.  */
     165  static pthread_mutex_t plugin_lock;
     166  
     167  #define LOCK_SECTION pthread_mutex_lock (&plugin_lock)
     168  #define UNLOCK_SECTION pthread_mutex_unlock (&plugin_lock)
     169  #else
     170  #define LOCK_SECTION
     171  #define UNLOCK_SECTION
     172  #endif
     173  
     174  static char *arguments_file_name;
     175  static ld_plugin_register_claim_file register_claim_file;
     176  static ld_plugin_register_all_symbols_read register_all_symbols_read;
     177  static ld_plugin_get_symbols get_symbols, get_symbols_v2, get_symbols_v3;
     178  static ld_plugin_register_cleanup register_cleanup;
     179  static ld_plugin_add_input_file add_input_file;
     180  static ld_plugin_add_input_library add_input_library;
     181  static ld_plugin_message message;
     182  static ld_plugin_add_symbols add_symbols, add_symbols_v2;
     183  static ld_plugin_get_api_version get_api_version;
     184  
     185  /* By default, use version LAPI_V0 if there is not negotiation.  */
     186  static enum linker_api_version api_version = LAPI_V0;
     187  
     188  static struct plugin_file_info *claimed_files = NULL;
     189  static unsigned int num_claimed_files = 0;
     190  static unsigned int non_claimed_files = 0;
     191  
     192  /* List of files with offloading.  */
     193  static struct plugin_offload_file *offload_files;
     194  /* Last file in the list.  */
     195  static struct plugin_offload_file *offload_files_last;
     196  /* Last non-archive file in the list.  */
     197  static struct plugin_offload_file *offload_files_last_obj;
     198  /* Last LTO file in the list.  */
     199  static struct plugin_offload_file *offload_files_last_lto;
     200  /* Total number of files with offloading.  */
     201  static unsigned num_offload_files;
     202  
     203  static char **output_files = NULL;
     204  static unsigned int num_output_files = 0;
     205  
     206  static char **lto_wrapper_argv;
     207  static int lto_wrapper_num_args;
     208  
     209  static char **pass_through_items = NULL;
     210  static unsigned int num_pass_through_items;
     211  
     212  static char *ltrans_objects = NULL;
     213  
     214  static bool debug;
     215  static bool save_temps;
     216  static bool verbose;
     217  static char nop;
     218  static char *resolution_file = NULL;
     219  static enum ld_plugin_output_file_type linker_output;
     220  static bool linker_output_set;
     221  static bool linker_output_known;
     222  static bool linker_output_auto_nolto_rel;
     223  static const char *link_output_name = NULL;
     224  
     225  /* This indicates link_output_name already contains the dot of the
     226     suffix, so we can skip it in extensions.  */
     227  static bool skip_in_suffix = false;
     228  
     229  /* The version of gold being used, or -1 if not gold.  The number is
     230     MAJOR * 100 + MINOR.  */
     231  static int gold_version = -1;
     232  
     233  /* Not used by default, but can be overridden at runtime
     234     by using -plugin-opt=-sym-style={none,win32,underscore|uscore}
     235     (in fact, only first letter of style arg is checked.)  */
     236  static enum symbol_style sym_style = ss_none;
     237  
     238  static void
     239  check_1 (int gate, enum ld_plugin_level level, const char *text)
     240  {
     241    if (gate)
     242      return;
     243  
     244    if (message)
     245      message (level, text);
     246    else
     247      {
     248        /* If there is no nicer way to inform the user, fallback to stderr. */
     249        fprintf (stderr, "%s\n", text);
     250        if (level == LDPL_FATAL)
     251  	abort ();
     252      }
     253  }
     254  
     255  /* This little wrapper allows check to be called with a non-integer
     256     first argument, such as a pointer that must be non-NULL.  We can't
     257     use c99 bool type to coerce it into range, so we explicitly test.  */
     258  #define check(GATE, LEVEL, TEXT) check_1 (((GATE) != 0), (LEVEL), (TEXT))
     259  
     260  /* Parse an entry of the IL symbol table. The data to be parsed is pointed
     261     by P and the result is written in ENTRY. The slot number is stored in SLOT.
     262     Returns the address of the next entry. */
     263  
     264  static char *
     265  parse_table_entry (char *p, struct ld_plugin_symbol *entry, 
     266  		   struct sym_aux *aux)
     267  {
     268    unsigned char t;
     269    enum ld_plugin_symbol_kind translate_kind[] =
     270      {
     271        LDPK_DEF,
     272        LDPK_WEAKDEF,
     273        LDPK_UNDEF,
     274        LDPK_WEAKUNDEF,
     275        LDPK_COMMON
     276      };
     277  
     278    enum ld_plugin_symbol_visibility translate_visibility[] =
     279      {
     280        LDPV_DEFAULT,
     281        LDPV_PROTECTED,
     282        LDPV_INTERNAL,
     283        LDPV_HIDDEN
     284      };
     285  
     286    switch (sym_style)
     287      {
     288      case ss_win32:
     289        if (p[0] == '@')
     290  	{
     291      /* cf. Duff's device.  */
     292      case ss_none:
     293  	  entry->name = xstrdup (p);
     294  	  break;
     295  	}
     296      /* FALL-THROUGH.  */
     297      case ss_uscore:
     298        entry->name = concat ("_", p, NULL);
     299        break;
     300      default:
     301        check (0, LDPL_FATAL, "invalid symbol style requested");
     302        break;
     303      }
     304    while (*p)
     305      p++;
     306    p++;
     307  
     308    entry->version = NULL;
     309  
     310    entry->comdat_key = p;
     311    while (*p)
     312      p++;
     313    p++;
     314  
     315    if (strlen (entry->comdat_key) == 0)
     316      entry->comdat_key = NULL;
     317    else
     318      entry->comdat_key = xstrdup (entry->comdat_key);
     319  
     320    entry->unused = entry->section_kind = entry->symbol_type = 0;
     321  
     322    t = *p;
     323    check (t <= 4, LDPL_FATAL, "invalid symbol kind found");
     324    entry->def = translate_kind[t];
     325    p++;
     326  
     327    t = *p;
     328    check (t <= 3, LDPL_FATAL, "invalid symbol visibility found");
     329    entry->visibility = translate_visibility[t];
     330    p++;
     331  
     332    memcpy (&entry->size, p, sizeof (uint64_t));
     333    p += 8;
     334  
     335    memcpy (&aux->slot, p, sizeof (uint32_t));
     336    p += 4;
     337  
     338    entry->resolution = LDPR_UNKNOWN;
     339  
     340    aux->next_conflict = -1;
     341  
     342    return p;
     343  }
     344  
     345  /* Parse an entry of the IL symbol table. The data to be parsed is pointed
     346     by P and the result is written in ENTRY. The slot number is stored in SLOT.
     347     Returns the address of the next entry. */
     348  
     349  static char *
     350  parse_table_entry_extension (char *p, struct ld_plugin_symbol *entry)
     351  {
     352    unsigned char t;
     353    enum ld_plugin_symbol_type symbol_types[] =
     354      {
     355        LDST_UNKNOWN,
     356        LDST_FUNCTION,
     357        LDST_VARIABLE,
     358      };
     359  
     360    t = *p;
     361    check (t <= 2, LDPL_FATAL, "invalid symbol type found");
     362    entry->symbol_type = symbol_types[t];
     363    p++;
     364    entry->section_kind = *p;
     365    p++;
     366  
     367    return p;
     368  }
     369  
     370  
     371  /* Translate the IL symbol table located between DATA and END. Append the
     372     slots and symbols to OUT. */
     373  
     374  static void
     375  translate (char *data, char *end, struct plugin_symtab *out)
     376  {
     377    struct sym_aux *aux;
     378    struct ld_plugin_symbol *syms = NULL;
     379    int n, len;
     380  
     381    /* This overestimates the output buffer sizes, but at least 
     382       the algorithm is O(1) now. */
     383  
     384    len = (end - data)/8 + out->nsyms + 1;
     385    syms = xrealloc (out->syms, len * sizeof (struct ld_plugin_symbol));
     386    aux = xrealloc (out->aux, len * sizeof (struct sym_aux));
     387    
     388    for (n = out->nsyms; data < end; n++) 
     389      { 
     390        aux[n].id = out->id; 
     391        data = parse_table_entry (data, &syms[n], &aux[n]);
     392      }
     393  
     394    assert(n < len);
     395  
     396    out->nsyms = n;
     397    out->syms = syms;
     398    out->aux = aux;
     399  }
     400  
     401  static void
     402  parse_symtab_extension (char *data, char *end, struct plugin_symtab *out)
     403  {
     404    unsigned long i;
     405    unsigned char version;
     406  
     407    if (data >= end)
     408      /* FIXME: Issue an error ?  */
     409      return;
     410  
     411    version = *data;
     412    data++;
     413  
     414    if (version != 1)
     415      return;
     416  
     417    /* Version 1 contains the following data per entry:
     418       - symbol_type
     419       - section_kind
     420       .  */
     421  
     422    unsigned long nsyms = (end - data) / 2;
     423  
     424    for (i = 0; i < nsyms; i++)
     425      data = parse_table_entry_extension (data, out->syms + i + out->last_sym);
     426  
     427    out->last_sym += nsyms;
     428  }
     429  
     430  /* Free all memory that is no longer needed after writing the symbol
     431     resolution. */
     432  
     433  static void
     434  free_1 (struct plugin_file_info *files, unsigned num_files)
     435  {
     436    unsigned int i;
     437    for (i = 0; i < num_files; i++)
     438      {
     439        struct plugin_file_info *info = &files[i];
     440        struct plugin_symtab *symtab = &info->symtab;
     441        unsigned int j;
     442        for (j = 0; j < symtab->nsyms; j++)
     443  	{
     444  	  struct ld_plugin_symbol *s = &symtab->syms[j];
     445  	  free (s->name);
     446  	  free (s->comdat_key);
     447  	}
     448        free (symtab->syms);
     449        symtab->syms = NULL;
     450      }
     451  }
     452  
     453  /* Free all remaining memory. */
     454  
     455  static void
     456  free_2 (void)
     457  {
     458    unsigned int i;
     459    for (i = 0; i < num_claimed_files; i++)
     460      {
     461        struct plugin_file_info *info = &claimed_files[i];
     462        struct plugin_symtab *symtab = &info->symtab;
     463        free (symtab->aux);
     464        free (info->name);
     465      }
     466  
     467    for (i = 0; i < num_output_files; i++)
     468      free (output_files[i]);
     469    free (output_files);
     470  
     471    free (claimed_files);
     472    claimed_files = NULL;
     473    num_claimed_files = 0;
     474  
     475    while (offload_files)
     476      {
     477        struct plugin_offload_file *ofld = offload_files;
     478        offload_files = offload_files->next;
     479        free (ofld);
     480      }
     481    num_offload_files = 0;
     482  
     483    free (arguments_file_name);
     484    arguments_file_name = NULL;
     485  }
     486  
     487  /* Dump SYMTAB to resolution file F. */
     488  
     489  static void
     490  dump_symtab (FILE *f, struct plugin_symtab *symtab)
     491  {
     492    unsigned j;
     493  
     494    for (j = 0; j < symtab->nsyms; j++)
     495      {
     496        uint32_t slot = symtab->aux[j].slot;
     497        unsigned int resolution = symtab->syms[j].resolution;
     498        
     499        assert (resolution != LDPR_UNKNOWN);
     500  
     501        fprintf (f, "%u %" PRI_LL "x %s %s\n",
     502                 (unsigned int) slot, symtab->aux[j].id,
     503  	       lto_resolution_str[resolution], 
     504  	       symtab->syms[j].name);
     505      }
     506  }
     507  
     508  /* Finish the conflicts' resolution information after the linker resolved
     509     the original symbols */
     510  
     511  static void
     512  finish_conflict_resolution (struct plugin_symtab *symtab, 
     513  			   struct plugin_symtab *conflicts)
     514  {
     515    int i, j;
     516  
     517    if (conflicts->nsyms == 0)
     518      return;
     519  
     520    for (i = 0; i < symtab->nsyms; i++)
     521      { 
     522        char resolution = LDPR_UNKNOWN;
     523  
     524        if (symtab->aux[i].next_conflict == -1)
     525  	continue;
     526  
     527        switch (symtab->syms[i].def) 
     528  	{
     529  	case LDPK_DEF:
     530  	case LDPK_COMMON: /* ??? */
     531  	  resolution = LDPR_RESOLVED_IR; 
     532  	  break;
     533  	case LDPK_WEAKDEF:
     534  	  resolution = LDPR_PREEMPTED_IR;
     535  	  break;
     536  	case LDPK_UNDEF:
     537  	case LDPK_WEAKUNDEF:
     538  	  resolution = symtab->syms[i].resolution;
     539  	  break;
     540  	default:
     541  	  assert (0);
     542  	}
     543  
     544        assert (resolution != LDPR_UNKNOWN);
     545  
     546        for (j = symtab->aux[i].next_conflict; 
     547  	   j != -1; 
     548  	   j = conflicts->aux[j].next_conflict)
     549  	conflicts->syms[j].resolution = resolution;
     550      }
     551  }
     552  
     553  /* Free symbol table SYMTAB. */
     554  
     555  static void
     556  free_symtab (struct plugin_symtab *symtab)
     557  {
     558    free (symtab->syms);
     559    symtab->syms = NULL;
     560    free (symtab->aux);
     561    symtab->aux = NULL;
     562  }
     563  
     564  /*  Writes the relocations to disk. */
     565  
     566  static void
     567  write_resolution (void)
     568  {
     569    unsigned int i, included_files = 0;
     570    FILE *f;
     571  
     572    check (resolution_file, LDPL_FATAL, "resolution file not specified");
     573    f = fopen (resolution_file, "w");
     574    check (f, LDPL_FATAL, "could not open file");
     575  
     576    for (i = 0; i < num_claimed_files; i++)
     577      {
     578        struct plugin_file_info *info = &claimed_files[i];
     579        struct plugin_symtab *symtab = &info->symtab;
     580        struct ld_plugin_symbol *syms = symtab->syms;
     581  
     582        /* Version 2 of API supports IRONLY_EXP resolution that is
     583  	 accepted by GCC-4.7 and newer.
     584  	 Version 3 can return LDPS_NO_SYMS that means the object
     585  	 will not be used at all.  */
     586        if (get_symbols_v3)
     587  	{
     588  	  enum ld_plugin_status status
     589  	    = get_symbols_v3 (info->handle, symtab->nsyms, syms);
     590  	  if (status == LDPS_NO_SYMS)
     591  	    {
     592  	      info->skip_file = true;
     593  	      continue;
     594  	    }
     595  	}
     596        else if (get_symbols_v2)
     597          get_symbols_v2 (info->handle, symtab->nsyms, syms);
     598        else
     599          get_symbols (info->handle, symtab->nsyms, syms);
     600  
     601        ++included_files;
     602  
     603        finish_conflict_resolution (symtab, &info->conflicts);
     604      }
     605  
     606    fprintf (f, "%d\n", included_files);
     607  
     608    for (i = 0; i < num_claimed_files; i++)
     609      {
     610        struct plugin_file_info *info = &claimed_files[i];
     611        struct plugin_symtab *symtab = &info->symtab;
     612  
     613        if (info->skip_file)
     614  	continue;
     615  
     616        fprintf (f, "%s %d\n", info->name, symtab->nsyms + info->conflicts.nsyms);
     617        dump_symtab (f, symtab);
     618        if (info->conflicts.nsyms)
     619  	{
     620  	  dump_symtab (f, &info->conflicts);
     621  	  free_symtab (&info->conflicts);
     622  	}
     623      }
     624    fclose (f);
     625  }
     626  
     627  /* Pass files generated by the lto-wrapper to the linker. FD is lto-wrapper's
     628     stdout. */
     629  
     630  static void
     631  add_output_files (FILE *f)
     632  {
     633    for (;;)
     634      {
     635        const unsigned piece = 32;
     636        char *buf, *s = xmalloc (piece);
     637        size_t len;
     638  
     639        buf = s;
     640  cont:
     641        if (!fgets (buf, piece, f))
     642  	{
     643  	  free (s);
     644  	  break;
     645  	}
     646        len = strlen (s);
     647        if (s[len - 1] != '\n')
     648  	{
     649  	  s = xrealloc (s, len + piece);
     650  	  buf = s + len;
     651  	  goto cont;
     652  	}
     653        s[len - 1] = '\0';
     654  
     655        num_output_files++;
     656        output_files
     657  	= xrealloc (output_files, num_output_files * sizeof (char *));
     658        output_files[num_output_files - 1] = s;
     659        add_input_file (output_files[num_output_files - 1]);
     660      }
     661  }
     662  
     663  /* Execute the lto-wrapper. ARGV[0] is the binary. The rest of ARGV is the
     664     argument list. */
     665  
     666  static void
     667  exec_lto_wrapper (char *argv[])
     668  {
     669    int t, i;
     670    int status;
     671    char *at_args;
     672    FILE *args;
     673    FILE *wrapper_output;
     674    char *new_argv[3];
     675    struct pex_obj *pex;
     676    const char *errmsg;
     677  
     678    /* Write argv to a file to avoid a command line that is too long
     679       Save the file locally on save-temps.  */
     680    const char *suffix = ".lto_wrapper_args";
     681    if (skip_in_suffix)
     682      suffix++;
     683    if (save_temps && link_output_name)
     684      arguments_file_name = concat (link_output_name, suffix, NULL);
     685    else
     686      arguments_file_name = make_temp_file (".lto_wrapper_args");
     687    check (arguments_file_name, LDPL_FATAL,
     688           "Failed to generate a temorary file name");
     689  
     690    args = fopen (arguments_file_name, "w");
     691    check (args, LDPL_FATAL, "could not open arguments file");
     692  
     693    t = writeargv (&argv[1], args);
     694    check (t == 0, LDPL_FATAL, "could not write arguments");
     695    t = fclose (args);
     696    check (t == 0, LDPL_FATAL, "could not close arguments file");
     697  
     698    at_args = concat ("@", arguments_file_name, NULL);
     699    check (at_args, LDPL_FATAL, "could not allocate");
     700  
     701    for (i = 1; argv[i]; i++)
     702      {
     703        char *a = argv[i];
     704        /* Check the input argument list for a verbose marker too.  */
     705        if (a[0] == '-' && a[1] == 'v' && a[2] == '\0')
     706  	{
     707  	  verbose = true;
     708  	  break;
     709  	}
     710      }
     711  
     712    if (verbose)
     713      {
     714        for (i = 0; argv[i]; i++)
     715  	fprintf (stderr, "%s ", argv[i]);
     716        fprintf (stderr, "\n");
     717      }
     718  
     719    new_argv[0] = argv[0];
     720    new_argv[1] = at_args;
     721    new_argv[2] = NULL;
     722  
     723    if (debug)
     724      {
     725        for (i = 0; new_argv[i]; i++)
     726  	fprintf (stderr, "%s ", new_argv[i]);
     727        fprintf (stderr, "\n");
     728      }
     729  
     730    pex = pex_init (PEX_USE_PIPES, "lto-wrapper", NULL);
     731    check (pex != NULL, LDPL_FATAL, "could not pex_init lto-wrapper");
     732  
     733    errmsg = pex_run (pex, 0, new_argv[0], new_argv, NULL, NULL, &t);
     734    check (errmsg == NULL, LDPL_FATAL, "could not run lto-wrapper");
     735    check (t == 0, LDPL_FATAL, "could not run lto-wrapper");
     736  
     737    wrapper_output = pex_read_output (pex, 0);
     738    check (wrapper_output, LDPL_FATAL, "could not read lto-wrapper output");
     739  
     740    add_output_files (wrapper_output);
     741  
     742    t = pex_get_status (pex, 1, &status);
     743    check (t == 1, LDPL_FATAL, "could not get lto-wrapper exit status");
     744    check (WIFEXITED (status) && WEXITSTATUS (status) == 0, LDPL_FATAL,
     745           "lto-wrapper failed");
     746  
     747    pex_free (pex);
     748  
     749    free (at_args);
     750  }
     751  
     752  /* Pass the original files back to the linker. */
     753  
     754  static void
     755  use_original_files (void)
     756  {
     757    unsigned i;
     758    for (i = 0; i < num_claimed_files; i++)
     759      {
     760        struct plugin_file_info *info = &claimed_files[i];
     761        add_input_file (info->name);
     762      }
     763  }
     764  
     765  
     766  /* Called by the linker once all symbols have been read. */
     767  
     768  static enum ld_plugin_status
     769  all_symbols_read_handler (void)
     770  {
     771    const unsigned num_lto_args
     772      = num_claimed_files + lto_wrapper_num_args + 2
     773        + !linker_output_known + !linker_output_auto_nolto_rel;
     774    unsigned i;
     775    char **lto_argv;
     776    const char *linker_output_str = NULL;
     777    const char **lto_arg_ptr;
     778    if (num_claimed_files + num_offload_files == 0)
     779      return LDPS_OK;
     780  
     781    if (nop)
     782      {
     783        use_original_files ();
     784        return LDPS_OK;
     785      }
     786  
     787    if (ltrans_objects)
     788      {
     789        FILE *objs = fopen (ltrans_objects, "r");
     790        add_output_files (objs);
     791        fclose (objs);
     792        return LDPS_OK;
     793      }
     794  
     795    lto_argv = (char **) xcalloc (sizeof (char *), num_lto_args);
     796    lto_arg_ptr = (const char **) lto_argv;
     797    assert (lto_wrapper_argv);
     798  
     799    write_resolution ();
     800  
     801    free_1 (claimed_files, num_claimed_files);
     802  
     803    for (i = 0; i < lto_wrapper_num_args; i++)
     804      *lto_arg_ptr++ = lto_wrapper_argv[i];
     805  
     806    if (!linker_output_known)
     807      {
     808        assert (linker_output_set);
     809        switch (linker_output)
     810  	{
     811  	case LDPO_REL:
     812  	  if (non_claimed_files)
     813  	    {
     814  	      if (!linker_output_auto_nolto_rel)
     815  		message (LDPL_WARNING, "incremental linking of LTO and non-LTO"
     816  			 " objects; using -flinker-output=nolto-rel which will"
     817  			 " bypass whole program optimization");
     818  	      linker_output_str = "-flinker-output=nolto-rel";
     819  	    }
     820  	  else
     821  	    linker_output_str = "-flinker-output=rel";
     822  	  break;
     823  	case LDPO_DYN:
     824  	  linker_output_str = "-flinker-output=dyn";
     825  	  break;
     826  	case LDPO_PIE:
     827  	  linker_output_str = "-flinker-output=pie";
     828  	  break;
     829  	case LDPO_EXEC:
     830  	  linker_output_str = "-flinker-output=exec";
     831  	  break;
     832  	default:
     833  	  message (LDPL_FATAL, "unsupported linker output %i", linker_output);
     834  	  break;
     835  	}
     836        *lto_arg_ptr++ = xstrdup (linker_output_str);
     837      }
     838  
     839    if (num_offload_files > 0)
     840      {
     841        FILE *f;
     842        char *arg;
     843        char *offload_objects_file_name;
     844        struct plugin_offload_file *ofld;
     845        const char *suffix = ".ofldlist";
     846  
     847        if (save_temps && link_output_name)
     848  	{
     849  	  suffix += skip_in_suffix;
     850  	  offload_objects_file_name = concat (link_output_name, suffix, NULL);
     851  	}
     852        else
     853  	offload_objects_file_name = make_temp_file (suffix);
     854        check (offload_objects_file_name, LDPL_FATAL,
     855  	     "Failed to generate a temporary file name");
     856        f = fopen (offload_objects_file_name, "w");
     857        check (f, LDPL_FATAL, "could not open file with offload objects");
     858        fprintf (f, "%u\n", num_offload_files);
     859  
     860        /* Skip the dummy item at the start of the list.  */
     861        ofld = offload_files->next;
     862        while (ofld)
     863  	{
     864  	  fprintf (f, "%s\n", ofld->name);
     865  	  ofld = ofld->next;
     866  	}
     867        fclose (f);
     868  
     869        arg = concat ("-foffload-objects=", offload_objects_file_name, NULL);
     870        check (arg, LDPL_FATAL, "could not allocate");
     871        *lto_arg_ptr++ = arg;
     872      }
     873  
     874    for (i = 0; i < num_claimed_files; i++)
     875      {
     876        struct plugin_file_info *info = &claimed_files[i];
     877  
     878        if (!info->skip_file)
     879  	*lto_arg_ptr++ = info->name;
     880      }
     881  
     882    *lto_arg_ptr++ = NULL;
     883    exec_lto_wrapper (lto_argv);
     884  
     885    free (lto_argv);
     886  
     887    /* --pass-through is not needed when using gold 1.11 or later.  */
     888    if (pass_through_items && gold_version < 111)
     889      {
     890        unsigned int i;
     891        for (i = 0; i < num_pass_through_items; i++)
     892          {
     893  	  if (startswith (pass_through_items[i], "-l"))
     894              add_input_library (pass_through_items[i] + 2);
     895            else
     896              add_input_file (pass_through_items[i]);
     897            free (pass_through_items[i]);
     898            pass_through_items[i] = NULL;
     899          }
     900        free (pass_through_items);
     901        pass_through_items = NULL;
     902      }
     903  
     904    return LDPS_OK;
     905  }
     906  
     907  /* Helper, as used in collect2.  */
     908  static int
     909  file_exists (const char *name)
     910  {
     911    return access (name, R_OK) == 0;
     912  }
     913  
     914  /* Unlink FILE unless we have save-temps set.
     915     Note that we're saving files if verbose output is set. */
     916  
     917  static void
     918  maybe_unlink (const char *file)
     919  {
     920    if (save_temps && file_exists (file))
     921      {
     922        if (verbose)
     923  	fprintf (stderr, "[Leaving %s]\n", file);
     924        return;
     925      }
     926  
     927    unlink_if_ordinary (file);
     928  }
     929  
     930  /* Remove temporary files at the end of the link. */
     931  
     932  static enum ld_plugin_status
     933  cleanup_handler (void)
     934  {
     935    unsigned int i;
     936  
     937    if (debug)
     938      return LDPS_OK;
     939  
     940    if (arguments_file_name)
     941      maybe_unlink (arguments_file_name);
     942  
     943    for (i = 0; i < num_output_files; i++)
     944      maybe_unlink (output_files[i]);
     945  
     946    free_2 ();
     947    return LDPS_OK;
     948  }
     949  
     950  #define SWAP(type, a, b) \
     951    do { type tmp_; tmp_ = (a); (a) = (b); (b) = tmp_; } while(0)
     952  
     953  /* Compare two hash table entries */
     954  
     955  static int eq_sym (const void *a, const void *b)
     956  {
     957    const struct ld_plugin_symbol *as = (const struct ld_plugin_symbol *)a;
     958    const struct ld_plugin_symbol *bs = (const struct ld_plugin_symbol *)b;
     959  
     960    return !strcmp (as->name, bs->name);
     961  }
     962  
     963  /* Hash a symbol */
     964  
     965  static hashval_t hash_sym (const void *a)
     966  {
     967    const struct ld_plugin_symbol *as = (const struct ld_plugin_symbol *)a;
     968  
     969    return htab_hash_string (as->name);
     970  }
     971  
     972  /* Determine how strong a symbol is */
     973  
     974  static int symbol_strength (struct ld_plugin_symbol *s)
     975  {
     976    switch (s->def) 
     977      { 
     978      case LDPK_UNDEF:
     979      case LDPK_WEAKUNDEF:
     980        return 0;
     981      case LDPK_WEAKDEF:
     982        return 1;
     983      default:
     984        return 2;
     985      }
     986  }
     987  
     988  /* In the ld -r case we can get dups in the LTO symbol tables, where
     989     the same symbol can have different resolutions (e.g. undefined and defined).
     990  
     991     We have to keep that in the LTO symbol tables, but the dups confuse
     992     gold and then finally gcc by supplying incorrect resolutions.
     993  
     994     Problem is that the main gold symbol table doesn't know about subids
     995     and does not distingush the same symbols in different states.
     996  
     997     So we drop duplicates from the linker visible symbol table
     998     and keep them in a private table. Then later do own symbol
     999     resolution for the duplicated based on the results for the
    1000     originals.
    1001  
    1002     Then when writing out the resolution file readd the dropped symbols.
    1003     
    1004     XXX how to handle common? */
    1005  
    1006  static void
    1007  resolve_conflicts (struct plugin_symtab *t, struct plugin_symtab *conflicts)
    1008  {
    1009    htab_t symtab = htab_create (t->nsyms, hash_sym, eq_sym, NULL);
    1010    int i;
    1011    int out;
    1012    int outlen;
    1013  
    1014    outlen = t->nsyms;
    1015    conflicts->syms = xmalloc (sizeof (struct ld_plugin_symbol) * outlen);
    1016    conflicts->aux = xmalloc (sizeof (struct sym_aux) * outlen);
    1017  
    1018    /* Move all duplicate symbols into the auxiliary conflicts table. */
    1019    out = 0;
    1020    for (i = 0; i < t->nsyms; i++) 
    1021      {
    1022        struct ld_plugin_symbol *s = &t->syms[i];
    1023        struct sym_aux *aux = &t->aux[i];
    1024        void **slot;
    1025  
    1026        slot = htab_find_slot (symtab, s, INSERT);
    1027        if (*slot != NULL)
    1028  	{
    1029  	  int cnf;
    1030  	  struct ld_plugin_symbol *orig = (struct ld_plugin_symbol *)*slot;
    1031  	  struct sym_aux *orig_aux = &t->aux[orig - t->syms];
    1032  
    1033  	  /* Always let the linker resolve the strongest symbol */
    1034  	  if (symbol_strength (orig) < symbol_strength (s)) 
    1035  	    {
    1036  	      SWAP (struct ld_plugin_symbol, *orig, *s);
    1037  	      SWAP (uint32_t, orig_aux->slot, aux->slot);
    1038  	      SWAP (unsigned long long, orig_aux->id, aux->id);
    1039  	      /* Don't swap conflict chain pointer */
    1040  	    } 
    1041  
    1042  	  /* Move current symbol into the conflicts table */
    1043  	  cnf = conflicts->nsyms++;
    1044  	  conflicts->syms[cnf] = *s;
    1045  	  conflicts->aux[cnf] = *aux;
    1046  	  aux = &conflicts->aux[cnf];
    1047  
    1048  	  /* Update conflicts chain of the original symbol */
    1049  	  aux->next_conflict = orig_aux->next_conflict;
    1050  	  orig_aux->next_conflict = cnf;
    1051  
    1052  	  continue;
    1053  	}
    1054  
    1055        /* Remove previous duplicates in the main table */
    1056        if (out < i)
    1057  	{
    1058  	  t->syms[out] = *s;
    1059  	  t->aux[out] = *aux;
    1060  	}
    1061  
    1062        /* Put original into the hash table */
    1063        *slot = &t->syms[out];
    1064        out++;
    1065      }
    1066  
    1067    assert (conflicts->nsyms <= outlen);
    1068    assert (conflicts->nsyms + out == t->nsyms);
    1069    
    1070    t->nsyms = out;
    1071    htab_delete (symtab);
    1072  }
    1073  
    1074  /* Process one section of an object file.  */
    1075  
    1076  static int 
    1077  process_symtab (void *data, const char *name, off_t offset, off_t length)
    1078  {
    1079    struct plugin_objfile *obj = (struct plugin_objfile *)data;
    1080    char *s;
    1081    char *secdatastart, *secdata;
    1082  
    1083    if (!startswith (name, ".gnu.lto_.symtab"))
    1084      return 1;
    1085  
    1086    s = strrchr (name, '.');
    1087    if (s)
    1088      sscanf (s, ".%" PRI_LL "x", &obj->out->id);
    1089    secdata = secdatastart = xmalloc (length);
    1090    offset += obj->file->offset;
    1091    if (offset != lseek (obj->file->fd, offset, SEEK_SET))
    1092      goto err;
    1093  
    1094    do
    1095      {
    1096        ssize_t got = read (obj->file->fd, secdata, length);
    1097        if (got == 0)
    1098  	break;
    1099        else if (got > 0)
    1100  	{
    1101  	  secdata += got;
    1102  	  length -= got;
    1103  	}
    1104        else if (errno != EINTR)
    1105  	goto err;
    1106      }
    1107    while (length > 0);
    1108    if (length > 0)
    1109      goto err;
    1110  
    1111    translate (secdatastart, secdata, obj->out);
    1112    obj->found++;
    1113    free (secdatastart);
    1114    return 1;
    1115  
    1116  err:
    1117    if (message)
    1118      message (LDPL_FATAL, "%s: corrupt object file", obj->file->name);
    1119    /* Force claim_file_handler to abandon this file.  */
    1120    obj->found = 0;
    1121    free (secdatastart);
    1122    return 0;
    1123  }
    1124  
    1125  /* Process one section of an object file.  */
    1126  
    1127  static int
    1128  process_symtab_extension (void *data, const char *name, off_t offset,
    1129  			  off_t length)
    1130  {
    1131    struct plugin_objfile *obj = (struct plugin_objfile *)data;
    1132    char *s;
    1133    char *secdatastart, *secdata;
    1134  
    1135    if (!startswith (name, ".gnu.lto_.ext_symtab"))
    1136      return 1;
    1137  
    1138    s = strrchr (name, '.');
    1139    if (s)
    1140      sscanf (s, ".%" PRI_LL "x", &obj->out->id);
    1141    secdata = secdatastart = xmalloc (length);
    1142    offset += obj->file->offset;
    1143    if (offset != lseek (obj->file->fd, offset, SEEK_SET))
    1144      goto err;
    1145  
    1146    do
    1147      {
    1148        ssize_t got = read (obj->file->fd, secdata, length);
    1149        if (got == 0)
    1150  	break;
    1151        else if (got > 0)
    1152  	{
    1153  	  secdata += got;
    1154  	  length -= got;
    1155  	}
    1156        else if (errno != EINTR)
    1157  	goto err;
    1158      }
    1159    while (length > 0);
    1160    if (length > 0)
    1161      goto err;
    1162  
    1163    parse_symtab_extension (secdatastart, secdata, obj->out);
    1164    obj->found++;
    1165    free (secdatastart);
    1166    return 1;
    1167  
    1168  err:
    1169    if (message)
    1170      message (LDPL_FATAL, "%s: corrupt object file", obj->file->name);
    1171    /* Force claim_file_handler to abandon this file.  */
    1172    obj->found = 0;
    1173    free (secdatastart);
    1174    return 0;
    1175  }
    1176  
    1177  
    1178  /* Find an offload section of an object file.  */
    1179  
    1180  static int
    1181  process_offload_section (void *data, const char *name, off_t offset, off_t len)
    1182  {
    1183    if (startswith (name, ".gnu.offload_lto_.opts"))
    1184      {
    1185        struct plugin_objfile *obj = (struct plugin_objfile *) data;
    1186        obj->offload = true;
    1187        return 0;
    1188      }
    1189  
    1190    return 1;
    1191  }
    1192  
    1193  /* Callback used by a linker to check if the plugin will claim FILE. Writes
    1194     the result in CLAIMED. */
    1195  
    1196  static enum ld_plugin_status
    1197  claim_file_handler (const struct ld_plugin_input_file *file, int *claimed)
    1198  {
    1199    enum ld_plugin_status status;
    1200    struct plugin_objfile obj;
    1201    struct plugin_file_info lto_file;
    1202    int err;
    1203    const char *errmsg;
    1204  
    1205    memset (&lto_file, 0, sizeof (struct plugin_file_info));
    1206  
    1207    if (file->offset != 0)
    1208      {
    1209        /* We pass the offset of the actual file, not the archive header.
    1210           Can't use PRIx64, because that's C99, so we have to print the
    1211  	 64-bit hex int as two 32-bit ones.  Use xasprintf instead of
    1212  	 asprintf because asprintf doesn't work as expected on some older
    1213  	 mingw32 hosts.  */
    1214        int lo, hi;
    1215        lo = file->offset & 0xffffffff;
    1216        hi = ((int64_t)file->offset >> 32) & 0xffffffff;
    1217        lto_file.name = hi ? xasprintf ("%s@0x%x%08x", file->name, hi, lo)
    1218        			 : xasprintf ("%s@0x%x", file->name, lo);
    1219      }
    1220    else
    1221      {
    1222        lto_file.name = xstrdup (file->name);
    1223      }
    1224    lto_file.handle = file->handle;
    1225  
    1226    *claimed = 0;
    1227    obj.file = file;
    1228    obj.found = 0;
    1229    obj.offload = false;
    1230    obj.out = &lto_file.symtab;
    1231    errmsg = NULL;
    1232    obj.objfile = simple_object_start_read (file->fd, file->offset, LTO_SEGMENT_NAME,
    1233  			&errmsg, &err);
    1234    /* No file, but also no error code means unrecognized format; just skip it.  */
    1235    if (!obj.objfile && !err)
    1236      goto err;
    1237  
    1238     if (obj.objfile)
    1239      {
    1240        errmsg = simple_object_find_sections (obj.objfile, process_symtab, &obj,
    1241  					    &err);
    1242        /*  Parsing symtab extension should be done only for add_symbols_v2 and
    1243  	  later versions.  */
    1244        if (!errmsg && add_symbols_v2 != NULL)
    1245  	{
    1246  	  obj.out->last_sym = 0;
    1247  	  errmsg = simple_object_find_sections (obj.objfile,
    1248  						process_symtab_extension,
    1249  						&obj, &err);
    1250  	}
    1251      }
    1252  
    1253    if (!obj.objfile || errmsg)
    1254      {
    1255        if (err && message)
    1256  	message (LDPL_FATAL, "%s: %s: %s", file->name, errmsg,
    1257  		xstrerror (err));
    1258        else if (message)
    1259  	message (LDPL_FATAL, "%s: %s", file->name, errmsg);
    1260        goto err;
    1261      }
    1262  
    1263    if (obj.objfile)
    1264      simple_object_find_sections (obj.objfile, process_offload_section,
    1265  				 &obj, &err);
    1266  
    1267    if (obj.found == 0 && !obj.offload)
    1268      goto err;
    1269  
    1270    if (obj.found > 1)
    1271      resolve_conflicts (&lto_file.symtab, &lto_file.conflicts);
    1272  
    1273    if (obj.found > 0)
    1274      {
    1275        if (add_symbols_v2)
    1276  	status = add_symbols_v2 (file->handle, lto_file.symtab.nsyms,
    1277  				 lto_file.symtab.syms);
    1278        else
    1279  	status = add_symbols (file->handle, lto_file.symtab.nsyms,
    1280  			      lto_file.symtab.syms);
    1281        check (status == LDPS_OK, LDPL_FATAL, "could not add symbols");
    1282  
    1283        LOCK_SECTION;
    1284        num_claimed_files++;
    1285        claimed_files =
    1286  	xrealloc (claimed_files,
    1287  		  num_claimed_files * sizeof (struct plugin_file_info));
    1288        claimed_files[num_claimed_files - 1] = lto_file;
    1289        UNLOCK_SECTION;
    1290  
    1291        *claimed = 1;
    1292      }
    1293  
    1294    LOCK_SECTION;
    1295    if (offload_files == NULL)
    1296      {
    1297        /* Add dummy item to the start of the list.  */
    1298        offload_files = xmalloc (sizeof (struct plugin_offload_file));
    1299        offload_files->name = NULL;
    1300        offload_files->next = NULL;
    1301        offload_files_last = offload_files;
    1302      }
    1303  
    1304    /* If this is an LTO file without offload, and it is the first LTO file, save
    1305       the pointer to the last offload file in the list.  Further offload LTO
    1306       files will be inserted after it, if any.  */
    1307    if (*claimed && !obj.offload && offload_files_last_lto == NULL)
    1308      offload_files_last_lto = offload_files_last;
    1309  
    1310    if (obj.offload)
    1311      {
    1312        /* Add file to the list.  The order must be exactly the same as the final
    1313  	 order after recompilation and linking, otherwise host and target tables
    1314  	 with addresses wouldn't match.  If a static library contains both LTO
    1315  	 and non-LTO objects, ld and gold link them in a different order.  */
    1316        struct plugin_offload_file *ofld
    1317  	= xmalloc (sizeof (struct plugin_offload_file));
    1318        ofld->name = lto_file.name;
    1319        ofld->next = NULL;
    1320  
    1321        if (*claimed && offload_files_last_lto == NULL && file->offset != 0
    1322  	  && gold_version == -1)
    1323  	{
    1324  	  /* ld only: insert first LTO file from the archive after the last real
    1325  	     object file immediately preceding the archive, or at the begin of
    1326  	     the list if there was no real objects before archives.  */
    1327  	  if (offload_files_last_obj != NULL)
    1328  	    {
    1329  	      ofld->next = offload_files_last_obj->next;
    1330  	      offload_files_last_obj->next = ofld;
    1331  	    }
    1332  	  else
    1333  	    {
    1334  	      ofld->next = offload_files->next;
    1335  	      offload_files->next = ofld;
    1336  	    }
    1337  	}
    1338        else if (*claimed && offload_files_last_lto != NULL)
    1339  	{
    1340  	  /* Insert LTO file after the last LTO file in the list.  */
    1341  	  ofld->next = offload_files_last_lto->next;
    1342  	  offload_files_last_lto->next = ofld;
    1343  	}
    1344        else
    1345  	/* Add non-LTO file or first non-archive LTO file to the end of the
    1346  	   list.  */
    1347  	offload_files_last->next = ofld;
    1348  
    1349        if (ofld->next == NULL)
    1350  	offload_files_last = ofld;
    1351        if (file->offset == 0)
    1352  	offload_files_last_obj = ofld;
    1353        if (*claimed)
    1354  	offload_files_last_lto = ofld;
    1355        num_offload_files++;
    1356      }
    1357  
    1358    UNLOCK_SECTION;
    1359  
    1360    goto cleanup;
    1361  
    1362   err:
    1363    LOCK_SECTION;
    1364    non_claimed_files++;
    1365    UNLOCK_SECTION;
    1366    free (lto_file.name);
    1367  
    1368   cleanup:
    1369    if (obj.objfile)
    1370      simple_object_release_read (obj.objfile);
    1371  
    1372    return LDPS_OK;
    1373  }
    1374  
    1375  /* Parse the plugin options. */
    1376  
    1377  static void
    1378  process_option (const char *option)
    1379  {
    1380    if (strcmp (option, "-linker-output-known") == 0)
    1381      linker_output_known = true;
    1382    /* Also accept "notlo" for backwards compatibility.  */
    1383    else if ((strcmp (option, "-linker-output-auto-nolto-rel") == 0)
    1384             || (strcmp (option, "-linker-output-auto-notlo-rel") == 0))
    1385      linker_output_auto_nolto_rel = true;
    1386    else if (strcmp (option, "-debug") == 0)
    1387      debug = true;
    1388    else if ((strcmp (option, "-v") == 0)
    1389             || (strcmp (option, "--verbose") == 0))
    1390      verbose = true;
    1391    else if (strcmp (option, "-save-temps") == 0)
    1392      save_temps = true;
    1393    else if (strcmp (option, "-nop") == 0)
    1394      nop = 1;
    1395    else if (startswith (option, "-pass-through="))
    1396      {
    1397        num_pass_through_items++;
    1398        pass_through_items = xrealloc (pass_through_items,
    1399  				     num_pass_through_items * sizeof (char *));
    1400        pass_through_items[num_pass_through_items - 1] =
    1401            xstrdup (option + strlen ("-pass-through="));
    1402      }
    1403    else if (startswith (option, "-sym-style="))
    1404      {
    1405        switch (option[sizeof ("-sym-style=") - 1])
    1406  	{
    1407  	case 'w':
    1408  	  sym_style = ss_win32;
    1409  	  break;
    1410  	case 'u':
    1411  	  sym_style = ss_uscore;
    1412  	  break;
    1413  	default:
    1414  	  sym_style = ss_none;
    1415  	  break;
    1416  	}
    1417      }
    1418    else if (startswith (option, "-ltrans-objects="))
    1419      ltrans_objects = xstrdup (option + strlen ("-ltrans-objects="));
    1420    else
    1421      {
    1422        int size;
    1423        char *opt = xstrdup (option);
    1424        lto_wrapper_num_args += 1;
    1425        size = lto_wrapper_num_args * sizeof (char *);
    1426        lto_wrapper_argv = (char **) xrealloc (lto_wrapper_argv, size);
    1427        lto_wrapper_argv[lto_wrapper_num_args - 1] = opt;
    1428        if (startswith (option, "-fresolution="))
    1429  	resolution_file = opt + sizeof ("-fresolution=") - 1;
    1430      }
    1431    save_temps = save_temps || debug;
    1432    verbose = verbose || debug;
    1433  }
    1434  
    1435  /* Negotiate linker API version.  */
    1436  
    1437  static void
    1438  negotiate_api_version (void)
    1439  {
    1440    const char *linker_identifier;
    1441    const char *linker_version;
    1442  
    1443    enum linker_api_version supported_api = LAPI_V0;
    1444  #if HAVE_PTHREAD_LOCKING
    1445    supported_api = LAPI_V1;
    1446  #endif
    1447  
    1448    api_version = get_api_version ("GCC", BASE_VERSION, LAPI_V0,
    1449  				 supported_api, &linker_identifier, &linker_version);
    1450    if (api_version > supported_api)
    1451      {
    1452        fprintf (stderr, "requested an unsupported API version (%d)\n", api_version);
    1453        abort ();
    1454      }
    1455  
    1456    switch (api_version)
    1457      {
    1458      case LAPI_V0:
    1459        break;
    1460      case LAPI_V1:
    1461        check (get_symbols_v3, LDPL_FATAL,
    1462  	     "get_symbols_v3 required for API version 1");
    1463        check (add_symbols_v2, LDPL_FATAL,
    1464  	     "add_symbols_v2 required for API version 1");
    1465        break;
    1466      default:
    1467        fprintf (stderr, "unsupported API version (%d)\n", api_version);
    1468        abort ();
    1469      }
    1470  }
    1471  
    1472  /* Called by a linker after loading the plugin. TV is the transfer vector. */
    1473  
    1474  enum ld_plugin_status
    1475  onload (struct ld_plugin_tv *tv)
    1476  {
    1477    struct ld_plugin_tv *p;
    1478    enum ld_plugin_status status;
    1479  
    1480  #if HAVE_PTHREAD_LOCKING
    1481    if (pthread_mutex_init (&plugin_lock, NULL) != 0)
    1482      {
    1483        fprintf (stderr, "mutex init failed\n");
    1484        abort ();
    1485      }
    1486  #endif
    1487  
    1488    p = tv;
    1489    while (p->tv_tag)
    1490      {
    1491        switch (p->tv_tag)
    1492  	{
    1493          case LDPT_MESSAGE:
    1494            message = p->tv_u.tv_message;
    1495            break;
    1496  	case LDPT_REGISTER_CLAIM_FILE_HOOK:
    1497  	  register_claim_file = p->tv_u.tv_register_claim_file;
    1498  	  break;
    1499  	case LDPT_ADD_SYMBOLS_V2:
    1500  	  add_symbols_v2 = p->tv_u.tv_add_symbols;
    1501  	  break;
    1502  	case LDPT_ADD_SYMBOLS:
    1503  	  add_symbols = p->tv_u.tv_add_symbols;
    1504  	  break;
    1505  	case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK:
    1506  	  register_all_symbols_read = p->tv_u.tv_register_all_symbols_read;
    1507  	  break;
    1508  	case LDPT_GET_SYMBOLS_V3:
    1509  	  get_symbols_v3 = p->tv_u.tv_get_symbols;
    1510  	  break;
    1511  	case LDPT_GET_SYMBOLS_V2:
    1512  	  get_symbols_v2 = p->tv_u.tv_get_symbols;
    1513  	  break;
    1514  	case LDPT_GET_SYMBOLS:
    1515  	  get_symbols = p->tv_u.tv_get_symbols;
    1516  	  break;
    1517  	case LDPT_REGISTER_CLEANUP_HOOK:
    1518  	  register_cleanup = p->tv_u.tv_register_cleanup;
    1519  	  break;
    1520  	case LDPT_ADD_INPUT_FILE:
    1521  	  add_input_file = p->tv_u.tv_add_input_file;
    1522  	  break;
    1523  	case LDPT_ADD_INPUT_LIBRARY:
    1524  	  add_input_library = p->tv_u.tv_add_input_library;
    1525  	  break;
    1526  	case LDPT_OPTION:
    1527  	  process_option (p->tv_u.tv_string);
    1528  	  break;
    1529  	case LDPT_GOLD_VERSION:
    1530  	  gold_version = p->tv_u.tv_val;
    1531  	  break;
    1532  	case LDPT_LINKER_OUTPUT:
    1533  	  linker_output = (enum ld_plugin_output_file_type) p->tv_u.tv_val;
    1534  	  linker_output_set = true;
    1535  	  break;
    1536  	case LDPT_OUTPUT_NAME:
    1537  	  /* We only use this to make user-friendly temp file names.  */
    1538  	  link_output_name = p->tv_u.tv_string;
    1539  	  break;
    1540  	case LDPT_GET_API_VERSION:
    1541  	  get_api_version = p->tv_u.tv_get_api_version;
    1542  	  break;
    1543  	default:
    1544  	  break;
    1545  	}
    1546        p++;
    1547      }
    1548  
    1549    if (get_api_version)
    1550      negotiate_api_version ();
    1551  
    1552    check (register_claim_file, LDPL_FATAL, "register_claim_file not found");
    1553    check (add_symbols, LDPL_FATAL, "add_symbols not found");
    1554    status = register_claim_file (claim_file_handler);
    1555    check (status == LDPS_OK, LDPL_FATAL,
    1556  	 "could not register the claim_file callback");
    1557  
    1558    if (register_cleanup)
    1559      {
    1560        status = register_cleanup (cleanup_handler);
    1561        check (status == LDPS_OK, LDPL_FATAL,
    1562  	     "could not register the cleanup callback");
    1563      }
    1564  
    1565    if (register_all_symbols_read)
    1566      {
    1567        check (get_symbols, LDPL_FATAL, "get_symbols not found");
    1568        status = register_all_symbols_read (all_symbols_read_handler);
    1569        check (status == LDPS_OK, LDPL_FATAL,
    1570  	     "could not register the all_symbols_read callback");
    1571      }
    1572  
    1573    char *collect_gcc_options = getenv ("COLLECT_GCC_OPTIONS");
    1574    if (collect_gcc_options)
    1575      {
    1576        /* Support -fno-use-linker-plugin by failing to load the plugin
    1577  	 for the case where it is auto-loaded by BFD.  */
    1578        if (strstr (collect_gcc_options, "'-fno-use-linker-plugin'"))
    1579  	return LDPS_ERR;
    1580  
    1581        if (strstr (collect_gcc_options, "'-save-temps'"))
    1582  	save_temps = true;
    1583  
    1584        if (strstr (collect_gcc_options, "'-v'")
    1585            || strstr (collect_gcc_options, "'--verbose'"))
    1586  	verbose = true;
    1587  
    1588        const char *p;
    1589        if ((p = strstr (collect_gcc_options, "'-dumpdir'")))
    1590  	{
    1591  	  p += sizeof ("'-dumpdir'");
    1592  	  while (*p == ' ')
    1593  	    p++;
    1594  	  const char *start = p;
    1595  	  int ticks = 0, escapes = 0;
    1596  	  /* Count ticks (') and escaped (\.) characters.  Stop at the
    1597  	     end of the options or at a blank after an even number of
    1598  	     ticks (not counting escaped ones.  */
    1599  	  for (p = start; *p; p++)
    1600  	    {
    1601  	      if (*p == '\'')
    1602  		{
    1603  		  ticks++;
    1604  		  continue;
    1605  		}
    1606  	      else if ((ticks % 2) != 0)
    1607  		{
    1608  		  if (*p == ' ')
    1609  		    break;
    1610  		  if (*p == '\\')
    1611  		    {
    1612  		      if (*++p)
    1613  			escapes++;
    1614  		      else
    1615  			p--;
    1616  		    }
    1617  		}
    1618  	    }
    1619  
    1620  	  /* Now allocate a new link_output_name and decode dumpdir
    1621  	     into it.  The loop uses the same logic, except it counts
    1622  	     ticks and escapes backwards (so ticks is adjusted if we
    1623  	     find an odd number of them), and it copies characters
    1624  	     that are escaped or not otherwise skipped.  */
    1625  	  int len = p - start - ticks - escapes + 1;
    1626  	  char *q = xmalloc (len);
    1627  	  link_output_name = q;
    1628  	  int oddticks = (ticks % 2);
    1629  	  ticks += oddticks;
    1630  	  for (p = start; *p; p++)
    1631  	    {
    1632  	      if (*p == '\'')
    1633  		{
    1634  		  ticks--;
    1635  		  continue;
    1636  		}
    1637  	      else if ((ticks % 2) != 0)
    1638  		{
    1639  		  if (*p == ' ')
    1640  		    break;
    1641  		  if (*p == '\\')
    1642  		    {
    1643  		      if (*++p)
    1644  			escapes--;
    1645  		      else
    1646  			p--;
    1647  		    }
    1648  		}
    1649  	      *q++ = *p;
    1650  	    }
    1651  	  *q = '\0';
    1652  	  assert (escapes == 0);
    1653  	  assert (ticks == oddticks);
    1654  	  assert (q - link_output_name == len - 1);
    1655  	  skip_in_suffix = true;
    1656  	}
    1657      }
    1658  
    1659    return LDPS_OK;
    1660  }