Fix build breakage when ld plugins disabled
[external/binutils.git] / ld / plugin.c
1 /* Plugin control for the GNU linker.
2    Copyright (C) 2010-2014 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 /* Report plugin symbols.  */
40 bfd_boolean report_plugin_symbols;
41
42 /* The suffix to append to the name of the real (claimed) object file
43    when generating a dummy BFD to hold the IR symbols sent from the
44    plugin.  For cosmetic use only; appears in maps, crefs etc.  */
45 #define IRONLY_SUFFIX " (symbol from plugin)"
46
47 /* Stores a single argument passed to a plugin.  */
48 typedef struct plugin_arg
49 {
50   struct plugin_arg *next;
51   const char *arg;
52 } plugin_arg_t;
53
54 /* Holds all details of a single plugin.  */
55 typedef struct plugin
56 {
57   /* Next on the list of plugins, or NULL at end of chain.  */
58   struct plugin *next;
59   /* The argument string given to --plugin.  */
60   const char *name;
61   /* The shared library handle returned by dlopen.  */
62   void *dlhandle;
63   /* The list of argument string given to --plugin-opt.  */
64   plugin_arg_t *args;
65   /* Number of args in the list, for convenience.  */
66   size_t n_args;
67   /* The plugin's event handlers.  */
68   ld_plugin_claim_file_handler claim_file_handler;
69   ld_plugin_all_symbols_read_handler all_symbols_read_handler;
70   ld_plugin_cleanup_handler cleanup_handler;
71   /* TRUE if the cleanup handlers have been called.  */
72   bfd_boolean cleanup_done;
73 } plugin_t;
74
75 /* The master list of all plugins.  */
76 static plugin_t *plugins_list = NULL;
77
78 /* We keep a tail pointer for easy linking on the end.  */
79 static plugin_t **plugins_tail_chain_ptr = &plugins_list;
80
81 /* The last plugin added to the list, for receiving args.  */
82 static plugin_t *last_plugin = NULL;
83
84 /* The tail of the arg chain of the last plugin added to the list.  */
85 static plugin_arg_t **last_plugin_args_tail_chain_ptr = NULL;
86
87 /* The plugin which is currently having a callback executed.  */
88 static plugin_t *called_plugin = NULL;
89
90 /* Last plugin to cause an error, if any.  */
91 static const char *error_plugin = NULL;
92
93 /* State of linker "notice" interface before we poked at it.  */
94 static bfd_boolean orig_notice_all;
95
96 /* Original linker callbacks, and the plugin version.  */
97 static const struct bfd_link_callbacks *orig_callbacks;
98 static struct bfd_link_callbacks plugin_callbacks;
99
100 /* Set at all symbols read time, to avoid recursively offering the plugin
101    its own newly-added input files and libs to claim.  */
102 bfd_boolean no_more_claiming = FALSE;
103
104 /* List of tags to set in the constant leading part of the tv array. */
105 static const enum ld_plugin_tag tv_header_tags[] =
106 {
107   LDPT_MESSAGE,
108   LDPT_API_VERSION,
109   LDPT_GNU_LD_VERSION,
110   LDPT_LINKER_OUTPUT,
111   LDPT_OUTPUT_NAME,
112   LDPT_REGISTER_CLAIM_FILE_HOOK,
113   LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK,
114   LDPT_REGISTER_CLEANUP_HOOK,
115   LDPT_ADD_SYMBOLS,
116   LDPT_GET_INPUT_FILE,
117   LDPT_RELEASE_INPUT_FILE,
118   LDPT_GET_SYMBOLS,
119   LDPT_GET_SYMBOLS_V2,
120   LDPT_ADD_INPUT_FILE,
121   LDPT_ADD_INPUT_LIBRARY,
122   LDPT_SET_EXTRA_LIBRARY_PATH
123 };
124
125 /* How many entries in the constant leading part of the tv array.  */
126 static const size_t tv_header_size = ARRAY_SIZE (tv_header_tags);
127
128 /* Forward references.  */
129 static bfd_boolean plugin_notice (struct bfd_link_info *,
130                                   struct bfd_link_hash_entry *,
131                                   struct bfd_link_hash_entry *,
132                                   bfd *, asection *, bfd_vma, flagword);
133
134 #if !defined (HAVE_DLFCN_H) && defined (HAVE_WINDOWS_H)
135
136 #define RTLD_NOW 0      /* Dummy value.  */
137
138 static void *
139 dlopen (const char *file, int mode ATTRIBUTE_UNUSED)
140 {
141   return LoadLibrary (file);
142 }
143
144 static void *
145 dlsym (void *handle, const char *name)
146 {
147   return GetProcAddress (handle, name);
148 }
149
150 static int
151 dlclose (void *handle)
152 {
153   FreeLibrary (handle);
154   return 0;
155 }
156
157 #endif /* !defined (HAVE_DLFCN_H) && defined (HAVE_WINDOWS_H)  */
158
159 #ifndef HAVE_DLFCN_H
160 static const char *
161 dlerror (void)
162 {
163   return "";
164 }
165 #endif
166
167 /* Helper function for exiting with error status.  */
168 static int
169 set_plugin_error (const char *plugin)
170 {
171   error_plugin = plugin;
172   return -1;
173 }
174
175 /* Test if an error occurred.  */
176 static bfd_boolean
177 plugin_error_p (void)
178 {
179   return error_plugin != NULL;
180 }
181
182 /* Return name of plugin which caused an error if any.  */
183 const char *
184 plugin_error_plugin (void)
185 {
186   return error_plugin ? error_plugin : _("<no plugin>");
187 }
188
189 /* Handle -plugin arg: find and load plugin, or return error.  */
190 void
191 plugin_opt_plugin (const char *plugin)
192 {
193   plugin_t *newplug;
194
195   newplug = xmalloc (sizeof *newplug);
196   memset (newplug, 0, sizeof *newplug);
197   newplug->name = plugin;
198   newplug->dlhandle = dlopen (plugin, RTLD_NOW);
199   if (!newplug->dlhandle)
200     einfo (_("%P%F: %s: error loading plugin: %s\n"), plugin, dlerror ());
201
202   /* Chain on end, so when we run list it is in command-line order.  */
203   *plugins_tail_chain_ptr = newplug;
204   plugins_tail_chain_ptr = &newplug->next;
205
206   /* Record it as current plugin for receiving args.  */
207   last_plugin = newplug;
208   last_plugin_args_tail_chain_ptr = &newplug->args;
209 }
210
211 /* Accumulate option arguments for last-loaded plugin, or return
212    error if none.  */
213 int
214 plugin_opt_plugin_arg (const char *arg)
215 {
216   plugin_arg_t *newarg;
217
218   if (!last_plugin)
219     return set_plugin_error (_("<no plugin>"));
220
221   /* Ignore -pass-through= from GCC driver.  */
222   if (*arg == '-')
223     {
224       const char *p = arg + 1;
225
226       if (*p == '-')
227         ++p;
228       if (strncmp (p, "pass-through=", 13) == 0)
229         return 0;
230     }
231
232   newarg = xmalloc (sizeof *newarg);
233   newarg->arg = arg;
234   newarg->next = NULL;
235
236   /* Chain on end to preserve command-line order.  */
237   *last_plugin_args_tail_chain_ptr = newarg;
238   last_plugin_args_tail_chain_ptr = &newarg->next;
239   last_plugin->n_args++;
240   return 0;
241 }
242
243 /* Create a dummy BFD.  */
244 bfd *
245 plugin_get_ir_dummy_bfd (const char *name, bfd *srctemplate)
246 {
247   bfd *abfd;
248
249   bfd_use_reserved_id = 1;
250   abfd = bfd_create (concat (name, IRONLY_SUFFIX, (const char *) NULL),
251                      srctemplate);
252   if (abfd != NULL)
253     {
254       abfd->flags |= BFD_LINKER_CREATED | BFD_PLUGIN;
255       bfd_set_arch_info (abfd, bfd_get_arch_info (srctemplate));
256       bfd_set_gp_size (abfd, bfd_get_gp_size (srctemplate));
257       if (bfd_make_writable (abfd)
258           && bfd_copy_private_bfd_data (srctemplate, abfd))
259         {
260           flagword flags;
261
262           /* Create section to own the symbols.  */
263           flags = (SEC_CODE | SEC_HAS_CONTENTS | SEC_READONLY
264                    | SEC_ALLOC | SEC_LOAD | SEC_KEEP | SEC_EXCLUDE);
265           if (bfd_make_section_anyway_with_flags (abfd, ".text", flags))
266             return abfd;
267         }
268     }
269   einfo (_("could not create dummy IR bfd: %F%E\n"));
270   return NULL;
271 }
272
273 /* Check if the BFD passed in is an IR dummy object file.  */
274 static bfd_boolean
275 is_ir_dummy_bfd (const bfd *abfd)
276 {
277   /* ABFD can sometimes legitimately be NULL, e.g. when called from one
278      of the linker callbacks for a symbol in the *ABS* or *UND* sections.
279      Likewise, the usrdata field may be NULL if ABFD was added by the
280      backend without a corresponding input statement, as happens e.g.
281      when processing DT_NEEDED dependencies.  */
282   return (abfd
283           && abfd->usrdata
284           && ((lang_input_statement_type *)(abfd->usrdata))->flags.claimed);
285 }
286
287 /* Helpers to convert between BFD and GOLD symbol formats.  */
288 static enum ld_plugin_status
289 asymbol_from_plugin_symbol (bfd *abfd, asymbol *asym,
290                             const struct ld_plugin_symbol *ldsym)
291 {
292   flagword flags = BSF_NO_FLAGS;
293   struct bfd_section *section;
294
295   asym->the_bfd = abfd;
296   asym->name = (ldsym->version
297                 ? concat (ldsym->name, "@", ldsym->version, (const char *) NULL)
298                 : ldsym->name);
299   asym->value = 0;
300   switch (ldsym->def)
301     {
302     case LDPK_WEAKDEF:
303       flags = BSF_WEAK;
304       /* FALLTHRU */
305     case LDPK_DEF:
306       flags |= BSF_GLOBAL;
307       if (ldsym->comdat_key)
308         {
309           char *name = concat (".gnu.linkonce.t.", ldsym->comdat_key,
310                                (const char *) NULL);
311           section = bfd_get_section_by_name (abfd, name);
312           if (section != NULL)
313             free (name);
314           else
315             {
316               flagword sflags;
317
318               sflags = (SEC_CODE | SEC_HAS_CONTENTS | SEC_READONLY
319                         | SEC_ALLOC | SEC_LOAD | SEC_KEEP | SEC_EXCLUDE
320                         | SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD);
321               section = bfd_make_section_anyway_with_flags (abfd, name, sflags);
322               if (section == NULL)
323                 return LDPS_ERR;
324             }
325         }
326       else
327         section = bfd_get_section_by_name (abfd, ".text");
328       break;
329
330     case LDPK_WEAKUNDEF:
331       flags = BSF_WEAK;
332       /* FALLTHRU */
333     case LDPK_UNDEF:
334       section = bfd_und_section_ptr;
335       break;
336
337     case LDPK_COMMON:
338       flags = BSF_GLOBAL;
339       section = bfd_com_section_ptr;
340       asym->value = ldsym->size;
341       /* For ELF targets, set alignment of common symbol to 1.  */
342       if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
343         {
344           ((elf_symbol_type *) asym)->internal_elf_sym.st_shndx = SHN_COMMON;
345           ((elf_symbol_type *) asym)->internal_elf_sym.st_value = 1;
346         }
347       break;
348
349     default:
350       return LDPS_ERR;
351     }
352   asym->flags = flags;
353   asym->section = section;
354
355   /* Visibility only applies on ELF targets.  */
356   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
357     {
358       elf_symbol_type *elfsym = elf_symbol_from (abfd, asym);
359       unsigned char visibility;
360
361       if (!elfsym)
362         einfo (_("%P%F: %s: non-ELF symbol in ELF BFD!\n"), asym->name);
363       switch (ldsym->visibility)
364         {
365         default:
366           einfo (_("%P%F: unknown ELF symbol visibility: %d!\n"),
367                  ldsym->visibility);
368         case LDPV_DEFAULT:
369           visibility = STV_DEFAULT;
370           break;
371         case LDPV_PROTECTED:
372           visibility = STV_PROTECTED;
373           break;
374         case LDPV_INTERNAL:
375           visibility = STV_INTERNAL;
376           break;
377         case LDPV_HIDDEN:
378           visibility = STV_HIDDEN;
379           break;
380         }
381       elfsym->internal_elf_sym.st_other
382         = (visibility | (elfsym->internal_elf_sym.st_other
383                          & ~ELF_ST_VISIBILITY (-1)));
384     }
385
386   return LDPS_OK;
387 }
388
389 /* Register a claim-file handler.  */
390 static enum ld_plugin_status
391 register_claim_file (ld_plugin_claim_file_handler handler)
392 {
393   ASSERT (called_plugin);
394   called_plugin->claim_file_handler = handler;
395   return LDPS_OK;
396 }
397
398 /* Register an all-symbols-read handler.  */
399 static enum ld_plugin_status
400 register_all_symbols_read (ld_plugin_all_symbols_read_handler handler)
401 {
402   ASSERT (called_plugin);
403   called_plugin->all_symbols_read_handler = handler;
404   return LDPS_OK;
405 }
406
407 /* Register a cleanup handler.  */
408 static enum ld_plugin_status
409 register_cleanup (ld_plugin_cleanup_handler handler)
410 {
411   ASSERT (called_plugin);
412   called_plugin->cleanup_handler = handler;
413   return LDPS_OK;
414 }
415
416 /* Add symbols from a plugin-claimed input file.  */
417 static enum ld_plugin_status
418 add_symbols (void *handle, int nsyms, const struct ld_plugin_symbol *syms)
419 {
420   asymbol **symptrs;
421   bfd *abfd = handle;
422   int n;
423
424   ASSERT (called_plugin);
425   symptrs = xmalloc (nsyms * sizeof *symptrs);
426   for (n = 0; n < nsyms; n++)
427     {
428       enum ld_plugin_status rv;
429       asymbol *bfdsym;
430
431       bfdsym = bfd_make_empty_symbol (abfd);
432       symptrs[n] = bfdsym;
433       rv = asymbol_from_plugin_symbol (abfd, bfdsym, syms + n);
434       if (rv != LDPS_OK)
435         return rv;
436     }
437   bfd_set_symtab (abfd, symptrs, nsyms);
438   return LDPS_OK;
439 }
440
441 /* Get the input file information with an open (possibly re-opened)
442    file descriptor.  */
443 static enum ld_plugin_status
444 get_input_file (const void *handle ATTRIBUTE_UNUSED,
445                 struct ld_plugin_input_file *file ATTRIBUTE_UNUSED)
446 {
447   ASSERT (called_plugin);
448   return LDPS_ERR;
449 }
450
451 /* Release the input file.  */
452 static enum ld_plugin_status
453 release_input_file (const void *handle ATTRIBUTE_UNUSED)
454 {
455   ASSERT (called_plugin);
456   return LDPS_ERR;
457 }
458
459 /* Return TRUE if a defined symbol might be reachable from outside the
460    universe of claimed objects.  */
461 static inline bfd_boolean
462 is_visible_from_outside (struct ld_plugin_symbol *lsym,
463                          struct bfd_link_hash_entry *blhe)
464 {
465   struct bfd_sym_chain *sym;
466
467   if (link_info.relocatable)
468     return TRUE;
469   if (link_info.export_dynamic || !link_info.executable)
470     {
471       /* Check if symbol is hidden by version script.  */
472       if (bfd_hide_sym_by_version (link_info.version_info,
473                                    blhe->root.string))
474         return FALSE;
475       /* Only ELF symbols really have visibility.  */
476       if (bfd_get_flavour (link_info.output_bfd) == bfd_target_elf_flavour)
477         {
478           struct elf_link_hash_entry *el = (struct elf_link_hash_entry *)blhe;
479           int vis = ELF_ST_VISIBILITY (el->other);
480           return vis == STV_DEFAULT || vis == STV_PROTECTED;
481         }
482       /* On non-ELF targets, we can safely make inferences by considering
483          what visibility the plugin would have liked to apply when it first
484          sent us the symbol.  During ELF symbol processing, visibility only
485          ever becomes more restrictive, not less, when symbols are merged,
486          so this is a conservative estimate; it may give false positives,
487          declaring something visible from outside when it in fact would
488          not have been, but this will only lead to missed optimisation
489          opportunities during LTRANS at worst; it will not give false
490          negatives, which can lead to the disastrous conclusion that the
491          related symbol is IRONLY.  (See GCC PR46319 for an example.)  */
492       return (lsym->visibility == LDPV_DEFAULT
493               || lsym->visibility == LDPV_PROTECTED);
494     }
495
496   for (sym = &entry_symbol; sym != NULL; sym = sym->next)
497     if (sym->name
498         && strcmp (sym->name, blhe->root.string) == 0)
499       return TRUE;
500
501   return FALSE;
502 }
503
504 /* Get the symbol resolution info for a plugin-claimed input file.  */
505 static enum ld_plugin_status
506 get_symbols (const void *handle, int nsyms, struct ld_plugin_symbol *syms,
507              int def_ironly_exp)
508 {
509   const bfd *abfd = handle;
510   int n;
511
512   ASSERT (called_plugin);
513   for (n = 0; n < nsyms; n++)
514     {
515       struct bfd_link_hash_entry *blhe;
516       asection *owner_sec;
517       int res;
518
519       if (syms[n].def != LDPK_UNDEF)
520         blhe = bfd_link_hash_lookup (link_info.hash, syms[n].name,
521                                      FALSE, FALSE, TRUE);
522       else
523         blhe = bfd_wrapped_link_hash_lookup (link_info.output_bfd, &link_info,
524                                              syms[n].name, FALSE, FALSE, TRUE);
525       if (!blhe)
526         {
527           res = LDPR_UNKNOWN;
528           goto report_symbol;
529         }
530
531       /* Determine resolution from blhe type and symbol's original type.  */
532       if (blhe->type == bfd_link_hash_undefined
533           || blhe->type == bfd_link_hash_undefweak)
534         {
535           res = LDPR_UNDEF;
536           goto report_symbol;
537         }
538       if (blhe->type != bfd_link_hash_defined
539           && blhe->type != bfd_link_hash_defweak
540           && blhe->type != bfd_link_hash_common)
541         {
542           /* We should not have a new, indirect or warning symbol here.  */
543           einfo ("%P%F: %s: plugin symbol table corrupt (sym type %d)\n",
544                  called_plugin->name, blhe->type);
545         }
546
547       /* Find out which section owns the symbol.  Since it's not undef,
548          it must have an owner; if it's not a common symbol, both defs
549          and weakdefs keep it in the same place. */
550       owner_sec = (blhe->type == bfd_link_hash_common
551                    ? blhe->u.c.p->section
552                    : blhe->u.def.section);
553
554
555       /* If it was originally undefined or common, then it has been
556          resolved; determine how.  */
557       if (syms[n].def == LDPK_UNDEF
558           || syms[n].def == LDPK_WEAKUNDEF
559           || syms[n].def == LDPK_COMMON)
560         {
561           if (owner_sec->owner == link_info.output_bfd)
562             res = LDPR_RESOLVED_EXEC;
563           else if (owner_sec->owner == abfd)
564             res = LDPR_PREVAILING_DEF_IRONLY;
565           else if (is_ir_dummy_bfd (owner_sec->owner))
566             res = LDPR_RESOLVED_IR;
567           else if (owner_sec->owner != NULL
568                    && (owner_sec->owner->flags & DYNAMIC) != 0)
569             res = LDPR_RESOLVED_DYN;
570           else
571             res = LDPR_RESOLVED_EXEC;
572         }
573
574       /* Was originally def, or weakdef.  Does it prevail?  If the
575          owner is the original dummy bfd that supplied it, then this
576          is the definition that has prevailed.  */
577       else if (owner_sec->owner == link_info.output_bfd)
578         res = LDPR_PREEMPTED_REG;
579       else if (owner_sec->owner == abfd)
580         res = LDPR_PREVAILING_DEF_IRONLY;
581
582       /* Was originally def, weakdef, or common, but has been pre-empted.  */
583       else if (is_ir_dummy_bfd (owner_sec->owner))
584         res = LDPR_PREEMPTED_IR;
585       else
586         res = LDPR_PREEMPTED_REG;
587
588       if (res == LDPR_PREVAILING_DEF_IRONLY)
589         {
590           /* We need to know if the sym is referenced from non-IR files.  Or
591              even potentially-referenced, perhaps in a future final link if
592              this is a partial one, perhaps dynamically at load-time if the
593              symbol is externally visible.  */
594           if (blhe->non_ir_ref)
595             res = LDPR_PREVAILING_DEF;
596           else if (is_visible_from_outside (&syms[n], blhe))
597             res = def_ironly_exp;
598         }
599
600     report_symbol:
601       syms[n].resolution = res;
602       if (report_plugin_symbols)
603         einfo (_("%P: %B: symbol `%s' "
604                  "definition: %d, visibility: %d, resolution: %d\n"),
605                abfd, syms[n].name,
606                syms[n].def, syms[n].visibility, res);
607     }
608   return LDPS_OK;
609 }
610
611 static enum ld_plugin_status
612 get_symbols_v1 (const void *handle, int nsyms, struct ld_plugin_symbol *syms)
613 {
614   return get_symbols (handle, nsyms, syms, LDPR_PREVAILING_DEF);
615 }
616
617 static enum ld_plugin_status
618 get_symbols_v2 (const void *handle, int nsyms, struct ld_plugin_symbol *syms)
619 {
620   return get_symbols (handle, nsyms, syms, LDPR_PREVAILING_DEF_IRONLY_EXP);
621 }
622
623 /* Add a new (real) input file generated by a plugin.  */
624 static enum ld_plugin_status
625 add_input_file (const char *pathname)
626 {
627   ASSERT (called_plugin);
628   if (!lang_add_input_file (xstrdup (pathname), lang_input_file_is_file_enum,
629                             NULL))
630     return LDPS_ERR;
631   return LDPS_OK;
632 }
633
634 /* Add a new (real) library required by a plugin.  */
635 static enum ld_plugin_status
636 add_input_library (const char *pathname)
637 {
638   ASSERT (called_plugin);
639   if (!lang_add_input_file (xstrdup (pathname), lang_input_file_is_l_enum,
640                             NULL))
641     return LDPS_ERR;
642   return LDPS_OK;
643 }
644
645 /* Set the extra library path to be used by libraries added via
646    add_input_library.  */
647 static enum ld_plugin_status
648 set_extra_library_path (const char *path)
649 {
650   ASSERT (called_plugin);
651   ldfile_add_library_path (xstrdup (path), FALSE);
652   return LDPS_OK;
653 }
654
655 /* Issue a diagnostic message from a plugin.  */
656 static enum ld_plugin_status
657 message (int level, const char *format, ...)
658 {
659   va_list args;
660   va_start (args, format);
661
662   switch (level)
663     {
664     case LDPL_INFO:
665       vfinfo (stdout, format, args, FALSE);
666       putchar ('\n');
667       break;
668     case LDPL_WARNING:
669       vfinfo (stdout, format, args, TRUE);
670       putchar ('\n');
671       break;
672     case LDPL_FATAL:
673     case LDPL_ERROR:
674     default:
675       {
676         char *newfmt = ACONCAT ((level == LDPL_FATAL ? "%P%F: " : "%P%X: ",
677                                  format, "\n", (const char *) NULL));
678         fflush (stdout);
679         vfinfo (stderr, newfmt, args, TRUE);
680         fflush (stderr);
681       }
682       break;
683     }
684
685   va_end (args);
686   return LDPS_OK;
687 }
688
689 /* Helper to size leading part of tv array and set it up. */
690 static void
691 set_tv_header (struct ld_plugin_tv *tv)
692 {
693   size_t i;
694
695   /* Version info.  */
696   static const unsigned int major = (unsigned)(BFD_VERSION / 100000000UL);
697   static const unsigned int minor = (unsigned)(BFD_VERSION / 1000000UL) % 100;
698
699   for (i = 0; i < tv_header_size; i++)
700     {
701       tv[i].tv_tag = tv_header_tags[i];
702 #define TVU(x) tv[i].tv_u.tv_ ## x
703       switch (tv[i].tv_tag)
704         {
705         case LDPT_MESSAGE:
706           TVU(message) = message;
707           break;
708         case LDPT_API_VERSION:
709           TVU(val) = LD_PLUGIN_API_VERSION;
710           break;
711         case LDPT_GNU_LD_VERSION:
712           TVU(val) = major * 100 + minor;
713           break;
714         case LDPT_LINKER_OUTPUT:
715           TVU(val) = (link_info.relocatable
716                       ? LDPO_REL
717                       : (link_info.executable
718                          ? (link_info.pie ? LDPO_PIE : LDPO_EXEC)
719                          : LDPO_DYN));
720           break;
721         case LDPT_OUTPUT_NAME:
722           TVU(string) = output_filename;
723           break;
724         case LDPT_REGISTER_CLAIM_FILE_HOOK:
725           TVU(register_claim_file) = register_claim_file;
726           break;
727         case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK:
728           TVU(register_all_symbols_read) = register_all_symbols_read;
729           break;
730         case LDPT_REGISTER_CLEANUP_HOOK:
731           TVU(register_cleanup) = register_cleanup;
732           break;
733         case LDPT_ADD_SYMBOLS:
734           TVU(add_symbols) = add_symbols;
735           break;
736         case LDPT_GET_INPUT_FILE:
737           TVU(get_input_file) = get_input_file;
738           break;
739         case LDPT_RELEASE_INPUT_FILE:
740           TVU(release_input_file) = release_input_file;
741           break;
742         case LDPT_GET_SYMBOLS:
743           TVU(get_symbols) = get_symbols_v1;
744           break;
745         case LDPT_GET_SYMBOLS_V2:
746           TVU(get_symbols) = get_symbols_v2;
747           break;
748         case LDPT_ADD_INPUT_FILE:
749           TVU(add_input_file) = add_input_file;
750           break;
751         case LDPT_ADD_INPUT_LIBRARY:
752           TVU(add_input_library) = add_input_library;
753           break;
754         case LDPT_SET_EXTRA_LIBRARY_PATH:
755           TVU(set_extra_library_path) = set_extra_library_path;
756           break;
757         default:
758           /* Added a new entry to the array without adding
759              a new case to set up its value is a bug.  */
760           FAIL ();
761         }
762 #undef TVU
763     }
764 }
765
766 /* Append the per-plugin args list and trailing LDPT_NULL to tv.  */
767 static void
768 set_tv_plugin_args (plugin_t *plugin, struct ld_plugin_tv *tv)
769 {
770   plugin_arg_t *arg = plugin->args;
771   while (arg)
772     {
773       tv->tv_tag = LDPT_OPTION;
774       tv->tv_u.tv_string = arg->arg;
775       arg = arg->next;
776       tv++;
777     }
778   tv->tv_tag = LDPT_NULL;
779   tv->tv_u.tv_val = 0;
780 }
781
782 /* Return true if any plugins are active this run.  Only valid
783    after options have been processed.  */
784 bfd_boolean
785 plugin_active_plugins_p (void)
786 {
787   return plugins_list != NULL;
788 }
789
790 /* Load up and initialise all plugins after argument parsing.  */
791 void
792 plugin_load_plugins (void)
793 {
794   struct ld_plugin_tv *my_tv;
795   unsigned int max_args = 0;
796   plugin_t *curplug = plugins_list;
797
798   /* If there are no plugins, we need do nothing this run.  */
799   if (!curplug)
800     return;
801
802   /* First pass over plugins to find max # args needed so that we
803      can size and allocate the tv array.  */
804   while (curplug)
805     {
806       if (curplug->n_args > max_args)
807         max_args = curplug->n_args;
808       curplug = curplug->next;
809     }
810
811   /* Allocate tv array and initialise constant part.  */
812   my_tv = xmalloc ((max_args + 1 + tv_header_size) * sizeof *my_tv);
813   set_tv_header (my_tv);
814
815   /* Pass over plugins again, activating them.  */
816   curplug = plugins_list;
817   while (curplug)
818     {
819       enum ld_plugin_status rv;
820       ld_plugin_onload onloadfn;
821
822       onloadfn = (ld_plugin_onload) dlsym (curplug->dlhandle, "onload");
823       if (!onloadfn)
824         onloadfn = (ld_plugin_onload) dlsym (curplug->dlhandle, "_onload");
825       if (!onloadfn)
826         einfo (_("%P%F: %s: error loading plugin: %s\n"),
827                curplug->name, dlerror ());
828       set_tv_plugin_args (curplug, &my_tv[tv_header_size]);
829       called_plugin = curplug;
830       rv = (*onloadfn) (my_tv);
831       called_plugin = NULL;
832       if (rv != LDPS_OK)
833         einfo (_("%P%F: %s: plugin error: %d\n"), curplug->name, rv);
834       curplug = curplug->next;
835     }
836
837   /* Since plugin(s) inited ok, assume they're going to want symbol
838      resolutions, which needs us to track which symbols are referenced
839      by non-IR files using the linker's notice callback.  */
840   orig_notice_all = link_info.notice_all;
841   orig_callbacks = link_info.callbacks;
842   plugin_callbacks = *orig_callbacks;
843   plugin_callbacks.notice = &plugin_notice;
844   link_info.notice_all = TRUE;
845   link_info.lto_plugin_active = TRUE;
846   link_info.callbacks = &plugin_callbacks;
847 }
848
849 /* Call 'claim file' hook for all plugins.  */
850 static int
851 plugin_call_claim_file (const struct ld_plugin_input_file *file, int *claimed)
852 {
853   plugin_t *curplug = plugins_list;
854   *claimed = FALSE;
855   if (no_more_claiming)
856     return 0;
857   while (curplug && !*claimed)
858     {
859       if (curplug->claim_file_handler)
860         {
861           enum ld_plugin_status rv;
862           called_plugin = curplug;
863           rv = (*curplug->claim_file_handler) (file, claimed);
864           called_plugin = NULL;
865           if (rv != LDPS_OK)
866             set_plugin_error (curplug->name);
867         }
868       curplug = curplug->next;
869     }
870   return plugin_error_p () ? -1 : 0;
871 }
872
873 void
874 plugin_maybe_claim (struct ld_plugin_input_file *file,
875                     lang_input_statement_type *entry)
876 {
877   int claimed = 0;
878
879   /* We create a dummy BFD, initially empty, to house whatever symbols
880      the plugin may want to add.  */
881   file->handle = plugin_get_ir_dummy_bfd (entry->the_bfd->filename,
882                                           entry->the_bfd);
883   if (plugin_call_claim_file (file, &claimed))
884     einfo (_("%P%F: %s: plugin reported error claiming file\n"),
885            plugin_error_plugin ());
886   /* fd belongs to us, not the plugin; but we don't need it.  */
887   close (file->fd);
888   if (claimed)
889     {
890       /* Discard the real file's BFD and substitute the dummy one.  */
891
892       /* BFD archive handling caches elements so we can't call
893          bfd_close for archives.  */
894       if (entry->the_bfd->my_archive == NULL)
895         bfd_close (entry->the_bfd);
896       entry->the_bfd = file->handle;
897       entry->flags.claimed = TRUE;
898       bfd_make_readable (entry->the_bfd);
899     }
900   else
901     {
902       /* If plugin didn't claim the file, we don't need the dummy bfd.
903          Can't avoid speculatively creating it, alas.  */
904       bfd_close_all_done (file->handle);
905       entry->flags.claimed = FALSE;
906     }
907 }
908
909 /* Call 'all symbols read' hook for all plugins.  */
910 int
911 plugin_call_all_symbols_read (void)
912 {
913   plugin_t *curplug = plugins_list;
914
915   /* Disable any further file-claiming.  */
916   no_more_claiming = TRUE;
917
918   while (curplug)
919     {
920       if (curplug->all_symbols_read_handler)
921         {
922           enum ld_plugin_status rv;
923           called_plugin = curplug;
924           rv = (*curplug->all_symbols_read_handler) ();
925           called_plugin = NULL;
926           if (rv != LDPS_OK)
927             set_plugin_error (curplug->name);
928         }
929       curplug = curplug->next;
930     }
931   return plugin_error_p () ? -1 : 0;
932 }
933
934 /* Call 'cleanup' hook for all plugins at exit.  */
935 void
936 plugin_call_cleanup (void)
937 {
938   plugin_t *curplug = plugins_list;
939   while (curplug)
940     {
941       if (curplug->cleanup_handler && !curplug->cleanup_done)
942         {
943           enum ld_plugin_status rv;
944           curplug->cleanup_done = TRUE;
945           called_plugin = curplug;
946           rv = (*curplug->cleanup_handler) ();
947           called_plugin = NULL;
948           if (rv != LDPS_OK)
949             info_msg (_("%P: %s: error in plugin cleanup: %d (ignored)\n"),
950                       curplug->name, rv);
951           dlclose (curplug->dlhandle);
952         }
953       curplug = curplug->next;
954     }
955 }
956
957 /* To determine which symbols should be resolved LDPR_PREVAILING_DEF
958    and which LDPR_PREVAILING_DEF_IRONLY, we notice all the symbols as
959    the linker adds them to the linker hash table.  Mark those
960    referenced from a non-IR file with non_ir_ref.  We have to
961    notice_all symbols, because we won't necessarily know until later
962    which ones will be contributed by IR files.  */
963 static bfd_boolean
964 plugin_notice (struct bfd_link_info *info,
965                struct bfd_link_hash_entry *h,
966                struct bfd_link_hash_entry *inh,
967                bfd *abfd,
968                asection *section,
969                bfd_vma value,
970                flagword flags)
971 {
972   struct bfd_link_hash_entry *orig_h = h;
973
974   if (h != NULL)
975     {
976       bfd *sym_bfd;
977
978       if (h->type == bfd_link_hash_warning)
979         h = h->u.i.link;
980
981       /* Nothing to do here if this def/ref is from an IR dummy BFD.  */
982       if (is_ir_dummy_bfd (abfd))
983         ;
984
985       /* Making an indirect symbol counts as a reference unless this
986          is a brand new symbol.  */
987       else if (bfd_is_ind_section (section)
988                || (flags & BSF_INDIRECT) != 0)
989         {
990           /* ??? Some of this is questionable.  See comments in
991              _bfd_generic_link_add_one_symbol for case IND.  */
992           if (h->type != bfd_link_hash_new)
993             {
994               h->non_ir_ref = TRUE;
995               inh->non_ir_ref = TRUE;
996             }
997           else if (inh->type == bfd_link_hash_new)
998             inh->non_ir_ref = TRUE;
999         }
1000
1001       /* Nothing to do here for warning symbols.  */
1002       else if ((flags & BSF_WARNING) != 0)
1003         ;
1004
1005       /* Nothing to do here for constructor symbols.  */
1006       else if ((flags & BSF_CONSTRUCTOR) != 0)
1007         ;
1008
1009       /* If this is a ref, set non_ir_ref.  */
1010       else if (bfd_is_und_section (section))
1011         {
1012           /* Replace the undefined dummy bfd with the real one.  */
1013           if ((h->type == bfd_link_hash_undefined
1014                || h->type == bfd_link_hash_undefweak)
1015               && (h->u.undef.abfd == NULL
1016                   || (h->u.undef.abfd->flags & BFD_PLUGIN) != 0))
1017             h->u.undef.abfd = abfd;
1018           h->non_ir_ref = TRUE;
1019         }
1020
1021       /* Otherwise, it must be a new def.  Ensure any symbol defined
1022          in an IR dummy BFD takes on a new value from a real BFD.
1023          Weak symbols are not normally overridden by a new weak
1024          definition, and strong symbols will normally cause multiple
1025          definition errors.  Avoid this by making the symbol appear
1026          to be undefined.  */
1027       else if (((h->type == bfd_link_hash_defweak
1028                  || h->type == bfd_link_hash_defined)
1029                 && is_ir_dummy_bfd (sym_bfd = h->u.def.section->owner))
1030                || (h->type == bfd_link_hash_common
1031                    && is_ir_dummy_bfd (sym_bfd = h->u.c.p->section->owner)))
1032         {
1033           h->type = bfd_link_hash_undefweak;
1034           h->u.undef.abfd = sym_bfd;
1035         }
1036     }
1037
1038   /* Continue with cref/nocrossref/trace-sym processing.  */
1039   if (orig_h == NULL
1040       || orig_notice_all
1041       || (info->notice_hash != NULL
1042           && bfd_hash_lookup (info->notice_hash, orig_h->root.string,
1043                               FALSE, FALSE) != NULL))
1044     return (*orig_callbacks->notice) (info, orig_h, inh,
1045                                       abfd, section, value, flags);
1046   return TRUE;
1047 }