* ldmain.c (main): Flush stdout before and stderr after printing
[external/binutils.git] / ld / plugin.c
1 /* Plugin control for the GNU linker.
2    Copyright 2010, 2011 Free Software Foundation, Inc.
3
4    This file is part of the GNU Binutils.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
19    MA 02110-1301, USA.  */
20
21 #include "sysdep.h"
22 #include "libiberty.h"
23 #include "bfd.h"
24 #include "bfdlink.h"
25 #include "bfdver.h"
26 #include "ld.h"
27 #include "ldmain.h"
28 #include "ldmisc.h"
29 #include "ldexp.h"
30 #include "ldlang.h"
31 #include "ldfile.h"
32 #include "plugin.h"
33 #include "plugin-api.h"
34 #include "elf-bfd.h"
35 #if !defined (HAVE_DLFCN_H) && defined (HAVE_WINDOWS_H)
36 #include <Windows.h>
37 #endif
38
39 /* The suffix to append to the name of the real (claimed) object file
40    when generating a dummy BFD to hold the IR symbols sent from the
41    plugin.  */
42 #define IRONLY_SUFFIX           ".ironly\004"
43
44 /* This is sizeof an array of chars, not sizeof a const char *.  We
45    also have to avoid inadvertently counting the trailing NUL.  */
46 #define IRONLY_SUFFIX_LEN       (sizeof (IRONLY_SUFFIX) - 1)
47
48 /* Stores a single argument passed to a plugin.  */
49 typedef struct plugin_arg
50 {
51   struct plugin_arg *next;
52   const char *arg;
53 } plugin_arg_t;
54
55 /* Holds all details of a single plugin.  */
56 typedef struct plugin
57 {
58   /* Next on the list of plugins, or NULL at end of chain.  */
59   struct plugin *next;
60   /* The argument string given to --plugin.  */
61   const char *name;
62   /* The shared library handle returned by dlopen.  */
63   void *dlhandle;
64   /* The list of argument string given to --plugin-opt.  */
65   plugin_arg_t *args;
66   /* Number of args in the list, for convenience.  */
67   size_t n_args;
68   /* The plugin's event handlers.  */
69   ld_plugin_claim_file_handler claim_file_handler;
70   ld_plugin_all_symbols_read_handler all_symbols_read_handler;
71   ld_plugin_cleanup_handler cleanup_handler;
72   /* TRUE if the cleanup handlers have been called.  */
73   bfd_boolean cleanup_done;
74 } plugin_t;
75
76 /* The master list of all plugins.  */
77 static plugin_t *plugins_list = NULL;
78
79 /* We keep a tail pointer for easy linking on the end.  */
80 static plugin_t **plugins_tail_chain_ptr = &plugins_list;
81
82 /* The last plugin added to the list, for receiving args.  */
83 static plugin_t *last_plugin = NULL;
84
85 /* The tail of the arg chain of the last plugin added to the list.  */
86 static plugin_arg_t **last_plugin_args_tail_chain_ptr = NULL;
87
88 /* The plugin which is currently having a callback executed.  */
89 static plugin_t *called_plugin = NULL;
90
91 /* Last plugin to cause an error, if any.  */
92 static const char *error_plugin = NULL;
93
94 /* A hash table that records symbols referenced by non-IR files.  Used
95    at get_symbols time to determine whether any prevailing defs from
96    IR files are referenced only from other IR files, so tthat we can
97    we can distinguish the LDPR_PREVAILING_DEF and LDPR_PREVAILING_DEF_IRONLY
98    cases when establishing symbol resolutions.  */
99 static struct bfd_hash_table *non_ironly_hash = NULL;
100
101 /* Set at all symbols read time, to avoid recursively offering the plugin
102    its own newly-added input files and libs to claim.  */
103 static bfd_boolean no_more_claiming = FALSE;
104
105 /* If the --allow-multiple-definition command-line option is active, we
106    have to disable it so that BFD always calls our hook, and simulate the
107    effect (when not resolving IR vs. real symbols) ourselves by ensuring
108    TRUE is returned from the hook.  */
109 static bfd_boolean plugin_cached_allow_multiple_defs = FALSE;
110
111 /* Call 'cleanup' hook for all plugins at exit.  */
112 static void plugin_call_cleanup (void);
113
114 /* List of tags to set in the constant leading part of the tv array. */
115 static const enum ld_plugin_tag tv_header_tags[] =
116 {
117   LDPT_MESSAGE,
118   LDPT_API_VERSION,
119   LDPT_GNU_LD_VERSION,
120   LDPT_LINKER_OUTPUT,
121   LDPT_OUTPUT_NAME,
122   LDPT_REGISTER_CLAIM_FILE_HOOK,
123   LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK,
124   LDPT_REGISTER_CLEANUP_HOOK,
125   LDPT_ADD_SYMBOLS,
126   LDPT_GET_INPUT_FILE,
127   LDPT_RELEASE_INPUT_FILE,
128   LDPT_GET_SYMBOLS,
129   LDPT_ADD_INPUT_FILE,
130   LDPT_ADD_INPUT_LIBRARY,
131   LDPT_SET_EXTRA_LIBRARY_PATH
132 };
133
134 /* How many entries in the constant leading part of the tv array.  */
135 static const size_t tv_header_size = ARRAY_SIZE (tv_header_tags);
136
137 #if !defined (HAVE_DLFCN_H) && defined (HAVE_WINDOWS_H)
138
139 #define RTLD_NOW 0      /* Dummy value.  */
140
141 static void *
142 dlopen (const char *file, int mode ATTRIBUTE_UNUSED)
143 {
144   return LoadLibrary (file);
145 }
146
147 static void *
148 dlsym (void *handle, const char *name)
149 {
150   return GetProcAddress (handle, name);
151 }
152
153 static int
154 dlclose (void *handle)
155 {
156   FreeLibrary (handle);
157   return 0;
158 }
159
160 #endif /* !defined (HAVE_DLFCN_H) && defined (HAVE_WINDOWS_H)  */
161
162 /* Helper function for exiting with error status.  */
163 static int
164 set_plugin_error (const char *plugin)
165 {
166   error_plugin = plugin;
167   return -1;
168 }
169
170 /* Test if an error occurred.  */
171 static bfd_boolean
172 plugin_error_p (void)
173 {
174   return error_plugin != NULL;
175 }
176
177 /* Return name of plugin which caused an error if any.  */
178 const char *
179 plugin_error_plugin (void)
180 {
181   return error_plugin ? error_plugin : _("<no plugin>");
182 }
183
184 /* Handle -plugin arg: find and load plugin, or return error.  */
185 int
186 plugin_opt_plugin (const char *plugin)
187 {
188   plugin_t *newplug;
189
190   newplug = xmalloc (sizeof *newplug);
191   memset (newplug, 0, sizeof *newplug);
192   newplug->name = plugin;
193   newplug->dlhandle = dlopen (plugin, RTLD_NOW);
194   if (!newplug->dlhandle)
195     return set_plugin_error (plugin);
196
197   /* Chain on end, so when we run list it is in command-line order.  */
198   *plugins_tail_chain_ptr = newplug;
199   plugins_tail_chain_ptr = &newplug->next;
200
201   /* Record it as current plugin for receiving args.  */
202   last_plugin = newplug;
203   last_plugin_args_tail_chain_ptr = &newplug->args;
204   return 0;
205 }
206
207 /* Accumulate option arguments for last-loaded plugin, or return
208    error if none.  */
209 int
210 plugin_opt_plugin_arg (const char *arg)
211 {
212   plugin_arg_t *newarg;
213
214   if (!last_plugin)
215     return set_plugin_error (_("<no plugin>"));
216
217   newarg = xmalloc (sizeof *newarg);
218   newarg->arg = arg;
219   newarg->next = NULL;
220
221   /* Chain on end to preserve command-line order.  */
222   *last_plugin_args_tail_chain_ptr = newarg;
223   last_plugin_args_tail_chain_ptr = &newarg->next;
224   last_plugin->n_args++;
225   return 0;
226 }
227
228 /* Create a dummy BFD.  */
229 bfd *
230 plugin_get_ir_dummy_bfd (const char *name, bfd *srctemplate)
231 {
232   asection *sec;
233   bfd *abfd;
234
235   bfd_use_reserved_id = 1;
236   abfd = bfd_create (concat (name, IRONLY_SUFFIX, (const char *)NULL),
237                      srctemplate);
238   bfd_set_arch_info (abfd, bfd_get_arch_info (srctemplate));
239   bfd_make_writable (abfd);
240   /* Create a minimal set of sections to own the symbols.  */
241   sec = bfd_make_section_old_way (abfd, ".text");
242   bfd_set_section_flags (abfd, sec,
243                          (SEC_CODE | SEC_HAS_CONTENTS | SEC_READONLY
244                           | SEC_ALLOC | SEC_LOAD | SEC_KEEP));
245   sec->output_section = sec;
246   sec->output_offset = 0;
247   return abfd;
248 }
249
250 /* Check if the BFD passed in is an IR dummy object file.  */
251 static bfd_boolean
252 is_ir_dummy_bfd (const bfd *abfd)
253 {
254   size_t namlen;
255
256   if (abfd == NULL)
257     return FALSE;
258   namlen = strlen (abfd->filename);
259   if (namlen < IRONLY_SUFFIX_LEN)
260     return FALSE;
261   return !strcmp (abfd->filename + namlen - IRONLY_SUFFIX_LEN, IRONLY_SUFFIX);
262 }
263
264 /* Helpers to convert between BFD and GOLD symbol formats.  */
265 static enum ld_plugin_status
266 asymbol_from_plugin_symbol (bfd *abfd, asymbol *asym,
267                             const struct ld_plugin_symbol *ldsym)
268 {
269   flagword flags = BSF_NO_FLAGS;
270   struct bfd_section *section;
271
272   asym->the_bfd = abfd;
273   asym->name = (ldsym->version
274                 ? concat (ldsym->name, "@", ldsym->version, NULL)
275                 : ldsym->name);
276   asym->value = 0;
277   switch (ldsym->def)
278     {
279     case LDPK_WEAKDEF:
280       flags = BSF_WEAK;
281       /* FALLTHRU */
282     case LDPK_DEF:
283       flags |= BSF_GLOBAL;
284       section = bfd_get_section_by_name (abfd, ".text");
285       break;
286
287     case LDPK_WEAKUNDEF:
288       flags = BSF_WEAK;
289       /* FALLTHRU */
290     case LDPK_UNDEF:
291       section = bfd_und_section_ptr;
292       break;
293
294     case LDPK_COMMON:
295       flags = BSF_GLOBAL;
296       section = bfd_com_section_ptr;
297       asym->value = ldsym->size;
298       /* For ELF targets, set alignment of common symbol to 1.  */
299       if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
300         ((elf_symbol_type *) asym)->internal_elf_sym.st_value = 1;
301       break;
302
303     default:
304       return LDPS_ERR;
305     }
306   asym->flags = flags;
307   asym->section = section;
308
309   /* Visibility only applies on ELF targets.  */
310   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
311     {
312       elf_symbol_type *elfsym = elf_symbol_from (abfd, asym);
313       unsigned char visibility;
314
315       if (!elfsym)
316         einfo (_("%P%F: %s: non-ELF symbol in ELF BFD!\n"), asym->name);
317       switch (ldsym->visibility)
318         {
319         default:
320           einfo (_("%P%F: unknown ELF symbol visibility: %d!\n"),
321                  ldsym->visibility);
322         case LDPV_DEFAULT:
323           visibility = STV_DEFAULT;
324           break;
325         case LDPV_PROTECTED:
326           visibility = STV_PROTECTED;
327           break;
328         case LDPV_INTERNAL:
329           visibility = STV_INTERNAL;
330           break;
331         case LDPV_HIDDEN:
332           visibility = STV_HIDDEN;
333           break;
334         }
335       elfsym->internal_elf_sym.st_other
336         = (visibility | (elfsym->internal_elf_sym.st_other
337                          & ~ELF_ST_VISIBILITY (-1)));
338     }
339
340   return LDPS_OK;
341 }
342
343 /* Register a claim-file handler.  */
344 static enum ld_plugin_status
345 register_claim_file (ld_plugin_claim_file_handler handler)
346 {
347   ASSERT (called_plugin);
348   called_plugin->claim_file_handler = handler;
349   return LDPS_OK;
350 }
351
352 /* Register an all-symbols-read handler.  */
353 static enum ld_plugin_status
354 register_all_symbols_read (ld_plugin_all_symbols_read_handler handler)
355 {
356   ASSERT (called_plugin);
357   called_plugin->all_symbols_read_handler = handler;
358   return LDPS_OK;
359 }
360
361 /* Register a cleanup handler.  */
362 static enum ld_plugin_status
363 register_cleanup (ld_plugin_cleanup_handler handler)
364 {
365   ASSERT (called_plugin);
366   called_plugin->cleanup_handler = handler;
367   return LDPS_OK;
368 }
369
370 /* Add symbols from a plugin-claimed input file.  */
371 static enum ld_plugin_status
372 add_symbols (void *handle, int nsyms, const struct ld_plugin_symbol *syms)
373 {
374   asymbol **symptrs;
375   bfd *abfd = handle;
376   int n;
377   ASSERT (called_plugin);
378   symptrs = xmalloc (nsyms * sizeof *symptrs);
379   for (n = 0; n < nsyms; n++)
380     {
381       enum ld_plugin_status rv;
382       asymbol *bfdsym = bfd_make_empty_symbol (abfd);
383       symptrs[n] = bfdsym;
384       rv = asymbol_from_plugin_symbol (abfd, bfdsym, syms + n);
385       if (rv != LDPS_OK)
386         return rv;
387     }
388   bfd_set_symtab (abfd, symptrs, nsyms);
389   return LDPS_OK;
390 }
391
392 /* Get the input file information with an open (possibly re-opened)
393    file descriptor.  */
394 static enum ld_plugin_status
395 get_input_file (const void *handle, struct ld_plugin_input_file *file)
396 {
397   ASSERT (called_plugin);
398   handle = handle;
399   file = file;
400   return LDPS_ERR;
401 }
402
403 /* Release the input file.  */
404 static enum ld_plugin_status
405 release_input_file (const void *handle)
406 {
407   ASSERT (called_plugin);
408   handle = handle;
409   return LDPS_ERR;
410 }
411
412 /* Return TRUE if a defined symbol might be reachable from outside the
413    universe of claimed objects.  */
414 static inline bfd_boolean
415 is_visible_from_outside (struct ld_plugin_symbol *lsym, asection *section,
416                          struct bfd_link_hash_entry *blhe)
417 {
418   /* Section's owner may be NULL if it is the absolute
419      section, fortunately is_ir_dummy_bfd handles that.  */
420   if (!is_ir_dummy_bfd (section->owner))
421     return TRUE;
422   if (link_info.relocatable)
423     return TRUE;
424   if (link_info.export_dynamic || link_info.shared)
425     {
426       /* Only ELF symbols really have visibility.  */
427       if (bfd_get_flavour (link_info.output_bfd) == bfd_target_elf_flavour)
428         {
429           struct elf_link_hash_entry *el = (struct elf_link_hash_entry *)blhe;
430           int vis = ELF_ST_VISIBILITY (el->other);
431           return vis == STV_DEFAULT || vis == STV_PROTECTED;
432         }
433       /* On non-ELF targets, we can safely make inferences by considering
434          what visibility the plugin would have liked to apply when it first
435          sent us the symbol.  During ELF symbol processing, visibility only
436          ever becomes more restrictive, not less, when symbols are merged,
437          so this is a conservative estimate; it may give false positives,
438          declaring something visible from outside when it in fact would
439          not have been, but this will only lead to missed optimisation
440          opportunities during LTRANS at worst; it will not give false
441          negatives, which can lead to the disastrous conclusion that the
442          related symbol is IRONLY.  (See GCC PR46319 for an example.)  */
443       return (lsym->visibility == LDPV_DEFAULT
444               || lsym->visibility == LDPV_PROTECTED);
445     }
446   return FALSE;
447 }
448
449 /* Get the symbol resolution info for a plugin-claimed input file.  */
450 static enum ld_plugin_status
451 get_symbols (const void *handle, int nsyms, struct ld_plugin_symbol *syms)
452 {
453   const bfd *abfd = handle;
454   int n;
455   ASSERT (called_plugin);
456   for (n = 0; n < nsyms; n++)
457     {
458       struct bfd_link_hash_entry *blhe;
459       bfd_boolean ironly;
460       asection *owner_sec;
461
462       blhe = bfd_link_hash_lookup (link_info.hash, syms[n].name,
463                                    FALSE, FALSE, TRUE);
464       if (!blhe)
465         {
466           syms[n].resolution = LDPR_UNKNOWN;
467           continue;
468         }
469
470       /* Determine resolution from blhe type and symbol's original type.  */
471       if (blhe->type == bfd_link_hash_undefined
472           || blhe->type == bfd_link_hash_undefweak)
473         {
474           syms[n].resolution = LDPR_UNDEF;
475           continue;
476         }
477       if (blhe->type != bfd_link_hash_defined
478           && blhe->type != bfd_link_hash_defweak
479           && blhe->type != bfd_link_hash_common)
480         {
481           /* We should not have a new, indirect or warning symbol here.  */
482           einfo ("%P%F: %s: plugin symbol table corrupt (sym type %d)\n",
483                  called_plugin->name, blhe->type);
484         }
485
486       /* Find out which section owns the symbol.  Since it's not undef,
487          it must have an owner; if it's not a common symbol, both defs
488          and weakdefs keep it in the same place. */
489       owner_sec = (blhe->type == bfd_link_hash_common)
490         ? blhe->u.c.p->section
491         : blhe->u.def.section;
492
493       /* We need to know if the sym is referenced from non-IR files.  Or
494          even potentially-referenced, perhaps in a future final link if
495          this is a partial one, perhaps dynamically at load-time if the
496          symbol is externally visible.  */
497       ironly = !is_visible_from_outside (&syms[n], owner_sec, blhe)
498         && !bfd_hash_lookup (non_ironly_hash, syms[n].name, FALSE, FALSE);
499
500       /* If it was originally undefined or common, then it has been
501          resolved; determine how.  */
502       if (syms[n].def == LDPK_UNDEF
503           || syms[n].def == LDPK_WEAKUNDEF
504           || syms[n].def == LDPK_COMMON)
505         {
506           if (owner_sec->owner == link_info.output_bfd)
507             syms[n].resolution = LDPR_RESOLVED_EXEC;
508           else if (owner_sec->owner == abfd)
509             syms[n].resolution = (ironly
510                                   ? LDPR_PREVAILING_DEF_IRONLY
511                                   : LDPR_PREVAILING_DEF);
512           else if (is_ir_dummy_bfd (owner_sec->owner))
513             syms[n].resolution = LDPR_RESOLVED_IR;
514           else if (owner_sec->owner != NULL
515                    && (owner_sec->owner->flags & DYNAMIC) != 0)
516             syms[n].resolution =  LDPR_RESOLVED_DYN;
517           else
518             syms[n].resolution = LDPR_RESOLVED_EXEC;
519           continue;
520         }
521
522       /* Was originally def, or weakdef.  Does it prevail?  If the
523          owner is the original dummy bfd that supplied it, then this
524          is the definition that has prevailed.  */
525       if (owner_sec->owner == link_info.output_bfd)
526         syms[n].resolution = LDPR_PREEMPTED_REG;
527       else if (owner_sec->owner == abfd)
528         {
529           syms[n].resolution = (ironly
530                                 ? LDPR_PREVAILING_DEF_IRONLY
531                                 : LDPR_PREVAILING_DEF);
532           continue;
533         }
534
535       /* Was originally def, weakdef, or common, but has been pre-empted.  */
536       syms[n].resolution = is_ir_dummy_bfd (owner_sec->owner)
537         ? LDPR_PREEMPTED_IR
538         : LDPR_PREEMPTED_REG;
539     }
540   return LDPS_OK;
541 }
542
543 /* Add a new (real) input file generated by a plugin.  */
544 static enum ld_plugin_status
545 add_input_file (const char *pathname)
546 {
547   ASSERT (called_plugin);
548   if (!lang_add_input_file (xstrdup (pathname), lang_input_file_is_file_enum,
549                             NULL))
550     return LDPS_ERR;
551   return LDPS_OK;
552 }
553
554 /* Add a new (real) library required by a plugin.  */
555 static enum ld_plugin_status
556 add_input_library (const char *pathname)
557 {
558   ASSERT (called_plugin);
559   if (!lang_add_input_file (xstrdup (pathname), lang_input_file_is_l_enum,
560                             NULL))
561     return LDPS_ERR;
562   return LDPS_OK;
563 }
564
565 /* Set the extra library path to be used by libraries added via
566    add_input_library.  */
567 static enum ld_plugin_status
568 set_extra_library_path (const char *path)
569 {
570   ASSERT (called_plugin);
571   ldfile_add_library_path (xstrdup (path), FALSE);
572   return LDPS_OK;
573 }
574
575 /* Issue a diagnostic message from a plugin.  */
576 static enum ld_plugin_status
577 message (int level, const char *format, ...)
578 {
579   va_list args;
580   va_start (args, format);
581
582   switch (level)
583     {
584     case LDPL_INFO:
585       vfinfo (stdout, format, args, FALSE);
586       putchar ('\n');
587       break;
588     case LDPL_WARNING:
589       vfinfo (stdout, format, args, TRUE);
590       putchar ('\n');
591       break;
592     case LDPL_FATAL:
593     case LDPL_ERROR:
594     default:
595         {
596           char *newfmt = ACONCAT ((level == LDPL_FATAL
597                                    ? "%P%F: " : "%P%X: ",
598                                    format, "\n", NULL));
599           fflush (stdout);
600           vfinfo (stderr, newfmt, args, TRUE);
601           fflush (stderr);
602         }
603       break;
604     }
605
606   va_end (args);
607   return LDPS_OK;
608 }
609
610 /* Helper to size leading part of tv array and set it up. */
611 static size_t
612 set_tv_header (struct ld_plugin_tv *tv)
613 {
614   size_t i;
615
616   /* Version info.  */
617   static const unsigned int major = (unsigned)(BFD_VERSION / 100000000UL);
618   static const unsigned int minor = (unsigned)(BFD_VERSION / 1000000UL) % 100;
619
620   if (!tv)
621     return tv_header_size;
622
623   for (i = 0; i < tv_header_size; i++)
624     {
625       tv[i].tv_tag = tv_header_tags[i];
626 #define TVU(x) tv[i].tv_u.tv_ ## x
627       switch (tv[i].tv_tag)
628         {
629         case LDPT_MESSAGE:
630           TVU(message) = message;
631           break;
632         case LDPT_API_VERSION:
633           TVU(val) = LD_PLUGIN_API_VERSION;
634           break;
635         case LDPT_GNU_LD_VERSION:
636           TVU(val) = major * 100 + minor;
637           break;
638         case LDPT_LINKER_OUTPUT:
639           TVU(val) = (link_info.relocatable
640                       ? LDPO_REL
641                       : (link_info.shared ? LDPO_DYN : LDPO_EXEC));
642           break;
643         case LDPT_OUTPUT_NAME:
644           TVU(string) = output_filename;
645           break;
646         case LDPT_REGISTER_CLAIM_FILE_HOOK:
647           TVU(register_claim_file) = register_claim_file;
648           break;
649         case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK:
650           TVU(register_all_symbols_read) = register_all_symbols_read;
651           break;
652         case LDPT_REGISTER_CLEANUP_HOOK:
653           TVU(register_cleanup) = register_cleanup;
654           break;
655         case LDPT_ADD_SYMBOLS:
656           TVU(add_symbols) = add_symbols;
657           break;
658         case LDPT_GET_INPUT_FILE:
659           TVU(get_input_file) = get_input_file;
660           break;
661         case LDPT_RELEASE_INPUT_FILE:
662           TVU(release_input_file) = release_input_file;
663           break;
664         case LDPT_GET_SYMBOLS:
665           TVU(get_symbols) = get_symbols;
666           break;
667         case LDPT_ADD_INPUT_FILE:
668           TVU(add_input_file) = add_input_file;
669           break;
670         case LDPT_ADD_INPUT_LIBRARY:
671           TVU(add_input_library) = add_input_library;
672           break;
673         case LDPT_SET_EXTRA_LIBRARY_PATH:
674           TVU(set_extra_library_path) = set_extra_library_path;
675           break;
676         default:
677           /* Added a new entry to the array without adding
678              a new case to set up its value is a bug.  */
679           FAIL ();
680         }
681 #undef TVU
682     }
683   return tv_header_size;
684 }
685
686 /* Append the per-plugin args list and trailing LDPT_NULL to tv.  */
687 static void
688 set_tv_plugin_args (plugin_t *plugin, struct ld_plugin_tv *tv)
689 {
690   plugin_arg_t *arg = plugin->args;
691   while (arg)
692     {
693       tv->tv_tag = LDPT_OPTION;
694       tv->tv_u.tv_string = arg->arg;
695       arg = arg->next;
696       tv++;
697     }
698   tv->tv_tag = LDPT_NULL;
699   tv->tv_u.tv_val = 0;
700 }
701
702 /* Return true if any plugins are active this run.  Only valid
703    after options have been processed.  */
704 bfd_boolean
705 plugin_active_plugins_p (void)
706 {
707   return plugins_list != NULL;
708 }
709
710 /* Load up and initialise all plugins after argument parsing.  */
711 int
712 plugin_load_plugins (void)
713 {
714   struct ld_plugin_tv *my_tv;
715   unsigned int max_args = 0;
716   plugin_t *curplug = plugins_list;
717
718   /* If there are no plugins, we need do nothing this run.  */
719   if (!curplug)
720     return 0;
721
722   xatexit (plugin_call_cleanup);
723
724   /* First pass over plugins to find max # args needed so that we
725      can size and allocate the tv array.  */
726   while (curplug)
727     {
728       if (curplug->n_args > max_args)
729         max_args = curplug->n_args;
730       curplug = curplug->next;
731     }
732
733   /* Allocate tv array and initialise constant part.  */
734   my_tv = xmalloc ((max_args + 1 + tv_header_size) * sizeof *my_tv);
735   set_tv_header (my_tv);
736
737   /* Pass over plugins again, activating them.  */
738   curplug = plugins_list;
739   while (curplug)
740     {
741       enum ld_plugin_status rv;
742       ld_plugin_onload onloadfn = dlsym (curplug->dlhandle, "onload");
743       if (!onloadfn)
744         onloadfn = dlsym (curplug->dlhandle, "_onload");
745       if (!onloadfn)
746         return set_plugin_error (curplug->name);
747       set_tv_plugin_args (curplug, &my_tv[tv_header_size]);
748       called_plugin = curplug;
749       rv = (*onloadfn) (my_tv);
750       called_plugin = NULL;
751       if (rv != LDPS_OK)
752         return set_plugin_error (curplug->name);
753       curplug = curplug->next;
754     }
755
756   /* Since plugin(s) inited ok, assume they're going to want symbol
757      resolutions, which needs us to track which symbols are referenced
758      by non-IR files using the linker's notice callback.  */
759   link_info.notice_all = TRUE;
760
761   return 0;
762 }
763
764 /* Call 'claim file' hook for all plugins.  */
765 int
766 plugin_call_claim_file (const struct ld_plugin_input_file *file, int *claimed)
767 {
768   plugin_t *curplug = plugins_list;
769   *claimed = FALSE;
770   if (no_more_claiming)
771     return 0;
772   while (curplug && !*claimed)
773     {
774       if (curplug->claim_file_handler)
775         {
776           enum ld_plugin_status rv;
777           called_plugin = curplug;
778           rv = (*curplug->claim_file_handler) (file, claimed);
779           called_plugin = NULL;
780           if (rv != LDPS_OK)
781             set_plugin_error (curplug->name);
782         }
783       curplug = curplug->next;
784     }
785   return plugin_error_p () ? -1 : 0;
786 }
787
788 /* Call 'all symbols read' hook for all plugins.  */
789 int
790 plugin_call_all_symbols_read (void)
791 {
792   plugin_t *curplug = plugins_list;
793
794   /* Disable any further file-claiming.  */
795   no_more_claiming = TRUE;
796
797   /* If --allow-multiple-definition is in effect, we need to disable it,
798      as the plugin infrastructure relies on the multiple_definition
799      callback to swap out the dummy IR-only BFDs for new real ones
800      when it starts opening the files added during this callback.  */
801   plugin_cached_allow_multiple_defs = link_info.allow_multiple_definition;
802   link_info.allow_multiple_definition = FALSE;
803
804   while (curplug)
805     {
806       if (curplug->all_symbols_read_handler)
807         {
808           enum ld_plugin_status rv;
809           called_plugin = curplug;
810           rv = (*curplug->all_symbols_read_handler) ();
811           called_plugin = NULL;
812           if (rv != LDPS_OK)
813             set_plugin_error (curplug->name);
814         }
815       curplug = curplug->next;
816     }
817   return plugin_error_p () ? -1 : 0;
818 }
819
820 /* Call 'cleanup' hook for all plugins at exit.  */
821 static void
822 plugin_call_cleanup (void)
823 {
824   plugin_t *curplug = plugins_list;
825   while (curplug)
826     {
827       if (curplug->cleanup_handler && !curplug->cleanup_done)
828         {
829           enum ld_plugin_status rv;
830           curplug->cleanup_done = TRUE;
831           called_plugin = curplug;
832           rv = (*curplug->cleanup_handler) ();
833           called_plugin = NULL;
834           if (rv != LDPS_OK)
835             set_plugin_error (curplug->name);
836           dlclose (curplug->dlhandle);
837         }
838       curplug = curplug->next;
839     }
840   if (plugin_error_p ())
841     info_msg (_("%P: %s: error in plugin cleanup (ignored)\n"),
842               plugin_error_plugin ());
843 }
844
845 /* Lazily init the non_ironly hash table.  */
846 static void
847 init_non_ironly_hash (void)
848 {
849   if (non_ironly_hash == NULL)
850     {
851       non_ironly_hash =
852         (struct bfd_hash_table *) xmalloc (sizeof (struct bfd_hash_table));
853       if (!bfd_hash_table_init_n (non_ironly_hash,
854                                   bfd_hash_newfunc,
855                                   sizeof (struct bfd_hash_entry),
856                                   61))
857         einfo (_("%P%F: bfd_hash_table_init failed: %E\n"));
858     }
859 }
860
861 /* To determine which symbols should be resolved LDPR_PREVAILING_DEF
862    and which LDPR_PREVAILING_DEF_IRONLY, we notice all the symbols as
863    the linker adds them to the linker hash table.  If we see a symbol
864    being referenced from a non-IR file, we add it to the non_ironly hash
865    table.  If we can't find it there at get_symbols time, we know that
866    it was referenced only by IR files.  We have to notice_all symbols,
867    because we won't necessarily know until later which ones will be
868    contributed by IR files.  */
869 bfd_boolean
870 plugin_notice (struct bfd_link_info *info ATTRIBUTE_UNUSED,
871                const char *name, bfd *abfd,
872                asection *section, bfd_vma value ATTRIBUTE_UNUSED)
873 {
874   bfd_boolean is_ref = bfd_is_und_section (section);
875   bfd_boolean is_dummy = is_ir_dummy_bfd (abfd);
876   init_non_ironly_hash ();
877   /* We only care about refs, not defs, indicated by section pointing
878      to the undefined section (according to the bfd linker notice callback
879      interface definition).  */
880   if (is_ref && !is_dummy)
881     {
882       /* This is a ref from a non-IR file, so note the ref'd symbol
883          in the non-IR-only hash.  */
884       if (!bfd_hash_lookup (non_ironly_hash, name, TRUE, TRUE))
885         einfo (_("%P%X: %s: hash table failure adding symbol %s\n"),
886                abfd->filename, name);
887     }
888   else if (!is_ref && is_dummy)
889     {
890       /* No further processing since this is a def from an IR dummy BFD.  */
891       return FALSE;
892     }
893
894   /* Continue with cref/nocrossref/trace-sym processing.  */
895   return TRUE;
896 }
897
898 /* When we add new object files to the link at all symbols read time,
899    these contain the real code and symbols generated from the IR files,
900    and so duplicate all the definitions already supplied by the dummy
901    IR-only BFDs that we created at claim files time.  We use the linker's
902    multiple-definitions callback hook to fix up the clash, discarding
903    the symbol from the IR-only BFD in favour of the symbol from the
904    real BFD.  We return true if this was not-really-a-clash because
905    we've fixed it up, or anyway if --allow-multiple-definition was in
906    effect (before we disabled it to ensure we got called back).  */
907 bfd_boolean
908 plugin_multiple_definition (struct bfd_link_info *info, const char *name,
909                             bfd *obfd, asection *osec ATTRIBUTE_UNUSED,
910                             bfd_vma oval ATTRIBUTE_UNUSED,
911                             bfd *nbfd, asection *nsec, bfd_vma nval)
912 {
913   if (is_ir_dummy_bfd (obfd))
914     {
915       struct bfd_link_hash_entry *blhe
916         = bfd_link_hash_lookup (info->hash, name, FALSE, FALSE, FALSE);
917       if (!blhe)
918         einfo (_("%P%X: %s: can't find IR symbol '%s'\n"), nbfd->filename,
919                name);
920       else if (blhe->type != bfd_link_hash_defined)
921         einfo (_("%P%x: %s: bad IR symbol type %d\n"), name, blhe->type);
922       /* Replace it with new details.  */
923       blhe->u.def.section = nsec;
924       blhe->u.def.value = nval;
925       return TRUE;
926     }
927   return plugin_cached_allow_multiple_defs;
928 }