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