1/* LTO plugin for gold and/or GNU ld.
2   Copyright (C) 2009, 2010 Free Software Foundation, Inc.
3   Contributed by Rafael Avila de Espindola (espindola@google.com).
4
5This program is free software; you can redistribute it and/or modify
6it under the terms of the GNU General Public License as published by
7the Free Software Foundation; either version 3, or (at your option)
8any later version.
9
10This program is distributed in the hope that it will be useful, but
11WITHOUT ANY WARRANTY; without even the implied warranty of
12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13General Public License for more details.
14
15You should have received a copy of the GNU General Public License
16along 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. Gold passes it an array of
20   function that the plugin uses to communicate back to gold.
21
22   With the functions provided by gold, the plugin can be notified when
23   gold first analyzes a file and pass a symbol table back to gold. 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 2 options of its 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
35#ifdef HAVE_CONFIG_H
36#include "config.h"
37#endif
38#if HAVE_STDINT_H
39#include <stdint.h>
40#endif
41#include <assert.h>
42#include <errno.h>
43#include <string.h>
44#include <stdlib.h>
45#include <stdio.h>
46#include <inttypes.h>
47#include <sys/stat.h>
48#include <unistd.h>
49#include <fcntl.h>
50#include <sys/types.h>
51#ifdef HAVE_SYS_WAIT_H
52#include <sys/wait.h>
53#endif
54#ifndef WIFEXITED
55#define WIFEXITED(S) (((S) & 0xff) == 0)
56#endif
57#ifndef WEXITSTATUS
58#define WEXITSTATUS(S) (((S) & 0xff00) >> 8)
59#endif
60#include <libiberty.h>
61#include <hashtab.h>
62#include "../gcc/lto/common.h"
63#include "simple-object.h"
64#include "plugin-api.h"
65
66/* We need to use I64 instead of ll width-specifier on native Windows.
67   The reason for this is that older MS-runtimes don't support the ll.  */
68#ifdef __MINGW32__
69#define PRI_LL "I64"
70#else
71#define PRI_LL "ll"
72#endif
73
74/* Handle opening elf files on hosts, such as Windows, that may use
75   text file handling that will break binary access.  */
76#ifndef O_BINARY
77# define O_BINARY 0
78#endif
79
80/* Segment name for LTO sections.  This is only used for Mach-O.
81   FIXME: This needs to be kept in sync with darwin.c.  */
82
83#define LTO_SEGMENT_NAME "__GNU_LTO"
84
85/* LTO magic section name.  */
86
87#define LTO_SECTION_PREFIX	".gnu.lto_.symtab"
88#define LTO_SECTION_PREFIX_LEN	(sizeof (LTO_SECTION_PREFIX) - 1)
89#define OFFLOAD_SECTION		".gnu.offload_lto_.opts"
90#define OFFLOAD_SECTION_LEN	(sizeof (OFFLOAD_SECTION) - 1)
91
92/* The part of the symbol table the plugin has to keep track of. Note that we
93   must keep SYMS until all_symbols_read is called to give the linker time to
94   copy the symbol information.
95   The id must be 64bit to minimze collisions. */
96
97struct sym_aux
98{
99  uint32_t slot;
100  unsigned long long id;
101  unsigned next_conflict;
102};
103
104struct plugin_symtab
105{
106  int nsyms;
107  struct sym_aux *aux;
108  struct ld_plugin_symbol *syms;
109  unsigned long long id;
110};
111
112/* Encapsulates object file data during symbol scan.  */
113struct plugin_objfile
114{
115  int found;
116  int offload;
117  simple_object_read *objfile;
118  struct plugin_symtab *out;
119  const struct ld_plugin_input_file *file;
120};
121
122/* All that we have to remember about a file. */
123
124struct plugin_file_info
125{
126  char *name;
127  void *handle;
128  struct plugin_symtab symtab;
129  struct plugin_symtab conflicts;
130};
131
132/* Until ASM_OUTPUT_LABELREF can be hookized and decoupled from
133   stdio file streams, we do simple label translation here.  */
134
135enum symbol_style
136{
137  ss_none,	/* No underscore prefix. */
138  ss_win32,	/* Underscore prefix any symbol not beginning with '@'.  */
139  ss_uscore,	/* Underscore prefix all symbols.  */
140};
141
142static char *arguments_file_name;
143static ld_plugin_register_claim_file register_claim_file;
144static ld_plugin_register_all_symbols_read register_all_symbols_read;
145static ld_plugin_get_symbols get_symbols, get_symbols_v2;
146static ld_plugin_register_cleanup register_cleanup;
147static ld_plugin_add_input_file add_input_file;
148static ld_plugin_add_input_library add_input_library;
149static ld_plugin_message message;
150static ld_plugin_add_symbols add_symbols;
151
152static struct plugin_file_info *claimed_files = NULL;
153static unsigned int num_claimed_files = 0;
154
155static struct plugin_file_info *offload_files = NULL;
156static unsigned int num_offload_files = 0;
157
158static char **output_files = NULL;
159static unsigned int num_output_files = 0;
160
161static char **lto_wrapper_argv;
162static int lto_wrapper_num_args;
163
164static char **pass_through_items = NULL;
165static unsigned int num_pass_through_items;
166
167static char debug;
168static char nop;
169static char *resolution_file = NULL;
170
171/* The version of gold being used, or -1 if not gold.  The number is
172   MAJOR * 100 + MINOR.  */
173static int gold_version = -1;
174
175/* Not used by default, but can be overridden at runtime
176   by using -plugin-opt=-sym-style={none,win32,underscore|uscore}
177   (in fact, only first letter of style arg is checked.)  */
178static enum symbol_style sym_style = ss_none;
179
180static void
181check_1 (int gate, enum ld_plugin_level level, const char *text)
182{
183  if (gate)
184    return;
185
186  if (message)
187    message (level, text);
188  else
189    {
190      /* If there is no nicer way to inform the user, fallback to stderr. */
191      fprintf (stderr, "%s\n", text);
192      if (level == LDPL_FATAL)
193	abort ();
194    }
195}
196
197/* This little wrapper allows check to be called with a non-integer
198   first argument, such as a pointer that must be non-NULL.  We can't
199   use c99 bool type to coerce it into range, so we explicitly test.  */
200#define check(GATE, LEVEL, TEXT) check_1 (((GATE) != 0), (LEVEL), (TEXT))
201
202/* Parse an entry of the IL symbol table. The data to be parsed is pointed
203   by P and the result is written in ENTRY. The slot number is stored in SLOT.
204   Returns the address of the next entry. */
205
206static char *
207parse_table_entry (char *p, struct ld_plugin_symbol *entry,
208		   struct sym_aux *aux)
209{
210  unsigned char t;
211  enum ld_plugin_symbol_kind translate_kind[] =
212    {
213      LDPK_DEF,
214      LDPK_WEAKDEF,
215      LDPK_UNDEF,
216      LDPK_WEAKUNDEF,
217      LDPK_COMMON
218    };
219
220  enum ld_plugin_symbol_visibility translate_visibility[] =
221    {
222      LDPV_DEFAULT,
223      LDPV_PROTECTED,
224      LDPV_INTERNAL,
225      LDPV_HIDDEN
226    };
227
228  switch (sym_style)
229    {
230    case ss_win32:
231      if (p[0] == '@')
232	{
233    /* cf. Duff's device.  */
234    case ss_none:
235	  entry->name = xstrdup (p);
236	  break;
237	}
238    /* FALL-THROUGH.  */
239    case ss_uscore:
240      entry->name = concat ("_", p, NULL);
241      break;
242    default:
243      check (0, LDPL_FATAL, "invalid symbol style requested");
244      break;
245    }
246  while (*p)
247    p++;
248  p++;
249
250  entry->version = NULL;
251
252  entry->comdat_key = p;
253  while (*p)
254    p++;
255  p++;
256
257  if (strlen (entry->comdat_key) == 0)
258    entry->comdat_key = NULL;
259  else
260    entry->comdat_key = xstrdup (entry->comdat_key);
261
262  t = *p;
263  check (t <= 4, LDPL_FATAL, "invalid symbol kind found");
264  entry->def = translate_kind[t];
265  p++;
266
267  t = *p;
268  check (t <= 3, LDPL_FATAL, "invalid symbol visibility found");
269  entry->visibility = translate_visibility[t];
270  p++;
271
272  memcpy (&entry->size, p, sizeof (uint64_t));
273  p += 8;
274
275  memcpy (&aux->slot, p, sizeof (uint32_t));
276  p += 4;
277
278  entry->resolution = LDPR_UNKNOWN;
279
280  aux->next_conflict = -1;
281
282  return p;
283}
284
285/* Translate the IL symbol table located between DATA and END. Append the
286   slots and symbols to OUT. */
287
288static void
289translate (char *data, char *end, struct plugin_symtab *out)
290{
291  struct sym_aux *aux;
292  struct ld_plugin_symbol *syms = NULL;
293  int n, len;
294
295  /* This overestimates the output buffer sizes, but at least
296     the algorithm is O(1) now. */
297
298  len = (end - data)/8 + out->nsyms + 1;
299  syms = xrealloc (out->syms, len * sizeof (struct ld_plugin_symbol));
300  aux = xrealloc (out->aux, len * sizeof (struct sym_aux));
301
302  for (n = out->nsyms; data < end; n++)
303    {
304      aux[n].id = out->id;
305      data = parse_table_entry (data, &syms[n], &aux[n]);
306    }
307
308  assert(n < len);
309
310  out->nsyms = n;
311  out->syms = syms;
312  out->aux = aux;
313}
314
315/* Free all memory that is no longer needed after writing the symbol
316   resolution. */
317
318static void
319free_1 (struct plugin_file_info *files, unsigned num_files)
320{
321  unsigned int i;
322  for (i = 0; i < num_files; i++)
323    {
324      struct plugin_file_info *info = &files[i];
325      struct plugin_symtab *symtab = &info->symtab;
326      unsigned int j;
327      for (j = 0; j < symtab->nsyms; j++)
328	{
329	  struct ld_plugin_symbol *s = &symtab->syms[j];
330	  free (s->name);
331	  free (s->comdat_key);
332	}
333      free (symtab->syms);
334      symtab->syms = NULL;
335    }
336}
337
338/* Free all remaining memory. */
339
340static void
341free_2 (void)
342{
343  unsigned int i;
344  for (i = 0; i < num_claimed_files; i++)
345    {
346      struct plugin_file_info *info = &claimed_files[i];
347      struct plugin_symtab *symtab = &info->symtab;
348      free (symtab->aux);
349      free (info->name);
350    }
351
352  for (i = 0; i < num_offload_files; i++)
353    {
354      struct plugin_file_info *info = &offload_files[i];
355      struct plugin_symtab *symtab = &info->symtab;
356      free (symtab->aux);
357      free (info->name);
358    }
359
360  for (i = 0; i < num_output_files; i++)
361    free (output_files[i]);
362  free (output_files);
363
364  free (claimed_files);
365  claimed_files = NULL;
366  num_claimed_files = 0;
367
368  free (offload_files);
369  offload_files = NULL;
370  num_offload_files = 0;
371
372  free (arguments_file_name);
373  arguments_file_name = NULL;
374}
375
376/* Dump SYMTAB to resolution file F. */
377
378static void
379dump_symtab (FILE *f, struct plugin_symtab *symtab)
380{
381  unsigned j;
382
383  for (j = 0; j < symtab->nsyms; j++)
384    {
385      uint32_t slot = symtab->aux[j].slot;
386      unsigned int resolution = symtab->syms[j].resolution;
387
388      assert (resolution != LDPR_UNKNOWN);
389
390      fprintf (f, "%u %" PRI_LL "x %s %s\n",
391               (unsigned int) slot, symtab->aux[j].id,
392	       lto_resolution_str[resolution],
393	       symtab->syms[j].name);
394    }
395}
396
397/* Finish the conflicts' resolution information after the linker resolved
398   the original symbols */
399
400static void
401finish_conflict_resolution (struct plugin_symtab *symtab,
402			   struct plugin_symtab *conflicts)
403{
404  int i, j;
405
406  if (conflicts->nsyms == 0)
407    return;
408
409  for (i = 0; i < symtab->nsyms; i++)
410    {
411      int resolution = LDPR_UNKNOWN;
412
413      if (symtab->aux[i].next_conflict == -1)
414	continue;
415
416      switch (symtab->syms[i].def)
417	{
418	case LDPK_DEF:
419	case LDPK_COMMON: /* ??? */
420	  resolution = LDPR_RESOLVED_IR;
421	  break;
422	case LDPK_WEAKDEF:
423	  resolution = LDPR_PREEMPTED_IR;
424	  break;
425	case LDPK_UNDEF:
426	case LDPK_WEAKUNDEF:
427	  resolution = symtab->syms[i].resolution;
428	  break;
429	default:
430	  assert (0);
431	}
432
433      assert (resolution != LDPR_UNKNOWN);
434
435      for (j = symtab->aux[i].next_conflict;
436	   j != -1;
437	   j = conflicts->aux[j].next_conflict)
438	conflicts->syms[j].resolution = resolution;
439    }
440}
441
442/* Free symbol table SYMTAB. */
443
444static void
445free_symtab (struct plugin_symtab *symtab)
446{
447  free (symtab->syms);
448  symtab->syms = NULL;
449  free (symtab->aux);
450  symtab->aux = NULL;
451}
452
453/*  Writes the relocations to disk. */
454
455static void
456write_resolution (void)
457{
458  unsigned int i;
459  FILE *f;
460
461  check (resolution_file, LDPL_FATAL, "resolution file not specified");
462  f = fopen (resolution_file, "w");
463  check (f, LDPL_FATAL, "could not open file");
464
465  fprintf (f, "%d\n", num_claimed_files);
466
467  for (i = 0; i < num_claimed_files; i++)
468    {
469      struct plugin_file_info *info = &claimed_files[i];
470      struct plugin_symtab *symtab = &info->symtab;
471      struct ld_plugin_symbol *syms = symtab->syms;
472
473      /* Version 2 of API supports IRONLY_EXP resolution that is
474         accepted by GCC-4.7 and newer.  */
475      if (get_symbols_v2)
476        get_symbols_v2 (info->handle, symtab->nsyms, syms);
477      else
478        get_symbols (info->handle, symtab->nsyms, syms);
479
480      finish_conflict_resolution (symtab, &info->conflicts);
481
482      fprintf (f, "%s %d\n", info->name, symtab->nsyms + info->conflicts.nsyms);
483      dump_symtab (f, symtab);
484      if (info->conflicts.nsyms)
485	{
486	  dump_symtab (f, &info->conflicts);
487	  free_symtab (&info->conflicts);
488	}
489    }
490  fclose (f);
491}
492
493/* Pass files generated by the lto-wrapper to the linker. FD is lto-wrapper's
494   stdout. */
495
496static void
497add_output_files (FILE *f)
498{
499  for (;;)
500    {
501      const unsigned piece = 32;
502      char *buf, *s = xmalloc (piece);
503      size_t len;
504
505      buf = s;
506cont:
507      if (!fgets (buf, piece, f))
508	{
509	  free (s);
510	  break;
511	}
512      len = strlen (s);
513      if (s[len - 1] != '\n')
514	{
515	  s = xrealloc (s, len + piece);
516	  buf = s + len;
517	  goto cont;
518	}
519      s[len - 1] = '\0';
520
521      num_output_files++;
522      output_files
523	= xrealloc (output_files, num_output_files * sizeof (char *));
524      output_files[num_output_files - 1] = s;
525      add_input_file (output_files[num_output_files - 1]);
526    }
527}
528
529/* Execute the lto-wrapper. ARGV[0] is the binary. The rest of ARGV is the
530   argument list. */
531
532static void
533exec_lto_wrapper (char *argv[])
534{
535  int t, i;
536  int status;
537  char *at_args;
538  FILE *args;
539  FILE *wrapper_output;
540  char *new_argv[3];
541  struct pex_obj *pex;
542  const char *errmsg;
543
544  /* Write argv to a file to avoid a command line that is too long. */
545  arguments_file_name = make_temp_file ("");
546  check (arguments_file_name, LDPL_FATAL,
547         "Failed to generate a temorary file name");
548
549  args = fopen (arguments_file_name, "w");
550  check (args, LDPL_FATAL, "could not open arguments file");
551
552  t = writeargv (&argv[1], args);
553  check (t == 0, LDPL_FATAL, "could not write arguments");
554  t = fclose (args);
555  check (t == 0, LDPL_FATAL, "could not close arguments file");
556
557  at_args = concat ("@", arguments_file_name, NULL);
558  check (at_args, LDPL_FATAL, "could not allocate");
559
560  for (i = 1; argv[i]; i++)
561    {
562      char *a = argv[i];
563      if (a[0] == '-' && a[1] == 'v' && a[2] == '\0')
564	{
565	  for (i = 0; argv[i]; i++)
566	    fprintf (stderr, "%s ", argv[i]);
567	  fprintf (stderr, "\n");
568	  break;
569	}
570    }
571
572  new_argv[0] = argv[0];
573  new_argv[1] = at_args;
574  new_argv[2] = NULL;
575
576  if (debug)
577    {
578      for (i = 0; new_argv[i]; i++)
579	fprintf (stderr, "%s ", new_argv[i]);
580      fprintf (stderr, "\n");
581    }
582
583
584  pex = pex_init (PEX_USE_PIPES, "lto-wrapper", NULL);
585  check (pex != NULL, LDPL_FATAL, "could not pex_init lto-wrapper");
586
587  errmsg = pex_run (pex, 0, new_argv[0], new_argv, NULL, NULL, &t);
588  check (errmsg == NULL, LDPL_FATAL, "could not run lto-wrapper");
589  check (t == 0, LDPL_FATAL, "could not run lto-wrapper");
590
591  wrapper_output = pex_read_output (pex, 0);
592  check (wrapper_output, LDPL_FATAL, "could not read lto-wrapper output");
593
594  add_output_files (wrapper_output);
595
596  t = pex_get_status (pex, 1, &status);
597  check (t == 1, LDPL_FATAL, "could not get lto-wrapper exit status");
598  check (WIFEXITED (status) && WEXITSTATUS (status) == 0, LDPL_FATAL,
599         "lto-wrapper failed");
600
601  pex_free (pex);
602
603  free (at_args);
604}
605
606/* Pass the original files back to the linker. */
607
608static void
609use_original_files (void)
610{
611  unsigned i;
612  for (i = 0; i < num_claimed_files; i++)
613    {
614      struct plugin_file_info *info = &claimed_files[i];
615      add_input_file (info->name);
616    }
617}
618
619
620/* Called by the linker once all symbols have been read. */
621
622static enum ld_plugin_status
623all_symbols_read_handler (void)
624{
625  unsigned i;
626  unsigned num_lto_args
627    = num_claimed_files + num_offload_files + lto_wrapper_num_args + 1;
628  char **lto_argv;
629  const char **lto_arg_ptr;
630  if (num_claimed_files + num_offload_files == 0)
631    return LDPS_OK;
632
633  if (nop)
634    {
635      use_original_files ();
636      return LDPS_OK;
637    }
638
639  lto_argv = (char **) xcalloc (sizeof (char *), num_lto_args);
640  lto_arg_ptr = (const char **) lto_argv;
641  assert (lto_wrapper_argv);
642
643  write_resolution ();
644
645  free_1 (claimed_files, num_claimed_files);
646  free_1 (offload_files, num_offload_files);
647
648  for (i = 0; i < lto_wrapper_num_args; i++)
649    *lto_arg_ptr++ = lto_wrapper_argv[i];
650
651  for (i = 0; i < num_claimed_files; i++)
652    {
653      struct plugin_file_info *info = &claimed_files[i];
654
655      *lto_arg_ptr++ = info->name;
656    }
657
658  for (i = 0; i < num_offload_files; i++)
659    {
660      struct plugin_file_info *info = &offload_files[i];
661
662      *lto_arg_ptr++ = info->name;
663    }
664
665  *lto_arg_ptr++ = NULL;
666  exec_lto_wrapper (lto_argv);
667
668  free (lto_argv);
669
670  /* --pass-through is not needed when using gold 1.11 or later.  */
671  if (pass_through_items && gold_version < 111)
672    {
673      unsigned int i;
674      for (i = 0; i < num_pass_through_items; i++)
675        {
676          if (strncmp (pass_through_items[i], "-l", 2) == 0)
677            add_input_library (pass_through_items[i] + 2);
678          else
679            add_input_file (pass_through_items[i]);
680          free (pass_through_items[i]);
681          pass_through_items[i] = NULL;
682        }
683      free (pass_through_items);
684      pass_through_items = NULL;
685    }
686
687  return LDPS_OK;
688}
689
690/* Remove temporary files at the end of the link. */
691
692static enum ld_plugin_status
693cleanup_handler (void)
694{
695  unsigned int i;
696  int t;
697
698  if (debug)
699    return LDPS_OK;
700
701  if (arguments_file_name)
702    {
703      t = unlink (arguments_file_name);
704      check (t == 0, LDPL_FATAL, "could not unlink arguments file");
705    }
706
707  for (i = 0; i < num_output_files; i++)
708    {
709      t = unlink (output_files[i]);
710      check (t == 0, LDPL_FATAL, "could not unlink output file");
711    }
712
713  free_2 ();
714  return LDPS_OK;
715}
716
717#define SWAP(type, a, b) \
718  do { type tmp_; tmp_ = (a); (a) = (b); (b) = tmp_; } while(0)
719
720/* Compare two hash table entries */
721
722static int eq_sym (const void *a, const void *b)
723{
724  const struct ld_plugin_symbol *as = (const struct ld_plugin_symbol *)a;
725  const struct ld_plugin_symbol *bs = (const struct ld_plugin_symbol *)b;
726
727  return !strcmp (as->name, bs->name);
728}
729
730/* Hash a symbol */
731
732static hashval_t hash_sym (const void *a)
733{
734  const struct ld_plugin_symbol *as = (const struct ld_plugin_symbol *)a;
735
736  return htab_hash_string (as->name);
737}
738
739/* Determine how strong a symbol is */
740
741static int symbol_strength (struct ld_plugin_symbol *s)
742{
743  switch (s->def)
744    {
745    case LDPK_UNDEF:
746    case LDPK_WEAKUNDEF:
747      return 0;
748    case LDPK_WEAKDEF:
749      return 1;
750    default:
751      return 2;
752    }
753}
754
755/* In the ld -r case we can get dups in the LTO symbol tables, where
756   the same symbol can have different resolutions (e.g. undefined and defined).
757
758   We have to keep that in the LTO symbol tables, but the dups confuse
759   gold and then finally gcc by supplying incorrect resolutions.
760
761   Problem is that the main gold symbol table doesn't know about subids
762   and does not distingush the same symbols in different states.
763
764   So we drop duplicates from the linker visible symbol table
765   and keep them in a private table. Then later do own symbol
766   resolution for the duplicated based on the results for the
767   originals.
768
769   Then when writing out the resolution file readd the dropped symbols.
770
771   XXX how to handle common? */
772
773static void
774resolve_conflicts (struct plugin_symtab *t, struct plugin_symtab *conflicts)
775{
776  htab_t symtab = htab_create (t->nsyms, hash_sym, eq_sym, NULL);
777  int i;
778  int out;
779  int outlen;
780
781  outlen = t->nsyms;
782  conflicts->syms = xmalloc (sizeof (struct ld_plugin_symbol) * outlen);
783  conflicts->aux = xmalloc (sizeof (struct sym_aux) * outlen);
784
785  /* Move all duplicate symbols into the auxiliary conflicts table. */
786  out = 0;
787  for (i = 0; i < t->nsyms; i++)
788    {
789      struct ld_plugin_symbol *s = &t->syms[i];
790      struct sym_aux *aux = &t->aux[i];
791      void **slot;
792
793      slot = htab_find_slot (symtab, s, INSERT);
794      if (*slot != NULL)
795	{
796	  int cnf;
797	  struct ld_plugin_symbol *orig = (struct ld_plugin_symbol *)*slot;
798	  struct sym_aux *orig_aux = &t->aux[orig - t->syms];
799
800	  /* Always let the linker resolve the strongest symbol */
801	  if (symbol_strength (orig) < symbol_strength (s))
802	    {
803	      SWAP (struct ld_plugin_symbol, *orig, *s);
804	      SWAP (uint32_t, orig_aux->slot, aux->slot);
805	      SWAP (unsigned long long, orig_aux->id, aux->id);
806	      /* Don't swap conflict chain pointer */
807	    }
808
809	  /* Move current symbol into the conflicts table */
810	  cnf = conflicts->nsyms++;
811	  conflicts->syms[cnf] = *s;
812	  conflicts->aux[cnf] = *aux;
813	  aux = &conflicts->aux[cnf];
814
815	  /* Update conflicts chain of the original symbol */
816	  aux->next_conflict = orig_aux->next_conflict;
817	  orig_aux->next_conflict = cnf;
818
819	  continue;
820	}
821
822      /* Remove previous duplicates in the main table */
823      if (out < i)
824	{
825	  t->syms[out] = *s;
826	  t->aux[out] = *aux;
827	}
828
829      /* Put original into the hash table */
830      *slot = &t->syms[out];
831      out++;
832    }
833
834  assert (conflicts->nsyms <= outlen);
835  assert (conflicts->nsyms + out == t->nsyms);
836
837  t->nsyms = out;
838  htab_delete (symtab);
839}
840
841/* Process one section of an object file.  */
842
843static int
844process_symtab (void *data, const char *name, off_t offset, off_t length)
845{
846  struct plugin_objfile *obj = (struct plugin_objfile *)data;
847  char *s;
848  char *secdatastart, *secdata;
849
850  if (strncmp (name, LTO_SECTION_PREFIX, LTO_SECTION_PREFIX_LEN) != 0)
851    return 1;
852
853  s = strrchr (name, '.');
854  if (s)
855    sscanf (s, ".%" PRI_LL "x", &obj->out->id);
856  secdata = secdatastart = xmalloc (length);
857  offset += obj->file->offset;
858  if (offset != lseek (obj->file->fd, offset, SEEK_SET))
859    goto err;
860
861  do
862    {
863      ssize_t got = read (obj->file->fd, secdata, length);
864      if (got == 0)
865	break;
866      else if (got > 0)
867	{
868	  secdata += got;
869	  length -= got;
870	}
871      else if (errno != EINTR)
872	goto err;
873    }
874  while (length > 0);
875  if (length > 0)
876    goto err;
877
878  translate (secdatastart, secdata, obj->out);
879  obj->found++;
880  free (secdatastart);
881  return 1;
882
883err:
884  if (message)
885    message (LDPL_FATAL, "%s: corrupt object file", obj->file->name);
886  /* Force claim_file_handler to abandon this file.  */
887  obj->found = 0;
888  free (secdatastart);
889  return 0;
890}
891
892/* Find an offload section of an object file.  */
893
894static int
895process_offload_section (void *data, const char *name, off_t offset, off_t len)
896{
897  if (!strncmp (name, OFFLOAD_SECTION, OFFLOAD_SECTION_LEN))
898    {
899      struct plugin_objfile *obj = (struct plugin_objfile *) data;
900      obj->offload = 1;
901      return 0;
902    }
903
904  return 1;
905}
906
907/* Callback used by gold to check if the plugin will claim FILE. Writes
908   the result in CLAIMED. */
909
910static enum ld_plugin_status
911claim_file_handler (const struct ld_plugin_input_file *file, int *claimed)
912{
913  enum ld_plugin_status status;
914  struct plugin_objfile obj;
915  struct plugin_file_info lto_file;
916  int err;
917  const char *errmsg;
918
919  memset (&lto_file, 0, sizeof (struct plugin_file_info));
920
921  if (file->offset != 0)
922    {
923      char *objname;
924      /* We pass the offset of the actual file, not the archive header.
925         Can't use PRIx64, because that's C99, so we have to print the
926	 64-bit hex int as two 32-bit ones. */
927      int lo, hi, t;
928      lo = file->offset & 0xffffffff;
929      hi = ((int64_t)file->offset >> 32) & 0xffffffff;
930      t = hi ? asprintf (&objname, "%s@0x%x%08x", file->name, lo, hi)
931	     : asprintf (&objname, "%s@0x%x", file->name, lo);
932      check (t >= 0, LDPL_FATAL, "asprintf failed");
933      lto_file.name = objname;
934    }
935  else
936    {
937      lto_file.name = xstrdup (file->name);
938    }
939  lto_file.handle = file->handle;
940
941  *claimed = 0;
942  obj.file = file;
943  obj.found = 0;
944  obj.offload = 0;
945  obj.out = &lto_file.symtab;
946  errmsg = NULL;
947  obj.objfile = simple_object_start_read (file->fd, file->offset, LTO_SEGMENT_NAME,
948			&errmsg, &err);
949  /* No file, but also no error code means unrecognized format; just skip it.  */
950  if (!obj.objfile && !err)
951    goto err;
952
953  if (obj.objfile)
954    errmsg = simple_object_find_sections (obj.objfile, process_symtab, &obj, &err);
955
956  if (!obj.objfile || errmsg)
957    {
958      if (err && message)
959	message (LDPL_FATAL, "%s: %s: %s", file->name, errmsg,
960		xstrerror (err));
961      else if (message)
962	message (LDPL_FATAL, "%s: %s", file->name, errmsg);
963      goto err;
964    }
965
966  if (obj.objfile)
967    simple_object_find_sections (obj.objfile, process_offload_section,
968				 &obj, &err);
969
970  if (obj.found == 0 && obj.offload == 0)
971    goto err;
972
973  if (obj.found > 1)
974    resolve_conflicts (&lto_file.symtab, &lto_file.conflicts);
975
976  if (obj.found > 0)
977    {
978      status = add_symbols (file->handle, lto_file.symtab.nsyms,
979			    lto_file.symtab.syms);
980      check (status == LDPS_OK, LDPL_FATAL, "could not add symbols");
981
982      num_claimed_files++;
983      claimed_files =
984	xrealloc (claimed_files,
985		  num_claimed_files * sizeof (struct plugin_file_info));
986      claimed_files[num_claimed_files - 1] = lto_file;
987    }
988
989  if (obj.found == 0 && obj.offload == 1)
990    {
991      num_offload_files++;
992      offload_files =
993	xrealloc (offload_files,
994		  num_offload_files * sizeof (struct plugin_file_info));
995      offload_files[num_offload_files - 1] = lto_file;
996    }
997
998  *claimed = 1;
999
1000  goto cleanup;
1001
1002 err:
1003  free (lto_file.name);
1004
1005 cleanup:
1006  if (obj.objfile)
1007    simple_object_release_read (obj.objfile);
1008
1009  return LDPS_OK;
1010}
1011
1012/* Parse the plugin options. */
1013
1014static void
1015process_option (const char *option)
1016{
1017  if (strcmp (option, "-debug") == 0)
1018    debug = 1;
1019  else if (strcmp (option, "-nop") == 0)
1020    nop = 1;
1021  else if (!strncmp (option, "-pass-through=", strlen("-pass-through=")))
1022    {
1023      num_pass_through_items++;
1024      pass_through_items = xrealloc (pass_through_items,
1025				     num_pass_through_items * sizeof (char *));
1026      pass_through_items[num_pass_through_items - 1] =
1027          xstrdup (option + strlen ("-pass-through="));
1028    }
1029  else if (!strncmp (option, "-sym-style=", sizeof ("-sym-style=") - 1))
1030    {
1031      switch (option[sizeof ("-sym-style=") - 1])
1032	{
1033	case 'w':
1034	  sym_style = ss_win32;
1035	  break;
1036	case 'u':
1037	  sym_style = ss_uscore;
1038	  break;
1039	default:
1040	  sym_style = ss_none;
1041	  break;
1042	}
1043    }
1044  else
1045    {
1046      int size;
1047      char *opt = xstrdup (option);
1048      lto_wrapper_num_args += 1;
1049      size = lto_wrapper_num_args * sizeof (char *);
1050      lto_wrapper_argv = (char **) xrealloc (lto_wrapper_argv, size);
1051      lto_wrapper_argv[lto_wrapper_num_args - 1] = opt;
1052      if (strncmp (option, "-fresolution=", sizeof ("-fresolution=") - 1) == 0)
1053	resolution_file = opt + sizeof ("-fresolution=") - 1;
1054    }
1055}
1056
1057/* Called by gold after loading the plugin. TV is the transfer vector. */
1058
1059enum ld_plugin_status
1060onload (struct ld_plugin_tv *tv)
1061{
1062  struct ld_plugin_tv *p;
1063  enum ld_plugin_status status;
1064
1065  p = tv;
1066  while (p->tv_tag)
1067    {
1068      switch (p->tv_tag)
1069	{
1070        case LDPT_MESSAGE:
1071          message = p->tv_u.tv_message;
1072          break;
1073	case LDPT_REGISTER_CLAIM_FILE_HOOK:
1074	  register_claim_file = p->tv_u.tv_register_claim_file;
1075	  break;
1076	case LDPT_ADD_SYMBOLS:
1077	  add_symbols = p->tv_u.tv_add_symbols;
1078	  break;
1079	case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK:
1080	  register_all_symbols_read = p->tv_u.tv_register_all_symbols_read;
1081	  break;
1082	case LDPT_GET_SYMBOLS_V2:
1083	  get_symbols_v2 = p->tv_u.tv_get_symbols;
1084	  break;
1085	case LDPT_GET_SYMBOLS:
1086	  get_symbols = p->tv_u.tv_get_symbols;
1087	  break;
1088	case LDPT_REGISTER_CLEANUP_HOOK:
1089	  register_cleanup = p->tv_u.tv_register_cleanup;
1090	  break;
1091	case LDPT_ADD_INPUT_FILE:
1092	  add_input_file = p->tv_u.tv_add_input_file;
1093	  break;
1094	case LDPT_ADD_INPUT_LIBRARY:
1095	  add_input_library = p->tv_u.tv_add_input_library;
1096	  break;
1097	case LDPT_OPTION:
1098	  process_option (p->tv_u.tv_string);
1099	  break;
1100	case LDPT_GOLD_VERSION:
1101	  gold_version = p->tv_u.tv_val;
1102	  break;
1103	default:
1104	  break;
1105	}
1106      p++;
1107    }
1108
1109  check (register_claim_file, LDPL_FATAL, "register_claim_file not found");
1110  check (add_symbols, LDPL_FATAL, "add_symbols not found");
1111  status = register_claim_file (claim_file_handler);
1112  check (status == LDPS_OK, LDPL_FATAL,
1113	 "could not register the claim_file callback");
1114
1115  if (register_cleanup)
1116    {
1117      status = register_cleanup (cleanup_handler);
1118      check (status == LDPS_OK, LDPL_FATAL,
1119	     "could not register the cleanup callback");
1120    }
1121
1122  if (register_all_symbols_read)
1123    {
1124      check (get_symbols, LDPL_FATAL, "get_symbols not found");
1125      status = register_all_symbols_read (all_symbols_read_handler);
1126      check (status == LDPS_OK, LDPL_FATAL,
1127	     "could not register the all_symbols_read callback");
1128    }
1129
1130  /* Support -fno-use-linker-plugin by failing to load the plugin
1131     for the case where it is auto-loaded by BFD.  */
1132  char *collect_gcc_options = getenv ("COLLECT_GCC_OPTIONS");
1133  if (collect_gcc_options
1134      && strstr (collect_gcc_options, "'-fno-use-linker-plugin'"))
1135    return LDPS_ERR;
1136
1137  return LDPS_OK;
1138}
1139