Add new plugin hooks to support querying section alignment and size.
[external/binutils.git] / gold / plugin.cc
1 // plugin.cc -- plugin manager for gold      -*- C++ -*-
2
3 // Copyright (C) 2008-2016 Free Software Foundation, Inc.
4 // Written by Cary Coutant <ccoutant@google.com>.
5
6 // This file is part of gold.
7
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 3 of the License, or
11 // (at your option) any later version.
12
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
21 // MA 02110-1301, USA.
22
23 #include "gold.h"
24
25 #include <cstdio>
26 #include <cstdarg>
27 #include <cstring>
28 #include <string>
29 #include <vector>
30
31 #ifdef ENABLE_PLUGINS
32 #ifdef HAVE_DLFCN_H
33 #include <dlfcn.h>
34 #elif defined (HAVE_WINDOWS_H)
35 #include <windows.h>
36 #else
37 #error Unknown how to handle dynamic-load-libraries.
38 #endif
39
40 #if !defined (HAVE_DLFCN_H) && defined (HAVE_WINDOWS_H)
41
42 #define RTLD_NOW 0      /* Dummy value.  */
43 static void *
44 dlopen(const char *file, int mode ATTRIBUTE_UNUSED)
45 {
46   return LoadLibrary(file);
47 }
48
49 static void *
50 dlsym(void *handle, const char *name)
51 {
52   return reinterpret_cast<void *>(
53      GetProcAddress(static_cast<HMODULE>(handle),name));
54 }
55
56 static const char *
57 dlerror(void)
58 {
59   return "unable to load dll";
60 }
61
62 #endif /* !defined (HAVE_DLFCN_H) && defined (HAVE_WINDOWS_H)  */
63 #endif /* ENABLE_PLUGINS */
64
65 #include "parameters.h"
66 #include "errors.h"
67 #include "fileread.h"
68 #include "layout.h"
69 #include "options.h"
70 #include "plugin.h"
71 #include "target.h"
72 #include "readsyms.h"
73 #include "symtab.h"
74 #include "descriptors.h"
75 #include "elfcpp.h"
76
77 namespace gold
78 {
79
80 #ifdef ENABLE_PLUGINS
81
82 // The linker's exported interfaces.
83
84 extern "C"
85 {
86
87 static enum ld_plugin_status
88 register_claim_file(ld_plugin_claim_file_handler handler);
89
90 static enum ld_plugin_status
91 register_all_symbols_read(ld_plugin_all_symbols_read_handler handler);
92
93 static enum ld_plugin_status
94 register_cleanup(ld_plugin_cleanup_handler handler);
95
96 static enum ld_plugin_status
97 add_symbols(void *handle, int nsyms, const struct ld_plugin_symbol *syms);
98
99 static enum ld_plugin_status
100 get_input_file(const void *handle, struct ld_plugin_input_file *file);
101
102 static enum ld_plugin_status
103 get_view(const void *handle, const void **viewp);
104
105 static enum ld_plugin_status
106 release_input_file(const void *handle);
107
108 static enum ld_plugin_status
109 get_symbols(const void *handle, int nsyms, struct ld_plugin_symbol *syms);
110
111 static enum ld_plugin_status
112 get_symbols_v2(const void *handle, int nsyms, struct ld_plugin_symbol *syms);
113
114 static enum ld_plugin_status
115 get_symbols_v3(const void *handle, int nsyms, struct ld_plugin_symbol *syms);
116
117 static enum ld_plugin_status
118 add_input_file(const char *pathname);
119
120 static enum ld_plugin_status
121 add_input_library(const char *pathname);
122
123 static enum ld_plugin_status
124 set_extra_library_path(const char *path);
125
126 static enum ld_plugin_status
127 message(int level, const char *format, ...);
128
129 static enum ld_plugin_status
130 get_input_section_count(const void* handle, unsigned int* count);
131
132 static enum ld_plugin_status
133 get_input_section_type(const struct ld_plugin_section section,
134                        unsigned int* type);
135
136 static enum ld_plugin_status
137 get_input_section_name(const struct ld_plugin_section section,
138                        char** section_name_ptr);
139
140 static enum ld_plugin_status
141 get_input_section_contents(const struct ld_plugin_section section,
142                            const unsigned char** section_contents,
143                            size_t* len);
144
145 static enum ld_plugin_status
146 update_section_order(const struct ld_plugin_section *section_list,
147                      unsigned int num_sections);
148
149 static enum ld_plugin_status
150 allow_section_ordering();
151
152 static enum ld_plugin_status
153 allow_unique_segment_for_sections();
154
155 static enum ld_plugin_status
156 unique_segment_for_sections(const char* segment_name,
157                             uint64_t flags,
158                             uint64_t align,
159                             const struct ld_plugin_section *section_list,
160                             unsigned int num_sections);
161
162 static enum ld_plugin_status
163 get_input_section_alignment(const struct ld_plugin_section section,
164                             unsigned int* addralign);
165
166 static enum ld_plugin_status
167 get_input_section_size(const struct ld_plugin_section section,
168                        uint64_t* secsize);
169
170 };
171
172 #endif // ENABLE_PLUGINS
173
174 static Pluginobj* make_sized_plugin_object(Input_file* input_file,
175                                            off_t offset, off_t filesize);
176
177 // Plugin methods.
178
179 // Load one plugin library.
180
181 void
182 Plugin::load()
183 {
184 #ifdef ENABLE_PLUGINS
185   // Load the plugin library.
186   // FIXME: Look for the library in standard locations.
187   this->handle_ = dlopen(this->filename_.c_str(), RTLD_NOW);
188   if (this->handle_ == NULL)
189     {
190       gold_error(_("%s: could not load plugin library: %s"),
191                  this->filename_.c_str(), dlerror());
192       return;
193     }
194
195   // Find the plugin's onload entry point.
196   void* ptr = dlsym(this->handle_, "onload");
197   if (ptr == NULL)
198     {
199       gold_error(_("%s: could not find onload entry point"),
200                  this->filename_.c_str());
201       return;
202     }
203   ld_plugin_onload onload;
204   gold_assert(sizeof(onload) == sizeof(ptr));
205   memcpy(&onload, &ptr, sizeof(ptr));
206
207   // Get the linker's version number.
208   const char* ver = get_version_string();
209   int major = 0;
210   int minor = 0;
211   sscanf(ver, "%d.%d", &major, &minor);
212
213   // Allocate and populate a transfer vector.
214   const int tv_fixed_size = 29;
215
216   int tv_size = this->args_.size() + tv_fixed_size;
217   ld_plugin_tv* tv = new ld_plugin_tv[tv_size];
218
219   // Put LDPT_MESSAGE at the front of the list so the plugin can use it
220   // while processing subsequent entries.
221   int i = 0;
222   tv[i].tv_tag = LDPT_MESSAGE;
223   tv[i].tv_u.tv_message = message;
224
225   ++i;
226   tv[i].tv_tag = LDPT_API_VERSION;
227   tv[i].tv_u.tv_val = LD_PLUGIN_API_VERSION;
228
229   ++i;
230   tv[i].tv_tag = LDPT_GOLD_VERSION;
231   tv[i].tv_u.tv_val = major * 100 + minor;
232
233   ++i;
234   tv[i].tv_tag = LDPT_LINKER_OUTPUT;
235   if (parameters->options().relocatable())
236     tv[i].tv_u.tv_val = LDPO_REL;
237   else if (parameters->options().shared())
238     tv[i].tv_u.tv_val = LDPO_DYN;
239   else if (parameters->options().pie())
240     tv[i].tv_u.tv_val = LDPO_PIE;
241   else
242     tv[i].tv_u.tv_val = LDPO_EXEC;
243
244   ++i;
245   tv[i].tv_tag = LDPT_OUTPUT_NAME;
246   tv[i].tv_u.tv_string = parameters->options().output();
247
248   for (unsigned int j = 0; j < this->args_.size(); ++j)
249     {
250       ++i;
251       tv[i].tv_tag = LDPT_OPTION;
252       tv[i].tv_u.tv_string = this->args_[j].c_str();
253     }
254
255   ++i;
256   tv[i].tv_tag = LDPT_REGISTER_CLAIM_FILE_HOOK;
257   tv[i].tv_u.tv_register_claim_file = register_claim_file;
258
259   ++i;
260   tv[i].tv_tag = LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK;
261   tv[i].tv_u.tv_register_all_symbols_read = register_all_symbols_read;
262
263   ++i;
264   tv[i].tv_tag = LDPT_REGISTER_CLEANUP_HOOK;
265   tv[i].tv_u.tv_register_cleanup = register_cleanup;
266
267   ++i;
268   tv[i].tv_tag = LDPT_ADD_SYMBOLS;
269   tv[i].tv_u.tv_add_symbols = add_symbols;
270
271   ++i;
272   tv[i].tv_tag = LDPT_GET_INPUT_FILE;
273   tv[i].tv_u.tv_get_input_file = get_input_file;
274
275   ++i;
276   tv[i].tv_tag = LDPT_GET_VIEW;
277   tv[i].tv_u.tv_get_view = get_view;
278
279   ++i;
280   tv[i].tv_tag = LDPT_RELEASE_INPUT_FILE;
281   tv[i].tv_u.tv_release_input_file = release_input_file;
282
283   ++i;
284   tv[i].tv_tag = LDPT_GET_SYMBOLS;
285   tv[i].tv_u.tv_get_symbols = get_symbols;
286
287   ++i;
288   tv[i].tv_tag = LDPT_GET_SYMBOLS_V2;
289   tv[i].tv_u.tv_get_symbols = get_symbols_v2;
290
291   ++i;
292   tv[i].tv_tag = LDPT_GET_SYMBOLS_V3;
293   tv[i].tv_u.tv_get_symbols = get_symbols_v3;
294
295   ++i;
296   tv[i].tv_tag = LDPT_ADD_INPUT_FILE;
297   tv[i].tv_u.tv_add_input_file = add_input_file;
298
299   ++i;
300   tv[i].tv_tag = LDPT_ADD_INPUT_LIBRARY;
301   tv[i].tv_u.tv_add_input_library = add_input_library;
302
303   ++i;
304   tv[i].tv_tag = LDPT_SET_EXTRA_LIBRARY_PATH;
305   tv[i].tv_u.tv_set_extra_library_path = set_extra_library_path;
306
307   ++i;
308   tv[i].tv_tag = LDPT_GET_INPUT_SECTION_COUNT;
309   tv[i].tv_u.tv_get_input_section_count = get_input_section_count;
310
311   ++i;
312   tv[i].tv_tag = LDPT_GET_INPUT_SECTION_TYPE;
313   tv[i].tv_u.tv_get_input_section_type = get_input_section_type;
314
315   ++i;
316   tv[i].tv_tag = LDPT_GET_INPUT_SECTION_NAME;
317   tv[i].tv_u.tv_get_input_section_name = get_input_section_name;
318
319   ++i;
320   tv[i].tv_tag = LDPT_GET_INPUT_SECTION_CONTENTS;
321   tv[i].tv_u.tv_get_input_section_contents = get_input_section_contents;
322
323   ++i;
324   tv[i].tv_tag = LDPT_UPDATE_SECTION_ORDER;
325   tv[i].tv_u.tv_update_section_order = update_section_order;
326
327   ++i;
328   tv[i].tv_tag = LDPT_ALLOW_SECTION_ORDERING;
329   tv[i].tv_u.tv_allow_section_ordering = allow_section_ordering;
330
331   ++i;
332   tv[i].tv_tag = LDPT_ALLOW_UNIQUE_SEGMENT_FOR_SECTIONS;
333   tv[i].tv_u.tv_allow_unique_segment_for_sections
334     = allow_unique_segment_for_sections;
335
336   ++i;
337   tv[i].tv_tag = LDPT_UNIQUE_SEGMENT_FOR_SECTIONS;
338   tv[i].tv_u.tv_unique_segment_for_sections = unique_segment_for_sections;
339
340   ++i;
341   tv[i].tv_tag = LDPT_GET_INPUT_SECTION_ALIGNMENT;
342   tv[i].tv_u.tv_get_input_section_alignment = get_input_section_alignment;
343
344   ++i;
345   tv[i].tv_tag = LDPT_GET_INPUT_SECTION_SIZE;
346   tv[i].tv_u.tv_get_input_section_size = get_input_section_size;
347
348   ++i;
349   tv[i].tv_tag = LDPT_NULL;
350   tv[i].tv_u.tv_val = 0;
351
352   gold_assert(i == tv_size - 1);
353
354   // Call the onload entry point.
355   (*onload)(tv);
356
357   delete[] tv;
358 #endif // ENABLE_PLUGINS
359 }
360
361 // Call the plugin claim-file handler.
362
363 inline bool
364 Plugin::claim_file(struct ld_plugin_input_file* plugin_input_file)
365 {
366   int claimed = 0;
367
368   if (this->claim_file_handler_ != NULL)
369     {
370       (*this->claim_file_handler_)(plugin_input_file, &claimed);
371       if (claimed)
372         return true;
373     }
374   return false;
375 }
376
377 // Call the all-symbols-read handler.
378
379 inline void
380 Plugin::all_symbols_read()
381 {
382   if (this->all_symbols_read_handler_ != NULL)
383     (*this->all_symbols_read_handler_)();
384 }
385
386 // Call the cleanup handler.
387
388 inline void
389 Plugin::cleanup()
390 {
391   if (this->cleanup_handler_ != NULL && !this->cleanup_done_)
392     {
393       // Set this flag before calling to prevent a recursive plunge
394       // in the event that a plugin's cleanup handler issues a
395       // fatal error.
396       this->cleanup_done_ = true;
397       (*this->cleanup_handler_)();
398     }
399 }
400
401 // This task is used to rescan archives as needed.
402
403 class Plugin_rescan : public Task
404 {
405  public:
406   Plugin_rescan(Task_token* this_blocker, Task_token* next_blocker)
407     : this_blocker_(this_blocker), next_blocker_(next_blocker)
408   { }
409
410   ~Plugin_rescan()
411   {
412     delete this->this_blocker_;
413   }
414
415   Task_token*
416   is_runnable()
417   {
418     if (this->this_blocker_->is_blocked())
419       return this->this_blocker_;
420     return NULL;
421   }
422
423   void
424   locks(Task_locker* tl)
425   { tl->add(this, this->next_blocker_); }
426
427   void
428   run(Workqueue*)
429   { parameters->options().plugins()->rescan(this); }
430
431   std::string
432   get_name() const
433   { return "Plugin_rescan"; }
434
435  private:
436   Task_token* this_blocker_;
437   Task_token* next_blocker_;
438 };
439
440 // Plugin_manager methods.
441
442 Plugin_manager::~Plugin_manager()
443 {
444   for (Plugin_list::iterator p = this->plugins_.begin();
445        p != this->plugins_.end();
446        ++p)
447     delete *p;
448   this->plugins_.clear();
449   for (Object_list::iterator obj = this->objects_.begin();
450        obj != this->objects_.end();
451        ++obj)
452     delete *obj;
453   this->objects_.clear();
454   delete this->lock_;
455 }
456
457 // Load all plugin libraries.
458
459 void
460 Plugin_manager::load_plugins(Layout* layout)
461 {
462   this->layout_ = layout;
463   for (this->current_ = this->plugins_.begin();
464        this->current_ != this->plugins_.end();
465        ++this->current_)
466     (*this->current_)->load();
467 }
468
469 // Call the plugin claim-file handlers in turn to see if any claim the file.
470
471 Pluginobj*
472 Plugin_manager::claim_file(Input_file* input_file, off_t offset,
473                            off_t filesize, Object* elf_object)
474 {
475   bool lock_initialized = this->initialize_lock_.initialize();
476
477   gold_assert(lock_initialized);
478   Hold_lock hl(*this->lock_);
479   if (this->in_replacement_phase_)
480     return NULL;
481
482   unsigned int handle = this->objects_.size();
483   this->input_file_ = input_file;
484   this->plugin_input_file_.name = input_file->filename().c_str();
485   this->plugin_input_file_.fd = input_file->file().descriptor();
486   this->plugin_input_file_.offset = offset;
487   this->plugin_input_file_.filesize = filesize;
488   this->plugin_input_file_.handle = reinterpret_cast<void*>(handle);
489   if (elf_object != NULL)
490     this->objects_.push_back(elf_object);
491   this->in_claim_file_handler_ = true;
492
493   for (this->current_ = this->plugins_.begin();
494        this->current_ != this->plugins_.end();
495        ++this->current_)
496     {
497       if ((*this->current_)->claim_file(&this->plugin_input_file_))
498         {
499           this->any_claimed_ = true;
500           this->in_claim_file_handler_ = false;
501
502           if (this->objects_.size() > handle
503               && this->objects_[handle]->pluginobj() != NULL)
504             return this->objects_[handle]->pluginobj();
505
506           // If the plugin claimed the file but did not call the
507           // add_symbols callback, we need to create the Pluginobj now.
508           Pluginobj* obj = this->make_plugin_object(handle);
509           return obj;
510         }
511     }
512
513   this->in_claim_file_handler_ = false;
514   return NULL;
515 }
516
517 // Save an archive.  This is used so that a plugin can add a file
518 // which refers to a symbol which was not previously referenced.  In
519 // that case we want to pretend that the symbol was referenced before,
520 // and pull in the archive object.
521
522 void
523 Plugin_manager::save_archive(Archive* archive)
524 {
525   if (this->in_replacement_phase_ || !this->any_claimed_)
526     delete archive;
527   else
528     this->rescannable_.push_back(Rescannable(archive));
529 }
530
531 // Save an Input_group.  This is like save_archive.
532
533 void
534 Plugin_manager::save_input_group(Input_group* input_group)
535 {
536   if (this->in_replacement_phase_ || !this->any_claimed_)
537     delete input_group;
538   else
539     this->rescannable_.push_back(Rescannable(input_group));
540 }
541
542 // Call the all-symbols-read handlers.
543
544 void
545 Plugin_manager::all_symbols_read(Workqueue* workqueue, Task* task,
546                                  Input_objects* input_objects,
547                                  Symbol_table* symtab,
548                                  Dirsearch* dirpath, Mapfile* mapfile,
549                                  Task_token** last_blocker)
550 {
551   this->in_replacement_phase_ = true;
552   this->workqueue_ = workqueue;
553   this->task_ = task;
554   this->input_objects_ = input_objects;
555   this->symtab_ = symtab;
556   this->dirpath_ = dirpath;
557   this->mapfile_ = mapfile;
558   this->this_blocker_ = NULL;
559
560   for (this->current_ = this->plugins_.begin();
561        this->current_ != this->plugins_.end();
562        ++this->current_)
563     (*this->current_)->all_symbols_read();
564
565   if (this->any_added_)
566     {
567       Task_token* next_blocker = new Task_token(true);
568       next_blocker->add_blocker();
569       workqueue->queue(new Plugin_rescan(this->this_blocker_, next_blocker));
570       this->this_blocker_ = next_blocker;
571     }
572
573   *last_blocker = this->this_blocker_;
574 }
575
576 // This is called when we see a new undefined symbol.  If we are in
577 // the replacement phase, this means that we may need to rescan some
578 // archives we have previously seen.
579
580 void
581 Plugin_manager::new_undefined_symbol(Symbol* sym)
582 {
583   if (this->in_replacement_phase_)
584     this->undefined_symbols_.push_back(sym);
585 }
586
587 // Rescan archives as needed.  This handles the case where a new
588 // object file added by a plugin has an undefined reference to some
589 // symbol defined in an archive.
590
591 void
592 Plugin_manager::rescan(Task* task)
593 {
594   size_t rescan_pos = 0;
595   size_t rescan_size = this->rescannable_.size();
596   while (!this->undefined_symbols_.empty())
597     {
598       if (rescan_pos >= rescan_size)
599         {
600           this->undefined_symbols_.clear();
601           return;
602         }
603
604       Undefined_symbol_list undefs;
605       undefs.reserve(this->undefined_symbols_.size());
606       this->undefined_symbols_.swap(undefs);
607
608       size_t min_rescan_pos = rescan_size;
609
610       for (Undefined_symbol_list::const_iterator p = undefs.begin();
611            p != undefs.end();
612            ++p)
613         {
614           if (!(*p)->is_undefined())
615             continue;
616
617           this->undefined_symbols_.push_back(*p);
618
619           // Find the first rescan archive which defines this symbol,
620           // starting at the current rescan position.  The rescan position
621           // exists so that given -la -lb -lc we don't look for undefined
622           // symbols in -lb back in -la, but instead get the definition
623           // from -lc.  Don't bother to look past the current minimum
624           // rescan position.
625           for (size_t i = rescan_pos; i < min_rescan_pos; ++i)
626             {
627               if (this->rescannable_defines(i, *p))
628                 {
629                   min_rescan_pos = i;
630                   break;
631                 }
632             }
633         }
634
635       if (min_rescan_pos >= rescan_size)
636         {
637           // We didn't find any rescannable archives which define any
638           // undefined symbols.
639           return;
640         }
641
642       const Rescannable& r(this->rescannable_[min_rescan_pos]);
643       if (r.is_archive)
644         {
645           Task_lock_obj<Archive> tl(task, r.u.archive);
646           r.u.archive->add_symbols(this->symtab_, this->layout_,
647                                    this->input_objects_, this->mapfile_);
648         }
649       else
650         {
651           size_t next_saw_undefined = this->symtab_->saw_undefined();
652           size_t saw_undefined;
653           do
654             {
655               saw_undefined = next_saw_undefined;
656
657               for (Input_group::const_iterator p = r.u.input_group->begin();
658                    p != r.u.input_group->end();
659                    ++p)
660                 {
661                   Task_lock_obj<Archive> tl(task, *p);
662
663                   (*p)->add_symbols(this->symtab_, this->layout_,
664                                     this->input_objects_, this->mapfile_);
665                 }
666
667               next_saw_undefined = this->symtab_->saw_undefined();
668             }
669           while (saw_undefined != next_saw_undefined);
670         }
671
672       for (size_t i = rescan_pos; i < min_rescan_pos + 1; ++i)
673         {
674           if (this->rescannable_[i].is_archive)
675             delete this->rescannable_[i].u.archive;
676           else
677             delete this->rescannable_[i].u.input_group;
678         }
679
680       rescan_pos = min_rescan_pos + 1;
681     }
682 }
683
684 // Return whether the rescannable at index I defines SYM.
685
686 bool
687 Plugin_manager::rescannable_defines(size_t i, Symbol* sym)
688 {
689   const Rescannable& r(this->rescannable_[i]);
690   if (r.is_archive)
691     return r.u.archive->defines_symbol(sym);
692   else
693     {
694       for (Input_group::const_iterator p = r.u.input_group->begin();
695            p != r.u.input_group->end();
696            ++p)
697         {
698           if ((*p)->defines_symbol(sym))
699             return true;
700         }
701       return false;
702     }
703 }
704
705 // Layout deferred objects.
706
707 void
708 Plugin_manager::layout_deferred_objects()
709 {
710   Deferred_layout_list::iterator obj;
711
712   for (obj = this->deferred_layout_objects_.begin();
713        obj != this->deferred_layout_objects_.end();
714        ++obj)
715     {
716       // Lock the object so we can read from it.  This is only called
717       // single-threaded from queue_middle_tasks, so it is OK to lock.
718       // Unfortunately we have no way to pass in a Task token.
719       const Task* dummy_task = reinterpret_cast<const Task*>(-1);
720       Task_lock_obj<Object> tl(dummy_task, *obj);
721       (*obj)->layout_deferred_sections(this->layout_);
722     }
723 }
724
725 // Call the cleanup handlers.
726
727 void
728 Plugin_manager::cleanup()
729 {
730   if (this->any_added_)
731     {
732       // If any input files were added, close all the input files.
733       // This is because the plugin may want to remove them, and on
734       // Windows you are not allowed to remove an open file.
735       close_all_descriptors();
736     }
737
738   for (this->current_ = this->plugins_.begin();
739        this->current_ != this->plugins_.end();
740        ++this->current_)
741     (*this->current_)->cleanup();
742 }
743
744 // Make a new Pluginobj object.  This is called when the plugin calls
745 // the add_symbols API.
746
747 Pluginobj*
748 Plugin_manager::make_plugin_object(unsigned int handle)
749 {
750   // Make sure we aren't asked to make an object for the same handle twice.
751   if (this->objects_.size() != handle
752       && this->objects_[handle]->pluginobj() != NULL)
753     return NULL;
754
755   Pluginobj* obj = make_sized_plugin_object(this->input_file_,
756                                             this->plugin_input_file_.offset,
757                                             this->plugin_input_file_.filesize);
758
759
760   // If the elf object for this file was pushed into the objects_ vector, delete
761   // it to make room for the Pluginobj as this file is claimed.
762   if (this->objects_.size() != handle)
763     this->objects_.pop_back();
764
765   this->objects_.push_back(obj);
766   return obj;
767 }
768
769 // Get the input file information with an open (possibly re-opened)
770 // file descriptor.
771
772 ld_plugin_status
773 Plugin_manager::get_input_file(unsigned int handle,
774                                struct ld_plugin_input_file* file)
775 {
776   Pluginobj* obj = this->object(handle)->pluginobj();
777   if (obj == NULL)
778     return LDPS_BAD_HANDLE;
779
780   obj->lock(this->task_);
781   file->name = obj->filename().c_str();
782   file->fd = obj->descriptor();
783   file->offset = obj->offset();
784   file->filesize = obj->filesize();
785   file->handle = reinterpret_cast<void*>(handle);
786   return LDPS_OK;
787 }
788
789 // Release the input file.
790
791 ld_plugin_status
792 Plugin_manager::release_input_file(unsigned int handle)
793 {
794   if (this->object(handle) == NULL)
795     return LDPS_BAD_HANDLE;
796
797   Pluginobj* obj = this->object(handle)->pluginobj();
798
799   if (obj == NULL)
800     return LDPS_BAD_HANDLE;
801
802   obj->unlock(this->task_);
803   return LDPS_OK;
804 }
805
806 // Get the elf object corresponding to the handle. Return NULL if we
807 // found a Pluginobj instead.
808
809 Object*
810 Plugin_manager::get_elf_object(const void* handle)
811 {
812   Object* obj = this->object(
813       static_cast<unsigned int>(reinterpret_cast<intptr_t>(handle)));
814
815   // The object should not be a Pluginobj.
816   if (obj == NULL
817       || obj->pluginobj() != NULL)
818     return NULL;
819
820   return obj;
821 }
822
823 ld_plugin_status
824 Plugin_manager::get_view(unsigned int handle, const void **viewp)
825 {
826   off_t offset;
827   size_t filesize;
828   Input_file *input_file;
829   if (this->in_claim_file_handler_)
830     {
831       // We are being called from the claim_file hook.
832       const struct ld_plugin_input_file &f = this->plugin_input_file_;
833       offset = f.offset;
834       filesize = f.filesize;
835       input_file = this->input_file_;
836     }
837   else
838     {
839       // An already claimed file.
840       if (this->object(handle) == NULL)
841         return LDPS_BAD_HANDLE;
842       Pluginobj* obj = this->object(handle)->pluginobj();
843       if (obj == NULL)
844         return LDPS_BAD_HANDLE;
845       offset = obj->offset();
846       filesize = obj->filesize();
847       input_file = obj->input_file();
848     }
849   *viewp = (void*) input_file->file().get_view(offset, 0, filesize, false,
850                                                false);
851   return LDPS_OK;
852 }
853
854 // Add a new library path.
855
856 ld_plugin_status
857 Plugin_manager::set_extra_library_path(const char* path)
858 {
859   this->extra_search_path_ = std::string(path);
860   return LDPS_OK;
861 }
862
863 // Add a new input file.
864
865 ld_plugin_status
866 Plugin_manager::add_input_file(const char* pathname, bool is_lib)
867 {
868   Input_file_argument file(pathname,
869                            (is_lib
870                             ? Input_file_argument::INPUT_FILE_TYPE_LIBRARY
871                             : Input_file_argument::INPUT_FILE_TYPE_FILE),
872                            (is_lib
873                             ? this->extra_search_path_.c_str()
874                             : ""),
875                            false,
876                            this->options_);
877   Input_argument* input_argument = new Input_argument(file);
878   Task_token* next_blocker = new Task_token(true);
879   next_blocker->add_blocker();
880   if (parameters->incremental())
881     gold_error(_("input files added by plug-ins in --incremental mode not "
882                  "supported yet"));
883   this->workqueue_->queue_soon(new Read_symbols(this->input_objects_,
884                                                 this->symtab_,
885                                                 this->layout_,
886                                                 this->dirpath_,
887                                                 0,
888                                                 this->mapfile_,
889                                                 input_argument,
890                                                 NULL,
891                                                 NULL,
892                                                 this->this_blocker_,
893                                                 next_blocker));
894   this->this_blocker_ = next_blocker;
895   this->any_added_ = true;
896   return LDPS_OK;
897 }
898
899 // Class Pluginobj.
900
901 Pluginobj::Pluginobj(const std::string& name, Input_file* input_file,
902                      off_t offset, off_t filesize)
903   : Object(name, input_file, false, offset),
904     nsyms_(0), syms_(NULL), symbols_(), filesize_(filesize), comdat_map_()
905 {
906 }
907
908 // Return TRUE if a defined symbol is referenced from outside the
909 // universe of claimed objects.  Only references from relocatable,
910 // non-IR (unclaimed) objects count as a reference.  References from
911 // dynamic objects count only as "visible".
912
913 static inline bool
914 is_referenced_from_outside(Symbol* lsym)
915 {
916   if (lsym->in_real_elf())
917     return true;
918   if (parameters->options().relocatable())
919     return true;
920   if (parameters->options().is_undefined(lsym->name()))
921     return true;
922   return false;
923 }
924
925 // Return TRUE if a defined symbol might be reachable from outside the
926 // load module.
927
928 static inline bool
929 is_visible_from_outside(Symbol* lsym)
930 {
931   if (lsym->in_dyn())
932     return true;
933   if (parameters->options().export_dynamic() || parameters->options().shared())
934     return lsym->is_externally_visible();
935   return false;
936 }
937
938 // Get symbol resolution info.
939
940 ld_plugin_status
941 Pluginobj::get_symbol_resolution_info(Symbol_table* symtab,
942                                       int nsyms,
943                                       ld_plugin_symbol* syms,
944                                       int version) const
945 {
946   // For version 1 of this interface, we cannot use
947   // LDPR_PREVAILING_DEF_IRONLY_EXP, so we return LDPR_PREVAILING_DEF
948   // instead.
949   const ld_plugin_symbol_resolution ldpr_prevailing_def_ironly_exp
950       = (version > 1
951          ? LDPR_PREVAILING_DEF_IRONLY_EXP
952          : LDPR_PREVAILING_DEF);
953
954   if (nsyms > this->nsyms_)
955     return LDPS_NO_SYMS;
956
957   if (static_cast<size_t>(nsyms) > this->symbols_.size())
958     {
959       // We never decided to include this object. We mark all symbols as
960       // preempted.
961       gold_assert(this->symbols_.size() == 0);
962       for (int i = 0; i < nsyms; i++)
963         syms[i].resolution = LDPR_PREEMPTED_REG;
964       return version > 2 ? LDPS_NO_SYMS : LDPS_OK;
965     }
966
967   for (int i = 0; i < nsyms; i++)
968     {
969       ld_plugin_symbol* isym = &syms[i];
970       Symbol* lsym = this->symbols_[i];
971       if (lsym->is_forwarder())
972         lsym = symtab->resolve_forwards(lsym);
973       ld_plugin_symbol_resolution res = LDPR_UNKNOWN;
974
975       if (lsym->is_undefined())
976         // The symbol remains undefined.
977         res = LDPR_UNDEF;
978       else if (isym->def == LDPK_UNDEF
979                || isym->def == LDPK_WEAKUNDEF
980                || isym->def == LDPK_COMMON)
981         {
982           // The original symbol was undefined or common.
983           if (lsym->source() != Symbol::FROM_OBJECT)
984             res = LDPR_RESOLVED_EXEC;
985           else if (lsym->object()->pluginobj() == this)
986             {
987               if (is_referenced_from_outside(lsym))
988                 res = LDPR_PREVAILING_DEF;
989               else if (is_visible_from_outside(lsym))
990                 res = ldpr_prevailing_def_ironly_exp;
991               else
992                 res = LDPR_PREVAILING_DEF_IRONLY;
993             }
994           else if (lsym->object()->pluginobj() != NULL)
995             res = LDPR_RESOLVED_IR;
996           else if (lsym->object()->is_dynamic())
997             res = LDPR_RESOLVED_DYN;
998           else
999             res = LDPR_RESOLVED_EXEC;
1000         }
1001       else
1002         {
1003           // The original symbol was a definition.
1004           if (lsym->source() != Symbol::FROM_OBJECT)
1005             res = LDPR_PREEMPTED_REG;
1006           else if (lsym->object() == static_cast<const Object*>(this))
1007             {
1008               if (is_referenced_from_outside(lsym))
1009                 res = LDPR_PREVAILING_DEF;
1010               else if (is_visible_from_outside(lsym))
1011                 res = ldpr_prevailing_def_ironly_exp;
1012               else
1013                 res = LDPR_PREVAILING_DEF_IRONLY;
1014             }
1015           else
1016             res = (lsym->object()->pluginobj() != NULL
1017                    ? LDPR_PREEMPTED_IR
1018                    : LDPR_PREEMPTED_REG);
1019         }
1020       isym->resolution = res;
1021     }
1022   return LDPS_OK;
1023 }
1024
1025 // Return TRUE if the comdat group with key COMDAT_KEY from this object
1026 // should be kept.
1027
1028 bool
1029 Pluginobj::include_comdat_group(std::string comdat_key, Layout* layout)
1030 {
1031   std::pair<Comdat_map::iterator, bool> ins =
1032     this->comdat_map_.insert(std::make_pair(comdat_key, false));
1033
1034   // If this is the first time we've seen this comdat key, ask the
1035   // layout object whether it should be included.
1036   if (ins.second)
1037     ins.first->second = layout->find_or_add_kept_section(comdat_key,
1038                                                          NULL, 0, true,
1039                                                          true, NULL);
1040
1041   return ins.first->second;
1042 }
1043
1044 // Class Sized_pluginobj.
1045
1046 template<int size, bool big_endian>
1047 Sized_pluginobj<size, big_endian>::Sized_pluginobj(
1048     const std::string& name,
1049     Input_file* input_file,
1050     off_t offset,
1051     off_t filesize)
1052   : Pluginobj(name, input_file, offset, filesize)
1053 {
1054 }
1055
1056 // Read the symbols.  Not used for plugin objects.
1057
1058 template<int size, bool big_endian>
1059 void
1060 Sized_pluginobj<size, big_endian>::do_read_symbols(Read_symbols_data*)
1061 {
1062   gold_unreachable();
1063 }
1064
1065 // Lay out the input sections.  Not used for plugin objects.
1066
1067 template<int size, bool big_endian>
1068 void
1069 Sized_pluginobj<size, big_endian>::do_layout(Symbol_table*, Layout*,
1070                                              Read_symbols_data*)
1071 {
1072   gold_unreachable();
1073 }
1074
1075 // Add the symbols to the symbol table.
1076
1077 template<int size, bool big_endian>
1078 void
1079 Sized_pluginobj<size, big_endian>::do_add_symbols(Symbol_table* symtab,
1080                                                   Read_symbols_data*,
1081                                                   Layout* layout)
1082 {
1083   const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
1084   unsigned char symbuf[sym_size];
1085   elfcpp::Sym<size, big_endian> sym(symbuf);
1086   elfcpp::Sym_write<size, big_endian> osym(symbuf);
1087
1088   this->symbols_.resize(this->nsyms_);
1089
1090   for (int i = 0; i < this->nsyms_; ++i)
1091     {
1092       const struct ld_plugin_symbol* isym = &this->syms_[i];
1093       const char* name = isym->name;
1094       const char* ver = isym->version;
1095       elfcpp::Elf_Half shndx;
1096       elfcpp::STB bind;
1097       elfcpp::STV vis;
1098
1099       if (name != NULL && name[0] == '\0')
1100         name = NULL;
1101       if (ver != NULL && ver[0] == '\0')
1102         ver = NULL;
1103
1104       switch (isym->def)
1105         {
1106         case LDPK_WEAKDEF:
1107         case LDPK_WEAKUNDEF:
1108           bind = elfcpp::STB_WEAK;
1109           break;
1110         case LDPK_DEF:
1111         case LDPK_UNDEF:
1112         case LDPK_COMMON:
1113         default:
1114           bind = elfcpp::STB_GLOBAL;
1115           break;
1116         }
1117
1118       switch (isym->def)
1119         {
1120         case LDPK_DEF:
1121         case LDPK_WEAKDEF:
1122           shndx = elfcpp::SHN_ABS;
1123           break;
1124         case LDPK_COMMON:
1125           shndx = elfcpp::SHN_COMMON;
1126           break;
1127         case LDPK_UNDEF:
1128         case LDPK_WEAKUNDEF:
1129         default:
1130           shndx = elfcpp::SHN_UNDEF;
1131           break;
1132         }
1133
1134       switch (isym->visibility)
1135         {
1136         case LDPV_PROTECTED:
1137           vis = elfcpp::STV_PROTECTED;
1138           break;
1139         case LDPV_INTERNAL:
1140           vis = elfcpp::STV_INTERNAL;
1141           break;
1142         case LDPV_HIDDEN:
1143           vis = elfcpp::STV_HIDDEN;
1144           break;
1145         case LDPV_DEFAULT:
1146         default:
1147           vis = elfcpp::STV_DEFAULT;
1148           break;
1149         }
1150
1151       if (isym->comdat_key != NULL
1152           && isym->comdat_key[0] != '\0'
1153           && !this->include_comdat_group(isym->comdat_key, layout))
1154         shndx = elfcpp::SHN_UNDEF;
1155
1156       osym.put_st_name(0);
1157       osym.put_st_value(0);
1158       osym.put_st_size(0);
1159       osym.put_st_info(bind, elfcpp::STT_NOTYPE);
1160       osym.put_st_other(vis, 0);
1161       osym.put_st_shndx(shndx);
1162
1163       this->symbols_[i] =
1164         symtab->add_from_pluginobj<size, big_endian>(this, name, ver, &sym);
1165     }
1166 }
1167
1168 template<int size, bool big_endian>
1169 Archive::Should_include
1170 Sized_pluginobj<size, big_endian>::do_should_include_member(
1171     Symbol_table* symtab,
1172     Layout* layout,
1173     Read_symbols_data*,
1174     std::string* why)
1175 {
1176   char* tmpbuf = NULL;
1177   size_t tmpbuflen = 0;
1178
1179   for (int i = 0; i < this->nsyms_; ++i)
1180     {
1181       const struct ld_plugin_symbol& sym = this->syms_[i];
1182       const char* name = sym.name;
1183       Symbol* symbol;
1184       Archive::Should_include t = Archive::should_include_member(symtab,
1185                                                                  layout,
1186                                                                  name,
1187                                                                  &symbol, why,
1188                                                                  &tmpbuf,
1189                                                                  &tmpbuflen);
1190       if (t == Archive::SHOULD_INCLUDE_YES)
1191         {
1192           if (tmpbuf != NULL)
1193             free(tmpbuf);
1194           return t;
1195         }
1196     }
1197   if (tmpbuf != NULL)
1198     free(tmpbuf);
1199   return Archive::SHOULD_INCLUDE_UNKNOWN;
1200 }
1201
1202 // Iterate over global symbols, calling a visitor class V for each.
1203
1204 template<int size, bool big_endian>
1205 void
1206 Sized_pluginobj<size, big_endian>::do_for_all_global_symbols(
1207     Read_symbols_data*,
1208     Library_base::Symbol_visitor_base* v)
1209 {
1210   for (int i = 0; i < this->nsyms_; ++i)
1211     {
1212       const struct ld_plugin_symbol& sym = this->syms_[i];
1213       if (sym.def != LDPK_UNDEF)
1214         v->visit(sym.name);
1215     }
1216 }
1217
1218 // Iterate over local symbols, calling a visitor class V for each GOT offset
1219 // associated with a local symbol.
1220 template<int size, bool big_endian>
1221 void
1222 Sized_pluginobj<size, big_endian>::do_for_all_local_got_entries(
1223     Got_offset_list::Visitor*) const
1224 {
1225   gold_unreachable();
1226 }
1227
1228 // Get the size of a section.  Not used for plugin objects.
1229
1230 template<int size, bool big_endian>
1231 uint64_t
1232 Sized_pluginobj<size, big_endian>::do_section_size(unsigned int)
1233 {
1234   gold_unreachable();
1235   return 0;
1236 }
1237
1238 // Get the name of a section.  Not used for plugin objects.
1239
1240 template<int size, bool big_endian>
1241 std::string
1242 Sized_pluginobj<size, big_endian>::do_section_name(unsigned int) const
1243 {
1244   gold_unreachable();
1245   return std::string();
1246 }
1247
1248 // Return a view of the contents of a section.  Not used for plugin objects.
1249
1250 template<int size, bool big_endian>
1251 const unsigned char*
1252 Sized_pluginobj<size, big_endian>::do_section_contents(
1253     unsigned int,
1254     section_size_type*,
1255     bool)
1256 {
1257   gold_unreachable();
1258   return NULL;
1259 }
1260
1261 // Return section flags.  Not used for plugin objects.
1262
1263 template<int size, bool big_endian>
1264 uint64_t
1265 Sized_pluginobj<size, big_endian>::do_section_flags(unsigned int)
1266 {
1267   gold_unreachable();
1268   return 0;
1269 }
1270
1271 // Return section entsize.  Not used for plugin objects.
1272
1273 template<int size, bool big_endian>
1274 uint64_t
1275 Sized_pluginobj<size, big_endian>::do_section_entsize(unsigned int)
1276 {
1277   gold_unreachable();
1278   return 0;
1279 }
1280
1281 // Return section address.  Not used for plugin objects.
1282
1283 template<int size, bool big_endian>
1284 uint64_t
1285 Sized_pluginobj<size, big_endian>::do_section_address(unsigned int)
1286 {
1287   gold_unreachable();
1288   return 0;
1289 }
1290
1291 // Return section type.  Not used for plugin objects.
1292
1293 template<int size, bool big_endian>
1294 unsigned int
1295 Sized_pluginobj<size, big_endian>::do_section_type(unsigned int)
1296 {
1297   gold_unreachable();
1298   return 0;
1299 }
1300
1301 // Return the section link field.  Not used for plugin objects.
1302
1303 template<int size, bool big_endian>
1304 unsigned int
1305 Sized_pluginobj<size, big_endian>::do_section_link(unsigned int)
1306 {
1307   gold_unreachable();
1308   return 0;
1309 }
1310
1311 // Return the section link field.  Not used for plugin objects.
1312
1313 template<int size, bool big_endian>
1314 unsigned int
1315 Sized_pluginobj<size, big_endian>::do_section_info(unsigned int)
1316 {
1317   gold_unreachable();
1318   return 0;
1319 }
1320
1321 // Return the section alignment.  Not used for plugin objects.
1322
1323 template<int size, bool big_endian>
1324 uint64_t
1325 Sized_pluginobj<size, big_endian>::do_section_addralign(unsigned int)
1326 {
1327   gold_unreachable();
1328   return 0;
1329 }
1330
1331 // Return the Xindex structure to use.  Not used for plugin objects.
1332
1333 template<int size, bool big_endian>
1334 Xindex*
1335 Sized_pluginobj<size, big_endian>::do_initialize_xindex()
1336 {
1337   gold_unreachable();
1338   return NULL;
1339 }
1340
1341 // Get symbol counts.  Don't count plugin objects; the replacement
1342 // files will provide the counts.
1343
1344 template<int size, bool big_endian>
1345 void
1346 Sized_pluginobj<size, big_endian>::do_get_global_symbol_counts(
1347     const Symbol_table*,
1348     size_t* defined,
1349     size_t* used) const
1350 {
1351   *defined = 0;
1352   *used = 0;
1353 }
1354
1355 // Get symbols.  Not used for plugin objects.
1356
1357 template<int size, bool big_endian>
1358 const Object::Symbols*
1359 Sized_pluginobj<size, big_endian>::do_get_global_symbols() const
1360 {
1361   gold_unreachable();
1362 }
1363
1364 // Class Plugin_finish.  This task runs after all replacement files have
1365 // been added.  For now, it's a placeholder for a possible plugin API
1366 // to allow the plugin to release most of its resources.  The cleanup
1367 // handlers must be called later, because they can remove the temporary
1368 // object files that are needed until the end of the link.
1369
1370 class Plugin_finish : public Task
1371 {
1372  public:
1373   Plugin_finish(Task_token* this_blocker, Task_token* next_blocker)
1374     : this_blocker_(this_blocker), next_blocker_(next_blocker)
1375   { }
1376
1377   ~Plugin_finish()
1378   {
1379     if (this->this_blocker_ != NULL)
1380       delete this->this_blocker_;
1381   }
1382
1383   Task_token*
1384   is_runnable()
1385   {
1386     if (this->this_blocker_ != NULL && this->this_blocker_->is_blocked())
1387       return this->this_blocker_;
1388     return NULL;
1389   }
1390
1391   void
1392   locks(Task_locker* tl)
1393   { tl->add(this, this->next_blocker_); }
1394
1395   void
1396   run(Workqueue*)
1397   {
1398     // We could call early cleanup handlers here.
1399   }
1400
1401   std::string
1402   get_name() const
1403   { return "Plugin_finish"; }
1404
1405  private:
1406   Task_token* this_blocker_;
1407   Task_token* next_blocker_;
1408 };
1409
1410 // Class Plugin_hook.
1411
1412 Plugin_hook::~Plugin_hook()
1413 {
1414 }
1415
1416 // Return whether a Plugin_hook task is runnable.
1417
1418 Task_token*
1419 Plugin_hook::is_runnable()
1420 {
1421   if (this->this_blocker_ != NULL && this->this_blocker_->is_blocked())
1422     return this->this_blocker_;
1423   return NULL;
1424 }
1425
1426 // Return a Task_locker for a Plugin_hook task.  We don't need any
1427 // locks here.
1428
1429 void
1430 Plugin_hook::locks(Task_locker*)
1431 {
1432 }
1433
1434 // Run the "all symbols read" plugin hook.
1435
1436 void
1437 Plugin_hook::run(Workqueue* workqueue)
1438 {
1439   gold_assert(this->options_.has_plugins());
1440   Symbol* start_sym = this->symtab_->lookup(parameters->entry());
1441   if (start_sym != NULL)
1442     start_sym->set_in_real_elf();
1443
1444   this->options_.plugins()->all_symbols_read(workqueue,
1445                                              this,
1446                                              this->input_objects_,
1447                                              this->symtab_,
1448                                              this->dirpath_,
1449                                              this->mapfile_,
1450                                              &this->this_blocker_);
1451   workqueue->queue_soon(new Plugin_finish(this->this_blocker_,
1452                                           this->next_blocker_));
1453 }
1454
1455 // The C interface routines called by the plugins.
1456
1457 #ifdef ENABLE_PLUGINS
1458
1459 // Register a claim-file handler.
1460
1461 static enum ld_plugin_status
1462 register_claim_file(ld_plugin_claim_file_handler handler)
1463 {
1464   gold_assert(parameters->options().has_plugins());
1465   parameters->options().plugins()->set_claim_file_handler(handler);
1466   return LDPS_OK;
1467 }
1468
1469 // Register an all-symbols-read handler.
1470
1471 static enum ld_plugin_status
1472 register_all_symbols_read(ld_plugin_all_symbols_read_handler handler)
1473 {
1474   gold_assert(parameters->options().has_plugins());
1475   parameters->options().plugins()->set_all_symbols_read_handler(handler);
1476   return LDPS_OK;
1477 }
1478
1479 // Register a cleanup handler.
1480
1481 static enum ld_plugin_status
1482 register_cleanup(ld_plugin_cleanup_handler handler)
1483 {
1484   gold_assert(parameters->options().has_plugins());
1485   parameters->options().plugins()->set_cleanup_handler(handler);
1486   return LDPS_OK;
1487 }
1488
1489 // Add symbols from a plugin-claimed input file.
1490
1491 static enum ld_plugin_status
1492 add_symbols(void* handle, int nsyms, const ld_plugin_symbol* syms)
1493 {
1494   gold_assert(parameters->options().has_plugins());
1495   Pluginobj* obj = parameters->options().plugins()->make_plugin_object(
1496       static_cast<unsigned int>(reinterpret_cast<intptr_t>(handle)));
1497   if (obj == NULL)
1498     return LDPS_ERR;
1499   obj->store_incoming_symbols(nsyms, syms);
1500   return LDPS_OK;
1501 }
1502
1503 // Get the input file information with an open (possibly re-opened)
1504 // file descriptor.
1505
1506 static enum ld_plugin_status
1507 get_input_file(const void* handle, struct ld_plugin_input_file* file)
1508 {
1509   gold_assert(parameters->options().has_plugins());
1510   unsigned int obj_index =
1511       static_cast<unsigned int>(reinterpret_cast<intptr_t>(handle));
1512   return parameters->options().plugins()->get_input_file(obj_index, file);
1513 }
1514
1515 // Release the input file.
1516
1517 static enum ld_plugin_status
1518 release_input_file(const void* handle)
1519 {
1520   gold_assert(parameters->options().has_plugins());
1521   unsigned int obj_index =
1522       static_cast<unsigned int>(reinterpret_cast<intptr_t>(handle));
1523   return parameters->options().plugins()->release_input_file(obj_index);
1524 }
1525
1526 static enum ld_plugin_status
1527 get_view(const void *handle, const void **viewp)
1528 {
1529   gold_assert(parameters->options().has_plugins());
1530   unsigned int obj_index =
1531       static_cast<unsigned int>(reinterpret_cast<intptr_t>(handle));
1532   return parameters->options().plugins()->get_view(obj_index, viewp);
1533 }
1534
1535 // Get the symbol resolution info for a plugin-claimed input file.
1536
1537 static enum ld_plugin_status
1538 get_symbols(const void* handle, int nsyms, ld_plugin_symbol* syms)
1539 {
1540   gold_assert(parameters->options().has_plugins());
1541   Plugin_manager* plugins = parameters->options().plugins();
1542   Object* obj = plugins->object(
1543     static_cast<unsigned int>(reinterpret_cast<intptr_t>(handle)));
1544   if (obj == NULL)
1545     return LDPS_ERR;
1546   Pluginobj* plugin_obj = obj->pluginobj();
1547   if (plugin_obj == NULL)
1548     return LDPS_ERR;
1549   Symbol_table* symtab = plugins->symtab();
1550   return plugin_obj->get_symbol_resolution_info(symtab, nsyms, syms, 1);
1551 }
1552
1553 // Version 2 of the above.  The only difference is that this version
1554 // is allowed to return the resolution code LDPR_PREVAILING_DEF_IRONLY_EXP.
1555
1556 static enum ld_plugin_status
1557 get_symbols_v2(const void* handle, int nsyms, ld_plugin_symbol* syms)
1558 {
1559   gold_assert(parameters->options().has_plugins());
1560   Plugin_manager* plugins = parameters->options().plugins();
1561   Object* obj = plugins->object(
1562     static_cast<unsigned int>(reinterpret_cast<intptr_t>(handle)));
1563   if (obj == NULL)
1564     return LDPS_ERR;
1565   Pluginobj* plugin_obj = obj->pluginobj();
1566   if (plugin_obj == NULL)
1567     return LDPS_ERR;
1568   Symbol_table* symtab = plugins->symtab();
1569   return plugin_obj->get_symbol_resolution_info(symtab, nsyms, syms, 2);
1570 }
1571
1572 // Version 3 of the above.  The only difference from v2 is that it
1573 // returns LDPS_NO_SYMS instead of LDPS_OK for the objects we never
1574 // decided to include.
1575
1576 static enum ld_plugin_status
1577 get_symbols_v3(const void* handle, int nsyms, ld_plugin_symbol* syms)
1578 {
1579   gold_assert(parameters->options().has_plugins());
1580   Plugin_manager* plugins = parameters->options().plugins();
1581   Object* obj = plugins->object(
1582     static_cast<unsigned int>(reinterpret_cast<intptr_t>(handle)));
1583   if (obj == NULL)
1584     return LDPS_ERR;
1585   Pluginobj* plugin_obj = obj->pluginobj();
1586   if (plugin_obj == NULL)
1587     return LDPS_ERR;
1588   Symbol_table* symtab = plugins->symtab();
1589   return plugin_obj->get_symbol_resolution_info(symtab, nsyms, syms, 3);
1590 }
1591
1592 // Add a new (real) input file generated by a plugin.
1593
1594 static enum ld_plugin_status
1595 add_input_file(const char* pathname)
1596 {
1597   gold_assert(parameters->options().has_plugins());
1598   return parameters->options().plugins()->add_input_file(pathname, false);
1599 }
1600
1601 // Add a new (real) library required by a plugin.
1602
1603 static enum ld_plugin_status
1604 add_input_library(const char* pathname)
1605 {
1606   gold_assert(parameters->options().has_plugins());
1607   return parameters->options().plugins()->add_input_file(pathname, true);
1608 }
1609
1610 // Set the extra library path to be used by libraries added via
1611 // add_input_library
1612
1613 static enum ld_plugin_status
1614 set_extra_library_path(const char* path)
1615 {
1616   gold_assert(parameters->options().has_plugins());
1617   return parameters->options().plugins()->set_extra_library_path(path);
1618 }
1619
1620 // Issue a diagnostic message from a plugin.
1621
1622 static enum ld_plugin_status
1623 message(int level, const char* format, ...)
1624 {
1625   va_list args;
1626   va_start(args, format);
1627
1628   switch (level)
1629     {
1630     case LDPL_INFO:
1631       parameters->errors()->info(format, args);
1632       break;
1633     case LDPL_WARNING:
1634       parameters->errors()->warning(format, args);
1635       break;
1636     case LDPL_ERROR:
1637     default:
1638       parameters->errors()->error(format, args);
1639       break;
1640     case LDPL_FATAL:
1641       parameters->errors()->fatal(format, args);
1642       break;
1643     }
1644
1645   va_end(args);
1646   return LDPS_OK;
1647 }
1648
1649 // Get the section count of the object corresponding to the handle.  This
1650 // plugin interface can only be called in the claim_file handler of the plugin.
1651
1652 static enum ld_plugin_status
1653 get_input_section_count(const void* handle, unsigned int* count)
1654 {
1655   gold_assert(parameters->options().has_plugins());
1656
1657   if (!parameters->options().plugins()->in_claim_file_handler())
1658     return LDPS_ERR;
1659
1660   Object* obj = parameters->options().plugins()->get_elf_object(handle);
1661
1662   if (obj == NULL)
1663     return LDPS_ERR;
1664
1665   *count = obj->shnum();
1666   return LDPS_OK;
1667 }
1668
1669 // Get the type of the specified section in the object corresponding
1670 // to the handle.  This plugin interface can only be called in the
1671 // claim_file handler of the plugin.
1672
1673 static enum ld_plugin_status
1674 get_input_section_type(const struct ld_plugin_section section,
1675                        unsigned int* type)
1676 {
1677   gold_assert(parameters->options().has_plugins());
1678
1679   if (!parameters->options().plugins()->in_claim_file_handler())
1680     return LDPS_ERR;
1681
1682   Object* obj
1683     = parameters->options().plugins()->get_elf_object(section.handle); 
1684
1685   if (obj == NULL)
1686     return LDPS_BAD_HANDLE;
1687
1688   *type = obj->section_type(section.shndx);
1689   return LDPS_OK;
1690 }
1691
1692 // Get the name of the specified section in the object corresponding
1693 // to the handle.  This plugin interface can only be called in the
1694 // claim_file handler of the plugin.
1695
1696 static enum ld_plugin_status
1697 get_input_section_name(const struct ld_plugin_section section,
1698                        char** section_name_ptr)
1699 {
1700   gold_assert(parameters->options().has_plugins());
1701
1702   if (!parameters->options().plugins()->in_claim_file_handler())
1703     return LDPS_ERR;
1704
1705   Object* obj
1706     = parameters->options().plugins()->get_elf_object(section.handle); 
1707
1708   if (obj == NULL)
1709     return LDPS_BAD_HANDLE;
1710
1711   // Check if the object is locked before getting the section name.
1712   gold_assert(obj->is_locked());
1713
1714   const std::string section_name = obj->section_name(section.shndx);
1715   *section_name_ptr = static_cast<char*>(malloc(section_name.length() + 1));
1716   memcpy(*section_name_ptr, section_name.c_str(), section_name.length() + 1);
1717   return LDPS_OK;
1718 }
1719
1720 // Get the contents of the specified section in the object corresponding
1721 // to the handle.  This plugin interface can only be called in the
1722 // claim_file handler of the plugin.
1723
1724 static enum ld_plugin_status
1725 get_input_section_contents(const struct ld_plugin_section section,
1726                            const unsigned char** section_contents_ptr,
1727                            size_t* len)
1728 {
1729   gold_assert(parameters->options().has_plugins());
1730
1731   if (!parameters->options().plugins()->in_claim_file_handler())
1732     return LDPS_ERR;
1733
1734   Object* obj
1735     = parameters->options().plugins()->get_elf_object(section.handle); 
1736
1737   if (obj == NULL)
1738     return LDPS_BAD_HANDLE;
1739
1740   // Check if the object is locked before getting the section contents.
1741   gold_assert(obj->is_locked());
1742
1743   section_size_type plen;
1744   *section_contents_ptr
1745       = obj->section_contents(section.shndx, &plen, false);
1746   *len = plen;
1747   return LDPS_OK;
1748 }
1749
1750 // Get the alignment of the specified section in the object corresponding
1751 // to the handle.  This plugin interface can only be called in the
1752 // claim_file handler of the plugin.
1753
1754 static enum ld_plugin_status
1755 get_input_section_alignment(const struct ld_plugin_section section,
1756                             unsigned int* addralign)
1757 {
1758   gold_assert(parameters->options().has_plugins());
1759
1760   if (!parameters->options().plugins()->in_claim_file_handler())
1761     return LDPS_ERR;
1762
1763   Object* obj
1764     = parameters->options().plugins()->get_elf_object(section.handle);
1765
1766   if (obj == NULL)
1767     return LDPS_BAD_HANDLE;
1768
1769   *addralign = obj->section_addralign(section.shndx);
1770   return LDPS_OK;
1771 }
1772
1773 // Get the size of the specified section in the object corresponding
1774 // to the handle.  This plugin interface can only be called in the
1775 // claim_file handler of the plugin.
1776
1777 static enum ld_plugin_status
1778 get_input_section_size(const struct ld_plugin_section section,
1779                        uint64_t* secsize)
1780 {
1781   gold_assert(parameters->options().has_plugins());
1782
1783   if (!parameters->options().plugins()->in_claim_file_handler())
1784     return LDPS_ERR;
1785
1786   Object* obj
1787     = parameters->options().plugins()->get_elf_object(section.handle);
1788
1789   if (obj == NULL)
1790     return LDPS_BAD_HANDLE;
1791
1792   *secsize = obj->section_size(section.shndx);
1793   return LDPS_OK;
1794 }
1795
1796
1797 // Specify the ordering of sections in the final layout. The sections are
1798 // specified as (handle,shndx) pairs in the two arrays in the order in
1799 // which they should appear in the final layout.
1800
1801 static enum ld_plugin_status
1802 update_section_order(const struct ld_plugin_section* section_list,
1803                      unsigned int num_sections)
1804 {
1805   gold_assert(parameters->options().has_plugins());
1806
1807   if (num_sections == 0)
1808     return LDPS_OK;
1809
1810   if (section_list == NULL)
1811     return LDPS_ERR;
1812
1813   Layout* layout = parameters->options().plugins()->layout();
1814   gold_assert (layout != NULL);
1815
1816   std::map<Section_id, unsigned int>* order_map
1817     = layout->get_section_order_map();
1818
1819   /* Store the mapping from Section_id to section position in layout's
1820      order_map to consult after output sections are added.  */
1821   for (unsigned int i = 0; i < num_sections; ++i)
1822     {
1823       Object* obj = parameters->options().plugins()->get_elf_object(
1824           section_list[i].handle);
1825       if (obj == NULL || obj->is_dynamic())
1826         return LDPS_BAD_HANDLE;
1827       unsigned int shndx = section_list[i].shndx;
1828       Section_id secn_id(static_cast<Relobj*>(obj), shndx);
1829       (*order_map)[secn_id] = i + 1;
1830     }
1831
1832   return LDPS_OK;
1833 }
1834
1835 // Let the linker know that the sections could be reordered.
1836
1837 static enum ld_plugin_status
1838 allow_section_ordering()
1839 {
1840   gold_assert(parameters->options().has_plugins());
1841   Layout* layout = parameters->options().plugins()->layout();
1842   layout->set_section_ordering_specified();
1843   return LDPS_OK;
1844 }
1845
1846 // Let the linker know that a subset of sections could be mapped
1847 // to a unique segment.
1848
1849 static enum ld_plugin_status
1850 allow_unique_segment_for_sections()
1851 {
1852   gold_assert(parameters->options().has_plugins());
1853   Layout* layout = parameters->options().plugins()->layout();
1854   layout->set_unique_segment_for_sections_specified();
1855   return LDPS_OK;
1856 }
1857
1858 // This function should map the list of sections specified in the
1859 // SECTION_LIST to a unique segment.  ELF segments do not have names
1860 // and the NAME is used to identify Output Section which should contain
1861 // the list of sections.  This Output Section will then be mapped to
1862 // a unique segment.  FLAGS is used to specify if any additional segment
1863 // flags need to be set.  For instance, a specific segment flag can be
1864 // set to identify this segment.  Unsetting segment flags is not possible.
1865 // ALIGN specifies the alignment of the segment.
1866
1867 static enum ld_plugin_status
1868 unique_segment_for_sections(const char* segment_name,
1869                             uint64_t flags,
1870                             uint64_t align,
1871                             const struct ld_plugin_section* section_list,
1872                             unsigned int num_sections)
1873 {
1874   gold_assert(parameters->options().has_plugins());
1875
1876   if (num_sections == 0)
1877     return LDPS_OK;
1878
1879   if (section_list == NULL)
1880     return LDPS_ERR;
1881
1882   Layout* layout = parameters->options().plugins()->layout();
1883   gold_assert (layout != NULL);
1884
1885   Layout::Unique_segment_info* s = new Layout::Unique_segment_info;
1886   s->name = segment_name;
1887   s->flags = flags;
1888   s->align = align;
1889
1890   for (unsigned int i = 0; i < num_sections; ++i)
1891     {
1892       Object* obj = parameters->options().plugins()->get_elf_object(
1893           section_list[i].handle);
1894       if (obj == NULL || obj->is_dynamic())
1895         return LDPS_BAD_HANDLE;
1896       unsigned int shndx = section_list[i].shndx;
1897       Const_section_id secn_id(static_cast<Relobj*>(obj), shndx);
1898       layout->insert_section_segment_map(secn_id, s);
1899     }
1900
1901   return LDPS_OK;
1902 }
1903
1904 #endif // ENABLE_PLUGINS
1905
1906 // Allocate a Pluginobj object of the appropriate size and endianness.
1907
1908 static Pluginobj*
1909 make_sized_plugin_object(Input_file* input_file, off_t offset, off_t filesize)
1910 {
1911   Pluginobj* obj = NULL;
1912
1913   parameters_force_valid_target();
1914   const Target& target(parameters->target());
1915
1916   if (target.get_size() == 32)
1917     {
1918       if (target.is_big_endian())
1919 #ifdef HAVE_TARGET_32_BIG
1920         obj = new Sized_pluginobj<32, true>(input_file->filename(),
1921                                             input_file, offset, filesize);
1922 #else
1923         gold_error(_("%s: not configured to support "
1924                      "32-bit big-endian object"),
1925                    input_file->filename().c_str());
1926 #endif
1927       else
1928 #ifdef HAVE_TARGET_32_LITTLE
1929         obj = new Sized_pluginobj<32, false>(input_file->filename(),
1930                                              input_file, offset, filesize);
1931 #else
1932         gold_error(_("%s: not configured to support "
1933                      "32-bit little-endian object"),
1934                    input_file->filename().c_str());
1935 #endif
1936     }
1937   else if (target.get_size() == 64)
1938     {
1939       if (target.is_big_endian())
1940 #ifdef HAVE_TARGET_64_BIG
1941         obj = new Sized_pluginobj<64, true>(input_file->filename(),
1942                                             input_file, offset, filesize);
1943 #else
1944         gold_error(_("%s: not configured to support "
1945                      "64-bit big-endian object"),
1946                    input_file->filename().c_str());
1947 #endif
1948       else
1949 #ifdef HAVE_TARGET_64_LITTLE
1950         obj = new Sized_pluginobj<64, false>(input_file->filename(),
1951                                              input_file, offset, filesize);
1952 #else
1953         gold_error(_("%s: not configured to support "
1954                      "64-bit little-endian object"),
1955                    input_file->filename().c_str());
1956 #endif
1957     }
1958
1959   gold_assert(obj != NULL);
1960   return obj;
1961 }
1962
1963 } // End namespace gold.