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