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