[GOLD] R_PPC64_REL16_HIGH relocs
[platform/upstream/binutils.git] / gold / symtab.cc
1 // symtab.cc -- the gold symbol table
2
3 // Copyright (C) 2006-2019 Free Software Foundation, Inc.
4 // Written by Ian Lance Taylor <iant@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 <cstring>
26 #include <stdint.h>
27 #include <algorithm>
28 #include <set>
29 #include <string>
30 #include <utility>
31 #include "demangle.h"
32
33 #include "gc.h"
34 #include "object.h"
35 #include "dwarf_reader.h"
36 #include "dynobj.h"
37 #include "output.h"
38 #include "target.h"
39 #include "workqueue.h"
40 #include "symtab.h"
41 #include "script.h"
42 #include "plugin.h"
43 #include "incremental.h"
44
45 namespace gold
46 {
47
48 // Class Symbol.
49
50 // Initialize fields in Symbol.  This initializes everything except
51 // u1_, u2_ and source_.
52
53 void
54 Symbol::init_fields(const char* name, const char* version,
55                     elfcpp::STT type, elfcpp::STB binding,
56                     elfcpp::STV visibility, unsigned char nonvis)
57 {
58   this->name_ = name;
59   this->version_ = version;
60   this->symtab_index_ = 0;
61   this->dynsym_index_ = 0;
62   this->got_offsets_.init();
63   this->plt_offset_ = -1U;
64   this->type_ = type;
65   this->binding_ = binding;
66   this->visibility_ = visibility;
67   this->nonvis_ = nonvis;
68   this->is_def_ = false;
69   this->is_forwarder_ = false;
70   this->has_alias_ = false;
71   this->needs_dynsym_entry_ = false;
72   this->in_reg_ = false;
73   this->in_dyn_ = false;
74   this->has_warning_ = false;
75   this->is_copied_from_dynobj_ = false;
76   this->is_forced_local_ = false;
77   this->is_ordinary_shndx_ = false;
78   this->in_real_elf_ = false;
79   this->is_defined_in_discarded_section_ = false;
80   this->undef_binding_set_ = false;
81   this->undef_binding_weak_ = false;
82   this->is_predefined_ = false;
83   this->is_protected_ = false;
84   this->non_zero_localentry_ = false;
85 }
86
87 // Return the demangled version of the symbol's name, but only
88 // if the --demangle flag was set.
89
90 static std::string
91 demangle(const char* name)
92 {
93   if (!parameters->options().do_demangle())
94     return name;
95
96   // cplus_demangle allocates memory for the result it returns,
97   // and returns NULL if the name is already demangled.
98   char* demangled_name = cplus_demangle(name, DMGL_ANSI | DMGL_PARAMS);
99   if (demangled_name == NULL)
100     return name;
101
102   std::string retval(demangled_name);
103   free(demangled_name);
104   return retval;
105 }
106
107 std::string
108 Symbol::demangled_name() const
109 {
110   return demangle(this->name());
111 }
112
113 // Initialize the fields in the base class Symbol for SYM in OBJECT.
114
115 template<int size, bool big_endian>
116 void
117 Symbol::init_base_object(const char* name, const char* version, Object* object,
118                          const elfcpp::Sym<size, big_endian>& sym,
119                          unsigned int st_shndx, bool is_ordinary)
120 {
121   this->init_fields(name, version, sym.get_st_type(), sym.get_st_bind(),
122                     sym.get_st_visibility(), sym.get_st_nonvis());
123   this->u1_.object = object;
124   this->u2_.shndx = st_shndx;
125   this->is_ordinary_shndx_ = is_ordinary;
126   this->source_ = FROM_OBJECT;
127   this->in_reg_ = !object->is_dynamic();
128   this->in_dyn_ = object->is_dynamic();
129   this->in_real_elf_ = object->pluginobj() == NULL;
130 }
131
132 // Initialize the fields in the base class Symbol for a symbol defined
133 // in an Output_data.
134
135 void
136 Symbol::init_base_output_data(const char* name, const char* version,
137                               Output_data* od, elfcpp::STT type,
138                               elfcpp::STB binding, elfcpp::STV visibility,
139                               unsigned char nonvis, bool offset_is_from_end,
140                               bool is_predefined)
141 {
142   this->init_fields(name, version, type, binding, visibility, nonvis);
143   this->u1_.output_data = od;
144   this->u2_.offset_is_from_end = offset_is_from_end;
145   this->source_ = IN_OUTPUT_DATA;
146   this->in_reg_ = true;
147   this->in_real_elf_ = true;
148   this->is_predefined_ = is_predefined;
149 }
150
151 // Initialize the fields in the base class Symbol for a symbol defined
152 // in an Output_segment.
153
154 void
155 Symbol::init_base_output_segment(const char* name, const char* version,
156                                  Output_segment* os, elfcpp::STT type,
157                                  elfcpp::STB binding, elfcpp::STV visibility,
158                                  unsigned char nonvis,
159                                  Segment_offset_base offset_base,
160                                  bool is_predefined)
161 {
162   this->init_fields(name, version, type, binding, visibility, nonvis);
163   this->u1_.output_segment = os;
164   this->u2_.offset_base = offset_base;
165   this->source_ = IN_OUTPUT_SEGMENT;
166   this->in_reg_ = true;
167   this->in_real_elf_ = true;
168   this->is_predefined_ = is_predefined;
169 }
170
171 // Initialize the fields in the base class Symbol for a symbol defined
172 // as a constant.
173
174 void
175 Symbol::init_base_constant(const char* name, const char* version,
176                            elfcpp::STT type, elfcpp::STB binding,
177                            elfcpp::STV visibility, unsigned char nonvis,
178                            bool is_predefined)
179 {
180   this->init_fields(name, version, type, binding, visibility, nonvis);
181   this->source_ = IS_CONSTANT;
182   this->in_reg_ = true;
183   this->in_real_elf_ = true;
184   this->is_predefined_ = is_predefined;
185 }
186
187 // Initialize the fields in the base class Symbol for an undefined
188 // symbol.
189
190 void
191 Symbol::init_base_undefined(const char* name, const char* version,
192                             elfcpp::STT type, elfcpp::STB binding,
193                             elfcpp::STV visibility, unsigned char nonvis)
194 {
195   this->init_fields(name, version, type, binding, visibility, nonvis);
196   this->dynsym_index_ = -1U;
197   this->source_ = IS_UNDEFINED;
198   this->in_reg_ = true;
199   this->in_real_elf_ = true;
200 }
201
202 // Allocate a common symbol in the base.
203
204 void
205 Symbol::allocate_base_common(Output_data* od)
206 {
207   gold_assert(this->is_common());
208   this->source_ = IN_OUTPUT_DATA;
209   this->u1_.output_data = od;
210   this->u2_.offset_is_from_end = false;
211 }
212
213 // Initialize the fields in Sized_symbol for SYM in OBJECT.
214
215 template<int size>
216 template<bool big_endian>
217 void
218 Sized_symbol<size>::init_object(const char* name, const char* version,
219                                 Object* object,
220                                 const elfcpp::Sym<size, big_endian>& sym,
221                                 unsigned int st_shndx, bool is_ordinary)
222 {
223   this->init_base_object(name, version, object, sym, st_shndx, is_ordinary);
224   this->value_ = sym.get_st_value();
225   this->symsize_ = sym.get_st_size();
226 }
227
228 // Initialize the fields in Sized_symbol for a symbol defined in an
229 // Output_data.
230
231 template<int size>
232 void
233 Sized_symbol<size>::init_output_data(const char* name, const char* version,
234                                      Output_data* od, Value_type value,
235                                      Size_type symsize, elfcpp::STT type,
236                                      elfcpp::STB binding,
237                                      elfcpp::STV visibility,
238                                      unsigned char nonvis,
239                                      bool offset_is_from_end,
240                                      bool is_predefined)
241 {
242   this->init_base_output_data(name, version, od, type, binding, visibility,
243                               nonvis, offset_is_from_end, is_predefined);
244   this->value_ = value;
245   this->symsize_ = symsize;
246 }
247
248 // Initialize the fields in Sized_symbol for a symbol defined in an
249 // Output_segment.
250
251 template<int size>
252 void
253 Sized_symbol<size>::init_output_segment(const char* name, const char* version,
254                                         Output_segment* os, Value_type value,
255                                         Size_type symsize, elfcpp::STT type,
256                                         elfcpp::STB binding,
257                                         elfcpp::STV visibility,
258                                         unsigned char nonvis,
259                                         Segment_offset_base offset_base,
260                                         bool is_predefined)
261 {
262   this->init_base_output_segment(name, version, os, type, binding, visibility,
263                                  nonvis, offset_base, is_predefined);
264   this->value_ = value;
265   this->symsize_ = symsize;
266 }
267
268 // Initialize the fields in Sized_symbol for a symbol defined as a
269 // constant.
270
271 template<int size>
272 void
273 Sized_symbol<size>::init_constant(const char* name, const char* version,
274                                   Value_type value, Size_type symsize,
275                                   elfcpp::STT type, elfcpp::STB binding,
276                                   elfcpp::STV visibility, unsigned char nonvis,
277                                   bool is_predefined)
278 {
279   this->init_base_constant(name, version, type, binding, visibility, nonvis,
280                            is_predefined);
281   this->value_ = value;
282   this->symsize_ = symsize;
283 }
284
285 // Initialize the fields in Sized_symbol for an undefined symbol.
286
287 template<int size>
288 void
289 Sized_symbol<size>::init_undefined(const char* name, const char* version,
290                                    Value_type value, elfcpp::STT type,
291                                    elfcpp::STB binding, elfcpp::STV visibility,
292                                    unsigned char nonvis)
293 {
294   this->init_base_undefined(name, version, type, binding, visibility, nonvis);
295   this->value_ = value;
296   this->symsize_ = 0;
297 }
298
299 // Return an allocated string holding the symbol's name as
300 // name@version.  This is used for relocatable links.
301
302 std::string
303 Symbol::versioned_name() const
304 {
305   gold_assert(this->version_ != NULL);
306   std::string ret = this->name_;
307   ret.push_back('@');
308   if (this->is_def_)
309     ret.push_back('@');
310   ret += this->version_;
311   return ret;
312 }
313
314 // Return true if SHNDX represents a common symbol.
315
316 bool
317 Symbol::is_common_shndx(unsigned int shndx)
318 {
319   return (shndx == elfcpp::SHN_COMMON
320           || shndx == parameters->target().small_common_shndx()
321           || shndx == parameters->target().large_common_shndx());
322 }
323
324 // Allocate a common symbol.
325
326 template<int size>
327 void
328 Sized_symbol<size>::allocate_common(Output_data* od, Value_type value)
329 {
330   this->allocate_base_common(od);
331   this->value_ = value;
332 }
333
334 // The ""'s around str ensure str is a string literal, so sizeof works.
335 #define strprefix(var, str)   (strncmp(var, str, sizeof("" str "") - 1) == 0)
336
337 // Return true if this symbol should be added to the dynamic symbol
338 // table.
339
340 bool
341 Symbol::should_add_dynsym_entry(Symbol_table* symtab) const
342 {
343   // If the symbol is only present on plugin files, the plugin decided we
344   // don't need it.
345   if (!this->in_real_elf())
346     return false;
347
348   // If the symbol is used by a dynamic relocation, we need to add it.
349   if (this->needs_dynsym_entry())
350     return true;
351
352   // If this symbol's section is not added, the symbol need not be added. 
353   // The section may have been GCed.  Note that export_dynamic is being 
354   // overridden here.  This should not be done for shared objects.
355   if (parameters->options().gc_sections() 
356       && !parameters->options().shared()
357       && this->source() == Symbol::FROM_OBJECT
358       && !this->object()->is_dynamic())
359     {
360       Relobj* relobj = static_cast<Relobj*>(this->object());
361       bool is_ordinary;
362       unsigned int shndx = this->shndx(&is_ordinary);
363       if (is_ordinary && shndx != elfcpp::SHN_UNDEF
364           && !relobj->is_section_included(shndx)
365           && !symtab->is_section_folded(relobj, shndx))
366         return false;
367     }
368
369   // If the symbol was forced dynamic in a --dynamic-list file
370   // or an --export-dynamic-symbol option, add it.
371   if (!this->is_from_dynobj()
372       && (parameters->options().in_dynamic_list(this->name())
373           || parameters->options().is_export_dynamic_symbol(this->name())))
374     {
375       if (!this->is_forced_local())
376         return true;
377       gold_warning(_("Cannot export local symbol '%s'"),
378                    this->demangled_name().c_str());
379       return false;
380     }
381
382   // If the symbol was forced local in a version script, do not add it.
383   if (this->is_forced_local())
384     return false;
385
386   // If dynamic-list-data was specified, add any STT_OBJECT.
387   if (parameters->options().dynamic_list_data()
388       && !this->is_from_dynobj()
389       && this->type() == elfcpp::STT_OBJECT)
390     return true;
391
392   // If --dynamic-list-cpp-new was specified, add any new/delete symbol.
393   // If --dynamic-list-cpp-typeinfo was specified, add any typeinfo symbols.
394   if ((parameters->options().dynamic_list_cpp_new()
395        || parameters->options().dynamic_list_cpp_typeinfo())
396       && !this->is_from_dynobj())
397     {
398       // TODO(csilvers): We could probably figure out if we're an operator
399       //                 new/delete or typeinfo without the need to demangle.
400       char* demangled_name = cplus_demangle(this->name(),
401                                             DMGL_ANSI | DMGL_PARAMS);
402       if (demangled_name == NULL)
403         {
404           // Not a C++ symbol, so it can't satisfy these flags
405         }
406       else if (parameters->options().dynamic_list_cpp_new()
407                && (strprefix(demangled_name, "operator new")
408                    || strprefix(demangled_name, "operator delete")))
409         {
410           free(demangled_name);
411           return true;
412         }
413       else if (parameters->options().dynamic_list_cpp_typeinfo()
414                && (strprefix(demangled_name, "typeinfo name for")
415                    || strprefix(demangled_name, "typeinfo for")))
416         {
417           free(demangled_name);
418           return true;
419         }
420       else
421         free(demangled_name);
422     }
423
424   // If exporting all symbols or building a shared library,
425   // or the symbol should be globally unique (GNU_UNIQUE),
426   // and the symbol is defined in a regular object and is
427   // externally visible, we need to add it.
428   if ((parameters->options().export_dynamic()
429        || parameters->options().shared()
430        || (parameters->options().gnu_unique()
431            && this->binding() == elfcpp::STB_GNU_UNIQUE))
432       && !this->is_from_dynobj()
433       && !this->is_undefined()
434       && this->is_externally_visible())
435     return true;
436
437   return false;
438 }
439
440 // Return true if the final value of this symbol is known at link
441 // time.
442
443 bool
444 Symbol::final_value_is_known() const
445 {
446   // If we are not generating an executable, then no final values are
447   // known, since they will change at runtime, with the exception of
448   // TLS symbols in a position-independent executable.
449   if ((parameters->options().output_is_position_independent()
450        || parameters->options().relocatable())
451       && !(this->type() == elfcpp::STT_TLS
452            && parameters->options().pie()))
453     return false;
454
455   // If the symbol is not from an object file, and is not undefined,
456   // then it is defined, and known.
457   if (this->source_ != FROM_OBJECT)
458     {
459       if (this->source_ != IS_UNDEFINED)
460         return true;
461     }
462   else
463     {
464       // If the symbol is from a dynamic object, then the final value
465       // is not known.
466       if (this->object()->is_dynamic())
467         return false;
468
469       // If the symbol is not undefined (it is defined or common),
470       // then the final value is known.
471       if (!this->is_undefined())
472         return true;
473     }
474
475   // If the symbol is undefined, then whether the final value is known
476   // depends on whether we are doing a static link.  If we are doing a
477   // dynamic link, then the final value could be filled in at runtime.
478   // This could reasonably be the case for a weak undefined symbol.
479   return parameters->doing_static_link();
480 }
481
482 // Return the output section where this symbol is defined.
483
484 Output_section*
485 Symbol::output_section() const
486 {
487   switch (this->source_)
488     {
489     case FROM_OBJECT:
490       {
491         unsigned int shndx = this->u2_.shndx;
492         if (shndx != elfcpp::SHN_UNDEF && this->is_ordinary_shndx_)
493           {
494             gold_assert(!this->u1_.object->is_dynamic());
495             gold_assert(this->u1_.object->pluginobj() == NULL);
496             Relobj* relobj = static_cast<Relobj*>(this->u1_.object);
497             return relobj->output_section(shndx);
498           }
499         return NULL;
500       }
501
502     case IN_OUTPUT_DATA:
503       return this->u1_.output_data->output_section();
504
505     case IN_OUTPUT_SEGMENT:
506     case IS_CONSTANT:
507     case IS_UNDEFINED:
508       return NULL;
509
510     default:
511       gold_unreachable();
512     }
513 }
514
515 // Set the symbol's output section.  This is used for symbols defined
516 // in scripts.  This should only be called after the symbol table has
517 // been finalized.
518
519 void
520 Symbol::set_output_section(Output_section* os)
521 {
522   switch (this->source_)
523     {
524     case FROM_OBJECT:
525     case IN_OUTPUT_DATA:
526       gold_assert(this->output_section() == os);
527       break;
528     case IS_CONSTANT:
529       this->source_ = IN_OUTPUT_DATA;
530       this->u1_.output_data = os;
531       this->u2_.offset_is_from_end = false;
532       break;
533     case IN_OUTPUT_SEGMENT:
534     case IS_UNDEFINED:
535     default:
536       gold_unreachable();
537     }
538 }
539
540 // Set the symbol's output segment.  This is used for pre-defined
541 // symbols whose segments aren't known until after layout is done
542 // (e.g., __ehdr_start).
543
544 void
545 Symbol::set_output_segment(Output_segment* os, Segment_offset_base base)
546 {
547   gold_assert(this->is_predefined_);
548   this->source_ = IN_OUTPUT_SEGMENT;
549   this->u1_.output_segment = os;
550   this->u2_.offset_base = base;
551 }
552
553 // Set the symbol to undefined.  This is used for pre-defined
554 // symbols whose segments aren't known until after layout is done
555 // (e.g., __ehdr_start).
556
557 void
558 Symbol::set_undefined()
559 {
560   this->source_ = IS_UNDEFINED;
561   this->is_predefined_ = false;
562 }
563
564 // Class Symbol_table.
565
566 Symbol_table::Symbol_table(unsigned int count,
567                            const Version_script_info& version_script)
568   : saw_undefined_(0), offset_(0), table_(count), namepool_(),
569     forwarders_(), commons_(), tls_commons_(), small_commons_(),
570     large_commons_(), forced_locals_(), warnings_(),
571     version_script_(version_script), gc_(NULL), icf_(NULL),
572     target_symbols_()
573 {
574   namepool_.reserve(count);
575 }
576
577 Symbol_table::~Symbol_table()
578 {
579 }
580
581 // The symbol table key equality function.  This is called with
582 // Stringpool keys.
583
584 inline bool
585 Symbol_table::Symbol_table_eq::operator()(const Symbol_table_key& k1,
586                                           const Symbol_table_key& k2) const
587 {
588   return k1.first == k2.first && k1.second == k2.second;
589 }
590
591 bool
592 Symbol_table::is_section_folded(Relobj* obj, unsigned int shndx) const
593 {
594   return (parameters->options().icf_enabled()
595           && this->icf_->is_section_folded(obj, shndx));
596 }
597
598 // For symbols that have been listed with a -u or --export-dynamic-symbol
599 // option, add them to the work list to avoid gc'ing them.
600
601 void 
602 Symbol_table::gc_mark_undef_symbols(Layout* layout)
603 {
604   for (options::String_set::const_iterator p =
605          parameters->options().undefined_begin();
606        p != parameters->options().undefined_end();
607        ++p)
608     {
609       const char* name = p->c_str();
610       Symbol* sym = this->lookup(name);
611       gold_assert(sym != NULL);
612       if (sym->source() == Symbol::FROM_OBJECT 
613           && !sym->object()->is_dynamic())
614         {
615           this->gc_mark_symbol(sym);
616         }
617     }
618
619   for (options::String_set::const_iterator p =
620          parameters->options().export_dynamic_symbol_begin();
621        p != parameters->options().export_dynamic_symbol_end();
622        ++p)
623     {
624       const char* name = p->c_str();
625       Symbol* sym = this->lookup(name);
626       // It's not an error if a symbol named by --export-dynamic-symbol
627       // is undefined.
628       if (sym != NULL
629           && sym->source() == Symbol::FROM_OBJECT 
630           && !sym->object()->is_dynamic())
631         {
632           this->gc_mark_symbol(sym);
633         }
634     }
635
636   for (Script_options::referenced_const_iterator p =
637          layout->script_options()->referenced_begin();
638        p != layout->script_options()->referenced_end();
639        ++p)
640     {
641       Symbol* sym = this->lookup(p->c_str());
642       gold_assert(sym != NULL);
643       if (sym->source() == Symbol::FROM_OBJECT
644           && !sym->object()->is_dynamic())
645         {
646           this->gc_mark_symbol(sym);
647         }
648     }
649 }
650
651 void
652 Symbol_table::gc_mark_symbol(Symbol* sym)
653 {
654   // Add the object and section to the work list.
655   bool is_ordinary;
656   unsigned int shndx = sym->shndx(&is_ordinary);
657   if (is_ordinary && shndx != elfcpp::SHN_UNDEF && !sym->object()->is_dynamic())
658     {
659       gold_assert(this->gc_!= NULL);
660       Relobj* relobj = static_cast<Relobj*>(sym->object());
661       this->gc_->worklist().push_back(Section_id(relobj, shndx));
662     }
663   parameters->target().gc_mark_symbol(this, sym);
664 }
665
666 // When doing garbage collection, keep symbols that have been seen in
667 // dynamic objects.
668 inline void 
669 Symbol_table::gc_mark_dyn_syms(Symbol* sym)
670 {
671   if (sym->in_dyn() && sym->source() == Symbol::FROM_OBJECT
672       && !sym->object()->is_dynamic())
673     this->gc_mark_symbol(sym);
674 }
675
676 // Make TO a symbol which forwards to FROM.
677
678 void
679 Symbol_table::make_forwarder(Symbol* from, Symbol* to)
680 {
681   gold_assert(from != to);
682   gold_assert(!from->is_forwarder() && !to->is_forwarder());
683   this->forwarders_[from] = to;
684   from->set_forwarder();
685 }
686
687 // Resolve the forwards from FROM, returning the real symbol.
688
689 Symbol*
690 Symbol_table::resolve_forwards(const Symbol* from) const
691 {
692   gold_assert(from->is_forwarder());
693   Unordered_map<const Symbol*, Symbol*>::const_iterator p =
694     this->forwarders_.find(from);
695   gold_assert(p != this->forwarders_.end());
696   return p->second;
697 }
698
699 // Look up a symbol by name.
700
701 Symbol*
702 Symbol_table::lookup(const char* name, const char* version) const
703 {
704   Stringpool::Key name_key;
705   name = this->namepool_.find(name, &name_key);
706   if (name == NULL)
707     return NULL;
708
709   Stringpool::Key version_key = 0;
710   if (version != NULL)
711     {
712       version = this->namepool_.find(version, &version_key);
713       if (version == NULL)
714         return NULL;
715     }
716
717   Symbol_table_key key(name_key, version_key);
718   Symbol_table::Symbol_table_type::const_iterator p = this->table_.find(key);
719   if (p == this->table_.end())
720     return NULL;
721   return p->second;
722 }
723
724 // Resolve a Symbol with another Symbol.  This is only used in the
725 // unusual case where there are references to both an unversioned
726 // symbol and a symbol with a version, and we then discover that that
727 // version is the default version.  Because this is unusual, we do
728 // this the slow way, by converting back to an ELF symbol.
729
730 template<int size, bool big_endian>
731 void
732 Symbol_table::resolve(Sized_symbol<size>* to, const Sized_symbol<size>* from)
733 {
734   unsigned char buf[elfcpp::Elf_sizes<size>::sym_size];
735   elfcpp::Sym_write<size, big_endian> esym(buf);
736   // We don't bother to set the st_name or the st_shndx field.
737   esym.put_st_value(from->value());
738   esym.put_st_size(from->symsize());
739   esym.put_st_info(from->binding(), from->type());
740   esym.put_st_other(from->visibility(), from->nonvis());
741   bool is_ordinary;
742   unsigned int shndx = from->shndx(&is_ordinary);
743   this->resolve(to, esym.sym(), shndx, is_ordinary, shndx, from->object(),
744                 from->version(), true);
745   if (from->in_reg())
746     to->set_in_reg();
747   if (from->in_dyn())
748     to->set_in_dyn();
749   if (parameters->options().gc_sections())
750     this->gc_mark_dyn_syms(to);
751 }
752
753 // Record that a symbol is forced to be local by a version script or
754 // by visibility.
755
756 void
757 Symbol_table::force_local(Symbol* sym)
758 {
759   if (!sym->is_defined() && !sym->is_common())
760     return;
761   if (sym->is_forced_local())
762     {
763       // We already got this one.
764       return;
765     }
766   sym->set_is_forced_local();
767   this->forced_locals_.push_back(sym);
768 }
769
770 // Adjust NAME for wrapping, and update *NAME_KEY if necessary.  This
771 // is only called for undefined symbols, when at least one --wrap
772 // option was used.
773
774 const char*
775 Symbol_table::wrap_symbol(const char* name, Stringpool::Key* name_key)
776 {
777   // For some targets, we need to ignore a specific character when
778   // wrapping, and add it back later.
779   char prefix = '\0';
780   if (name[0] == parameters->target().wrap_char())
781     {
782       prefix = name[0];
783       ++name;
784     }
785
786   if (parameters->options().is_wrap(name))
787     {
788       // Turn NAME into __wrap_NAME.
789       std::string s;
790       if (prefix != '\0')
791         s += prefix;
792       s += "__wrap_";
793       s += name;
794
795       // This will give us both the old and new name in NAMEPOOL_, but
796       // that is OK.  Only the versions we need will wind up in the
797       // real string table in the output file.
798       return this->namepool_.add(s.c_str(), true, name_key);
799     }
800
801   const char* const real_prefix = "__real_";
802   const size_t real_prefix_length = strlen(real_prefix);
803   if (strncmp(name, real_prefix, real_prefix_length) == 0
804       && parameters->options().is_wrap(name + real_prefix_length))
805     {
806       // Turn __real_NAME into NAME.
807       std::string s;
808       if (prefix != '\0')
809         s += prefix;
810       s += name + real_prefix_length;
811       return this->namepool_.add(s.c_str(), true, name_key);
812     }
813
814   return name;
815 }
816
817 // This is called when we see a symbol NAME/VERSION, and the symbol
818 // already exists in the symbol table, and VERSION is marked as being
819 // the default version.  SYM is the NAME/VERSION symbol we just added.
820 // DEFAULT_IS_NEW is true if this is the first time we have seen the
821 // symbol NAME/NULL.  PDEF points to the entry for NAME/NULL.
822
823 template<int size, bool big_endian>
824 void
825 Symbol_table::define_default_version(Sized_symbol<size>* sym,
826                                      bool default_is_new,
827                                      Symbol_table_type::iterator pdef)
828 {
829   if (default_is_new)
830     {
831       // This is the first time we have seen NAME/NULL.  Make
832       // NAME/NULL point to NAME/VERSION, and mark SYM as the default
833       // version.
834       pdef->second = sym;
835       sym->set_is_default();
836     }
837   else if (pdef->second == sym)
838     {
839       // NAME/NULL already points to NAME/VERSION.  Don't mark the
840       // symbol as the default if it is not already the default.
841     }
842   else
843     {
844       // This is the unfortunate case where we already have entries
845       // for both NAME/VERSION and NAME/NULL.  We now see a symbol
846       // NAME/VERSION where VERSION is the default version.  We have
847       // already resolved this new symbol with the existing
848       // NAME/VERSION symbol.
849
850       // It's possible that NAME/NULL and NAME/VERSION are both
851       // defined in regular objects.  This can only happen if one
852       // object file defines foo and another defines foo@@ver.  This
853       // is somewhat obscure, but we call it a multiple definition
854       // error.
855
856       // It's possible that NAME/NULL actually has a version, in which
857       // case it won't be the same as VERSION.  This happens with
858       // ver_test_7.so in the testsuite for the symbol t2_2.  We see
859       // t2_2@@VER2, so we define both t2_2/VER2 and t2_2/NULL.  We
860       // then see an unadorned t2_2 in an object file and give it
861       // version VER1 from the version script.  This looks like a
862       // default definition for VER1, so it looks like we should merge
863       // t2_2/NULL with t2_2/VER1.  That doesn't make sense, but it's
864       // not obvious that this is an error, either.  So we just punt.
865
866       // If one of the symbols has non-default visibility, and the
867       // other is defined in a shared object, then they are different
868       // symbols.
869
870       // If the two symbols are from different shared objects,
871       // they are different symbols.
872
873       // Otherwise, we just resolve the symbols as though they were
874       // the same.
875
876       if (pdef->second->version() != NULL)
877         gold_assert(pdef->second->version() != sym->version());
878       else if (sym->visibility() != elfcpp::STV_DEFAULT
879                && pdef->second->is_from_dynobj())
880         ;
881       else if (pdef->second->visibility() != elfcpp::STV_DEFAULT
882                && sym->is_from_dynobj())
883         ;
884       else if (pdef->second->is_from_dynobj()
885                && sym->is_from_dynobj()
886                && pdef->second->is_defined()
887                && pdef->second->object() != sym->object())
888         ;
889       else
890         {
891           const Sized_symbol<size>* symdef;
892           symdef = this->get_sized_symbol<size>(pdef->second);
893           Symbol_table::resolve<size, big_endian>(sym, symdef);
894           this->make_forwarder(pdef->second, sym);
895           pdef->second = sym;
896           sym->set_is_default();
897         }
898     }
899 }
900
901 // Add one symbol from OBJECT to the symbol table.  NAME is symbol
902 // name and VERSION is the version; both are canonicalized.  DEF is
903 // whether this is the default version.  ST_SHNDX is the symbol's
904 // section index; IS_ORDINARY is whether this is a normal section
905 // rather than a special code.
906
907 // If IS_DEFAULT_VERSION is true, then this is the definition of a
908 // default version of a symbol.  That means that any lookup of
909 // NAME/NULL and any lookup of NAME/VERSION should always return the
910 // same symbol.  This is obvious for references, but in particular we
911 // want to do this for definitions: overriding NAME/NULL should also
912 // override NAME/VERSION.  If we don't do that, it would be very hard
913 // to override functions in a shared library which uses versioning.
914
915 // We implement this by simply making both entries in the hash table
916 // point to the same Symbol structure.  That is easy enough if this is
917 // the first time we see NAME/NULL or NAME/VERSION, but it is possible
918 // that we have seen both already, in which case they will both have
919 // independent entries in the symbol table.  We can't simply change
920 // the symbol table entry, because we have pointers to the entries
921 // attached to the object files.  So we mark the entry attached to the
922 // object file as a forwarder, and record it in the forwarders_ map.
923 // Note that entries in the hash table will never be marked as
924 // forwarders.
925 //
926 // ORIG_ST_SHNDX and ST_SHNDX are almost always the same.
927 // ORIG_ST_SHNDX is the section index in the input file, or SHN_UNDEF
928 // for a special section code.  ST_SHNDX may be modified if the symbol
929 // is defined in a section being discarded.
930
931 template<int size, bool big_endian>
932 Sized_symbol<size>*
933 Symbol_table::add_from_object(Object* object,
934                               const char* name,
935                               Stringpool::Key name_key,
936                               const char* version,
937                               Stringpool::Key version_key,
938                               bool is_default_version,
939                               const elfcpp::Sym<size, big_endian>& sym,
940                               unsigned int st_shndx,
941                               bool is_ordinary,
942                               unsigned int orig_st_shndx)
943 {
944   // Print a message if this symbol is being traced.
945   if (parameters->options().is_trace_symbol(name))
946     {
947       if (orig_st_shndx == elfcpp::SHN_UNDEF)
948         gold_info(_("%s: reference to %s"), object->name().c_str(), name);
949       else
950         gold_info(_("%s: definition of %s"), object->name().c_str(), name);
951     }
952
953   // For an undefined symbol, we may need to adjust the name using
954   // --wrap.
955   if (orig_st_shndx == elfcpp::SHN_UNDEF
956       && parameters->options().any_wrap())
957     {
958       const char* wrap_name = this->wrap_symbol(name, &name_key);
959       if (wrap_name != name)
960         {
961           // If we see a reference to malloc with version GLIBC_2.0,
962           // and we turn it into a reference to __wrap_malloc, then we
963           // discard the version number.  Otherwise the user would be
964           // required to specify the correct version for
965           // __wrap_malloc.
966           version = NULL;
967           version_key = 0;
968           name = wrap_name;
969         }
970     }
971
972   Symbol* const snull = NULL;
973   std::pair<typename Symbol_table_type::iterator, bool> ins =
974     this->table_.insert(std::make_pair(std::make_pair(name_key, version_key),
975                                        snull));
976
977   std::pair<typename Symbol_table_type::iterator, bool> insdefault =
978     std::make_pair(this->table_.end(), false);
979   if (is_default_version)
980     {
981       const Stringpool::Key vnull_key = 0;
982       insdefault = this->table_.insert(std::make_pair(std::make_pair(name_key,
983                                                                      vnull_key),
984                                                       snull));
985     }
986
987   // ins.first: an iterator, which is a pointer to a pair.
988   // ins.first->first: the key (a pair of name and version).
989   // ins.first->second: the value (Symbol*).
990   // ins.second: true if new entry was inserted, false if not.
991
992   Sized_symbol<size>* ret = NULL;
993   bool was_undefined_in_reg;
994   bool was_common;
995   if (!ins.second)
996     {
997       // We already have an entry for NAME/VERSION.
998       ret = this->get_sized_symbol<size>(ins.first->second);
999       gold_assert(ret != NULL);
1000
1001       was_undefined_in_reg = ret->is_undefined() && ret->in_reg();
1002       // Commons from plugins are just placeholders.
1003       was_common = ret->is_common() && ret->object()->pluginobj() == NULL;
1004
1005       this->resolve(ret, sym, st_shndx, is_ordinary, orig_st_shndx, object,
1006                     version, is_default_version);
1007       if (parameters->options().gc_sections())
1008         this->gc_mark_dyn_syms(ret);
1009
1010       if (is_default_version)
1011         this->define_default_version<size, big_endian>(ret, insdefault.second,
1012                                                        insdefault.first);
1013       else
1014         {
1015           bool dummy;
1016           if (version != NULL
1017               && ret->source() == Symbol::FROM_OBJECT
1018               && ret->object() == object
1019               && is_ordinary
1020               && ret->shndx(&dummy) == st_shndx
1021               && ret->is_default())
1022             {
1023               // We have seen NAME/VERSION already, and marked it as the
1024               // default version, but now we see a definition for
1025               // NAME/VERSION that is not the default version. This can
1026               // happen when the assembler generates two symbols for
1027               // a symbol as a result of a ".symver foo,foo@VER"
1028               // directive. We see the first unversioned symbol and
1029               // we may mark it as the default version (from a
1030               // version script); then we see the second versioned
1031               // symbol and we need to override the first.
1032               // In any other case, the two symbols should have generated
1033               // a multiple definition error.
1034               // (See PR gold/18703.)
1035               ret->set_is_not_default();
1036               const Stringpool::Key vnull_key = 0;
1037               this->table_.erase(std::make_pair(name_key, vnull_key));
1038             }
1039         }
1040     }
1041   else
1042     {
1043       // This is the first time we have seen NAME/VERSION.
1044       gold_assert(ins.first->second == NULL);
1045
1046       if (is_default_version && !insdefault.second)
1047         {
1048           // We already have an entry for NAME/NULL.  If we override
1049           // it, then change it to NAME/VERSION.
1050           ret = this->get_sized_symbol<size>(insdefault.first->second);
1051
1052           // If the existing symbol already has a version,
1053           // don't override it with the new symbol.
1054           // This should only happen when the new symbol
1055           // is from a shared library.
1056           if (ret->version() != NULL)
1057             {
1058               if (!object->is_dynamic())
1059                 {
1060                   gold_warning(_("%s: conflicting default version definition"
1061                                  " for %s@@%s"),
1062                                object->name().c_str(), name, version);
1063                   if (ret->source() == Symbol::FROM_OBJECT)
1064                     gold_info(_("%s: %s: previous definition of %s@@%s here"),
1065                               program_name,
1066                               ret->object()->name().c_str(),
1067                               name, ret->version());
1068                 }
1069               ret = NULL;
1070               is_default_version = false;
1071             }
1072           else
1073             {
1074               was_undefined_in_reg = ret->is_undefined() && ret->in_reg();
1075               // Commons from plugins are just placeholders.
1076               was_common = (ret->is_common()
1077                             && ret->object()->pluginobj() == NULL);
1078
1079               this->resolve(ret, sym, st_shndx, is_ordinary, orig_st_shndx,
1080                             object, version, is_default_version);
1081               if (parameters->options().gc_sections())
1082                 this->gc_mark_dyn_syms(ret);
1083               ins.first->second = ret;
1084             }
1085         }
1086
1087       if (ret == NULL)
1088         {
1089           was_undefined_in_reg = false;
1090           was_common = false;
1091
1092           Sized_target<size, big_endian>* target =
1093             parameters->sized_target<size, big_endian>();
1094           if (!target->has_make_symbol())
1095             ret = new Sized_symbol<size>();
1096           else
1097             {
1098               ret = target->make_symbol(name, sym.get_st_type(), object,
1099                                         st_shndx, sym.get_st_value());
1100               if (ret == NULL)
1101                 {
1102                   // This means that we don't want a symbol table
1103                   // entry after all.
1104                   if (!is_default_version)
1105                     this->table_.erase(ins.first);
1106                   else
1107                     {
1108                       this->table_.erase(insdefault.first);
1109                       // Inserting INSDEFAULT invalidated INS.
1110                       this->table_.erase(std::make_pair(name_key,
1111                                                         version_key));
1112                     }
1113                   return NULL;
1114                 }
1115             }
1116
1117           ret->init_object(name, version, object, sym, st_shndx, is_ordinary);
1118
1119           ins.first->second = ret;
1120           if (is_default_version)
1121             {
1122               // This is the first time we have seen NAME/NULL.  Point
1123               // it at the new entry for NAME/VERSION.
1124               gold_assert(insdefault.second);
1125               insdefault.first->second = ret;
1126             }
1127         }
1128
1129       if (is_default_version)
1130         ret->set_is_default();
1131     }
1132
1133   // Record every time we see a new undefined symbol, to speed up archive
1134   // groups. We only care about symbols undefined in regular objects here
1135   // because undefined symbols only in dynamic objects should't trigger rescans.
1136   if (!was_undefined_in_reg && ret->is_undefined() && ret->in_reg())
1137     {
1138       ++this->saw_undefined_;
1139       if (parameters->options().has_plugins())
1140         parameters->options().plugins()->new_undefined_symbol(ret);
1141     }
1142
1143   // Keep track of common symbols, to speed up common symbol
1144   // allocation.  Don't record commons from plugin objects;
1145   // we need to wait until we see the real symbol in the
1146   // replacement file.
1147   if (!was_common && ret->is_common() && ret->object()->pluginobj() == NULL)
1148     {
1149       if (ret->type() == elfcpp::STT_TLS)
1150         this->tls_commons_.push_back(ret);
1151       else if (!is_ordinary
1152                && st_shndx == parameters->target().small_common_shndx())
1153         this->small_commons_.push_back(ret);
1154       else if (!is_ordinary
1155                && st_shndx == parameters->target().large_common_shndx())
1156         this->large_commons_.push_back(ret);
1157       else
1158         this->commons_.push_back(ret);
1159     }
1160
1161   // If we're not doing a relocatable link, then any symbol with
1162   // hidden or internal visibility is local.
1163   if ((ret->visibility() == elfcpp::STV_HIDDEN
1164        || ret->visibility() == elfcpp::STV_INTERNAL)
1165       && (ret->binding() == elfcpp::STB_GLOBAL
1166           || ret->binding() == elfcpp::STB_GNU_UNIQUE
1167           || ret->binding() == elfcpp::STB_WEAK)
1168       && !parameters->options().relocatable())
1169     this->force_local(ret);
1170
1171   return ret;
1172 }
1173
1174 // Add all the symbols in a relocatable object to the hash table.
1175
1176 template<int size, bool big_endian>
1177 void
1178 Symbol_table::add_from_relobj(
1179     Sized_relobj_file<size, big_endian>* relobj,
1180     const unsigned char* syms,
1181     size_t count,
1182     size_t symndx_offset,
1183     const char* sym_names,
1184     size_t sym_name_size,
1185     typename Sized_relobj_file<size, big_endian>::Symbols* sympointers,
1186     size_t* defined)
1187 {
1188   *defined = 0;
1189
1190   gold_assert(size == parameters->target().get_size());
1191
1192   const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
1193
1194   const bool just_symbols = relobj->just_symbols();
1195
1196   const unsigned char* p = syms;
1197   for (size_t i = 0; i < count; ++i, p += sym_size)
1198     {
1199       (*sympointers)[i] = NULL;
1200
1201       elfcpp::Sym<size, big_endian> sym(p);
1202
1203       unsigned int st_name = sym.get_st_name();
1204       if (st_name >= sym_name_size)
1205         {
1206           relobj->error(_("bad global symbol name offset %u at %zu"),
1207                         st_name, i);
1208           continue;
1209         }
1210
1211       const char* name = sym_names + st_name;
1212
1213       if (!parameters->options().relocatable()
1214           && name[0] == '_'
1215           && name[1] == '_'
1216           && strcmp (name + (name[2] == '_'), "__gnu_lto_slim") == 0)
1217         gold_info(_("%s: plugin needed to handle lto object"),
1218                   relobj->name().c_str());
1219
1220       bool is_ordinary;
1221       unsigned int st_shndx = relobj->adjust_sym_shndx(i + symndx_offset,
1222                                                        sym.get_st_shndx(),
1223                                                        &is_ordinary);
1224       unsigned int orig_st_shndx = st_shndx;
1225       if (!is_ordinary)
1226         orig_st_shndx = elfcpp::SHN_UNDEF;
1227
1228       if (st_shndx != elfcpp::SHN_UNDEF)
1229         ++*defined;
1230
1231       // A symbol defined in a section which we are not including must
1232       // be treated as an undefined symbol.
1233       bool is_defined_in_discarded_section = false;
1234       if (st_shndx != elfcpp::SHN_UNDEF
1235           && is_ordinary
1236           && !relobj->is_section_included(st_shndx)
1237           && !this->is_section_folded(relobj, st_shndx))
1238         {
1239           st_shndx = elfcpp::SHN_UNDEF;
1240           is_defined_in_discarded_section = true;
1241         }
1242
1243       // In an object file, an '@' in the name separates the symbol
1244       // name from the version name.  If there are two '@' characters,
1245       // this is the default version.
1246       const char* ver = strchr(name, '@');
1247       Stringpool::Key ver_key = 0;
1248       int namelen = 0;
1249       // IS_DEFAULT_VERSION: is the version default?
1250       // IS_FORCED_LOCAL: is the symbol forced local?
1251       bool is_default_version = false;
1252       bool is_forced_local = false;
1253
1254       // FIXME: For incremental links, we don't store version information,
1255       // so we need to ignore version symbols for now.
1256       if (parameters->incremental_update() && ver != NULL)
1257         {
1258           namelen = ver - name;
1259           ver = NULL;
1260         }
1261
1262       if (ver != NULL)
1263         {
1264           // The symbol name is of the form foo@VERSION or foo@@VERSION
1265           namelen = ver - name;
1266           ++ver;
1267           if (*ver == '@')
1268             {
1269               is_default_version = true;
1270               ++ver;
1271             }
1272           ver = this->namepool_.add(ver, true, &ver_key);
1273         }
1274       // We don't want to assign a version to an undefined symbol,
1275       // even if it is listed in the version script.  FIXME: What
1276       // about a common symbol?
1277       else
1278         {
1279           namelen = strlen(name);
1280           if (!this->version_script_.empty()
1281               && st_shndx != elfcpp::SHN_UNDEF)
1282             {
1283               // The symbol name did not have a version, but the
1284               // version script may assign a version anyway.
1285               std::string version;
1286               bool is_global;
1287               if (this->version_script_.get_symbol_version(name, &version,
1288                                                            &is_global))
1289                 {
1290                   if (!is_global)
1291                     is_forced_local = true;
1292                   else if (!version.empty())
1293                     {
1294                       ver = this->namepool_.add_with_length(version.c_str(),
1295                                                             version.length(),
1296                                                             true,
1297                                                             &ver_key);
1298                       is_default_version = true;
1299                     }
1300                 }
1301             }
1302         }
1303
1304       elfcpp::Sym<size, big_endian>* psym = &sym;
1305       unsigned char symbuf[sym_size];
1306       elfcpp::Sym<size, big_endian> sym2(symbuf);
1307       if (just_symbols)
1308         {
1309           memcpy(symbuf, p, sym_size);
1310           elfcpp::Sym_write<size, big_endian> sw(symbuf);
1311           if (orig_st_shndx != elfcpp::SHN_UNDEF
1312               && is_ordinary
1313               && relobj->e_type() == elfcpp::ET_REL)
1314             {
1315               // Symbol values in relocatable object files are section
1316               // relative.  This is normally what we want, but since here
1317               // we are converting the symbol to absolute we need to add
1318               // the section address.  The section address in an object
1319               // file is normally zero, but people can use a linker
1320               // script to change it.
1321               sw.put_st_value(sym.get_st_value()
1322                               + relobj->section_address(orig_st_shndx));
1323             }
1324           st_shndx = elfcpp::SHN_ABS;
1325           is_ordinary = false;
1326           psym = &sym2;
1327         }
1328
1329       // Fix up visibility if object has no-export set.
1330       if (relobj->no_export()
1331           && (orig_st_shndx != elfcpp::SHN_UNDEF || !is_ordinary))
1332         {
1333           // We may have copied symbol already above.
1334           if (psym != &sym2)
1335             {
1336               memcpy(symbuf, p, sym_size);
1337               psym = &sym2;
1338             }
1339
1340           elfcpp::STV visibility = sym2.get_st_visibility();
1341           if (visibility == elfcpp::STV_DEFAULT
1342               || visibility == elfcpp::STV_PROTECTED)
1343             {
1344               elfcpp::Sym_write<size, big_endian> sw(symbuf);
1345               unsigned char nonvis = sym2.get_st_nonvis();
1346               sw.put_st_other(elfcpp::STV_HIDDEN, nonvis);
1347             }
1348         }
1349
1350       Stringpool::Key name_key;
1351       name = this->namepool_.add_with_length(name, namelen, true,
1352                                              &name_key);
1353
1354       Sized_symbol<size>* res;
1355       res = this->add_from_object(relobj, name, name_key, ver, ver_key,
1356                                   is_default_version, *psym, st_shndx,
1357                                   is_ordinary, orig_st_shndx);
1358
1359       if (res == NULL)
1360         continue;
1361       
1362       if (is_forced_local)
1363         this->force_local(res);
1364
1365       // Do not treat this symbol as garbage if this symbol will be
1366       // exported to the dynamic symbol table.  This is true when
1367       // building a shared library or using --export-dynamic and
1368       // the symbol is externally visible.
1369       if (parameters->options().gc_sections()
1370           && res->is_externally_visible()
1371           && !res->is_from_dynobj()
1372           && (parameters->options().shared()
1373               || parameters->options().export_dynamic()
1374               || parameters->options().in_dynamic_list(res->name())))
1375         this->gc_mark_symbol(res);
1376
1377       if (is_defined_in_discarded_section)
1378         res->set_is_defined_in_discarded_section();
1379
1380       (*sympointers)[i] = res;
1381     }
1382 }
1383
1384 // Add a symbol from a plugin-claimed file.
1385
1386 template<int size, bool big_endian>
1387 Symbol*
1388 Symbol_table::add_from_pluginobj(
1389     Sized_pluginobj<size, big_endian>* obj,
1390     const char* name,
1391     const char* ver,
1392     elfcpp::Sym<size, big_endian>* sym)
1393 {
1394   unsigned int st_shndx = sym->get_st_shndx();
1395   bool is_ordinary = st_shndx < elfcpp::SHN_LORESERVE;
1396
1397   Stringpool::Key ver_key = 0;
1398   bool is_default_version = false;
1399   bool is_forced_local = false;
1400
1401   if (ver != NULL)
1402     {
1403       ver = this->namepool_.add(ver, true, &ver_key);
1404     }
1405   // We don't want to assign a version to an undefined symbol,
1406   // even if it is listed in the version script.  FIXME: What
1407   // about a common symbol?
1408   else
1409     {
1410       if (!this->version_script_.empty()
1411           && st_shndx != elfcpp::SHN_UNDEF)
1412         {
1413           // The symbol name did not have a version, but the
1414           // version script may assign a version anyway.
1415           std::string version;
1416           bool is_global;
1417           if (this->version_script_.get_symbol_version(name, &version,
1418                                                        &is_global))
1419             {
1420               if (!is_global)
1421                 is_forced_local = true;
1422               else if (!version.empty())
1423                 {
1424                   ver = this->namepool_.add_with_length(version.c_str(),
1425                                                         version.length(),
1426                                                         true,
1427                                                         &ver_key);
1428                   is_default_version = true;
1429                 }
1430             }
1431         }
1432     }
1433
1434   Stringpool::Key name_key;
1435   name = this->namepool_.add(name, true, &name_key);
1436
1437   Sized_symbol<size>* res;
1438   res = this->add_from_object(obj, name, name_key, ver, ver_key,
1439                               is_default_version, *sym, st_shndx,
1440                               is_ordinary, st_shndx);
1441
1442   if (res == NULL)
1443     return NULL;
1444
1445   if (is_forced_local)
1446     this->force_local(res);
1447
1448   return res;
1449 }
1450
1451 // Add all the symbols in a dynamic object to the hash table.
1452
1453 template<int size, bool big_endian>
1454 void
1455 Symbol_table::add_from_dynobj(
1456     Sized_dynobj<size, big_endian>* dynobj,
1457     const unsigned char* syms,
1458     size_t count,
1459     const char* sym_names,
1460     size_t sym_name_size,
1461     const unsigned char* versym,
1462     size_t versym_size,
1463     const std::vector<const char*>* version_map,
1464     typename Sized_relobj_file<size, big_endian>::Symbols* sympointers,
1465     size_t* defined)
1466 {
1467   *defined = 0;
1468
1469   gold_assert(size == parameters->target().get_size());
1470
1471   if (dynobj->just_symbols())
1472     {
1473       gold_error(_("--just-symbols does not make sense with a shared object"));
1474       return;
1475     }
1476
1477   // FIXME: For incremental links, we don't store version information,
1478   // so we need to ignore version symbols for now.
1479   if (parameters->incremental_update())
1480     versym = NULL;
1481
1482   if (versym != NULL && versym_size / 2 < count)
1483     {
1484       dynobj->error(_("too few symbol versions"));
1485       return;
1486     }
1487
1488   const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
1489
1490   // We keep a list of all STT_OBJECT symbols, so that we can resolve
1491   // weak aliases.  This is necessary because if the dynamic object
1492   // provides the same variable under two names, one of which is a
1493   // weak definition, and the regular object refers to the weak
1494   // definition, we have to put both the weak definition and the
1495   // strong definition into the dynamic symbol table.  Given a weak
1496   // definition, the only way that we can find the corresponding
1497   // strong definition, if any, is to search the symbol table.
1498   std::vector<Sized_symbol<size>*> object_symbols;
1499
1500   const unsigned char* p = syms;
1501   const unsigned char* vs = versym;
1502   for (size_t i = 0; i < count; ++i, p += sym_size, vs += 2)
1503     {
1504       elfcpp::Sym<size, big_endian> sym(p);
1505
1506       if (sympointers != NULL)
1507         (*sympointers)[i] = NULL;
1508
1509       // Ignore symbols with local binding or that have
1510       // internal or hidden visibility.
1511       if (sym.get_st_bind() == elfcpp::STB_LOCAL
1512           || sym.get_st_visibility() == elfcpp::STV_INTERNAL
1513           || sym.get_st_visibility() == elfcpp::STV_HIDDEN)
1514         continue;
1515
1516       // A protected symbol in a shared library must be treated as a
1517       // normal symbol when viewed from outside the shared library.
1518       // Implement this by overriding the visibility here.
1519       // Likewise, an IFUNC symbol in a shared library must be treated
1520       // as a normal FUNC symbol.
1521       elfcpp::Sym<size, big_endian>* psym = &sym;
1522       unsigned char symbuf[sym_size];
1523       elfcpp::Sym<size, big_endian> sym2(symbuf);
1524       if (sym.get_st_visibility() == elfcpp::STV_PROTECTED
1525           || sym.get_st_type() == elfcpp::STT_GNU_IFUNC)
1526         {
1527           memcpy(symbuf, p, sym_size);
1528           elfcpp::Sym_write<size, big_endian> sw(symbuf);
1529           if (sym.get_st_visibility() == elfcpp::STV_PROTECTED)
1530             sw.put_st_other(elfcpp::STV_DEFAULT, sym.get_st_nonvis());
1531           if (sym.get_st_type() == elfcpp::STT_GNU_IFUNC)
1532             sw.put_st_info(sym.get_st_bind(), elfcpp::STT_FUNC);
1533           psym = &sym2;
1534         }
1535
1536       unsigned int st_name = psym->get_st_name();
1537       if (st_name >= sym_name_size)
1538         {
1539           dynobj->error(_("bad symbol name offset %u at %zu"),
1540                         st_name, i);
1541           continue;
1542         }
1543
1544       const char* name = sym_names + st_name;
1545
1546       bool is_ordinary;
1547       unsigned int st_shndx = dynobj->adjust_sym_shndx(i, psym->get_st_shndx(),
1548                                                        &is_ordinary);
1549
1550       if (st_shndx != elfcpp::SHN_UNDEF)
1551         ++*defined;
1552
1553       Sized_symbol<size>* res;
1554
1555       if (versym == NULL)
1556         {
1557           Stringpool::Key name_key;
1558           name = this->namepool_.add(name, true, &name_key);
1559           res = this->add_from_object(dynobj, name, name_key, NULL, 0,
1560                                       false, *psym, st_shndx, is_ordinary,
1561                                       st_shndx);
1562         }
1563       else
1564         {
1565           // Read the version information.
1566
1567           unsigned int v = elfcpp::Swap<16, big_endian>::readval(vs);
1568
1569           bool hidden = (v & elfcpp::VERSYM_HIDDEN) != 0;
1570           v &= elfcpp::VERSYM_VERSION;
1571
1572           // The Sun documentation says that V can be VER_NDX_LOCAL,
1573           // or VER_NDX_GLOBAL, or a version index.  The meaning of
1574           // VER_NDX_LOCAL is defined as "Symbol has local scope."
1575           // The old GNU linker will happily generate VER_NDX_LOCAL
1576           // for an undefined symbol.  I don't know what the Sun
1577           // linker will generate.
1578
1579           if (v == static_cast<unsigned int>(elfcpp::VER_NDX_LOCAL)
1580               && st_shndx != elfcpp::SHN_UNDEF)
1581             {
1582               // This symbol should not be visible outside the object.
1583               continue;
1584             }
1585
1586           // At this point we are definitely going to add this symbol.
1587           Stringpool::Key name_key;
1588           name = this->namepool_.add(name, true, &name_key);
1589
1590           if (v == static_cast<unsigned int>(elfcpp::VER_NDX_LOCAL)
1591               || v == static_cast<unsigned int>(elfcpp::VER_NDX_GLOBAL))
1592             {
1593               // This symbol does not have a version.
1594               res = this->add_from_object(dynobj, name, name_key, NULL, 0,
1595                                           false, *psym, st_shndx, is_ordinary,
1596                                           st_shndx);
1597             }
1598           else
1599             {
1600               if (v >= version_map->size())
1601                 {
1602                   dynobj->error(_("versym for symbol %zu out of range: %u"),
1603                                 i, v);
1604                   continue;
1605                 }
1606
1607               const char* version = (*version_map)[v];
1608               if (version == NULL)
1609                 {
1610                   dynobj->error(_("versym for symbol %zu has no name: %u"),
1611                                 i, v);
1612                   continue;
1613                 }
1614
1615               Stringpool::Key version_key;
1616               version = this->namepool_.add(version, true, &version_key);
1617
1618               // If this is an absolute symbol, and the version name
1619               // and symbol name are the same, then this is the
1620               // version definition symbol.  These symbols exist to
1621               // support using -u to pull in particular versions.  We
1622               // do not want to record a version for them.
1623               if (st_shndx == elfcpp::SHN_ABS
1624                   && !is_ordinary
1625                   && name_key == version_key)
1626                 res = this->add_from_object(dynobj, name, name_key, NULL, 0,
1627                                             false, *psym, st_shndx, is_ordinary,
1628                                             st_shndx);
1629               else
1630                 {
1631                   const bool is_default_version =
1632                     !hidden && st_shndx != elfcpp::SHN_UNDEF;
1633                   res = this->add_from_object(dynobj, name, name_key, version,
1634                                               version_key, is_default_version,
1635                                               *psym, st_shndx,
1636                                               is_ordinary, st_shndx);
1637                 }
1638             }
1639         }
1640
1641       if (res == NULL)
1642         continue;
1643
1644       // Note that it is possible that RES was overridden by an
1645       // earlier object, in which case it can't be aliased here.
1646       if (st_shndx != elfcpp::SHN_UNDEF
1647           && is_ordinary
1648           && psym->get_st_type() == elfcpp::STT_OBJECT
1649           && res->source() == Symbol::FROM_OBJECT
1650           && res->object() == dynobj)
1651         object_symbols.push_back(res);
1652
1653       // If the symbol has protected visibility in the dynobj,
1654       // mark it as such if it was not overridden.
1655       if (res->source() == Symbol::FROM_OBJECT
1656           && res->object() == dynobj
1657           && sym.get_st_visibility() == elfcpp::STV_PROTECTED)
1658         res->set_is_protected();
1659
1660       if (sympointers != NULL)
1661         (*sympointers)[i] = res;
1662     }
1663
1664   this->record_weak_aliases(&object_symbols);
1665 }
1666
1667 // Add a symbol from a incremental object file.
1668
1669 template<int size, bool big_endian>
1670 Sized_symbol<size>*
1671 Symbol_table::add_from_incrobj(
1672     Object* obj,
1673     const char* name,
1674     const char* ver,
1675     elfcpp::Sym<size, big_endian>* sym)
1676 {
1677   unsigned int st_shndx = sym->get_st_shndx();
1678   bool is_ordinary = st_shndx < elfcpp::SHN_LORESERVE;
1679
1680   Stringpool::Key ver_key = 0;
1681   bool is_default_version = false;
1682
1683   Stringpool::Key name_key;
1684   name = this->namepool_.add(name, true, &name_key);
1685
1686   Sized_symbol<size>* res;
1687   res = this->add_from_object(obj, name, name_key, ver, ver_key,
1688                               is_default_version, *sym, st_shndx,
1689                               is_ordinary, st_shndx);
1690
1691   return res;
1692 }
1693
1694 // This is used to sort weak aliases.  We sort them first by section
1695 // index, then by offset, then by weak ahead of strong.
1696
1697 template<int size>
1698 class Weak_alias_sorter
1699 {
1700  public:
1701   bool operator()(const Sized_symbol<size>*, const Sized_symbol<size>*) const;
1702 };
1703
1704 template<int size>
1705 bool
1706 Weak_alias_sorter<size>::operator()(const Sized_symbol<size>* s1,
1707                                     const Sized_symbol<size>* s2) const
1708 {
1709   bool is_ordinary;
1710   unsigned int s1_shndx = s1->shndx(&is_ordinary);
1711   gold_assert(is_ordinary);
1712   unsigned int s2_shndx = s2->shndx(&is_ordinary);
1713   gold_assert(is_ordinary);
1714   if (s1_shndx != s2_shndx)
1715     return s1_shndx < s2_shndx;
1716
1717   if (s1->value() != s2->value())
1718     return s1->value() < s2->value();
1719   if (s1->binding() != s2->binding())
1720     {
1721       if (s1->binding() == elfcpp::STB_WEAK)
1722         return true;
1723       if (s2->binding() == elfcpp::STB_WEAK)
1724         return false;
1725     }
1726   return std::string(s1->name()) < std::string(s2->name());
1727 }
1728
1729 // SYMBOLS is a list of object symbols from a dynamic object.  Look
1730 // for any weak aliases, and record them so that if we add the weak
1731 // alias to the dynamic symbol table, we also add the corresponding
1732 // strong symbol.
1733
1734 template<int size>
1735 void
1736 Symbol_table::record_weak_aliases(std::vector<Sized_symbol<size>*>* symbols)
1737 {
1738   // Sort the vector by section index, then by offset, then by weak
1739   // ahead of strong.
1740   std::sort(symbols->begin(), symbols->end(), Weak_alias_sorter<size>());
1741
1742   // Walk through the vector.  For each weak definition, record
1743   // aliases.
1744   for (typename std::vector<Sized_symbol<size>*>::const_iterator p =
1745          symbols->begin();
1746        p != symbols->end();
1747        ++p)
1748     {
1749       if ((*p)->binding() != elfcpp::STB_WEAK)
1750         continue;
1751
1752       // Build a circular list of weak aliases.  Each symbol points to
1753       // the next one in the circular list.
1754
1755       Sized_symbol<size>* from_sym = *p;
1756       typename std::vector<Sized_symbol<size>*>::const_iterator q;
1757       for (q = p + 1; q != symbols->end(); ++q)
1758         {
1759           bool dummy;
1760           if ((*q)->shndx(&dummy) != from_sym->shndx(&dummy)
1761               || (*q)->value() != from_sym->value())
1762             break;
1763
1764           this->weak_aliases_[from_sym] = *q;
1765           from_sym->set_has_alias();
1766           from_sym = *q;
1767         }
1768
1769       if (from_sym != *p)
1770         {
1771           this->weak_aliases_[from_sym] = *p;
1772           from_sym->set_has_alias();
1773         }
1774
1775       p = q - 1;
1776     }
1777 }
1778
1779 // Create and return a specially defined symbol.  If ONLY_IF_REF is
1780 // true, then only create the symbol if there is a reference to it.
1781 // If this does not return NULL, it sets *POLDSYM to the existing
1782 // symbol if there is one.  This sets *RESOLVE_OLDSYM if we should
1783 // resolve the newly created symbol to the old one.  This
1784 // canonicalizes *PNAME and *PVERSION.
1785
1786 template<int size, bool big_endian>
1787 Sized_symbol<size>*
1788 Symbol_table::define_special_symbol(const char** pname, const char** pversion,
1789                                     bool only_if_ref,
1790                                     elfcpp::STV visibility,
1791                                     Sized_symbol<size>** poldsym,
1792                                     bool* resolve_oldsym, bool is_forced_local)
1793 {
1794   *resolve_oldsym = false;
1795   *poldsym = NULL;
1796
1797   // If the caller didn't give us a version, see if we get one from
1798   // the version script.
1799   std::string v;
1800   bool is_default_version = false;
1801   if (!is_forced_local && *pversion == NULL)
1802     {
1803       bool is_global;
1804       if (this->version_script_.get_symbol_version(*pname, &v, &is_global))
1805         {
1806           if (is_global && !v.empty())
1807             {
1808               *pversion = v.c_str();
1809               // If we get the version from a version script, then we
1810               // are also the default version.
1811               is_default_version = true;
1812             }
1813         }
1814     }
1815
1816   Symbol* oldsym;
1817   Sized_symbol<size>* sym;
1818
1819   bool add_to_table = false;
1820   typename Symbol_table_type::iterator add_loc = this->table_.end();
1821   bool add_def_to_table = false;
1822   typename Symbol_table_type::iterator add_def_loc = this->table_.end();
1823
1824   if (only_if_ref)
1825     {
1826       oldsym = this->lookup(*pname, *pversion);
1827       if (oldsym == NULL && is_default_version)
1828         oldsym = this->lookup(*pname, NULL);
1829       if (oldsym == NULL)
1830         return NULL;
1831       if (!oldsym->is_undefined())
1832         {
1833           // Skip if the old definition is from a regular object.
1834           if (!oldsym->is_from_dynobj())
1835             return NULL;
1836
1837           // If the symbol has hidden or internal visibility, ignore
1838           // definition and reference from a dynamic object.
1839           if ((visibility == elfcpp::STV_HIDDEN
1840                || visibility == elfcpp::STV_INTERNAL)
1841               && !oldsym->in_reg())
1842             return NULL;
1843         }
1844
1845       *pname = oldsym->name();
1846       if (is_default_version)
1847         *pversion = this->namepool_.add(*pversion, true, NULL);
1848       else
1849         *pversion = oldsym->version();
1850     }
1851   else
1852     {
1853       // Canonicalize NAME and VERSION.
1854       Stringpool::Key name_key;
1855       *pname = this->namepool_.add(*pname, true, &name_key);
1856
1857       Stringpool::Key version_key = 0;
1858       if (*pversion != NULL)
1859         *pversion = this->namepool_.add(*pversion, true, &version_key);
1860
1861       Symbol* const snull = NULL;
1862       std::pair<typename Symbol_table_type::iterator, bool> ins =
1863         this->table_.insert(std::make_pair(std::make_pair(name_key,
1864                                                           version_key),
1865                                            snull));
1866
1867       std::pair<typename Symbol_table_type::iterator, bool> insdefault =
1868         std::make_pair(this->table_.end(), false);
1869       if (is_default_version)
1870         {
1871           const Stringpool::Key vnull = 0;
1872           insdefault =
1873             this->table_.insert(std::make_pair(std::make_pair(name_key,
1874                                                               vnull),
1875                                                snull));
1876         }
1877
1878       if (!ins.second)
1879         {
1880           // We already have a symbol table entry for NAME/VERSION.
1881           oldsym = ins.first->second;
1882           gold_assert(oldsym != NULL);
1883
1884           if (is_default_version)
1885             {
1886               Sized_symbol<size>* soldsym =
1887                 this->get_sized_symbol<size>(oldsym);
1888               this->define_default_version<size, big_endian>(soldsym,
1889                                                              insdefault.second,
1890                                                              insdefault.first);
1891             }
1892         }
1893       else
1894         {
1895           // We haven't seen this symbol before.
1896           gold_assert(ins.first->second == NULL);
1897
1898           add_to_table = true;
1899           add_loc = ins.first;
1900
1901           if (is_default_version
1902               && !insdefault.second
1903               && insdefault.first->second->version() == NULL)
1904             {
1905               // We are adding NAME/VERSION, and it is the default
1906               // version.  We already have an entry for NAME/NULL
1907               // that does not already have a version.
1908               oldsym = insdefault.first->second;
1909               *resolve_oldsym = true;
1910             }
1911           else
1912             {
1913               oldsym = NULL;
1914
1915               if (is_default_version)
1916                 {
1917                   add_def_to_table = true;
1918                   add_def_loc = insdefault.first;
1919                 }
1920             }
1921         }
1922     }
1923
1924   const Target& target = parameters->target();
1925   if (!target.has_make_symbol())
1926     sym = new Sized_symbol<size>();
1927   else
1928     {
1929       Sized_target<size, big_endian>* sized_target =
1930         parameters->sized_target<size, big_endian>();
1931       sym = sized_target->make_symbol(*pname, elfcpp::STT_NOTYPE,
1932                                       NULL, elfcpp::SHN_UNDEF, 0);
1933       if (sym == NULL)
1934         return NULL;
1935     }
1936
1937   if (add_to_table)
1938     add_loc->second = sym;
1939   else
1940     gold_assert(oldsym != NULL);
1941
1942   if (add_def_to_table)
1943     add_def_loc->second = sym;
1944
1945   *poldsym = this->get_sized_symbol<size>(oldsym);
1946
1947   return sym;
1948 }
1949
1950 // Define a symbol based on an Output_data.
1951
1952 Symbol*
1953 Symbol_table::define_in_output_data(const char* name,
1954                                     const char* version,
1955                                     Defined defined,
1956                                     Output_data* od,
1957                                     uint64_t value,
1958                                     uint64_t symsize,
1959                                     elfcpp::STT type,
1960                                     elfcpp::STB binding,
1961                                     elfcpp::STV visibility,
1962                                     unsigned char nonvis,
1963                                     bool offset_is_from_end,
1964                                     bool only_if_ref)
1965 {
1966   if (parameters->target().get_size() == 32)
1967     {
1968 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
1969       return this->do_define_in_output_data<32>(name, version, defined, od,
1970                                                 value, symsize, type, binding,
1971                                                 visibility, nonvis,
1972                                                 offset_is_from_end,
1973                                                 only_if_ref);
1974 #else
1975       gold_unreachable();
1976 #endif
1977     }
1978   else if (parameters->target().get_size() == 64)
1979     {
1980 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
1981       return this->do_define_in_output_data<64>(name, version, defined, od,
1982                                                 value, symsize, type, binding,
1983                                                 visibility, nonvis,
1984                                                 offset_is_from_end,
1985                                                 only_if_ref);
1986 #else
1987       gold_unreachable();
1988 #endif
1989     }
1990   else
1991     gold_unreachable();
1992 }
1993
1994 // Define a symbol in an Output_data, sized version.
1995
1996 template<int size>
1997 Sized_symbol<size>*
1998 Symbol_table::do_define_in_output_data(
1999     const char* name,
2000     const char* version,
2001     Defined defined,
2002     Output_data* od,
2003     typename elfcpp::Elf_types<size>::Elf_Addr value,
2004     typename elfcpp::Elf_types<size>::Elf_WXword symsize,
2005     elfcpp::STT type,
2006     elfcpp::STB binding,
2007     elfcpp::STV visibility,
2008     unsigned char nonvis,
2009     bool offset_is_from_end,
2010     bool only_if_ref)
2011 {
2012   Sized_symbol<size>* sym;
2013   Sized_symbol<size>* oldsym;
2014   bool resolve_oldsym;
2015   const bool is_forced_local = binding == elfcpp::STB_LOCAL;
2016
2017   if (parameters->target().is_big_endian())
2018     {
2019 #if defined(HAVE_TARGET_32_BIG) || defined(HAVE_TARGET_64_BIG)
2020       sym = this->define_special_symbol<size, true>(&name, &version,
2021                                                     only_if_ref,
2022                                                     visibility,
2023                                                     &oldsym,
2024                                                     &resolve_oldsym,
2025                                                     is_forced_local);
2026 #else
2027       gold_unreachable();
2028 #endif
2029     }
2030   else
2031     {
2032 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_64_LITTLE)
2033       sym = this->define_special_symbol<size, false>(&name, &version,
2034                                                      only_if_ref,
2035                                                      visibility,
2036                                                      &oldsym,
2037                                                      &resolve_oldsym,
2038                                                      is_forced_local);
2039 #else
2040       gold_unreachable();
2041 #endif
2042     }
2043
2044   if (sym == NULL)
2045     return NULL;
2046
2047   sym->init_output_data(name, version, od, value, symsize, type, binding,
2048                         visibility, nonvis, offset_is_from_end,
2049                         defined == PREDEFINED);
2050
2051   if (oldsym == NULL)
2052     {
2053       if (is_forced_local || this->version_script_.symbol_is_local(name))
2054         this->force_local(sym);
2055       else if (version != NULL)
2056         sym->set_is_default();
2057       return sym;
2058     }
2059
2060   if (Symbol_table::should_override_with_special(oldsym, type, defined))
2061     this->override_with_special(oldsym, sym);
2062
2063   if (resolve_oldsym)
2064     return sym;
2065   else
2066     {
2067       if (defined == PREDEFINED
2068           && (is_forced_local || this->version_script_.symbol_is_local(name)))
2069         this->force_local(oldsym);
2070       delete sym;
2071       return oldsym;
2072     }
2073 }
2074
2075 // Define a symbol based on an Output_segment.
2076
2077 Symbol*
2078 Symbol_table::define_in_output_segment(const char* name,
2079                                        const char* version,
2080                                        Defined defined,
2081                                        Output_segment* os,
2082                                        uint64_t value,
2083                                        uint64_t symsize,
2084                                        elfcpp::STT type,
2085                                        elfcpp::STB binding,
2086                                        elfcpp::STV visibility,
2087                                        unsigned char nonvis,
2088                                        Symbol::Segment_offset_base offset_base,
2089                                        bool only_if_ref)
2090 {
2091   if (parameters->target().get_size() == 32)
2092     {
2093 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
2094       return this->do_define_in_output_segment<32>(name, version, defined, os,
2095                                                    value, symsize, type,
2096                                                    binding, visibility, nonvis,
2097                                                    offset_base, only_if_ref);
2098 #else
2099       gold_unreachable();
2100 #endif
2101     }
2102   else if (parameters->target().get_size() == 64)
2103     {
2104 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
2105       return this->do_define_in_output_segment<64>(name, version, defined, os,
2106                                                    value, symsize, type,
2107                                                    binding, visibility, nonvis,
2108                                                    offset_base, only_if_ref);
2109 #else
2110       gold_unreachable();
2111 #endif
2112     }
2113   else
2114     gold_unreachable();
2115 }
2116
2117 // Define a symbol in an Output_segment, sized version.
2118
2119 template<int size>
2120 Sized_symbol<size>*
2121 Symbol_table::do_define_in_output_segment(
2122     const char* name,
2123     const char* version,
2124     Defined defined,
2125     Output_segment* os,
2126     typename elfcpp::Elf_types<size>::Elf_Addr value,
2127     typename elfcpp::Elf_types<size>::Elf_WXword symsize,
2128     elfcpp::STT type,
2129     elfcpp::STB binding,
2130     elfcpp::STV visibility,
2131     unsigned char nonvis,
2132     Symbol::Segment_offset_base offset_base,
2133     bool only_if_ref)
2134 {
2135   Sized_symbol<size>* sym;
2136   Sized_symbol<size>* oldsym;
2137   bool resolve_oldsym;
2138   const bool is_forced_local = binding == elfcpp::STB_LOCAL;
2139
2140   if (parameters->target().is_big_endian())
2141     {
2142 #if defined(HAVE_TARGET_32_BIG) || defined(HAVE_TARGET_64_BIG)
2143       sym = this->define_special_symbol<size, true>(&name, &version,
2144                                                     only_if_ref,
2145                                                     visibility,
2146                                                     &oldsym,
2147                                                     &resolve_oldsym,
2148                                                     is_forced_local);
2149 #else
2150       gold_unreachable();
2151 #endif
2152     }
2153   else
2154     {
2155 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_64_LITTLE)
2156       sym = this->define_special_symbol<size, false>(&name, &version,
2157                                                      only_if_ref,
2158                                                      visibility,
2159                                                      &oldsym,
2160                                                      &resolve_oldsym,
2161                                                      is_forced_local);
2162 #else
2163       gold_unreachable();
2164 #endif
2165     }
2166
2167   if (sym == NULL)
2168     return NULL;
2169
2170   sym->init_output_segment(name, version, os, value, symsize, type, binding,
2171                            visibility, nonvis, offset_base,
2172                            defined == PREDEFINED);
2173
2174   if (oldsym == NULL)
2175     {
2176       if (is_forced_local || this->version_script_.symbol_is_local(name))
2177         this->force_local(sym);
2178       else if (version != NULL)
2179         sym->set_is_default();
2180       return sym;
2181     }
2182
2183   if (Symbol_table::should_override_with_special(oldsym, type, defined))
2184     this->override_with_special(oldsym, sym);
2185
2186   if (resolve_oldsym)
2187     return sym;
2188   else
2189     {
2190       if (is_forced_local || this->version_script_.symbol_is_local(name))
2191         this->force_local(oldsym);
2192       delete sym;
2193       return oldsym;
2194     }
2195 }
2196
2197 // Define a special symbol with a constant value.  It is a multiple
2198 // definition error if this symbol is already defined.
2199
2200 Symbol*
2201 Symbol_table::define_as_constant(const char* name,
2202                                  const char* version,
2203                                  Defined defined,
2204                                  uint64_t value,
2205                                  uint64_t symsize,
2206                                  elfcpp::STT type,
2207                                  elfcpp::STB binding,
2208                                  elfcpp::STV visibility,
2209                                  unsigned char nonvis,
2210                                  bool only_if_ref,
2211                                  bool force_override)
2212 {
2213   if (parameters->target().get_size() == 32)
2214     {
2215 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
2216       return this->do_define_as_constant<32>(name, version, defined, value,
2217                                              symsize, type, binding,
2218                                              visibility, nonvis, only_if_ref,
2219                                              force_override);
2220 #else
2221       gold_unreachable();
2222 #endif
2223     }
2224   else if (parameters->target().get_size() == 64)
2225     {
2226 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
2227       return this->do_define_as_constant<64>(name, version, defined, value,
2228                                              symsize, type, binding,
2229                                              visibility, nonvis, only_if_ref,
2230                                              force_override);
2231 #else
2232       gold_unreachable();
2233 #endif
2234     }
2235   else
2236     gold_unreachable();
2237 }
2238
2239 // Define a symbol as a constant, sized version.
2240
2241 template<int size>
2242 Sized_symbol<size>*
2243 Symbol_table::do_define_as_constant(
2244     const char* name,
2245     const char* version,
2246     Defined defined,
2247     typename elfcpp::Elf_types<size>::Elf_Addr value,
2248     typename elfcpp::Elf_types<size>::Elf_WXword symsize,
2249     elfcpp::STT type,
2250     elfcpp::STB binding,
2251     elfcpp::STV visibility,
2252     unsigned char nonvis,
2253     bool only_if_ref,
2254     bool force_override)
2255 {
2256   Sized_symbol<size>* sym;
2257   Sized_symbol<size>* oldsym;
2258   bool resolve_oldsym;
2259   const bool is_forced_local = binding == elfcpp::STB_LOCAL;
2260
2261   if (parameters->target().is_big_endian())
2262     {
2263 #if defined(HAVE_TARGET_32_BIG) || defined(HAVE_TARGET_64_BIG)
2264       sym = this->define_special_symbol<size, true>(&name, &version,
2265                                                     only_if_ref,
2266                                                     visibility,
2267                                                     &oldsym,
2268                                                     &resolve_oldsym,
2269                                                     is_forced_local);
2270 #else
2271       gold_unreachable();
2272 #endif
2273     }
2274   else
2275     {
2276 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_64_LITTLE)
2277       sym = this->define_special_symbol<size, false>(&name, &version,
2278                                                      only_if_ref,
2279                                                      visibility,
2280                                                      &oldsym,
2281                                                      &resolve_oldsym,
2282                                                      is_forced_local);
2283 #else
2284       gold_unreachable();
2285 #endif
2286     }
2287
2288   if (sym == NULL)
2289     return NULL;
2290
2291   sym->init_constant(name, version, value, symsize, type, binding, visibility,
2292                      nonvis, defined == PREDEFINED);
2293
2294   if (oldsym == NULL)
2295     {
2296       // Version symbols are absolute symbols with name == version.
2297       // We don't want to force them to be local.
2298       if ((version == NULL
2299            || name != version
2300            || value != 0)
2301           && (is_forced_local || this->version_script_.symbol_is_local(name)))
2302         this->force_local(sym);
2303       else if (version != NULL
2304                && (name != version || value != 0))
2305         sym->set_is_default();
2306       return sym;
2307     }
2308
2309   if (force_override
2310       || Symbol_table::should_override_with_special(oldsym, type, defined))
2311     this->override_with_special(oldsym, sym);
2312
2313   if (resolve_oldsym)
2314     return sym;
2315   else
2316     {
2317       if (is_forced_local || this->version_script_.symbol_is_local(name))
2318         this->force_local(oldsym);
2319       delete sym;
2320       return oldsym;
2321     }
2322 }
2323
2324 // Define a set of symbols in output sections.
2325
2326 void
2327 Symbol_table::define_symbols(const Layout* layout, int count,
2328                              const Define_symbol_in_section* p,
2329                              bool only_if_ref)
2330 {
2331   for (int i = 0; i < count; ++i, ++p)
2332     {
2333       Output_section* os = layout->find_output_section(p->output_section);
2334       if (os != NULL)
2335         this->define_in_output_data(p->name, NULL, PREDEFINED, os, p->value,
2336                                     p->size, p->type, p->binding,
2337                                     p->visibility, p->nonvis,
2338                                     p->offset_is_from_end,
2339                                     only_if_ref || p->only_if_ref);
2340       else
2341         this->define_as_constant(p->name, NULL, PREDEFINED, 0, p->size,
2342                                  p->type, p->binding, p->visibility, p->nonvis,
2343                                  only_if_ref || p->only_if_ref,
2344                                  false);
2345     }
2346 }
2347
2348 // Define a set of symbols in output segments.
2349
2350 void
2351 Symbol_table::define_symbols(const Layout* layout, int count,
2352                              const Define_symbol_in_segment* p,
2353                              bool only_if_ref)
2354 {
2355   for (int i = 0; i < count; ++i, ++p)
2356     {
2357       Output_segment* os = layout->find_output_segment(p->segment_type,
2358                                                        p->segment_flags_set,
2359                                                        p->segment_flags_clear);
2360       if (os != NULL)
2361         this->define_in_output_segment(p->name, NULL, PREDEFINED, os, p->value,
2362                                        p->size, p->type, p->binding,
2363                                        p->visibility, p->nonvis,
2364                                        p->offset_base,
2365                                        only_if_ref || p->only_if_ref);
2366       else
2367         this->define_as_constant(p->name, NULL, PREDEFINED, 0, p->size,
2368                                  p->type, p->binding, p->visibility, p->nonvis,
2369                                  only_if_ref || p->only_if_ref,
2370                                  false);
2371     }
2372 }
2373
2374 // Define CSYM using a COPY reloc.  POSD is the Output_data where the
2375 // symbol should be defined--typically a .dyn.bss section.  VALUE is
2376 // the offset within POSD.
2377
2378 template<int size>
2379 void
2380 Symbol_table::define_with_copy_reloc(
2381     Sized_symbol<size>* csym,
2382     Output_data* posd,
2383     typename elfcpp::Elf_types<size>::Elf_Addr value)
2384 {
2385   gold_assert(csym->is_from_dynobj());
2386   gold_assert(!csym->is_copied_from_dynobj());
2387   Object* object = csym->object();
2388   gold_assert(object->is_dynamic());
2389   Dynobj* dynobj = static_cast<Dynobj*>(object);
2390
2391   // Our copied variable has to override any variable in a shared
2392   // library.
2393   elfcpp::STB binding = csym->binding();
2394   if (binding == elfcpp::STB_WEAK)
2395     binding = elfcpp::STB_GLOBAL;
2396
2397   this->define_in_output_data(csym->name(), csym->version(), COPY,
2398                               posd, value, csym->symsize(),
2399                               csym->type(), binding,
2400                               csym->visibility(), csym->nonvis(),
2401                               false, false);
2402
2403   csym->set_is_copied_from_dynobj();
2404   csym->set_needs_dynsym_entry();
2405
2406   this->copied_symbol_dynobjs_[csym] = dynobj;
2407
2408   // We have now defined all aliases, but we have not entered them all
2409   // in the copied_symbol_dynobjs_ map.
2410   if (csym->has_alias())
2411     {
2412       Symbol* sym = csym;
2413       while (true)
2414         {
2415           sym = this->weak_aliases_[sym];
2416           if (sym == csym)
2417             break;
2418           gold_assert(sym->output_data() == posd);
2419
2420           sym->set_is_copied_from_dynobj();
2421           this->copied_symbol_dynobjs_[sym] = dynobj;
2422         }
2423     }
2424 }
2425
2426 // SYM is defined using a COPY reloc.  Return the dynamic object where
2427 // the original definition was found.
2428
2429 Dynobj*
2430 Symbol_table::get_copy_source(const Symbol* sym) const
2431 {
2432   gold_assert(sym->is_copied_from_dynobj());
2433   Copied_symbol_dynobjs::const_iterator p =
2434     this->copied_symbol_dynobjs_.find(sym);
2435   gold_assert(p != this->copied_symbol_dynobjs_.end());
2436   return p->second;
2437 }
2438
2439 // Add any undefined symbols named on the command line.
2440
2441 void
2442 Symbol_table::add_undefined_symbols_from_command_line(Layout* layout)
2443 {
2444   if (parameters->options().any_undefined()
2445       || layout->script_options()->any_unreferenced())
2446     {
2447       if (parameters->target().get_size() == 32)
2448         {
2449 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
2450           this->do_add_undefined_symbols_from_command_line<32>(layout);
2451 #else
2452           gold_unreachable();
2453 #endif
2454         }
2455       else if (parameters->target().get_size() == 64)
2456         {
2457 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
2458           this->do_add_undefined_symbols_from_command_line<64>(layout);
2459 #else
2460           gold_unreachable();
2461 #endif
2462         }
2463       else
2464         gold_unreachable();
2465     }
2466 }
2467
2468 template<int size>
2469 void
2470 Symbol_table::do_add_undefined_symbols_from_command_line(Layout* layout)
2471 {
2472   for (options::String_set::const_iterator p =
2473          parameters->options().undefined_begin();
2474        p != parameters->options().undefined_end();
2475        ++p)
2476     this->add_undefined_symbol_from_command_line<size>(p->c_str());
2477
2478   for (options::String_set::const_iterator p =
2479          parameters->options().export_dynamic_symbol_begin();
2480        p != parameters->options().export_dynamic_symbol_end();
2481        ++p)
2482     this->add_undefined_symbol_from_command_line<size>(p->c_str());
2483
2484   for (Script_options::referenced_const_iterator p =
2485          layout->script_options()->referenced_begin();
2486        p != layout->script_options()->referenced_end();
2487        ++p)
2488     this->add_undefined_symbol_from_command_line<size>(p->c_str());
2489 }
2490
2491 template<int size>
2492 void
2493 Symbol_table::add_undefined_symbol_from_command_line(const char* name)
2494 {
2495   if (this->lookup(name) != NULL)
2496     return;
2497
2498   const char* version = NULL;
2499
2500   Sized_symbol<size>* sym;
2501   Sized_symbol<size>* oldsym;
2502   bool resolve_oldsym;
2503   if (parameters->target().is_big_endian())
2504     {
2505 #if defined(HAVE_TARGET_32_BIG) || defined(HAVE_TARGET_64_BIG)
2506       sym = this->define_special_symbol<size, true>(&name, &version,
2507                                                     false,
2508                                                     elfcpp::STV_DEFAULT,
2509                                                     &oldsym,
2510                                                     &resolve_oldsym,
2511                                                     false);
2512 #else
2513       gold_unreachable();
2514 #endif
2515     }
2516   else
2517     {
2518 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_64_LITTLE)
2519       sym = this->define_special_symbol<size, false>(&name, &version,
2520                                                      false,
2521                                                      elfcpp::STV_DEFAULT,
2522                                                      &oldsym,
2523                                                      &resolve_oldsym,
2524                                                      false);
2525 #else
2526       gold_unreachable();
2527 #endif
2528     }
2529
2530   gold_assert(oldsym == NULL);
2531
2532   sym->init_undefined(name, version, 0, elfcpp::STT_NOTYPE, elfcpp::STB_GLOBAL,
2533                       elfcpp::STV_DEFAULT, 0);
2534   ++this->saw_undefined_;
2535 }
2536
2537 // Set the dynamic symbol indexes.  INDEX is the index of the first
2538 // global dynamic symbol.  Pointers to the global symbols are stored
2539 // into the vector SYMS.  The names are added to DYNPOOL.
2540 // This returns an updated dynamic symbol index.
2541
2542 unsigned int
2543 Symbol_table::set_dynsym_indexes(unsigned int index,
2544                                  unsigned int* pforced_local_count,
2545                                  std::vector<Symbol*>* syms,
2546                                  Stringpool* dynpool,
2547                                  Versions* versions)
2548 {
2549   // First process all the symbols which have been forced to be local,
2550   // as they must appear before all global symbols.
2551   unsigned int forced_local_count = 0;
2552   for (Forced_locals::iterator p = this->forced_locals_.begin();
2553        p != this->forced_locals_.end();
2554        ++p)
2555     {
2556       Symbol* sym = *p;
2557       gold_assert(sym->is_forced_local());
2558       if (sym->has_dynsym_index())
2559         continue;
2560       if (!sym->should_add_dynsym_entry(this))
2561         sym->set_dynsym_index(-1U);
2562       else
2563         {
2564           sym->set_dynsym_index(index);
2565           ++index;
2566           ++forced_local_count;
2567           dynpool->add(sym->name(), false, NULL);
2568         }
2569     }
2570   *pforced_local_count = forced_local_count;
2571
2572   // Allow a target to set dynsym indexes.
2573   if (parameters->target().has_custom_set_dynsym_indexes())
2574     {
2575       std::vector<Symbol*> dyn_symbols;
2576       for (Symbol_table_type::iterator p = this->table_.begin();
2577            p != this->table_.end();
2578            ++p)
2579         {
2580           Symbol* sym = p->second;
2581           if (sym->is_forced_local())
2582             continue;
2583           if (!sym->should_add_dynsym_entry(this))
2584             sym->set_dynsym_index(-1U);
2585           else
2586             dyn_symbols.push_back(sym);
2587         }
2588
2589       return parameters->target().set_dynsym_indexes(&dyn_symbols, index, syms,
2590                                                      dynpool, versions, this);
2591     }
2592
2593   for (Symbol_table_type::iterator p = this->table_.begin();
2594        p != this->table_.end();
2595        ++p)
2596     {
2597       Symbol* sym = p->second;
2598
2599       if (sym->is_forced_local())
2600         continue;
2601
2602       // Note that SYM may already have a dynamic symbol index, since
2603       // some symbols appear more than once in the symbol table, with
2604       // and without a version.
2605
2606       if (!sym->should_add_dynsym_entry(this))
2607         sym->set_dynsym_index(-1U);
2608       else if (!sym->has_dynsym_index())
2609         {
2610           sym->set_dynsym_index(index);
2611           ++index;
2612           syms->push_back(sym);
2613           dynpool->add(sym->name(), false, NULL);
2614
2615           // Record any version information, except those from
2616           // as-needed libraries not seen to be needed.  Note that the
2617           // is_needed state for such libraries can change in this loop.
2618           if (sym->version() != NULL)
2619             {
2620               if (!sym->is_from_dynobj()
2621                   || !sym->object()->as_needed()
2622                   || sym->object()->is_needed())
2623                 versions->record_version(this, dynpool, sym);
2624               else
2625                 {
2626                   if (parameters->options().warn_drop_version())
2627                     gold_warning(_("discarding version information for "
2628                                    "%s@%s, defined in unused shared library %s "
2629                                    "(linked with --as-needed)"),
2630                                  sym->name(), sym->version(),
2631                                  sym->object()->name().c_str());
2632                   sym->clear_version();
2633                 }
2634             }
2635         }
2636     }
2637
2638   // Finish up the versions.  In some cases this may add new dynamic
2639   // symbols.
2640   index = versions->finalize(this, index, syms);
2641
2642   // Process target-specific symbols.
2643   for (std::vector<Symbol*>::iterator p = this->target_symbols_.begin();
2644        p != this->target_symbols_.end();
2645        ++p)
2646     {
2647       (*p)->set_dynsym_index(index);
2648       ++index;
2649       syms->push_back(*p);
2650       dynpool->add((*p)->name(), false, NULL);
2651     }
2652
2653   return index;
2654 }
2655
2656 // Set the final values for all the symbols.  The index of the first
2657 // global symbol in the output file is *PLOCAL_SYMCOUNT.  Record the
2658 // file offset OFF.  Add their names to POOL.  Return the new file
2659 // offset.  Update *PLOCAL_SYMCOUNT if necessary.  DYNOFF and
2660 // DYN_GLOBAL_INDEX refer to the start of the symbols that will be
2661 // written from the global symbol table in Symtab::write_globals(),
2662 // which will include forced-local symbols.  DYN_GLOBAL_INDEX is
2663 // not necessarily the same as the sh_info field for the .dynsym
2664 // section, which will point to the first real global symbol.
2665
2666 off_t
2667 Symbol_table::finalize(off_t off, off_t dynoff, size_t dyn_global_index,
2668                        size_t dyncount, Stringpool* pool,
2669                        unsigned int* plocal_symcount)
2670 {
2671   off_t ret;
2672
2673   gold_assert(*plocal_symcount != 0);
2674   this->first_global_index_ = *plocal_symcount;
2675
2676   this->dynamic_offset_ = dynoff;
2677   this->first_dynamic_global_index_ = dyn_global_index;
2678   this->dynamic_count_ = dyncount;
2679
2680   if (parameters->target().get_size() == 32)
2681     {
2682 #if defined(HAVE_TARGET_32_BIG) || defined(HAVE_TARGET_32_LITTLE)
2683       ret = this->sized_finalize<32>(off, pool, plocal_symcount);
2684 #else
2685       gold_unreachable();
2686 #endif
2687     }
2688   else if (parameters->target().get_size() == 64)
2689     {
2690 #if defined(HAVE_TARGET_64_BIG) || defined(HAVE_TARGET_64_LITTLE)
2691       ret = this->sized_finalize<64>(off, pool, plocal_symcount);
2692 #else
2693       gold_unreachable();
2694 #endif
2695     }
2696   else
2697     gold_unreachable();
2698
2699   // Now that we have the final symbol table, we can reliably note
2700   // which symbols should get warnings.
2701   this->warnings_.note_warnings(this);
2702
2703   return ret;
2704 }
2705
2706 // SYM is going into the symbol table at *PINDEX.  Add the name to
2707 // POOL, update *PINDEX and *POFF.
2708
2709 template<int size>
2710 void
2711 Symbol_table::add_to_final_symtab(Symbol* sym, Stringpool* pool,
2712                                   unsigned int* pindex, off_t* poff)
2713 {
2714   sym->set_symtab_index(*pindex);
2715   if (sym->version() == NULL || !parameters->options().relocatable())
2716     pool->add(sym->name(), false, NULL);
2717   else
2718     pool->add(sym->versioned_name(), true, NULL);
2719   ++*pindex;
2720   *poff += elfcpp::Elf_sizes<size>::sym_size;
2721 }
2722
2723 // Set the final value for all the symbols.  This is called after
2724 // Layout::finalize, so all the output sections have their final
2725 // address.
2726
2727 template<int size>
2728 off_t
2729 Symbol_table::sized_finalize(off_t off, Stringpool* pool,
2730                              unsigned int* plocal_symcount)
2731 {
2732   off = align_address(off, size >> 3);
2733   this->offset_ = off;
2734
2735   unsigned int index = *plocal_symcount;
2736   const unsigned int orig_index = index;
2737
2738   // First do all the symbols which have been forced to be local, as
2739   // they must appear before all global symbols.
2740   for (Forced_locals::iterator p = this->forced_locals_.begin();
2741        p != this->forced_locals_.end();
2742        ++p)
2743     {
2744       Symbol* sym = *p;
2745       gold_assert(sym->is_forced_local());
2746       if (this->sized_finalize_symbol<size>(sym))
2747         {
2748           this->add_to_final_symtab<size>(sym, pool, &index, &off);
2749           ++*plocal_symcount;
2750         }
2751     }
2752
2753   // Now do all the remaining symbols.
2754   for (Symbol_table_type::iterator p = this->table_.begin();
2755        p != this->table_.end();
2756        ++p)
2757     {
2758       Symbol* sym = p->second;
2759       if (this->sized_finalize_symbol<size>(sym))
2760         this->add_to_final_symtab<size>(sym, pool, &index, &off);
2761     }
2762
2763   // Now do target-specific symbols.
2764   for (std::vector<Symbol*>::iterator p = this->target_symbols_.begin();
2765        p != this->target_symbols_.end();
2766        ++p)
2767     {
2768       this->add_to_final_symtab<size>(*p, pool, &index, &off);
2769     }
2770
2771   this->output_count_ = index - orig_index;
2772
2773   return off;
2774 }
2775
2776 // Compute the final value of SYM and store status in location PSTATUS.
2777 // During relaxation, this may be called multiple times for a symbol to
2778 // compute its would-be final value in each relaxation pass.
2779
2780 template<int size>
2781 typename Sized_symbol<size>::Value_type
2782 Symbol_table::compute_final_value(
2783     const Sized_symbol<size>* sym,
2784     Compute_final_value_status* pstatus) const
2785 {
2786   typedef typename Sized_symbol<size>::Value_type Value_type;
2787   Value_type value;
2788
2789   switch (sym->source())
2790     {
2791     case Symbol::FROM_OBJECT:
2792       {
2793         bool is_ordinary;
2794         unsigned int shndx = sym->shndx(&is_ordinary);
2795
2796         if (!is_ordinary
2797             && shndx != elfcpp::SHN_ABS
2798             && !Symbol::is_common_shndx(shndx))
2799           {
2800             *pstatus = CFVS_UNSUPPORTED_SYMBOL_SECTION;
2801             return 0;
2802           }
2803
2804         Object* symobj = sym->object();
2805         if (symobj->is_dynamic())
2806           {
2807             value = 0;
2808             shndx = elfcpp::SHN_UNDEF;
2809           }
2810         else if (symobj->pluginobj() != NULL)
2811           {
2812             value = 0;
2813             shndx = elfcpp::SHN_UNDEF;
2814           }
2815         else if (shndx == elfcpp::SHN_UNDEF)
2816           value = 0;
2817         else if (!is_ordinary
2818                  && (shndx == elfcpp::SHN_ABS
2819                      || Symbol::is_common_shndx(shndx)))
2820           value = sym->value();
2821         else
2822           {
2823             Relobj* relobj = static_cast<Relobj*>(symobj);
2824             Output_section* os = relobj->output_section(shndx);
2825
2826             if (this->is_section_folded(relobj, shndx))
2827               {
2828                 gold_assert(os == NULL);
2829                 // Get the os of the section it is folded onto.
2830                 Section_id folded = this->icf_->get_folded_section(relobj,
2831                                                                    shndx);
2832                 gold_assert(folded.first != NULL);
2833                 Relobj* folded_obj = reinterpret_cast<Relobj*>(folded.first);
2834                 unsigned folded_shndx = folded.second;
2835
2836                 os = folded_obj->output_section(folded_shndx);  
2837                 gold_assert(os != NULL);
2838
2839                 // Replace (relobj, shndx) with canonical ICF input section.
2840                 shndx = folded_shndx;
2841                 relobj = folded_obj;
2842               }
2843
2844             uint64_t secoff64 = relobj->output_section_offset(shndx);
2845             if (os == NULL)
2846               {
2847                 bool static_or_reloc = (parameters->doing_static_link() ||
2848                                         parameters->options().relocatable());
2849                 gold_assert(static_or_reloc || sym->dynsym_index() == -1U);
2850
2851                 *pstatus = CFVS_NO_OUTPUT_SECTION;
2852                 return 0;
2853               }
2854
2855             if (secoff64 == -1ULL)
2856               {
2857                 // The section needs special handling (e.g., a merge section).
2858
2859                 value = os->output_address(relobj, shndx, sym->value());
2860               }
2861             else
2862               {
2863                 Value_type secoff =
2864                   convert_types<Value_type, uint64_t>(secoff64);
2865                 if (sym->type() == elfcpp::STT_TLS)
2866                   value = sym->value() + os->tls_offset() + secoff;
2867                 else
2868                   value = sym->value() + os->address() + secoff;
2869               }
2870           }
2871       }
2872       break;
2873
2874     case Symbol::IN_OUTPUT_DATA:
2875       {
2876         Output_data* od = sym->output_data();
2877         value = sym->value();
2878         if (sym->type() != elfcpp::STT_TLS)
2879           value += od->address();
2880         else
2881           {
2882             Output_section* os = od->output_section();
2883             gold_assert(os != NULL);
2884             value += os->tls_offset() + (od->address() - os->address());
2885           }
2886         if (sym->offset_is_from_end())
2887           value += od->data_size();
2888       }
2889       break;
2890
2891     case Symbol::IN_OUTPUT_SEGMENT:
2892       {
2893         Output_segment* os = sym->output_segment();
2894         value = sym->value();
2895         if (sym->type() != elfcpp::STT_TLS)
2896           value += os->vaddr();
2897         switch (sym->offset_base())
2898           {
2899           case Symbol::SEGMENT_START:
2900             break;
2901           case Symbol::SEGMENT_END:
2902             value += os->memsz();
2903             break;
2904           case Symbol::SEGMENT_BSS:
2905             value += os->filesz();
2906             break;
2907           default:
2908             gold_unreachable();
2909           }
2910       }
2911       break;
2912
2913     case Symbol::IS_CONSTANT:
2914       value = sym->value();
2915       break;
2916
2917     case Symbol::IS_UNDEFINED:
2918       value = 0;
2919       break;
2920
2921     default:
2922       gold_unreachable();
2923     }
2924
2925   *pstatus = CFVS_OK;
2926   return value;
2927 }
2928
2929 // Finalize the symbol SYM.  This returns true if the symbol should be
2930 // added to the symbol table, false otherwise.
2931
2932 template<int size>
2933 bool
2934 Symbol_table::sized_finalize_symbol(Symbol* unsized_sym)
2935 {
2936   typedef typename Sized_symbol<size>::Value_type Value_type;
2937
2938   Sized_symbol<size>* sym = static_cast<Sized_symbol<size>*>(unsized_sym);
2939
2940   // The default version of a symbol may appear twice in the symbol
2941   // table.  We only need to finalize it once.
2942   if (sym->has_symtab_index())
2943     return false;
2944
2945   if (!sym->in_reg())
2946     {
2947       gold_assert(!sym->has_symtab_index());
2948       sym->set_symtab_index(-1U);
2949       gold_assert(sym->dynsym_index() == -1U);
2950       return false;
2951     }
2952
2953   // If the symbol is only present on plugin files, the plugin decided we
2954   // don't need it.
2955   if (!sym->in_real_elf())
2956     {
2957       gold_assert(!sym->has_symtab_index());
2958       sym->set_symtab_index(-1U);
2959       return false;
2960     }
2961
2962   // Compute final symbol value.
2963   Compute_final_value_status status;
2964   Value_type value = this->compute_final_value(sym, &status);
2965
2966   switch (status)
2967     {
2968     case CFVS_OK:
2969       break;
2970     case CFVS_UNSUPPORTED_SYMBOL_SECTION:
2971       {
2972         bool is_ordinary;
2973         unsigned int shndx = sym->shndx(&is_ordinary);
2974         gold_error(_("%s: unsupported symbol section 0x%x"),
2975                    sym->demangled_name().c_str(), shndx);
2976       }
2977       break;
2978     case CFVS_NO_OUTPUT_SECTION:
2979       sym->set_symtab_index(-1U);
2980       return false;
2981     default:
2982       gold_unreachable();
2983     }
2984
2985   sym->set_value(value);
2986
2987   if (parameters->options().strip_all()
2988       || !parameters->options().should_retain_symbol(sym->name()))
2989     {
2990       sym->set_symtab_index(-1U);
2991       return false;
2992     }
2993
2994   return true;
2995 }
2996
2997 // Write out the global symbols.
2998
2999 void
3000 Symbol_table::write_globals(const Stringpool* sympool,
3001                             const Stringpool* dynpool,
3002                             Output_symtab_xindex* symtab_xindex,
3003                             Output_symtab_xindex* dynsym_xindex,
3004                             Output_file* of) const
3005 {
3006   switch (parameters->size_and_endianness())
3007     {
3008 #ifdef HAVE_TARGET_32_LITTLE
3009     case Parameters::TARGET_32_LITTLE:
3010       this->sized_write_globals<32, false>(sympool, dynpool, symtab_xindex,
3011                                            dynsym_xindex, of);
3012       break;
3013 #endif
3014 #ifdef HAVE_TARGET_32_BIG
3015     case Parameters::TARGET_32_BIG:
3016       this->sized_write_globals<32, true>(sympool, dynpool, symtab_xindex,
3017                                           dynsym_xindex, of);
3018       break;
3019 #endif
3020 #ifdef HAVE_TARGET_64_LITTLE
3021     case Parameters::TARGET_64_LITTLE:
3022       this->sized_write_globals<64, false>(sympool, dynpool, symtab_xindex,
3023                                            dynsym_xindex, of);
3024       break;
3025 #endif
3026 #ifdef HAVE_TARGET_64_BIG
3027     case Parameters::TARGET_64_BIG:
3028       this->sized_write_globals<64, true>(sympool, dynpool, symtab_xindex,
3029                                           dynsym_xindex, of);
3030       break;
3031 #endif
3032     default:
3033       gold_unreachable();
3034     }
3035 }
3036
3037 // Write out the global symbols.
3038
3039 template<int size, bool big_endian>
3040 void
3041 Symbol_table::sized_write_globals(const Stringpool* sympool,
3042                                   const Stringpool* dynpool,
3043                                   Output_symtab_xindex* symtab_xindex,
3044                                   Output_symtab_xindex* dynsym_xindex,
3045                                   Output_file* of) const
3046 {
3047   const Target& target = parameters->target();
3048
3049   const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
3050
3051   const unsigned int output_count = this->output_count_;
3052   const section_size_type oview_size = output_count * sym_size;
3053   const unsigned int first_global_index = this->first_global_index_;
3054   unsigned char* psyms;
3055   if (this->offset_ == 0 || output_count == 0)
3056     psyms = NULL;
3057   else
3058     psyms = of->get_output_view(this->offset_, oview_size);
3059
3060   const unsigned int dynamic_count = this->dynamic_count_;
3061   const section_size_type dynamic_size = dynamic_count * sym_size;
3062   const unsigned int first_dynamic_global_index =
3063     this->first_dynamic_global_index_;
3064   unsigned char* dynamic_view;
3065   if (this->dynamic_offset_ == 0 || dynamic_count == 0)
3066     dynamic_view = NULL;
3067   else
3068     dynamic_view = of->get_output_view(this->dynamic_offset_, dynamic_size);
3069
3070   for (Symbol_table_type::const_iterator p = this->table_.begin();
3071        p != this->table_.end();
3072        ++p)
3073     {
3074       Sized_symbol<size>* sym = static_cast<Sized_symbol<size>*>(p->second);
3075
3076       // Possibly warn about unresolved symbols in shared libraries.
3077       this->warn_about_undefined_dynobj_symbol(sym);
3078
3079       unsigned int sym_index = sym->symtab_index();
3080       unsigned int dynsym_index;
3081       if (dynamic_view == NULL)
3082         dynsym_index = -1U;
3083       else
3084         dynsym_index = sym->dynsym_index();
3085
3086       if (sym_index == -1U && dynsym_index == -1U)
3087         {
3088           // This symbol is not included in the output file.
3089           continue;
3090         }
3091
3092       unsigned int shndx;
3093       typename elfcpp::Elf_types<size>::Elf_Addr sym_value = sym->value();
3094       typename elfcpp::Elf_types<size>::Elf_Addr dynsym_value = sym_value;
3095       elfcpp::STB binding = sym->binding();
3096
3097       // If --weak-unresolved-symbols is set, change binding of unresolved
3098       // global symbols to STB_WEAK.
3099       if (parameters->options().weak_unresolved_symbols()
3100           && binding == elfcpp::STB_GLOBAL
3101           && sym->is_undefined())
3102         binding = elfcpp::STB_WEAK;
3103
3104       // If --no-gnu-unique is set, change STB_GNU_UNIQUE to STB_GLOBAL.
3105       if (binding == elfcpp::STB_GNU_UNIQUE
3106           && !parameters->options().gnu_unique())
3107         binding = elfcpp::STB_GLOBAL;
3108
3109       switch (sym->source())
3110         {
3111         case Symbol::FROM_OBJECT:
3112           {
3113             bool is_ordinary;
3114             unsigned int in_shndx = sym->shndx(&is_ordinary);
3115
3116             if (!is_ordinary
3117                 && in_shndx != elfcpp::SHN_ABS
3118                 && !Symbol::is_common_shndx(in_shndx))
3119               {
3120                 gold_error(_("%s: unsupported symbol section 0x%x"),
3121                            sym->demangled_name().c_str(), in_shndx);
3122                 shndx = in_shndx;
3123               }
3124             else
3125               {
3126                 Object* symobj = sym->object();
3127                 if (symobj->is_dynamic())
3128                   {
3129                     if (sym->needs_dynsym_value())
3130                       dynsym_value = target.dynsym_value(sym);
3131                     shndx = elfcpp::SHN_UNDEF;
3132                     if (sym->is_undef_binding_weak())
3133                       binding = elfcpp::STB_WEAK;
3134                     else
3135                       binding = elfcpp::STB_GLOBAL;
3136                   }
3137                 else if (symobj->pluginobj() != NULL)
3138                   shndx = elfcpp::SHN_UNDEF;
3139                 else if (in_shndx == elfcpp::SHN_UNDEF
3140                          || (!is_ordinary
3141                              && (in_shndx == elfcpp::SHN_ABS
3142                                  || Symbol::is_common_shndx(in_shndx))))
3143                   shndx = in_shndx;
3144                 else
3145                   {
3146                     Relobj* relobj = static_cast<Relobj*>(symobj);
3147                     Output_section* os = relobj->output_section(in_shndx);
3148                     if (this->is_section_folded(relobj, in_shndx))
3149                       {
3150                         // This global symbol must be written out even though
3151                         // it is folded.
3152                         // Get the os of the section it is folded onto.
3153                         Section_id folded =
3154                              this->icf_->get_folded_section(relobj, in_shndx);
3155                         gold_assert(folded.first !=NULL);
3156                         Relobj* folded_obj = 
3157                           reinterpret_cast<Relobj*>(folded.first);
3158                         os = folded_obj->output_section(folded.second);  
3159                         gold_assert(os != NULL);
3160                       }
3161                     gold_assert(os != NULL);
3162                     shndx = os->out_shndx();
3163
3164                     if (shndx >= elfcpp::SHN_LORESERVE)
3165                       {
3166                         if (sym_index != -1U)
3167                           symtab_xindex->add(sym_index, shndx);
3168                         if (dynsym_index != -1U)
3169                           dynsym_xindex->add(dynsym_index, shndx);
3170                         shndx = elfcpp::SHN_XINDEX;
3171                       }
3172
3173                     // In object files symbol values are section
3174                     // relative.
3175                     if (parameters->options().relocatable())
3176                       sym_value -= os->address();
3177                   }
3178               }
3179           }
3180           break;
3181
3182         case Symbol::IN_OUTPUT_DATA:
3183           {
3184             Output_data* od = sym->output_data();
3185
3186             shndx = od->out_shndx();
3187             if (shndx >= elfcpp::SHN_LORESERVE)
3188               {
3189                 if (sym_index != -1U)
3190                   symtab_xindex->add(sym_index, shndx);
3191                 if (dynsym_index != -1U)
3192                   dynsym_xindex->add(dynsym_index, shndx);
3193                 shndx = elfcpp::SHN_XINDEX;
3194               }
3195
3196             // In object files symbol values are section
3197             // relative.
3198             if (parameters->options().relocatable())
3199               {
3200                 Output_section* os = od->output_section();
3201                 gold_assert(os != NULL);
3202                 sym_value -= os->address();
3203               }
3204           }
3205           break;
3206
3207         case Symbol::IN_OUTPUT_SEGMENT:
3208           {
3209             Output_segment* oseg = sym->output_segment();
3210             Output_section* osect = oseg->first_section();
3211             if (osect == NULL)
3212               shndx = elfcpp::SHN_ABS;
3213             else
3214               shndx = osect->out_shndx();
3215           }
3216           break;
3217
3218         case Symbol::IS_CONSTANT:
3219           shndx = elfcpp::SHN_ABS;
3220           break;
3221
3222         case Symbol::IS_UNDEFINED:
3223           shndx = elfcpp::SHN_UNDEF;
3224           break;
3225
3226         default:
3227           gold_unreachable();
3228         }
3229
3230       if (sym_index != -1U)
3231         {
3232           sym_index -= first_global_index;
3233           gold_assert(sym_index < output_count);
3234           unsigned char* ps = psyms + (sym_index * sym_size);
3235           this->sized_write_symbol<size, big_endian>(sym, sym_value, shndx,
3236                                                      binding, sympool, ps);
3237         }
3238
3239       if (dynsym_index != -1U)
3240         {
3241           dynsym_index -= first_dynamic_global_index;
3242           gold_assert(dynsym_index < dynamic_count);
3243           unsigned char* pd = dynamic_view + (dynsym_index * sym_size);
3244           this->sized_write_symbol<size, big_endian>(sym, dynsym_value, shndx,
3245                                                      binding, dynpool, pd);
3246           // Allow a target to adjust dynamic symbol value.
3247           parameters->target().adjust_dyn_symbol(sym, pd);
3248         }
3249     }
3250
3251   // Write the target-specific symbols.
3252   for (std::vector<Symbol*>::const_iterator p = this->target_symbols_.begin();
3253        p != this->target_symbols_.end();
3254        ++p)
3255     {
3256       Sized_symbol<size>* sym = static_cast<Sized_symbol<size>*>(*p);
3257
3258       unsigned int sym_index = sym->symtab_index();
3259       unsigned int dynsym_index;
3260       if (dynamic_view == NULL)
3261         dynsym_index = -1U;
3262       else
3263         dynsym_index = sym->dynsym_index();
3264
3265       unsigned int shndx;
3266       switch (sym->source())
3267         {
3268         case Symbol::IS_CONSTANT:
3269           shndx = elfcpp::SHN_ABS;
3270           break;
3271         case Symbol::IS_UNDEFINED:
3272           shndx = elfcpp::SHN_UNDEF;
3273           break;
3274         default:
3275           gold_unreachable();
3276         }
3277
3278       if (sym_index != -1U)
3279         {
3280           sym_index -= first_global_index;
3281           gold_assert(sym_index < output_count);
3282           unsigned char* ps = psyms + (sym_index * sym_size);
3283           this->sized_write_symbol<size, big_endian>(sym, sym->value(), shndx,
3284                                                      sym->binding(), sympool,
3285                                                      ps);
3286         }
3287
3288       if (dynsym_index != -1U)
3289         {
3290           dynsym_index -= first_dynamic_global_index;
3291           gold_assert(dynsym_index < dynamic_count);
3292           unsigned char* pd = dynamic_view + (dynsym_index * sym_size);
3293           this->sized_write_symbol<size, big_endian>(sym, sym->value(), shndx,
3294                                                      sym->binding(), dynpool,
3295                                                      pd);
3296         }
3297     }
3298
3299   of->write_output_view(this->offset_, oview_size, psyms);
3300   if (dynamic_view != NULL)
3301     of->write_output_view(this->dynamic_offset_, dynamic_size, dynamic_view);
3302 }
3303
3304 // Write out the symbol SYM, in section SHNDX, to P.  POOL is the
3305 // strtab holding the name.
3306
3307 template<int size, bool big_endian>
3308 void
3309 Symbol_table::sized_write_symbol(
3310     Sized_symbol<size>* sym,
3311     typename elfcpp::Elf_types<size>::Elf_Addr value,
3312     unsigned int shndx,
3313     elfcpp::STB binding,
3314     const Stringpool* pool,
3315     unsigned char* p) const
3316 {
3317   elfcpp::Sym_write<size, big_endian> osym(p);
3318   if (sym->version() == NULL || !parameters->options().relocatable())
3319     osym.put_st_name(pool->get_offset(sym->name()));
3320   else
3321     osym.put_st_name(pool->get_offset(sym->versioned_name()));
3322   osym.put_st_value(value);
3323   // Use a symbol size of zero for undefined symbols from shared libraries.
3324   if (shndx == elfcpp::SHN_UNDEF && sym->is_from_dynobj())
3325     osym.put_st_size(0);
3326   else
3327     osym.put_st_size(sym->symsize());
3328   elfcpp::STT type = sym->type();
3329   gold_assert(type != elfcpp::STT_GNU_IFUNC || !sym->is_from_dynobj());
3330   // A version script may have overridden the default binding.
3331   if (sym->is_forced_local())
3332     osym.put_st_info(elfcpp::elf_st_info(elfcpp::STB_LOCAL, type));
3333   else
3334     osym.put_st_info(elfcpp::elf_st_info(binding, type));
3335   osym.put_st_other(elfcpp::elf_st_other(sym->visibility(), sym->nonvis()));
3336   osym.put_st_shndx(shndx);
3337 }
3338
3339 // Check for unresolved symbols in shared libraries.  This is
3340 // controlled by the --allow-shlib-undefined option.
3341
3342 // We only warn about libraries for which we have seen all the
3343 // DT_NEEDED entries.  We don't try to track down DT_NEEDED entries
3344 // which were not seen in this link.  If we didn't see a DT_NEEDED
3345 // entry, we aren't going to be able to reliably report whether the
3346 // symbol is undefined.
3347
3348 // We also don't warn about libraries found in a system library
3349 // directory (e.g., /lib or /usr/lib); we assume that those libraries
3350 // are OK.  This heuristic avoids problems on GNU/Linux, in which -ldl
3351 // can have undefined references satisfied by ld-linux.so.
3352
3353 inline void
3354 Symbol_table::warn_about_undefined_dynobj_symbol(Symbol* sym) const
3355 {
3356   bool dummy;
3357   if (sym->source() == Symbol::FROM_OBJECT
3358       && sym->object()->is_dynamic()
3359       && sym->shndx(&dummy) == elfcpp::SHN_UNDEF
3360       && sym->binding() != elfcpp::STB_WEAK
3361       && !parameters->options().allow_shlib_undefined()
3362       && !parameters->target().is_defined_by_abi(sym)
3363       && !sym->object()->is_in_system_directory())
3364     {
3365       // A very ugly cast.
3366       Dynobj* dynobj = static_cast<Dynobj*>(sym->object());
3367       if (!dynobj->has_unknown_needed_entries())
3368         gold_undefined_symbol(sym);
3369     }
3370 }
3371
3372 // Write out a section symbol.  Return the update offset.
3373
3374 void
3375 Symbol_table::write_section_symbol(const Output_section* os,
3376                                    Output_symtab_xindex* symtab_xindex,
3377                                    Output_file* of,
3378                                    off_t offset) const
3379 {
3380   switch (parameters->size_and_endianness())
3381     {
3382 #ifdef HAVE_TARGET_32_LITTLE
3383     case Parameters::TARGET_32_LITTLE:
3384       this->sized_write_section_symbol<32, false>(os, symtab_xindex, of,
3385                                                   offset);
3386       break;
3387 #endif
3388 #ifdef HAVE_TARGET_32_BIG
3389     case Parameters::TARGET_32_BIG:
3390       this->sized_write_section_symbol<32, true>(os, symtab_xindex, of,
3391                                                  offset);
3392       break;
3393 #endif
3394 #ifdef HAVE_TARGET_64_LITTLE
3395     case Parameters::TARGET_64_LITTLE:
3396       this->sized_write_section_symbol<64, false>(os, symtab_xindex, of,
3397                                                   offset);
3398       break;
3399 #endif
3400 #ifdef HAVE_TARGET_64_BIG
3401     case Parameters::TARGET_64_BIG:
3402       this->sized_write_section_symbol<64, true>(os, symtab_xindex, of,
3403                                                  offset);
3404       break;
3405 #endif
3406     default:
3407       gold_unreachable();
3408     }
3409 }
3410
3411 // Write out a section symbol, specialized for size and endianness.
3412
3413 template<int size, bool big_endian>
3414 void
3415 Symbol_table::sized_write_section_symbol(const Output_section* os,
3416                                          Output_symtab_xindex* symtab_xindex,
3417                                          Output_file* of,
3418                                          off_t offset) const
3419 {
3420   const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
3421
3422   unsigned char* pov = of->get_output_view(offset, sym_size);
3423
3424   elfcpp::Sym_write<size, big_endian> osym(pov);
3425   osym.put_st_name(0);
3426   if (parameters->options().relocatable())
3427     osym.put_st_value(0);
3428   else
3429     osym.put_st_value(os->address());
3430   osym.put_st_size(0);
3431   osym.put_st_info(elfcpp::elf_st_info(elfcpp::STB_LOCAL,
3432                                        elfcpp::STT_SECTION));
3433   osym.put_st_other(elfcpp::elf_st_other(elfcpp::STV_DEFAULT, 0));
3434
3435   unsigned int shndx = os->out_shndx();
3436   if (shndx >= elfcpp::SHN_LORESERVE)
3437     {
3438       symtab_xindex->add(os->symtab_index(), shndx);
3439       shndx = elfcpp::SHN_XINDEX;
3440     }
3441   osym.put_st_shndx(shndx);
3442
3443   of->write_output_view(offset, sym_size, pov);
3444 }
3445
3446 // Print statistical information to stderr.  This is used for --stats.
3447
3448 void
3449 Symbol_table::print_stats() const
3450 {
3451 #if defined(HAVE_TR1_UNORDERED_MAP) || defined(HAVE_EXT_HASH_MAP)
3452   fprintf(stderr, _("%s: symbol table entries: %zu; buckets: %zu\n"),
3453           program_name, this->table_.size(), this->table_.bucket_count());
3454 #else
3455   fprintf(stderr, _("%s: symbol table entries: %zu\n"),
3456           program_name, this->table_.size());
3457 #endif
3458   this->namepool_.print_stats("symbol table stringpool");
3459 }
3460
3461 // We check for ODR violations by looking for symbols with the same
3462 // name for which the debugging information reports that they were
3463 // defined in disjoint source locations.  When comparing the source
3464 // location, we consider instances with the same base filename to be
3465 // the same.  This is because different object files/shared libraries
3466 // can include the same header file using different paths, and
3467 // different optimization settings can make the line number appear to
3468 // be a couple lines off, and we don't want to report an ODR violation
3469 // in those cases.
3470
3471 // This struct is used to compare line information, as returned by
3472 // Dwarf_line_info::one_addr2line.  It implements a < comparison
3473 // operator used with std::sort.
3474
3475 struct Odr_violation_compare
3476 {
3477   bool
3478   operator()(const std::string& s1, const std::string& s2) const
3479   {
3480     // Inputs should be of the form "dirname/filename:linenum" where
3481     // "dirname/" is optional.  We want to compare just the filename:linenum.
3482
3483     // Find the last '/' in each string.
3484     std::string::size_type s1begin = s1.rfind('/');
3485     std::string::size_type s2begin = s2.rfind('/');
3486     // If there was no '/' in a string, start at the beginning.
3487     if (s1begin == std::string::npos)
3488       s1begin = 0;
3489     if (s2begin == std::string::npos)
3490       s2begin = 0;
3491     return s1.compare(s1begin, std::string::npos,
3492                       s2, s2begin, std::string::npos) < 0;
3493   }
3494 };
3495
3496 // Returns all of the lines attached to LOC, not just the one the
3497 // instruction actually came from.
3498 std::vector<std::string>
3499 Symbol_table::linenos_from_loc(const Task* task,
3500                                const Symbol_location& loc)
3501 {
3502   // We need to lock the object in order to read it.  This
3503   // means that we have to run in a singleton Task.  If we
3504   // want to run this in a general Task for better
3505   // performance, we will need one Task for object, plus
3506   // appropriate locking to ensure that we don't conflict with
3507   // other uses of the object.  Also note, one_addr2line is not
3508   // currently thread-safe.
3509   Task_lock_obj<Object> tl(task, loc.object);
3510
3511   std::vector<std::string> result;
3512   Symbol_location code_loc = loc;
3513   parameters->target().function_location(&code_loc);
3514   // 16 is the size of the object-cache that one_addr2line should use.
3515   std::string canonical_result = Dwarf_line_info::one_addr2line(
3516       code_loc.object, code_loc.shndx, code_loc.offset, 16, &result);
3517   if (!canonical_result.empty())
3518     result.push_back(canonical_result);
3519   return result;
3520 }
3521
3522 // OutputIterator that records if it was ever assigned to.  This
3523 // allows it to be used with std::set_intersection() to check for
3524 // intersection rather than computing the intersection.
3525 struct Check_intersection
3526 {
3527   Check_intersection()
3528     : value_(false)
3529   {}
3530
3531   bool had_intersection() const
3532   { return this->value_; }
3533
3534   Check_intersection& operator++()
3535   { return *this; }
3536
3537   Check_intersection& operator*()
3538   { return *this; }
3539
3540   template<typename T>
3541   Check_intersection& operator=(const T&)
3542   {
3543     this->value_ = true;
3544     return *this;
3545   }
3546
3547  private:
3548   bool value_;
3549 };
3550
3551 // Check candidate_odr_violations_ to find symbols with the same name
3552 // but apparently different definitions (different source-file/line-no
3553 // for each line assigned to the first instruction).
3554
3555 void
3556 Symbol_table::detect_odr_violations(const Task* task,
3557                                     const char* output_file_name) const
3558 {
3559   for (Odr_map::const_iterator it = candidate_odr_violations_.begin();
3560        it != candidate_odr_violations_.end();
3561        ++it)
3562     {
3563       const char* const symbol_name = it->first;
3564
3565       std::string first_object_name;
3566       std::vector<std::string> first_object_linenos;
3567
3568       Unordered_set<Symbol_location, Symbol_location_hash>::const_iterator
3569           locs = it->second.begin();
3570       const Unordered_set<Symbol_location, Symbol_location_hash>::const_iterator
3571           locs_end = it->second.end();
3572       for (; locs != locs_end && first_object_linenos.empty(); ++locs)
3573         {
3574           // Save the line numbers from the first definition to
3575           // compare to the other definitions.  Ideally, we'd compare
3576           // every definition to every other, but we don't want to
3577           // take O(N^2) time to do this.  This shortcut may cause
3578           // false negatives that appear or disappear depending on the
3579           // link order, but it won't cause false positives.
3580           first_object_name = locs->object->name();
3581           first_object_linenos = this->linenos_from_loc(task, *locs);
3582         }
3583       if (first_object_linenos.empty())
3584         continue;
3585
3586       // Sort by Odr_violation_compare to make std::set_intersection work.
3587       std::string first_object_canonical_result = first_object_linenos.back();
3588       std::sort(first_object_linenos.begin(), first_object_linenos.end(),
3589                 Odr_violation_compare());
3590
3591       for (; locs != locs_end; ++locs)
3592         {
3593           std::vector<std::string> linenos =
3594               this->linenos_from_loc(task, *locs);
3595           // linenos will be empty if we couldn't parse the debug info.
3596           if (linenos.empty())
3597             continue;
3598           // Sort by Odr_violation_compare to make std::set_intersection work.
3599           gold_assert(!linenos.empty());
3600           std::string second_object_canonical_result = linenos.back();
3601           std::sort(linenos.begin(), linenos.end(), Odr_violation_compare());
3602
3603           Check_intersection intersection_result =
3604               std::set_intersection(first_object_linenos.begin(),
3605                                     first_object_linenos.end(),
3606                                     linenos.begin(),
3607                                     linenos.end(),
3608                                     Check_intersection(),
3609                                     Odr_violation_compare());
3610           if (!intersection_result.had_intersection())
3611             {
3612               gold_warning(_("while linking %s: symbol '%s' defined in "
3613                              "multiple places (possible ODR violation):"),
3614                            output_file_name, demangle(symbol_name).c_str());
3615               // This only prints one location from each definition,
3616               // which may not be the location we expect to intersect
3617               // with another definition.  We could print the whole
3618               // set of locations, but that seems too verbose.
3619               fprintf(stderr, _("  %s from %s\n"),
3620                       first_object_canonical_result.c_str(),
3621                       first_object_name.c_str());
3622               fprintf(stderr, _("  %s from %s\n"),
3623                       second_object_canonical_result.c_str(),
3624                       locs->object->name().c_str());
3625               // Only print one broken pair, to avoid needing to
3626               // compare against a list of the disjoint definition
3627               // locations we've found so far.  (If we kept comparing
3628               // against just the first one, we'd get a lot of
3629               // redundant complaints about the second definition
3630               // location.)
3631               break;
3632             }
3633         }
3634     }
3635   // We only call one_addr2line() in this function, so we can clear its cache.
3636   Dwarf_line_info::clear_addr2line_cache();
3637 }
3638
3639 // Warnings functions.
3640
3641 // Add a new warning.
3642
3643 void
3644 Warnings::add_warning(Symbol_table* symtab, const char* name, Object* obj,
3645                       const std::string& warning)
3646 {
3647   name = symtab->canonicalize_name(name);
3648   this->warnings_[name].set(obj, warning);
3649 }
3650
3651 // Look through the warnings and mark the symbols for which we should
3652 // warn.  This is called during Layout::finalize when we know the
3653 // sources for all the symbols.
3654
3655 void
3656 Warnings::note_warnings(Symbol_table* symtab)
3657 {
3658   for (Warning_table::iterator p = this->warnings_.begin();
3659        p != this->warnings_.end();
3660        ++p)
3661     {
3662       Symbol* sym = symtab->lookup(p->first, NULL);
3663       if (sym != NULL
3664           && sym->source() == Symbol::FROM_OBJECT
3665           && sym->object() == p->second.object)
3666         sym->set_has_warning();
3667     }
3668 }
3669
3670 // Issue a warning.  This is called when we see a relocation against a
3671 // symbol for which has a warning.
3672
3673 template<int size, bool big_endian>
3674 void
3675 Warnings::issue_warning(const Symbol* sym,
3676                         const Relocate_info<size, big_endian>* relinfo,
3677                         size_t relnum, off_t reloffset) const
3678 {
3679   gold_assert(sym->has_warning());
3680
3681   // We don't want to issue a warning for a relocation against the
3682   // symbol in the same object file in which the symbol is defined.
3683   if (sym->object() == relinfo->object)
3684     return;
3685
3686   Warning_table::const_iterator p = this->warnings_.find(sym->name());
3687   gold_assert(p != this->warnings_.end());
3688   gold_warning_at_location(relinfo, relnum, reloffset,
3689                            "%s", p->second.text.c_str());
3690 }
3691
3692 // Instantiate the templates we need.  We could use the configure
3693 // script to restrict this to only the ones needed for implemented
3694 // targets.
3695
3696 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
3697 template
3698 void
3699 Sized_symbol<32>::allocate_common(Output_data*, Value_type);
3700 #endif
3701
3702 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
3703 template
3704 void
3705 Sized_symbol<64>::allocate_common(Output_data*, Value_type);
3706 #endif
3707
3708 #ifdef HAVE_TARGET_32_LITTLE
3709 template
3710 void
3711 Symbol_table::add_from_relobj<32, false>(
3712     Sized_relobj_file<32, false>* relobj,
3713     const unsigned char* syms,
3714     size_t count,
3715     size_t symndx_offset,
3716     const char* sym_names,
3717     size_t sym_name_size,
3718     Sized_relobj_file<32, false>::Symbols* sympointers,
3719     size_t* defined);
3720 #endif
3721
3722 #ifdef HAVE_TARGET_32_BIG
3723 template
3724 void
3725 Symbol_table::add_from_relobj<32, true>(
3726     Sized_relobj_file<32, true>* relobj,
3727     const unsigned char* syms,
3728     size_t count,
3729     size_t symndx_offset,
3730     const char* sym_names,
3731     size_t sym_name_size,
3732     Sized_relobj_file<32, true>::Symbols* sympointers,
3733     size_t* defined);
3734 #endif
3735
3736 #ifdef HAVE_TARGET_64_LITTLE
3737 template
3738 void
3739 Symbol_table::add_from_relobj<64, false>(
3740     Sized_relobj_file<64, false>* relobj,
3741     const unsigned char* syms,
3742     size_t count,
3743     size_t symndx_offset,
3744     const char* sym_names,
3745     size_t sym_name_size,
3746     Sized_relobj_file<64, false>::Symbols* sympointers,
3747     size_t* defined);
3748 #endif
3749
3750 #ifdef HAVE_TARGET_64_BIG
3751 template
3752 void
3753 Symbol_table::add_from_relobj<64, true>(
3754     Sized_relobj_file<64, true>* relobj,
3755     const unsigned char* syms,
3756     size_t count,
3757     size_t symndx_offset,
3758     const char* sym_names,
3759     size_t sym_name_size,
3760     Sized_relobj_file<64, true>::Symbols* sympointers,
3761     size_t* defined);
3762 #endif
3763
3764 #ifdef HAVE_TARGET_32_LITTLE
3765 template
3766 Symbol*
3767 Symbol_table::add_from_pluginobj<32, false>(
3768     Sized_pluginobj<32, false>* obj,
3769     const char* name,
3770     const char* ver,
3771     elfcpp::Sym<32, false>* sym);
3772 #endif
3773
3774 #ifdef HAVE_TARGET_32_BIG
3775 template
3776 Symbol*
3777 Symbol_table::add_from_pluginobj<32, true>(
3778     Sized_pluginobj<32, true>* obj,
3779     const char* name,
3780     const char* ver,
3781     elfcpp::Sym<32, true>* sym);
3782 #endif
3783
3784 #ifdef HAVE_TARGET_64_LITTLE
3785 template
3786 Symbol*
3787 Symbol_table::add_from_pluginobj<64, false>(
3788     Sized_pluginobj<64, false>* obj,
3789     const char* name,
3790     const char* ver,
3791     elfcpp::Sym<64, false>* sym);
3792 #endif
3793
3794 #ifdef HAVE_TARGET_64_BIG
3795 template
3796 Symbol*
3797 Symbol_table::add_from_pluginobj<64, true>(
3798     Sized_pluginobj<64, true>* obj,
3799     const char* name,
3800     const char* ver,
3801     elfcpp::Sym<64, true>* sym);
3802 #endif
3803
3804 #ifdef HAVE_TARGET_32_LITTLE
3805 template
3806 void
3807 Symbol_table::add_from_dynobj<32, false>(
3808     Sized_dynobj<32, false>* dynobj,
3809     const unsigned char* syms,
3810     size_t count,
3811     const char* sym_names,
3812     size_t sym_name_size,
3813     const unsigned char* versym,
3814     size_t versym_size,
3815     const std::vector<const char*>* version_map,
3816     Sized_relobj_file<32, false>::Symbols* sympointers,
3817     size_t* defined);
3818 #endif
3819
3820 #ifdef HAVE_TARGET_32_BIG
3821 template
3822 void
3823 Symbol_table::add_from_dynobj<32, true>(
3824     Sized_dynobj<32, true>* dynobj,
3825     const unsigned char* syms,
3826     size_t count,
3827     const char* sym_names,
3828     size_t sym_name_size,
3829     const unsigned char* versym,
3830     size_t versym_size,
3831     const std::vector<const char*>* version_map,
3832     Sized_relobj_file<32, true>::Symbols* sympointers,
3833     size_t* defined);
3834 #endif
3835
3836 #ifdef HAVE_TARGET_64_LITTLE
3837 template
3838 void
3839 Symbol_table::add_from_dynobj<64, false>(
3840     Sized_dynobj<64, false>* dynobj,
3841     const unsigned char* syms,
3842     size_t count,
3843     const char* sym_names,
3844     size_t sym_name_size,
3845     const unsigned char* versym,
3846     size_t versym_size,
3847     const std::vector<const char*>* version_map,
3848     Sized_relobj_file<64, false>::Symbols* sympointers,
3849     size_t* defined);
3850 #endif
3851
3852 #ifdef HAVE_TARGET_64_BIG
3853 template
3854 void
3855 Symbol_table::add_from_dynobj<64, true>(
3856     Sized_dynobj<64, true>* dynobj,
3857     const unsigned char* syms,
3858     size_t count,
3859     const char* sym_names,
3860     size_t sym_name_size,
3861     const unsigned char* versym,
3862     size_t versym_size,
3863     const std::vector<const char*>* version_map,
3864     Sized_relobj_file<64, true>::Symbols* sympointers,
3865     size_t* defined);
3866 #endif
3867
3868 #ifdef HAVE_TARGET_32_LITTLE
3869 template
3870 Sized_symbol<32>*
3871 Symbol_table::add_from_incrobj(
3872     Object* obj,
3873     const char* name,
3874     const char* ver,
3875     elfcpp::Sym<32, false>* sym);
3876 #endif
3877
3878 #ifdef HAVE_TARGET_32_BIG
3879 template
3880 Sized_symbol<32>*
3881 Symbol_table::add_from_incrobj(
3882     Object* obj,
3883     const char* name,
3884     const char* ver,
3885     elfcpp::Sym<32, true>* sym);
3886 #endif
3887
3888 #ifdef HAVE_TARGET_64_LITTLE
3889 template
3890 Sized_symbol<64>*
3891 Symbol_table::add_from_incrobj(
3892     Object* obj,
3893     const char* name,
3894     const char* ver,
3895     elfcpp::Sym<64, false>* sym);
3896 #endif
3897
3898 #ifdef HAVE_TARGET_64_BIG
3899 template
3900 Sized_symbol<64>*
3901 Symbol_table::add_from_incrobj(
3902     Object* obj,
3903     const char* name,
3904     const char* ver,
3905     elfcpp::Sym<64, true>* sym);
3906 #endif
3907
3908 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
3909 template
3910 void
3911 Symbol_table::define_with_copy_reloc<32>(
3912     Sized_symbol<32>* sym,
3913     Output_data* posd,
3914     elfcpp::Elf_types<32>::Elf_Addr value);
3915 #endif
3916
3917 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
3918 template
3919 void
3920 Symbol_table::define_with_copy_reloc<64>(
3921     Sized_symbol<64>* sym,
3922     Output_data* posd,
3923     elfcpp::Elf_types<64>::Elf_Addr value);
3924 #endif
3925
3926 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
3927 template
3928 void
3929 Sized_symbol<32>::init_output_data(const char* name, const char* version,
3930                                    Output_data* od, Value_type value,
3931                                    Size_type symsize, elfcpp::STT type,
3932                                    elfcpp::STB binding,
3933                                    elfcpp::STV visibility,
3934                                    unsigned char nonvis,
3935                                    bool offset_is_from_end,
3936                                    bool is_predefined);
3937
3938 template
3939 void
3940 Sized_symbol<32>::init_constant(const char* name, const char* version,
3941                                 Value_type value, Size_type symsize,
3942                                 elfcpp::STT type, elfcpp::STB binding,
3943                                 elfcpp::STV visibility, unsigned char nonvis,
3944                                 bool is_predefined);
3945
3946 template
3947 void
3948 Sized_symbol<32>::init_undefined(const char* name, const char* version,
3949                                  Value_type value, elfcpp::STT type,
3950                                  elfcpp::STB binding, elfcpp::STV visibility,
3951                                  unsigned char nonvis);
3952 #endif
3953
3954 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
3955 template
3956 void
3957 Sized_symbol<64>::init_output_data(const char* name, const char* version,
3958                                    Output_data* od, Value_type value,
3959                                    Size_type symsize, elfcpp::STT type,
3960                                    elfcpp::STB binding,
3961                                    elfcpp::STV visibility,
3962                                    unsigned char nonvis,
3963                                    bool offset_is_from_end,
3964                                    bool is_predefined);
3965
3966 template
3967 void
3968 Sized_symbol<64>::init_constant(const char* name, const char* version,
3969                                 Value_type value, Size_type symsize,
3970                                 elfcpp::STT type, elfcpp::STB binding,
3971                                 elfcpp::STV visibility, unsigned char nonvis,
3972                                 bool is_predefined);
3973
3974 template
3975 void
3976 Sized_symbol<64>::init_undefined(const char* name, const char* version,
3977                                  Value_type value, elfcpp::STT type,
3978                                  elfcpp::STB binding, elfcpp::STV visibility,
3979                                  unsigned char nonvis);
3980 #endif
3981
3982 #ifdef HAVE_TARGET_32_LITTLE
3983 template
3984 void
3985 Warnings::issue_warning<32, false>(const Symbol* sym,
3986                                    const Relocate_info<32, false>* relinfo,
3987                                    size_t relnum, off_t reloffset) const;
3988 #endif
3989
3990 #ifdef HAVE_TARGET_32_BIG
3991 template
3992 void
3993 Warnings::issue_warning<32, true>(const Symbol* sym,
3994                                   const Relocate_info<32, true>* relinfo,
3995                                   size_t relnum, off_t reloffset) const;
3996 #endif
3997
3998 #ifdef HAVE_TARGET_64_LITTLE
3999 template
4000 void
4001 Warnings::issue_warning<64, false>(const Symbol* sym,
4002                                    const Relocate_info<64, false>* relinfo,
4003                                    size_t relnum, off_t reloffset) const;
4004 #endif
4005
4006 #ifdef HAVE_TARGET_64_BIG
4007 template
4008 void
4009 Warnings::issue_warning<64, true>(const Symbol* sym,
4010                                   const Relocate_info<64, true>* relinfo,
4011                                   size_t relnum, off_t reloffset) const;
4012 #endif
4013
4014 } // End namespace gold.