compiler: rename "requires" to "needs"
[official-gcc.git] / lto-plugin / lto-plugin.c
blob635e126946bcf58274f5cfb76bda7b1b224fa139
1 /* LTO plugin for linkers like gold, GNU ld or mold.
2 Copyright (C) 2009-2022 Free Software Foundation, Inc.
3 Contributed by Rafael Avila de Espindola (espindola@google.com).
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.
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.
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/>. */
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.
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.
27 More information at http://gcc.gnu.org/wiki/whopr/driver.
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 */
41 #ifdef HAVE_CONFIG_H
42 #include "config.h"
43 #if !HAVE_PTHREAD_H
44 #error POSIX threads are mandatory dependency
45 #endif
46 #endif
48 #if HAVE_STDINT_H
49 #include <stdint.h>
50 #endif
51 #include <stdbool.h>
52 #include <assert.h>
53 #include <errno.h>
54 #include <string.h>
55 #include <stdlib.h>
56 #include <stdio.h>
57 #include <inttypes.h>
58 #include <sys/stat.h>
59 #include <unistd.h>
60 #include <fcntl.h>
61 #include <sys/types.h>
62 #include <pthread.h>
63 #ifdef HAVE_SYS_WAIT_H
64 #include <sys/wait.h>
65 #endif
66 #ifndef WIFEXITED
67 #define WIFEXITED(S) (((S) & 0xff) == 0)
68 #endif
69 #ifndef WEXITSTATUS
70 #define WEXITSTATUS(S) (((S) & 0xff00) >> 8)
71 #endif
72 #include <libiberty.h>
73 #include <hashtab.h>
74 #include "../gcc/lto/common.h"
75 #include "simple-object.h"
76 #include "plugin-api.h"
78 /* We need to use I64 instead of ll width-specifier on native Windows.
79 The reason for this is that older MS-runtimes don't support the ll. */
80 #ifdef __MINGW32__
81 #define PRI_LL "I64"
82 #else
83 #define PRI_LL "ll"
84 #endif
86 /* Handle opening elf files on hosts, such as Windows, that may use
87 text file handling that will break binary access. */
88 #ifndef O_BINARY
89 # define O_BINARY 0
90 #endif
92 /* Segment name for LTO sections. This is only used for Mach-O.
93 FIXME: This needs to be kept in sync with darwin.c. */
95 #define LTO_SEGMENT_NAME "__GNU_LTO"
97 /* Return true if STR string starts with PREFIX. */
99 static inline bool
100 startswith (const char *str, const char *prefix)
102 return strncmp (str, prefix, strlen (prefix)) == 0;
105 /* The part of the symbol table the plugin has to keep track of. Note that we
106 must keep SYMS until all_symbols_read is called to give the linker time to
107 copy the symbol information.
108 The id must be 64bit to minimze collisions. */
110 struct sym_aux
112 uint32_t slot;
113 unsigned long long id;
114 unsigned next_conflict;
117 struct plugin_symtab
119 int nsyms;
120 int last_sym;
121 struct sym_aux *aux;
122 struct ld_plugin_symbol *syms;
123 unsigned long long id;
126 /* Encapsulates object file data during symbol scan. */
127 struct plugin_objfile
129 int found;
130 bool offload;
131 simple_object_read *objfile;
132 struct plugin_symtab *out;
133 const struct ld_plugin_input_file *file;
136 /* All that we have to remember about a file. */
138 struct plugin_file_info
140 char *name;
141 void *handle;
142 struct plugin_symtab symtab;
143 struct plugin_symtab conflicts;
144 bool skip_file;
147 /* List item with name of the file with offloading. */
149 struct plugin_offload_file
151 char *name;
152 struct plugin_offload_file *next;
155 /* Until ASM_OUTPUT_LABELREF can be hookized and decoupled from
156 stdio file streams, we do simple label translation here. */
158 enum symbol_style
160 ss_none, /* No underscore prefix. */
161 ss_win32, /* Underscore prefix any symbol not beginning with '@'. */
162 ss_uscore, /* Underscore prefix all symbols. */
165 /* Plug-in mutex. */
166 static pthread_mutex_t plugin_lock;
168 static char *arguments_file_name;
169 static ld_plugin_register_claim_file register_claim_file;
170 static ld_plugin_register_all_symbols_read register_all_symbols_read;
171 static ld_plugin_get_symbols get_symbols, get_symbols_v2, get_symbols_v3;
172 static ld_plugin_register_cleanup register_cleanup;
173 static ld_plugin_add_input_file add_input_file;
174 static ld_plugin_add_input_library add_input_library;
175 static ld_plugin_message message;
176 static ld_plugin_add_symbols add_symbols, add_symbols_v2;
178 static struct plugin_file_info *claimed_files = NULL;
179 static unsigned int num_claimed_files = 0;
180 static unsigned int non_claimed_files = 0;
182 /* List of files with offloading. */
183 static struct plugin_offload_file *offload_files;
184 /* Last file in the list. */
185 static struct plugin_offload_file *offload_files_last;
186 /* Last non-archive file in the list. */
187 static struct plugin_offload_file *offload_files_last_obj;
188 /* Last LTO file in the list. */
189 static struct plugin_offload_file *offload_files_last_lto;
190 /* Total number of files with offloading. */
191 static unsigned num_offload_files;
193 static char **output_files = NULL;
194 static unsigned int num_output_files = 0;
196 static char **lto_wrapper_argv;
197 static int lto_wrapper_num_args;
199 static char **pass_through_items = NULL;
200 static unsigned int num_pass_through_items;
202 static char *ltrans_objects = NULL;
204 static bool debug;
205 static bool save_temps;
206 static bool verbose;
207 static char nop;
208 static char *resolution_file = NULL;
209 static enum ld_plugin_output_file_type linker_output;
210 static bool linker_output_set;
211 static bool linker_output_known;
212 static bool linker_output_auto_nolto_rel;
213 static const char *link_output_name = NULL;
215 /* This indicates link_output_name already contains the dot of the
216 suffix, so we can skip it in extensions. */
217 static bool skip_in_suffix = false;
219 /* The version of gold being used, or -1 if not gold. The number is
220 MAJOR * 100 + MINOR. */
221 static int gold_version = -1;
223 /* Not used by default, but can be overridden at runtime
224 by using -plugin-opt=-sym-style={none,win32,underscore|uscore}
225 (in fact, only first letter of style arg is checked.) */
226 static enum symbol_style sym_style = ss_none;
228 static void
229 check_1 (int gate, enum ld_plugin_level level, const char *text)
231 if (gate)
232 return;
234 if (message)
235 message (level, text);
236 else
238 /* If there is no nicer way to inform the user, fallback to stderr. */
239 fprintf (stderr, "%s\n", text);
240 if (level == LDPL_FATAL)
241 abort ();
245 /* This little wrapper allows check to be called with a non-integer
246 first argument, such as a pointer that must be non-NULL. We can't
247 use c99 bool type to coerce it into range, so we explicitly test. */
248 #define check(GATE, LEVEL, TEXT) check_1 (((GATE) != 0), (LEVEL), (TEXT))
250 /* Parse an entry of the IL symbol table. The data to be parsed is pointed
251 by P and the result is written in ENTRY. The slot number is stored in SLOT.
252 Returns the address of the next entry. */
254 static char *
255 parse_table_entry (char *p, struct ld_plugin_symbol *entry,
256 struct sym_aux *aux)
258 unsigned char t;
259 enum ld_plugin_symbol_kind translate_kind[] =
261 LDPK_DEF,
262 LDPK_WEAKDEF,
263 LDPK_UNDEF,
264 LDPK_WEAKUNDEF,
265 LDPK_COMMON
268 enum ld_plugin_symbol_visibility translate_visibility[] =
270 LDPV_DEFAULT,
271 LDPV_PROTECTED,
272 LDPV_INTERNAL,
273 LDPV_HIDDEN
276 switch (sym_style)
278 case ss_win32:
279 if (p[0] == '@')
281 /* cf. Duff's device. */
282 case ss_none:
283 entry->name = xstrdup (p);
284 break;
286 /* FALL-THROUGH. */
287 case ss_uscore:
288 entry->name = concat ("_", p, NULL);
289 break;
290 default:
291 check (0, LDPL_FATAL, "invalid symbol style requested");
292 break;
294 while (*p)
295 p++;
296 p++;
298 entry->version = NULL;
300 entry->comdat_key = p;
301 while (*p)
302 p++;
303 p++;
305 if (strlen (entry->comdat_key) == 0)
306 entry->comdat_key = NULL;
307 else
308 entry->comdat_key = xstrdup (entry->comdat_key);
310 entry->unused = entry->section_kind = entry->symbol_type = 0;
312 t = *p;
313 check (t <= 4, LDPL_FATAL, "invalid symbol kind found");
314 entry->def = translate_kind[t];
315 p++;
317 t = *p;
318 check (t <= 3, LDPL_FATAL, "invalid symbol visibility found");
319 entry->visibility = translate_visibility[t];
320 p++;
322 memcpy (&entry->size, p, sizeof (uint64_t));
323 p += 8;
325 memcpy (&aux->slot, p, sizeof (uint32_t));
326 p += 4;
328 entry->resolution = LDPR_UNKNOWN;
330 aux->next_conflict = -1;
332 return p;
335 /* Parse an entry of the IL symbol table. The data to be parsed is pointed
336 by P and the result is written in ENTRY. The slot number is stored in SLOT.
337 Returns the address of the next entry. */
339 static char *
340 parse_table_entry_extension (char *p, struct ld_plugin_symbol *entry)
342 unsigned char t;
343 enum ld_plugin_symbol_type symbol_types[] =
345 LDST_UNKNOWN,
346 LDST_FUNCTION,
347 LDST_VARIABLE,
350 t = *p;
351 check (t <= 2, LDPL_FATAL, "invalid symbol type found");
352 entry->symbol_type = symbol_types[t];
353 p++;
354 entry->section_kind = *p;
355 p++;
357 return p;
361 /* Translate the IL symbol table located between DATA and END. Append the
362 slots and symbols to OUT. */
364 static void
365 translate (char *data, char *end, struct plugin_symtab *out)
367 struct sym_aux *aux;
368 struct ld_plugin_symbol *syms = NULL;
369 int n, len;
371 /* This overestimates the output buffer sizes, but at least
372 the algorithm is O(1) now. */
374 len = (end - data)/8 + out->nsyms + 1;
375 syms = xrealloc (out->syms, len * sizeof (struct ld_plugin_symbol));
376 aux = xrealloc (out->aux, len * sizeof (struct sym_aux));
378 for (n = out->nsyms; data < end; n++)
380 aux[n].id = out->id;
381 data = parse_table_entry (data, &syms[n], &aux[n]);
384 assert(n < len);
386 out->nsyms = n;
387 out->syms = syms;
388 out->aux = aux;
391 static void
392 parse_symtab_extension (char *data, char *end, struct plugin_symtab *out)
394 unsigned long i;
395 unsigned char version;
397 if (data >= end)
398 /* FIXME: Issue an error ? */
399 return;
401 version = *data;
402 data++;
404 if (version != 1)
405 return;
407 /* Version 1 contains the following data per entry:
408 - symbol_type
409 - section_kind
410 . */
412 unsigned long nsyms = (end - data) / 2;
414 for (i = 0; i < nsyms; i++)
415 data = parse_table_entry_extension (data, out->syms + i + out->last_sym);
417 out->last_sym += nsyms;
420 /* Free all memory that is no longer needed after writing the symbol
421 resolution. */
423 static void
424 free_1 (struct plugin_file_info *files, unsigned num_files)
426 unsigned int i;
427 for (i = 0; i < num_files; i++)
429 struct plugin_file_info *info = &files[i];
430 struct plugin_symtab *symtab = &info->symtab;
431 unsigned int j;
432 for (j = 0; j < symtab->nsyms; j++)
434 struct ld_plugin_symbol *s = &symtab->syms[j];
435 free (s->name);
436 free (s->comdat_key);
438 free (symtab->syms);
439 symtab->syms = NULL;
443 /* Free all remaining memory. */
445 static void
446 free_2 (void)
448 unsigned int i;
449 for (i = 0; i < num_claimed_files; i++)
451 struct plugin_file_info *info = &claimed_files[i];
452 struct plugin_symtab *symtab = &info->symtab;
453 free (symtab->aux);
454 free (info->name);
457 for (i = 0; i < num_output_files; i++)
458 free (output_files[i]);
459 free (output_files);
461 free (claimed_files);
462 claimed_files = NULL;
463 num_claimed_files = 0;
465 while (offload_files)
467 struct plugin_offload_file *ofld = offload_files;
468 offload_files = offload_files->next;
469 free (ofld);
471 num_offload_files = 0;
473 free (arguments_file_name);
474 arguments_file_name = NULL;
477 /* Dump SYMTAB to resolution file F. */
479 static void
480 dump_symtab (FILE *f, struct plugin_symtab *symtab)
482 unsigned j;
484 for (j = 0; j < symtab->nsyms; j++)
486 uint32_t slot = symtab->aux[j].slot;
487 unsigned int resolution = symtab->syms[j].resolution;
489 assert (resolution != LDPR_UNKNOWN);
491 fprintf (f, "%u %" PRI_LL "x %s %s\n",
492 (unsigned int) slot, symtab->aux[j].id,
493 lto_resolution_str[resolution],
494 symtab->syms[j].name);
498 /* Finish the conflicts' resolution information after the linker resolved
499 the original symbols */
501 static void
502 finish_conflict_resolution (struct plugin_symtab *symtab,
503 struct plugin_symtab *conflicts)
505 int i, j;
507 if (conflicts->nsyms == 0)
508 return;
510 for (i = 0; i < symtab->nsyms; i++)
512 char resolution = LDPR_UNKNOWN;
514 if (symtab->aux[i].next_conflict == -1)
515 continue;
517 switch (symtab->syms[i].def)
519 case LDPK_DEF:
520 case LDPK_COMMON: /* ??? */
521 resolution = LDPR_RESOLVED_IR;
522 break;
523 case LDPK_WEAKDEF:
524 resolution = LDPR_PREEMPTED_IR;
525 break;
526 case LDPK_UNDEF:
527 case LDPK_WEAKUNDEF:
528 resolution = symtab->syms[i].resolution;
529 break;
530 default:
531 assert (0);
534 assert (resolution != LDPR_UNKNOWN);
536 for (j = symtab->aux[i].next_conflict;
537 j != -1;
538 j = conflicts->aux[j].next_conflict)
539 conflicts->syms[j].resolution = resolution;
543 /* Free symbol table SYMTAB. */
545 static void
546 free_symtab (struct plugin_symtab *symtab)
548 free (symtab->syms);
549 symtab->syms = NULL;
550 free (symtab->aux);
551 symtab->aux = NULL;
554 /* Writes the relocations to disk. */
556 static void
557 write_resolution (void)
559 unsigned int i, included_files = 0;
560 FILE *f;
562 check (resolution_file, LDPL_FATAL, "resolution file not specified");
563 f = fopen (resolution_file, "w");
564 check (f, LDPL_FATAL, "could not open file");
566 for (i = 0; i < num_claimed_files; i++)
568 struct plugin_file_info *info = &claimed_files[i];
569 struct plugin_symtab *symtab = &info->symtab;
570 struct ld_plugin_symbol *syms = symtab->syms;
572 /* Version 2 of API supports IRONLY_EXP resolution that is
573 accepted by GCC-4.7 and newer.
574 Version 3 can return LDPS_NO_SYMS that means the object
575 will not be used at all. */
576 if (get_symbols_v3)
578 enum ld_plugin_status status
579 = get_symbols_v3 (info->handle, symtab->nsyms, syms);
580 if (status == LDPS_NO_SYMS)
582 info->skip_file = true;
583 continue;
586 else if (get_symbols_v2)
587 get_symbols_v2 (info->handle, symtab->nsyms, syms);
588 else
589 get_symbols (info->handle, symtab->nsyms, syms);
591 ++included_files;
593 finish_conflict_resolution (symtab, &info->conflicts);
596 fprintf (f, "%d\n", included_files);
598 for (i = 0; i < num_claimed_files; i++)
600 struct plugin_file_info *info = &claimed_files[i];
601 struct plugin_symtab *symtab = &info->symtab;
603 if (info->skip_file)
604 continue;
606 fprintf (f, "%s %d\n", info->name, symtab->nsyms + info->conflicts.nsyms);
607 dump_symtab (f, symtab);
608 if (info->conflicts.nsyms)
610 dump_symtab (f, &info->conflicts);
611 free_symtab (&info->conflicts);
614 fclose (f);
617 /* Pass files generated by the lto-wrapper to the linker. FD is lto-wrapper's
618 stdout. */
620 static void
621 add_output_files (FILE *f)
623 for (;;)
625 const unsigned piece = 32;
626 char *buf, *s = xmalloc (piece);
627 size_t len;
629 buf = s;
630 cont:
631 if (!fgets (buf, piece, f))
633 free (s);
634 break;
636 len = strlen (s);
637 if (s[len - 1] != '\n')
639 s = xrealloc (s, len + piece);
640 buf = s + len;
641 goto cont;
643 s[len - 1] = '\0';
645 num_output_files++;
646 output_files
647 = xrealloc (output_files, num_output_files * sizeof (char *));
648 output_files[num_output_files - 1] = s;
649 add_input_file (output_files[num_output_files - 1]);
653 /* Execute the lto-wrapper. ARGV[0] is the binary. The rest of ARGV is the
654 argument list. */
656 static void
657 exec_lto_wrapper (char *argv[])
659 int t, i;
660 int status;
661 char *at_args;
662 FILE *args;
663 FILE *wrapper_output;
664 char *new_argv[3];
665 struct pex_obj *pex;
666 const char *errmsg;
668 /* Write argv to a file to avoid a command line that is too long
669 Save the file locally on save-temps. */
670 const char *suffix = ".lto_wrapper_args";
671 if (skip_in_suffix)
672 suffix++;
673 if (save_temps && link_output_name)
674 arguments_file_name = concat (link_output_name, suffix, NULL);
675 else
676 arguments_file_name = make_temp_file (".lto_wrapper_args");
677 check (arguments_file_name, LDPL_FATAL,
678 "Failed to generate a temorary file name");
680 args = fopen (arguments_file_name, "w");
681 check (args, LDPL_FATAL, "could not open arguments file");
683 t = writeargv (&argv[1], args);
684 check (t == 0, LDPL_FATAL, "could not write arguments");
685 t = fclose (args);
686 check (t == 0, LDPL_FATAL, "could not close arguments file");
688 at_args = concat ("@", arguments_file_name, NULL);
689 check (at_args, LDPL_FATAL, "could not allocate");
691 for (i = 1; argv[i]; i++)
693 char *a = argv[i];
694 /* Check the input argument list for a verbose marker too. */
695 if (a[0] == '-' && a[1] == 'v' && a[2] == '\0')
697 verbose = true;
698 break;
702 if (verbose)
704 for (i = 0; argv[i]; i++)
705 fprintf (stderr, "%s ", argv[i]);
706 fprintf (stderr, "\n");
709 new_argv[0] = argv[0];
710 new_argv[1] = at_args;
711 new_argv[2] = NULL;
713 if (debug)
715 for (i = 0; new_argv[i]; i++)
716 fprintf (stderr, "%s ", new_argv[i]);
717 fprintf (stderr, "\n");
720 pex = pex_init (PEX_USE_PIPES, "lto-wrapper", NULL);
721 check (pex != NULL, LDPL_FATAL, "could not pex_init lto-wrapper");
723 errmsg = pex_run (pex, 0, new_argv[0], new_argv, NULL, NULL, &t);
724 check (errmsg == NULL, LDPL_FATAL, "could not run lto-wrapper");
725 check (t == 0, LDPL_FATAL, "could not run lto-wrapper");
727 wrapper_output = pex_read_output (pex, 0);
728 check (wrapper_output, LDPL_FATAL, "could not read lto-wrapper output");
730 add_output_files (wrapper_output);
732 t = pex_get_status (pex, 1, &status);
733 check (t == 1, LDPL_FATAL, "could not get lto-wrapper exit status");
734 check (WIFEXITED (status) && WEXITSTATUS (status) == 0, LDPL_FATAL,
735 "lto-wrapper failed");
737 pex_free (pex);
739 free (at_args);
742 /* Pass the original files back to the linker. */
744 static void
745 use_original_files (void)
747 unsigned i;
748 for (i = 0; i < num_claimed_files; i++)
750 struct plugin_file_info *info = &claimed_files[i];
751 add_input_file (info->name);
756 /* Called by the linker once all symbols have been read. */
758 static enum ld_plugin_status
759 all_symbols_read_handler (void)
761 const unsigned num_lto_args
762 = num_claimed_files + lto_wrapper_num_args + 2
763 + !linker_output_known + !linker_output_auto_nolto_rel;
764 unsigned i;
765 char **lto_argv;
766 const char *linker_output_str = NULL;
767 const char **lto_arg_ptr;
768 if (num_claimed_files + num_offload_files == 0)
769 return LDPS_OK;
771 if (nop)
773 use_original_files ();
774 return LDPS_OK;
777 if (ltrans_objects)
779 FILE *objs = fopen (ltrans_objects, "r");
780 add_output_files (objs);
781 fclose (objs);
782 return LDPS_OK;
785 lto_argv = (char **) xcalloc (sizeof (char *), num_lto_args);
786 lto_arg_ptr = (const char **) lto_argv;
787 assert (lto_wrapper_argv);
789 write_resolution ();
791 free_1 (claimed_files, num_claimed_files);
793 for (i = 0; i < lto_wrapper_num_args; i++)
794 *lto_arg_ptr++ = lto_wrapper_argv[i];
796 if (!linker_output_known)
798 assert (linker_output_set);
799 switch (linker_output)
801 case LDPO_REL:
802 if (non_claimed_files)
804 if (!linker_output_auto_nolto_rel)
805 message (LDPL_WARNING, "incremental linking of LTO and non-LTO"
806 " objects; using -flinker-output=nolto-rel which will"
807 " bypass whole program optimization");
808 linker_output_str = "-flinker-output=nolto-rel";
810 else
811 linker_output_str = "-flinker-output=rel";
812 break;
813 case LDPO_DYN:
814 linker_output_str = "-flinker-output=dyn";
815 break;
816 case LDPO_PIE:
817 linker_output_str = "-flinker-output=pie";
818 break;
819 case LDPO_EXEC:
820 linker_output_str = "-flinker-output=exec";
821 break;
822 default:
823 message (LDPL_FATAL, "unsupported linker output %i", linker_output);
824 break;
826 *lto_arg_ptr++ = xstrdup (linker_output_str);
829 if (num_offload_files > 0)
831 FILE *f;
832 char *arg;
833 char *offload_objects_file_name;
834 struct plugin_offload_file *ofld;
835 const char *suffix = ".ofldlist";
837 if (save_temps && link_output_name)
839 suffix += skip_in_suffix;
840 offload_objects_file_name = concat (link_output_name, suffix, NULL);
842 else
843 offload_objects_file_name = make_temp_file (suffix);
844 check (offload_objects_file_name, LDPL_FATAL,
845 "Failed to generate a temporary file name");
846 f = fopen (offload_objects_file_name, "w");
847 check (f, LDPL_FATAL, "could not open file with offload objects");
848 fprintf (f, "%u\n", num_offload_files);
850 /* Skip the dummy item at the start of the list. */
851 ofld = offload_files->next;
852 while (ofld)
854 fprintf (f, "%s\n", ofld->name);
855 ofld = ofld->next;
857 fclose (f);
859 arg = concat ("-foffload-objects=", offload_objects_file_name, NULL);
860 check (arg, LDPL_FATAL, "could not allocate");
861 *lto_arg_ptr++ = arg;
864 for (i = 0; i < num_claimed_files; i++)
866 struct plugin_file_info *info = &claimed_files[i];
868 if (!info->skip_file)
869 *lto_arg_ptr++ = info->name;
872 *lto_arg_ptr++ = NULL;
873 exec_lto_wrapper (lto_argv);
875 free (lto_argv);
877 /* --pass-through is not needed when using gold 1.11 or later. */
878 if (pass_through_items && gold_version < 111)
880 unsigned int i;
881 for (i = 0; i < num_pass_through_items; i++)
883 if (startswith (pass_through_items[i], "-l"))
884 add_input_library (pass_through_items[i] + 2);
885 else
886 add_input_file (pass_through_items[i]);
887 free (pass_through_items[i]);
888 pass_through_items[i] = NULL;
890 free (pass_through_items);
891 pass_through_items = NULL;
894 return LDPS_OK;
897 /* Helper, as used in collect2. */
898 static int
899 file_exists (const char *name)
901 return access (name, R_OK) == 0;
904 /* Unlink FILE unless we have save-temps set.
905 Note that we're saving files if verbose output is set. */
907 static void
908 maybe_unlink (const char *file)
910 if (save_temps && file_exists (file))
912 if (verbose)
913 fprintf (stderr, "[Leaving %s]\n", file);
914 return;
917 unlink_if_ordinary (file);
920 /* Remove temporary files at the end of the link. */
922 static enum ld_plugin_status
923 cleanup_handler (void)
925 unsigned int i;
927 if (debug)
928 return LDPS_OK;
930 if (arguments_file_name)
931 maybe_unlink (arguments_file_name);
933 for (i = 0; i < num_output_files; i++)
934 maybe_unlink (output_files[i]);
936 free_2 ();
937 return LDPS_OK;
940 #define SWAP(type, a, b) \
941 do { type tmp_; tmp_ = (a); (a) = (b); (b) = tmp_; } while(0)
943 /* Compare two hash table entries */
945 static int eq_sym (const void *a, const void *b)
947 const struct ld_plugin_symbol *as = (const struct ld_plugin_symbol *)a;
948 const struct ld_plugin_symbol *bs = (const struct ld_plugin_symbol *)b;
950 return !strcmp (as->name, bs->name);
953 /* Hash a symbol */
955 static hashval_t hash_sym (const void *a)
957 const struct ld_plugin_symbol *as = (const struct ld_plugin_symbol *)a;
959 return htab_hash_string (as->name);
962 /* Determine how strong a symbol is */
964 static int symbol_strength (struct ld_plugin_symbol *s)
966 switch (s->def)
968 case LDPK_UNDEF:
969 case LDPK_WEAKUNDEF:
970 return 0;
971 case LDPK_WEAKDEF:
972 return 1;
973 default:
974 return 2;
978 /* In the ld -r case we can get dups in the LTO symbol tables, where
979 the same symbol can have different resolutions (e.g. undefined and defined).
981 We have to keep that in the LTO symbol tables, but the dups confuse
982 gold and then finally gcc by supplying incorrect resolutions.
984 Problem is that the main gold symbol table doesn't know about subids
985 and does not distingush the same symbols in different states.
987 So we drop duplicates from the linker visible symbol table
988 and keep them in a private table. Then later do own symbol
989 resolution for the duplicated based on the results for the
990 originals.
992 Then when writing out the resolution file readd the dropped symbols.
994 XXX how to handle common? */
996 static void
997 resolve_conflicts (struct plugin_symtab *t, struct plugin_symtab *conflicts)
999 htab_t symtab = htab_create (t->nsyms, hash_sym, eq_sym, NULL);
1000 int i;
1001 int out;
1002 int outlen;
1004 outlen = t->nsyms;
1005 conflicts->syms = xmalloc (sizeof (struct ld_plugin_symbol) * outlen);
1006 conflicts->aux = xmalloc (sizeof (struct sym_aux) * outlen);
1008 /* Move all duplicate symbols into the auxiliary conflicts table. */
1009 out = 0;
1010 for (i = 0; i < t->nsyms; i++)
1012 struct ld_plugin_symbol *s = &t->syms[i];
1013 struct sym_aux *aux = &t->aux[i];
1014 void **slot;
1016 slot = htab_find_slot (symtab, s, INSERT);
1017 if (*slot != NULL)
1019 int cnf;
1020 struct ld_plugin_symbol *orig = (struct ld_plugin_symbol *)*slot;
1021 struct sym_aux *orig_aux = &t->aux[orig - t->syms];
1023 /* Always let the linker resolve the strongest symbol */
1024 if (symbol_strength (orig) < symbol_strength (s))
1026 SWAP (struct ld_plugin_symbol, *orig, *s);
1027 SWAP (uint32_t, orig_aux->slot, aux->slot);
1028 SWAP (unsigned long long, orig_aux->id, aux->id);
1029 /* Don't swap conflict chain pointer */
1032 /* Move current symbol into the conflicts table */
1033 cnf = conflicts->nsyms++;
1034 conflicts->syms[cnf] = *s;
1035 conflicts->aux[cnf] = *aux;
1036 aux = &conflicts->aux[cnf];
1038 /* Update conflicts chain of the original symbol */
1039 aux->next_conflict = orig_aux->next_conflict;
1040 orig_aux->next_conflict = cnf;
1042 continue;
1045 /* Remove previous duplicates in the main table */
1046 if (out < i)
1048 t->syms[out] = *s;
1049 t->aux[out] = *aux;
1052 /* Put original into the hash table */
1053 *slot = &t->syms[out];
1054 out++;
1057 assert (conflicts->nsyms <= outlen);
1058 assert (conflicts->nsyms + out == t->nsyms);
1060 t->nsyms = out;
1061 htab_delete (symtab);
1064 /* Process one section of an object file. */
1066 static int
1067 process_symtab (void *data, const char *name, off_t offset, off_t length)
1069 struct plugin_objfile *obj = (struct plugin_objfile *)data;
1070 char *s;
1071 char *secdatastart, *secdata;
1073 if (!startswith (name, ".gnu.lto_.symtab"))
1074 return 1;
1076 s = strrchr (name, '.');
1077 if (s)
1078 sscanf (s, ".%" PRI_LL "x", &obj->out->id);
1079 secdata = secdatastart = xmalloc (length);
1080 offset += obj->file->offset;
1081 if (offset != lseek (obj->file->fd, offset, SEEK_SET))
1082 goto err;
1086 ssize_t got = read (obj->file->fd, secdata, length);
1087 if (got == 0)
1088 break;
1089 else if (got > 0)
1091 secdata += got;
1092 length -= got;
1094 else if (errno != EINTR)
1095 goto err;
1097 while (length > 0);
1098 if (length > 0)
1099 goto err;
1101 translate (secdatastart, secdata, obj->out);
1102 obj->found++;
1103 free (secdatastart);
1104 return 1;
1106 err:
1107 if (message)
1108 message (LDPL_FATAL, "%s: corrupt object file", obj->file->name);
1109 /* Force claim_file_handler to abandon this file. */
1110 obj->found = 0;
1111 free (secdatastart);
1112 return 0;
1115 /* Process one section of an object file. */
1117 static int
1118 process_symtab_extension (void *data, const char *name, off_t offset,
1119 off_t length)
1121 struct plugin_objfile *obj = (struct plugin_objfile *)data;
1122 char *s;
1123 char *secdatastart, *secdata;
1125 if (!startswith (name, ".gnu.lto_.ext_symtab"))
1126 return 1;
1128 s = strrchr (name, '.');
1129 if (s)
1130 sscanf (s, ".%" PRI_LL "x", &obj->out->id);
1131 secdata = secdatastart = xmalloc (length);
1132 offset += obj->file->offset;
1133 if (offset != lseek (obj->file->fd, offset, SEEK_SET))
1134 goto err;
1138 ssize_t got = read (obj->file->fd, secdata, length);
1139 if (got == 0)
1140 break;
1141 else if (got > 0)
1143 secdata += got;
1144 length -= got;
1146 else if (errno != EINTR)
1147 goto err;
1149 while (length > 0);
1150 if (length > 0)
1151 goto err;
1153 parse_symtab_extension (secdatastart, secdata, obj->out);
1154 obj->found++;
1155 free (secdatastart);
1156 return 1;
1158 err:
1159 if (message)
1160 message (LDPL_FATAL, "%s: corrupt object file", obj->file->name);
1161 /* Force claim_file_handler to abandon this file. */
1162 obj->found = 0;
1163 free (secdatastart);
1164 return 0;
1168 /* Find an offload section of an object file. */
1170 static int
1171 process_offload_section (void *data, const char *name, off_t offset, off_t len)
1173 if (startswith (name, ".gnu.offload_lto_.opts"))
1175 struct plugin_objfile *obj = (struct plugin_objfile *) data;
1176 obj->offload = true;
1177 return 0;
1180 return 1;
1183 /* Callback used by a linker to check if the plugin will claim FILE. Writes
1184 the result in CLAIMED. */
1186 static enum ld_plugin_status
1187 claim_file_handler (const struct ld_plugin_input_file *file, int *claimed)
1189 enum ld_plugin_status status;
1190 struct plugin_objfile obj;
1191 struct plugin_file_info lto_file;
1192 int err;
1193 const char *errmsg;
1195 memset (&lto_file, 0, sizeof (struct plugin_file_info));
1197 if (file->offset != 0)
1199 /* We pass the offset of the actual file, not the archive header.
1200 Can't use PRIx64, because that's C99, so we have to print the
1201 64-bit hex int as two 32-bit ones. Use xasprintf instead of
1202 asprintf because asprintf doesn't work as expected on some older
1203 mingw32 hosts. */
1204 int lo, hi;
1205 lo = file->offset & 0xffffffff;
1206 hi = ((int64_t)file->offset >> 32) & 0xffffffff;
1207 lto_file.name = hi ? xasprintf ("%s@0x%x%08x", file->name, hi, lo)
1208 : xasprintf ("%s@0x%x", file->name, lo);
1210 else
1212 lto_file.name = xstrdup (file->name);
1214 lto_file.handle = file->handle;
1216 *claimed = 0;
1217 obj.file = file;
1218 obj.found = 0;
1219 obj.offload = false;
1220 obj.out = &lto_file.symtab;
1221 errmsg = NULL;
1222 obj.objfile = simple_object_start_read (file->fd, file->offset, LTO_SEGMENT_NAME,
1223 &errmsg, &err);
1224 /* No file, but also no error code means unrecognized format; just skip it. */
1225 if (!obj.objfile && !err)
1226 goto err;
1228 if (obj.objfile)
1230 errmsg = simple_object_find_sections (obj.objfile, process_symtab, &obj,
1231 &err);
1232 /* Parsing symtab extension should be done only for add_symbols_v2 and
1233 later versions. */
1234 if (!errmsg && add_symbols_v2 != NULL)
1236 obj.out->last_sym = 0;
1237 errmsg = simple_object_find_sections (obj.objfile,
1238 process_symtab_extension,
1239 &obj, &err);
1243 if (!obj.objfile || errmsg)
1245 if (err && message)
1246 message (LDPL_FATAL, "%s: %s: %s", file->name, errmsg,
1247 xstrerror (err));
1248 else if (message)
1249 message (LDPL_FATAL, "%s: %s", file->name, errmsg);
1250 goto err;
1253 if (obj.objfile)
1254 simple_object_find_sections (obj.objfile, process_offload_section,
1255 &obj, &err);
1257 if (obj.found == 0 && !obj.offload)
1258 goto err;
1260 if (obj.found > 1)
1261 resolve_conflicts (&lto_file.symtab, &lto_file.conflicts);
1263 if (obj.found > 0)
1265 if (add_symbols_v2)
1266 status = add_symbols_v2 (file->handle, lto_file.symtab.nsyms,
1267 lto_file.symtab.syms);
1268 else
1269 status = add_symbols (file->handle, lto_file.symtab.nsyms,
1270 lto_file.symtab.syms);
1271 check (status == LDPS_OK, LDPL_FATAL, "could not add symbols");
1273 pthread_mutex_lock (&plugin_lock);
1274 num_claimed_files++;
1275 claimed_files =
1276 xrealloc (claimed_files,
1277 num_claimed_files * sizeof (struct plugin_file_info));
1278 claimed_files[num_claimed_files - 1] = lto_file;
1279 pthread_mutex_unlock (&plugin_lock);
1281 *claimed = 1;
1284 pthread_mutex_lock (&plugin_lock);
1285 if (offload_files == NULL)
1287 /* Add dummy item to the start of the list. */
1288 offload_files = xmalloc (sizeof (struct plugin_offload_file));
1289 offload_files->name = NULL;
1290 offload_files->next = NULL;
1291 offload_files_last = offload_files;
1294 /* If this is an LTO file without offload, and it is the first LTO file, save
1295 the pointer to the last offload file in the list. Further offload LTO
1296 files will be inserted after it, if any. */
1297 if (*claimed && !obj.offload && offload_files_last_lto == NULL)
1298 offload_files_last_lto = offload_files_last;
1300 if (obj.offload)
1302 /* Add file to the list. The order must be exactly the same as the final
1303 order after recompilation and linking, otherwise host and target tables
1304 with addresses wouldn't match. If a static library contains both LTO
1305 and non-LTO objects, ld and gold link them in a different order. */
1306 struct plugin_offload_file *ofld
1307 = xmalloc (sizeof (struct plugin_offload_file));
1308 ofld->name = lto_file.name;
1309 ofld->next = NULL;
1311 if (*claimed && offload_files_last_lto == NULL && file->offset != 0
1312 && gold_version == -1)
1314 /* ld only: insert first LTO file from the archive after the last real
1315 object file immediately preceding the archive, or at the begin of
1316 the list if there was no real objects before archives. */
1317 if (offload_files_last_obj != NULL)
1319 ofld->next = offload_files_last_obj->next;
1320 offload_files_last_obj->next = ofld;
1322 else
1324 ofld->next = offload_files->next;
1325 offload_files->next = ofld;
1328 else if (*claimed && offload_files_last_lto != NULL)
1330 /* Insert LTO file after the last LTO file in the list. */
1331 ofld->next = offload_files_last_lto->next;
1332 offload_files_last_lto->next = ofld;
1334 else
1335 /* Add non-LTO file or first non-archive LTO file to the end of the
1336 list. */
1337 offload_files_last->next = ofld;
1339 if (ofld->next == NULL)
1340 offload_files_last = ofld;
1341 if (file->offset == 0)
1342 offload_files_last_obj = ofld;
1343 if (*claimed)
1344 offload_files_last_lto = ofld;
1345 num_offload_files++;
1347 pthread_mutex_unlock (&plugin_lock);
1349 goto cleanup;
1351 err:
1352 pthread_mutex_lock (&plugin_lock);
1353 non_claimed_files++;
1354 pthread_mutex_unlock (&plugin_lock);
1355 free (lto_file.name);
1357 cleanup:
1358 if (obj.objfile)
1359 simple_object_release_read (obj.objfile);
1361 return LDPS_OK;
1364 /* Parse the plugin options. */
1366 static void
1367 process_option (const char *option)
1369 if (strcmp (option, "-linker-output-known") == 0)
1370 linker_output_known = true;
1371 /* Also accept "notlo" for backwards compatibility. */
1372 else if ((strcmp (option, "-linker-output-auto-nolto-rel") == 0)
1373 || (strcmp (option, "-linker-output-auto-notlo-rel") == 0))
1374 linker_output_auto_nolto_rel = true;
1375 else if (strcmp (option, "-debug") == 0)
1376 debug = true;
1377 else if ((strcmp (option, "-v") == 0)
1378 || (strcmp (option, "--verbose") == 0))
1379 verbose = true;
1380 else if (strcmp (option, "-save-temps") == 0)
1381 save_temps = true;
1382 else if (strcmp (option, "-nop") == 0)
1383 nop = 1;
1384 else if (startswith (option, "-pass-through="))
1386 num_pass_through_items++;
1387 pass_through_items = xrealloc (pass_through_items,
1388 num_pass_through_items * sizeof (char *));
1389 pass_through_items[num_pass_through_items - 1] =
1390 xstrdup (option + strlen ("-pass-through="));
1392 else if (startswith (option, "-sym-style="))
1394 switch (option[sizeof ("-sym-style=") - 1])
1396 case 'w':
1397 sym_style = ss_win32;
1398 break;
1399 case 'u':
1400 sym_style = ss_uscore;
1401 break;
1402 default:
1403 sym_style = ss_none;
1404 break;
1407 else if (startswith (option, "-ltrans-objects="))
1408 ltrans_objects = xstrdup (option + strlen ("-ltrans-objects="));
1409 else
1411 int size;
1412 char *opt = xstrdup (option);
1413 lto_wrapper_num_args += 1;
1414 size = lto_wrapper_num_args * sizeof (char *);
1415 lto_wrapper_argv = (char **) xrealloc (lto_wrapper_argv, size);
1416 lto_wrapper_argv[lto_wrapper_num_args - 1] = opt;
1417 if (startswith (option, "-fresolution="))
1418 resolution_file = opt + sizeof ("-fresolution=") - 1;
1420 save_temps = save_temps || debug;
1421 verbose = verbose || debug;
1424 /* Called by a linker after loading the plugin. TV is the transfer vector. */
1426 enum ld_plugin_status
1427 onload (struct ld_plugin_tv *tv)
1429 struct ld_plugin_tv *p;
1430 enum ld_plugin_status status;
1432 if (pthread_mutex_init (&plugin_lock, NULL) != 0)
1434 fprintf (stderr, "mutex init failed\n");
1435 abort ();
1438 p = tv;
1439 while (p->tv_tag)
1441 switch (p->tv_tag)
1443 case LDPT_MESSAGE:
1444 message = p->tv_u.tv_message;
1445 break;
1446 case LDPT_REGISTER_CLAIM_FILE_HOOK:
1447 register_claim_file = p->tv_u.tv_register_claim_file;
1448 break;
1449 case LDPT_ADD_SYMBOLS_V2:
1450 add_symbols_v2 = p->tv_u.tv_add_symbols;
1451 break;
1452 case LDPT_ADD_SYMBOLS:
1453 add_symbols = p->tv_u.tv_add_symbols;
1454 break;
1455 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK:
1456 register_all_symbols_read = p->tv_u.tv_register_all_symbols_read;
1457 break;
1458 case LDPT_GET_SYMBOLS_V3:
1459 get_symbols_v3 = p->tv_u.tv_get_symbols;
1460 break;
1461 case LDPT_GET_SYMBOLS_V2:
1462 get_symbols_v2 = p->tv_u.tv_get_symbols;
1463 break;
1464 case LDPT_GET_SYMBOLS:
1465 get_symbols = p->tv_u.tv_get_symbols;
1466 break;
1467 case LDPT_REGISTER_CLEANUP_HOOK:
1468 register_cleanup = p->tv_u.tv_register_cleanup;
1469 break;
1470 case LDPT_ADD_INPUT_FILE:
1471 add_input_file = p->tv_u.tv_add_input_file;
1472 break;
1473 case LDPT_ADD_INPUT_LIBRARY:
1474 add_input_library = p->tv_u.tv_add_input_library;
1475 break;
1476 case LDPT_OPTION:
1477 process_option (p->tv_u.tv_string);
1478 break;
1479 case LDPT_GOLD_VERSION:
1480 gold_version = p->tv_u.tv_val;
1481 break;
1482 case LDPT_LINKER_OUTPUT:
1483 linker_output = (enum ld_plugin_output_file_type) p->tv_u.tv_val;
1484 linker_output_set = true;
1485 break;
1486 case LDPT_OUTPUT_NAME:
1487 /* We only use this to make user-friendly temp file names. */
1488 link_output_name = p->tv_u.tv_string;
1489 break;
1490 default:
1491 break;
1493 p++;
1496 check (register_claim_file, LDPL_FATAL, "register_claim_file not found");
1497 check (add_symbols, LDPL_FATAL, "add_symbols not found");
1498 status = register_claim_file (claim_file_handler);
1499 check (status == LDPS_OK, LDPL_FATAL,
1500 "could not register the claim_file callback");
1502 if (register_cleanup)
1504 status = register_cleanup (cleanup_handler);
1505 check (status == LDPS_OK, LDPL_FATAL,
1506 "could not register the cleanup callback");
1509 if (register_all_symbols_read)
1511 check (get_symbols, LDPL_FATAL, "get_symbols not found");
1512 status = register_all_symbols_read (all_symbols_read_handler);
1513 check (status == LDPS_OK, LDPL_FATAL,
1514 "could not register the all_symbols_read callback");
1517 char *collect_gcc_options = getenv ("COLLECT_GCC_OPTIONS");
1518 if (collect_gcc_options)
1520 /* Support -fno-use-linker-plugin by failing to load the plugin
1521 for the case where it is auto-loaded by BFD. */
1522 if (strstr (collect_gcc_options, "'-fno-use-linker-plugin'"))
1523 return LDPS_ERR;
1525 if (strstr (collect_gcc_options, "'-save-temps'"))
1526 save_temps = true;
1528 if (strstr (collect_gcc_options, "'-v'")
1529 || strstr (collect_gcc_options, "'--verbose'"))
1530 verbose = true;
1532 const char *p;
1533 if ((p = strstr (collect_gcc_options, "'-dumpdir'")))
1535 p += sizeof ("'-dumpdir'");
1536 while (*p == ' ')
1537 p++;
1538 const char *start = p;
1539 int ticks = 0, escapes = 0;
1540 /* Count ticks (') and escaped (\.) characters. Stop at the
1541 end of the options or at a blank after an even number of
1542 ticks (not counting escaped ones. */
1543 for (p = start; *p; p++)
1545 if (*p == '\'')
1547 ticks++;
1548 continue;
1550 else if ((ticks % 2) != 0)
1552 if (*p == ' ')
1553 break;
1554 if (*p == '\\')
1556 if (*++p)
1557 escapes++;
1558 else
1559 p--;
1564 /* Now allocate a new link_output_name and decode dumpdir
1565 into it. The loop uses the same logic, except it counts
1566 ticks and escapes backwards (so ticks is adjusted if we
1567 find an odd number of them), and it copies characters
1568 that are escaped or not otherwise skipped. */
1569 int len = p - start - ticks - escapes + 1;
1570 char *q = xmalloc (len);
1571 link_output_name = q;
1572 int oddticks = (ticks % 2);
1573 ticks += oddticks;
1574 for (p = start; *p; p++)
1576 if (*p == '\'')
1578 ticks--;
1579 continue;
1581 else if ((ticks % 2) != 0)
1583 if (*p == ' ')
1584 break;
1585 if (*p == '\\')
1587 if (*++p)
1588 escapes--;
1589 else
1590 p--;
1593 *q++ = *p;
1595 *q = '\0';
1596 assert (escapes == 0);
1597 assert (ticks == oddticks);
1598 assert (q - link_output_name == len - 1);
1599 skip_in_suffix = true;
1603 return LDPS_OK;