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