1 // object.cc -- support for an object file for linking in gold
2 
3 // Copyright 2006, 2007, 2008 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 <cerrno>
26 #include <cstring>
27 #include <cstdarg>
28 #include "demangle.h"
29 #include "libiberty.h"
30 
31 #include "target-select.h"
32 #include "dwarf_reader.h"
33 #include "layout.h"
34 #include "output.h"
35 #include "symtab.h"
36 #include "cref.h"
37 #include "reloc.h"
38 #include "object.h"
39 #include "dynobj.h"
40 
41 namespace gold
42 {
43 
44 // Class Xindex.
45 
46 // Initialize the symtab_xindex_ array.  Find the SHT_SYMTAB_SHNDX
47 // section and read it in.  SYMTAB_SHNDX is the index of the symbol
48 // table we care about.
49 
50 template<int size, bool big_endian>
51 void
52 Xindex::initialize_symtab_xindex(Object* object, unsigned int symtab_shndx)
53 {
54   if (!this->symtab_xindex_.empty())
55     return;
56 
57   gold_assert(symtab_shndx != 0);
58 
59   // Look through the sections in reverse order, on the theory that it
60   // is more likely to be near the end than the beginning.
61   unsigned int i = object->shnum();
62   while (i > 0)
63     {
64       --i;
65       if (object->section_type(i) == elfcpp::SHT_SYMTAB_SHNDX
66 	  && this->adjust_shndx(object->section_link(i)) == symtab_shndx)
67 	{
68 	  this->read_symtab_xindex<size, big_endian>(object, i, NULL);
69 	  return;
70 	}
71     }
72 
73   object->error(_("missing SHT_SYMTAB_SHNDX section"));
74 }
75 
76 // Read in the symtab_xindex_ array, given the section index of the
77 // SHT_SYMTAB_SHNDX section.  If PSHDRS is not NULL, it points at the
78 // section headers.
79 
80 template<int size, bool big_endian>
81 void
82 Xindex::read_symtab_xindex(Object* object, unsigned int xindex_shndx,
83 			   const unsigned char* pshdrs)
84 {
85   section_size_type bytecount;
86   const unsigned char* contents;
87   if (pshdrs == NULL)
88     contents = object->section_contents(xindex_shndx, &bytecount, false);
89   else
90     {
91       const unsigned char* p = (pshdrs
92 				+ (xindex_shndx
93 				   * elfcpp::Elf_sizes<size>::shdr_size));
94       typename elfcpp::Shdr<size, big_endian> shdr(p);
95       bytecount = convert_to_section_size_type(shdr.get_sh_size());
96       contents = object->get_view(shdr.get_sh_offset(), bytecount, true, false);
97     }
98 
99   gold_assert(this->symtab_xindex_.empty());
100   this->symtab_xindex_.reserve(bytecount / 4);
101   for (section_size_type i = 0; i < bytecount; i += 4)
102     {
103       unsigned int shndx = elfcpp::Swap<32, big_endian>::readval(contents + i);
104       // We preadjust the section indexes we save.
105       this->symtab_xindex_.push_back(this->adjust_shndx(shndx));
106     }
107 }
108 
109 // Symbol symndx has a section of SHN_XINDEX; return the real section
110 // index.
111 
112 unsigned int
113 Xindex::sym_xindex_to_shndx(Object* object, unsigned int symndx)
114 {
115   if (symndx >= this->symtab_xindex_.size())
116     {
117       object->error(_("symbol %u out of range for SHT_SYMTAB_SHNDX section"),
118 		    symndx);
119       return elfcpp::SHN_UNDEF;
120     }
121   unsigned int shndx = this->symtab_xindex_[symndx];
122   if (shndx < elfcpp::SHN_LORESERVE || shndx >= object->shnum())
123     {
124       object->error(_("extended index for symbol %u out of range: %u"),
125 		    symndx, shndx);
126       return elfcpp::SHN_UNDEF;
127     }
128   return shndx;
129 }
130 
131 // Class Object.
132 
133 // Set the target based on fields in the ELF file header.
134 
135 void
136 Object::set_target(int machine, int size, bool big_endian, int osabi,
137 		   int abiversion)
138 {
139   Target* target = select_target(machine, size, big_endian, osabi, abiversion);
140   if (target == NULL)
141     gold_fatal(_("%s: unsupported ELF machine number %d"),
142 	       this->name().c_str(), machine);
143   this->target_ = target;
144 }
145 
146 // Report an error for this object file.  This is used by the
147 // elfcpp::Elf_file interface, and also called by the Object code
148 // itself.
149 
150 void
151 Object::error(const char* format, ...) const
152 {
153   va_list args;
154   va_start(args, format);
155   char* buf = NULL;
156   if (vasprintf(&buf, format, args) < 0)
157     gold_nomem();
158   va_end(args);
159   gold_error(_("%s: %s"), this->name().c_str(), buf);
160   free(buf);
161 }
162 
163 // Return a view of the contents of a section.
164 
165 const unsigned char*
166 Object::section_contents(unsigned int shndx, section_size_type* plen,
167 			 bool cache)
168 {
169   Location loc(this->do_section_contents(shndx));
170   *plen = convert_to_section_size_type(loc.data_size);
171   return this->get_view(loc.file_offset, *plen, true, cache);
172 }
173 
174 // Read the section data into SD.  This is code common to Sized_relobj
175 // and Sized_dynobj, so we put it into Object.
176 
177 template<int size, bool big_endian>
178 void
179 Object::read_section_data(elfcpp::Elf_file<size, big_endian, Object>* elf_file,
180 			  Read_symbols_data* sd)
181 {
182   const int shdr_size = elfcpp::Elf_sizes<size>::shdr_size;
183 
184   // Read the section headers.
185   const off_t shoff = elf_file->shoff();
186   const unsigned int shnum = this->shnum();
187   sd->section_headers = this->get_lasting_view(shoff, shnum * shdr_size,
188 					       true, true);
189 
190   // Read the section names.
191   const unsigned char* pshdrs = sd->section_headers->data();
192   const unsigned char* pshdrnames = pshdrs + elf_file->shstrndx() * shdr_size;
193   typename elfcpp::Shdr<size, big_endian> shdrnames(pshdrnames);
194 
195   if (shdrnames.get_sh_type() != elfcpp::SHT_STRTAB)
196     this->error(_("section name section has wrong type: %u"),
197 		static_cast<unsigned int>(shdrnames.get_sh_type()));
198 
199   sd->section_names_size =
200     convert_to_section_size_type(shdrnames.get_sh_size());
201   sd->section_names = this->get_lasting_view(shdrnames.get_sh_offset(),
202 					     sd->section_names_size, false,
203 					     false);
204 }
205 
206 // If NAME is the name of a special .gnu.warning section, arrange for
207 // the warning to be issued.  SHNDX is the section index.  Return
208 // whether it is a warning section.
209 
210 bool
211 Object::handle_gnu_warning_section(const char* name, unsigned int shndx,
212 				   Symbol_table* symtab)
213 {
214   const char warn_prefix[] = ".gnu.warning.";
215   const int warn_prefix_len = sizeof warn_prefix - 1;
216   if (strncmp(name, warn_prefix, warn_prefix_len) == 0)
217     {
218       // Read the section contents to get the warning text.  It would
219       // be nicer if we only did this if we have to actually issue a
220       // warning.  Unfortunately, warnings are issued as we relocate
221       // sections.  That means that we can not lock the object then,
222       // as we might try to issue the same warning multiple times
223       // simultaneously.
224       section_size_type len;
225       const unsigned char* contents = this->section_contents(shndx, &len,
226 							     false);
227       std::string warning(reinterpret_cast<const char*>(contents), len);
228       symtab->add_warning(name + warn_prefix_len, this, warning);
229       return true;
230     }
231   return false;
232 }
233 
234 // Class Sized_relobj.
235 
236 template<int size, bool big_endian>
237 Sized_relobj<size, big_endian>::Sized_relobj(
238     const std::string& name,
239     Input_file* input_file,
240     off_t offset,
241     const elfcpp::Ehdr<size, big_endian>& ehdr)
242   : Relobj(name, input_file, offset),
243     elf_file_(this, ehdr),
244     symtab_shndx_(-1U),
245     local_symbol_count_(0),
246     output_local_symbol_count_(0),
247     output_local_dynsym_count_(0),
248     symbols_(),
249     defined_count_(0),
250     local_symbol_offset_(0),
251     local_dynsym_offset_(0),
252     local_values_(),
253     local_got_offsets_(),
254     kept_comdat_sections_(),
255     comdat_groups_(),
256     has_eh_frame_(false)
257 {
258 }
259 
260 template<int size, bool big_endian>
261 Sized_relobj<size, big_endian>::~Sized_relobj()
262 {
263 }
264 
265 // Set up an object file based on the file header.  This sets up the
266 // target and reads the section information.
267 
268 template<int size, bool big_endian>
269 void
270 Sized_relobj<size, big_endian>::setup(
271     const elfcpp::Ehdr<size, big_endian>& ehdr)
272 {
273   this->set_target(ehdr.get_e_machine(), size, big_endian,
274 		   ehdr.get_e_ident()[elfcpp::EI_OSABI],
275 		   ehdr.get_e_ident()[elfcpp::EI_ABIVERSION]);
276 
277   const unsigned int shnum = this->elf_file_.shnum();
278   this->set_shnum(shnum);
279 }
280 
281 // Find the SHT_SYMTAB section, given the section headers.  The ELF
282 // standard says that maybe in the future there can be more than one
283 // SHT_SYMTAB section.  Until somebody figures out how that could
284 // work, we assume there is only one.
285 
286 template<int size, bool big_endian>
287 void
288 Sized_relobj<size, big_endian>::find_symtab(const unsigned char* pshdrs)
289 {
290   const unsigned int shnum = this->shnum();
291   this->symtab_shndx_ = 0;
292   if (shnum > 0)
293     {
294       // Look through the sections in reverse order, since gas tends
295       // to put the symbol table at the end.
296       const unsigned char* p = pshdrs + shnum * This::shdr_size;
297       unsigned int i = shnum;
298       unsigned int xindex_shndx = 0;
299       unsigned int xindex_link = 0;
300       while (i > 0)
301 	{
302 	  --i;
303 	  p -= This::shdr_size;
304 	  typename This::Shdr shdr(p);
305 	  if (shdr.get_sh_type() == elfcpp::SHT_SYMTAB)
306 	    {
307 	      this->symtab_shndx_ = i;
308 	      if (xindex_shndx > 0 && xindex_link == i)
309 		{
310 		  Xindex* xindex =
311 		    new Xindex(this->elf_file_.large_shndx_offset());
312 		  xindex->read_symtab_xindex<size, big_endian>(this,
313 							       xindex_shndx,
314 							       pshdrs);
315 		  this->set_xindex(xindex);
316 		}
317 	      break;
318 	    }
319 
320 	  // Try to pick up the SHT_SYMTAB_SHNDX section, if there is
321 	  // one.  This will work if it follows the SHT_SYMTAB
322 	  // section.
323 	  if (shdr.get_sh_type() == elfcpp::SHT_SYMTAB_SHNDX)
324 	    {
325 	      xindex_shndx = i;
326 	      xindex_link = this->adjust_shndx(shdr.get_sh_link());
327 	    }
328 	}
329     }
330 }
331 
332 // Return the Xindex structure to use for object with lots of
333 // sections.
334 
335 template<int size, bool big_endian>
336 Xindex*
337 Sized_relobj<size, big_endian>::do_initialize_xindex()
338 {
339   gold_assert(this->symtab_shndx_ != -1U);
340   Xindex* xindex = new Xindex(this->elf_file_.large_shndx_offset());
341   xindex->initialize_symtab_xindex<size, big_endian>(this, this->symtab_shndx_);
342   return xindex;
343 }
344 
345 // Return whether SHDR has the right type and flags to be a GNU
346 // .eh_frame section.
347 
348 template<int size, bool big_endian>
349 bool
350 Sized_relobj<size, big_endian>::check_eh_frame_flags(
351     const elfcpp::Shdr<size, big_endian>* shdr) const
352 {
353   return (shdr->get_sh_type() == elfcpp::SHT_PROGBITS
354 	  && (shdr->get_sh_flags() & elfcpp::SHF_ALLOC) != 0);
355 }
356 
357 // Return whether there is a GNU .eh_frame section, given the section
358 // headers and the section names.
359 
360 template<int size, bool big_endian>
361 bool
362 Sized_relobj<size, big_endian>::find_eh_frame(
363     const unsigned char* pshdrs,
364     const char* names,
365     section_size_type names_size) const
366 {
367   const unsigned int shnum = this->shnum();
368   const unsigned char* p = pshdrs + This::shdr_size;
369   for (unsigned int i = 1; i < shnum; ++i, p += This::shdr_size)
370     {
371       typename This::Shdr shdr(p);
372       if (this->check_eh_frame_flags(&shdr))
373 	{
374 	  if (shdr.get_sh_name() >= names_size)
375 	    {
376 	      this->error(_("bad section name offset for section %u: %lu"),
377 			  i, static_cast<unsigned long>(shdr.get_sh_name()));
378 	      continue;
379 	    }
380 
381 	  const char* name = names + shdr.get_sh_name();
382 	  if (strcmp(name, ".eh_frame") == 0)
383 	    return true;
384 	}
385     }
386   return false;
387 }
388 
389 // Read the sections and symbols from an object file.
390 
391 template<int size, bool big_endian>
392 void
393 Sized_relobj<size, big_endian>::do_read_symbols(Read_symbols_data* sd)
394 {
395   this->read_section_data(&this->elf_file_, sd);
396 
397   const unsigned char* const pshdrs = sd->section_headers->data();
398 
399   this->find_symtab(pshdrs);
400 
401   const unsigned char* namesu = sd->section_names->data();
402   const char* names = reinterpret_cast<const char*>(namesu);
403   if (memmem(names, sd->section_names_size, ".eh_frame", 10) != NULL)
404     {
405       if (this->find_eh_frame(pshdrs, names, sd->section_names_size))
406         this->has_eh_frame_ = true;
407     }
408 
409   sd->symbols = NULL;
410   sd->symbols_size = 0;
411   sd->external_symbols_offset = 0;
412   sd->symbol_names = NULL;
413   sd->symbol_names_size = 0;
414 
415   if (this->symtab_shndx_ == 0)
416     {
417       // No symbol table.  Weird but legal.
418       return;
419     }
420 
421   // Get the symbol table section header.
422   typename This::Shdr symtabshdr(pshdrs
423 				 + this->symtab_shndx_ * This::shdr_size);
424   gold_assert(symtabshdr.get_sh_type() == elfcpp::SHT_SYMTAB);
425 
426   // If this object has a .eh_frame section, we need all the symbols.
427   // Otherwise we only need the external symbols.  While it would be
428   // simpler to just always read all the symbols, I've seen object
429   // files with well over 2000 local symbols, which for a 64-bit
430   // object file format is over 5 pages that we don't need to read
431   // now.
432 
433   const int sym_size = This::sym_size;
434   const unsigned int loccount = symtabshdr.get_sh_info();
435   this->local_symbol_count_ = loccount;
436   this->local_values_.resize(loccount);
437   section_offset_type locsize = loccount * sym_size;
438   off_t dataoff = symtabshdr.get_sh_offset();
439   section_size_type datasize =
440     convert_to_section_size_type(symtabshdr.get_sh_size());
441   off_t extoff = dataoff + locsize;
442   section_size_type extsize = datasize - locsize;
443 
444   off_t readoff = this->has_eh_frame_ ? dataoff : extoff;
445   section_size_type readsize = this->has_eh_frame_ ? datasize : extsize;
446 
447   if (readsize == 0)
448     {
449       // No external symbols.  Also weird but also legal.
450       return;
451     }
452 
453   File_view* fvsymtab = this->get_lasting_view(readoff, readsize, true, false);
454 
455   // Read the section header for the symbol names.
456   unsigned int strtab_shndx = this->adjust_shndx(symtabshdr.get_sh_link());
457   if (strtab_shndx >= this->shnum())
458     {
459       this->error(_("invalid symbol table name index: %u"), strtab_shndx);
460       return;
461     }
462   typename This::Shdr strtabshdr(pshdrs + strtab_shndx * This::shdr_size);
463   if (strtabshdr.get_sh_type() != elfcpp::SHT_STRTAB)
464     {
465       this->error(_("symbol table name section has wrong type: %u"),
466 		  static_cast<unsigned int>(strtabshdr.get_sh_type()));
467       return;
468     }
469 
470   // Read the symbol names.
471   File_view* fvstrtab = this->get_lasting_view(strtabshdr.get_sh_offset(),
472 					       strtabshdr.get_sh_size(),
473 					       false, true);
474 
475   sd->symbols = fvsymtab;
476   sd->symbols_size = readsize;
477   sd->external_symbols_offset = this->has_eh_frame_ ? locsize : 0;
478   sd->symbol_names = fvstrtab;
479   sd->symbol_names_size =
480     convert_to_section_size_type(strtabshdr.get_sh_size());
481 }
482 
483 // Return the section index of symbol SYM.  Set *VALUE to its value in
484 // the object file.  Set *IS_ORDINARY if this is an ordinary section
485 // index.  not a special cod between SHN_LORESERVE and SHN_HIRESERVE.
486 // Note that for a symbol which is not defined in this object file,
487 // this will set *VALUE to 0 and return SHN_UNDEF; it will not return
488 // the final value of the symbol in the link.
489 
490 template<int size, bool big_endian>
491 unsigned int
492 Sized_relobj<size, big_endian>::symbol_section_and_value(unsigned int sym,
493 							 Address* value,
494 							 bool* is_ordinary)
495 {
496   section_size_type symbols_size;
497   const unsigned char* symbols = this->section_contents(this->symtab_shndx_,
498 							&symbols_size,
499 							false);
500 
501   const size_t count = symbols_size / This::sym_size;
502   gold_assert(sym < count);
503 
504   elfcpp::Sym<size, big_endian> elfsym(symbols + sym * This::sym_size);
505   *value = elfsym.get_st_value();
506 
507   return this->adjust_sym_shndx(sym, elfsym.get_st_shndx(), is_ordinary);
508 }
509 
510 // Return whether to include a section group in the link.  LAYOUT is
511 // used to keep track of which section groups we have already seen.
512 // INDEX is the index of the section group and SHDR is the section
513 // header.  If we do not want to include this group, we set bits in
514 // OMIT for each section which should be discarded.
515 
516 template<int size, bool big_endian>
517 bool
518 Sized_relobj<size, big_endian>::include_section_group(
519     Symbol_table* symtab,
520     Layout* layout,
521     unsigned int index,
522     const char* name,
523     const unsigned char* shdrs,
524     const char* section_names,
525     section_size_type section_names_size,
526     std::vector<bool>* omit)
527 {
528   // Read the section contents.
529   typename This::Shdr shdr(shdrs + index * This::shdr_size);
530   const unsigned char* pcon = this->get_view(shdr.get_sh_offset(),
531 					     shdr.get_sh_size(), true, false);
532   const elfcpp::Elf_Word* pword =
533     reinterpret_cast<const elfcpp::Elf_Word*>(pcon);
534 
535   // The first word contains flags.  We only care about COMDAT section
536   // groups.  Other section groups are always included in the link
537   // just like ordinary sections.
538   elfcpp::Elf_Word flags = elfcpp::Swap<32, big_endian>::readval(pword);
539 
540   // Look up the group signature, which is the name of a symbol.  This
541   // is a lot of effort to go to to read a string.  Why didn't they
542   // just have the group signature point into the string table, rather
543   // than indirect through a symbol?
544 
545   // Get the appropriate symbol table header (this will normally be
546   // the single SHT_SYMTAB section, but in principle it need not be).
547   const unsigned int link = this->adjust_shndx(shdr.get_sh_link());
548   typename This::Shdr symshdr(this, this->elf_file_.section_header(link));
549 
550   // Read the symbol table entry.
551   unsigned int symndx = shdr.get_sh_info();
552   if (symndx >= symshdr.get_sh_size() / This::sym_size)
553     {
554       this->error(_("section group %u info %u out of range"),
555 		  index, symndx);
556       return false;
557     }
558   off_t symoff = symshdr.get_sh_offset() + symndx * This::sym_size;
559   const unsigned char* psym = this->get_view(symoff, This::sym_size, true,
560 					     false);
561   elfcpp::Sym<size, big_endian> sym(psym);
562 
563   // Read the symbol table names.
564   section_size_type symnamelen;
565   const unsigned char* psymnamesu;
566   psymnamesu = this->section_contents(this->adjust_shndx(symshdr.get_sh_link()),
567 				      &symnamelen, true);
568   const char* psymnames = reinterpret_cast<const char*>(psymnamesu);
569 
570   // Get the section group signature.
571   if (sym.get_st_name() >= symnamelen)
572     {
573       this->error(_("symbol %u name offset %u out of range"),
574 		  symndx, sym.get_st_name());
575       return false;
576     }
577 
578   std::string signature(psymnames + sym.get_st_name());
579 
580   // It seems that some versions of gas will create a section group
581   // associated with a section symbol, and then fail to give a name to
582   // the section symbol.  In such a case, use the name of the section.
583   if (signature[0] == '\0' && sym.get_st_type() == elfcpp::STT_SECTION)
584     {
585       bool is_ordinary;
586       unsigned int sym_shndx = this->adjust_sym_shndx(symndx,
587 						      sym.get_st_shndx(),
588 						      &is_ordinary);
589       if (!is_ordinary || sym_shndx >= this->shnum())
590 	{
591 	  this->error(_("symbol %u invalid section index %u"),
592 		      symndx, sym_shndx);
593 	  return false;
594 	}
595       typename This::Shdr member_shdr(shdrs + sym_shndx * This::shdr_size);
596       if (member_shdr.get_sh_name() < section_names_size)
597         signature = section_names + member_shdr.get_sh_name();
598     }
599 
600   // Record this section group in the layout, and see whether we've already
601   // seen one with the same signature.
602   bool include_group = ((flags & elfcpp::GRP_COMDAT) == 0
603                         || layout->add_comdat(this, index, signature, true));
604 
605   Sized_relobj<size, big_endian>* kept_object = NULL;
606   Comdat_group* kept_group = NULL;
607 
608   if (!include_group)
609     {
610       // This group is being discarded.  Find the object and group
611       // that was kept in its place.
612       unsigned int kept_group_index = 0;
613       Relobj* kept_relobj = layout->find_kept_object(signature,
614                                                      &kept_group_index);
615       kept_object = static_cast<Sized_relobj<size, big_endian>*>(kept_relobj);
616       if (kept_object != NULL)
617         kept_group = kept_object->find_comdat_group(kept_group_index);
618     }
619   else if (flags & elfcpp::GRP_COMDAT)
620     {
621       // This group is being kept.  Create the table to map section names
622       // to section indexes and add it to the table of groups.
623       kept_group = new Comdat_group();
624       this->add_comdat_group(index, kept_group);
625     }
626 
627   size_t count = shdr.get_sh_size() / sizeof(elfcpp::Elf_Word);
628 
629   std::vector<unsigned int> shndxes;
630   bool relocate_group = include_group && parameters->options().relocatable();
631   if (relocate_group)
632     shndxes.reserve(count - 1);
633 
634   for (size_t i = 1; i < count; ++i)
635     {
636       elfcpp::Elf_Word secnum =
637 	this->adjust_shndx(elfcpp::Swap<32, big_endian>::readval(pword + i));
638 
639       if (relocate_group)
640 	shndxes.push_back(secnum);
641 
642       if (secnum >= this->shnum())
643 	{
644 	  this->error(_("section %u in section group %u out of range"),
645 		      secnum, index);
646 	  continue;
647 	}
648 
649       // Check for an earlier section number, since we're going to get
650       // it wrong--we may have already decided to include the section.
651       if (secnum < index)
652         this->error(_("invalid section group %u refers to earlier section %u"),
653                     index, secnum);
654 
655       // Get the name of the member section.
656       typename This::Shdr member_shdr(shdrs + secnum * This::shdr_size);
657       if (member_shdr.get_sh_name() >= section_names_size)
658         {
659           // This is an error, but it will be diagnosed eventually
660           // in do_layout, so we don't need to do anything here but
661           // ignore it.
662           continue;
663         }
664       std::string mname(section_names + member_shdr.get_sh_name());
665 
666       if (!include_group)
667         {
668           (*omit)[secnum] = true;
669           if (kept_group != NULL)
670             {
671               // Find the corresponding kept section, and store that info
672               // in the discarded section table.
673               Comdat_group::const_iterator p = kept_group->find(mname);
674               if (p != kept_group->end())
675                 {
676                   Kept_comdat_section* kept =
677                     new Kept_comdat_section(kept_object, p->second);
678                   this->set_kept_comdat_section(secnum, kept);
679                 }
680             }
681         }
682       else if (flags & elfcpp::GRP_COMDAT)
683         {
684           // Add the section to the kept group table.
685           gold_assert(kept_group != NULL);
686           kept_group->insert(std::make_pair(mname, secnum));
687         }
688     }
689 
690   if (relocate_group)
691     layout->layout_group(symtab, this, index, name, signature.c_str(),
692 			 shdr, flags, &shndxes);
693 
694   return include_group;
695 }
696 
697 // Whether to include a linkonce section in the link.  NAME is the
698 // name of the section and SHDR is the section header.
699 
700 // Linkonce sections are a GNU extension implemented in the original
701 // GNU linker before section groups were defined.  The semantics are
702 // that we only include one linkonce section with a given name.  The
703 // name of a linkonce section is normally .gnu.linkonce.T.SYMNAME,
704 // where T is the type of section and SYMNAME is the name of a symbol.
705 // In an attempt to make linkonce sections interact well with section
706 // groups, we try to identify SYMNAME and use it like a section group
707 // signature.  We want to block section groups with that signature,
708 // but not other linkonce sections with that signature.  We also use
709 // the full name of the linkonce section as a normal section group
710 // signature.
711 
712 template<int size, bool big_endian>
713 bool
714 Sized_relobj<size, big_endian>::include_linkonce_section(
715     Layout* layout,
716     unsigned int index,
717     const char* name,
718     const elfcpp::Shdr<size, big_endian>&)
719 {
720   // In general the symbol name we want will be the string following
721   // the last '.'.  However, we have to handle the case of
722   // .gnu.linkonce.t.__i686.get_pc_thunk.bx, which was generated by
723   // some versions of gcc.  So we use a heuristic: if the name starts
724   // with ".gnu.linkonce.t.", we use everything after that.  Otherwise
725   // we look for the last '.'.  We can't always simply skip
726   // ".gnu.linkonce.X", because we have to deal with cases like
727   // ".gnu.linkonce.d.rel.ro.local".
728   const char* const linkonce_t = ".gnu.linkonce.t.";
729   const char* symname;
730   if (strncmp(name, linkonce_t, strlen(linkonce_t)) == 0)
731     symname = name + strlen(linkonce_t);
732   else
733     symname = strrchr(name, '.') + 1;
734   std::string sig1(symname);
735   std::string sig2(name);
736   bool include1 = layout->add_comdat(this, index, sig1, false);
737   bool include2 = layout->add_comdat(this, index, sig2, true);
738 
739   if (!include2)
740     {
741       // The section is being discarded on the basis of its section
742       // name (i.e., the kept section was also a linkonce section).
743       // In this case, the section index stored with the layout object
744       // is the linkonce section that was kept.
745       unsigned int kept_group_index = 0;
746       Relobj* kept_relobj = layout->find_kept_object(sig2, &kept_group_index);
747       if (kept_relobj != NULL)
748         {
749           Sized_relobj<size, big_endian>* kept_object
750               = static_cast<Sized_relobj<size, big_endian>*>(kept_relobj);
751           Kept_comdat_section* kept =
752             new Kept_comdat_section(kept_object, kept_group_index);
753           this->set_kept_comdat_section(index, kept);
754         }
755     }
756   else if (!include1)
757     {
758       // The section is being discarded on the basis of its symbol
759       // name.  This means that the corresponding kept section was
760       // part of a comdat group, and it will be difficult to identify
761       // the specific section within that group that corresponds to
762       // this linkonce section.  We'll handle the simple case where
763       // the group has only one member section.  Otherwise, it's not
764       // worth the effort.
765       unsigned int kept_group_index = 0;
766       Relobj* kept_relobj = layout->find_kept_object(sig1, &kept_group_index);
767       if (kept_relobj != NULL)
768         {
769           Sized_relobj<size, big_endian>* kept_object =
770               static_cast<Sized_relobj<size, big_endian>*>(kept_relobj);
771           Comdat_group* kept_group =
772             kept_object->find_comdat_group(kept_group_index);
773           if (kept_group != NULL && kept_group->size() == 1)
774             {
775               Comdat_group::const_iterator p = kept_group->begin();
776               gold_assert(p != kept_group->end());
777               Kept_comdat_section* kept =
778                 new Kept_comdat_section(kept_object, p->second);
779               this->set_kept_comdat_section(index, kept);
780             }
781         }
782     }
783 
784   return include1 && include2;
785 }
786 
787 // Lay out the input sections.  We walk through the sections and check
788 // whether they should be included in the link.  If they should, we
789 // pass them to the Layout object, which will return an output section
790 // and an offset.
791 
792 template<int size, bool big_endian>
793 void
794 Sized_relobj<size, big_endian>::do_layout(Symbol_table* symtab,
795 					  Layout* layout,
796 					  Read_symbols_data* sd)
797 {
798   const unsigned int shnum = this->shnum();
799   if (shnum == 0)
800     return;
801 
802   // Get the section headers.
803   const unsigned char* shdrs = sd->section_headers->data();
804   const unsigned char* pshdrs;
805 
806   // Get the section names.
807   const unsigned char* pnamesu = sd->section_names->data();
808   const char* pnames = reinterpret_cast<const char*>(pnamesu);
809 
810   // For each section, record the index of the reloc section if any.
811   // Use 0 to mean that there is no reloc section, -1U to mean that
812   // there is more than one.
813   std::vector<unsigned int> reloc_shndx(shnum, 0);
814   std::vector<unsigned int> reloc_type(shnum, elfcpp::SHT_NULL);
815   // Skip the first, dummy, section.
816   pshdrs = shdrs + This::shdr_size;
817   for (unsigned int i = 1; i < shnum; ++i, pshdrs += This::shdr_size)
818     {
819       typename This::Shdr shdr(pshdrs);
820 
821       unsigned int sh_type = shdr.get_sh_type();
822       if (sh_type == elfcpp::SHT_REL || sh_type == elfcpp::SHT_RELA)
823 	{
824 	  unsigned int target_shndx = this->adjust_shndx(shdr.get_sh_info());
825 	  if (target_shndx == 0 || target_shndx >= shnum)
826 	    {
827 	      this->error(_("relocation section %u has bad info %u"),
828 			  i, target_shndx);
829 	      continue;
830 	    }
831 
832 	  if (reloc_shndx[target_shndx] != 0)
833 	    reloc_shndx[target_shndx] = -1U;
834 	  else
835 	    {
836 	      reloc_shndx[target_shndx] = i;
837 	      reloc_type[target_shndx] = sh_type;
838 	    }
839 	}
840     }
841 
842   Output_sections& out_sections(this->output_sections());
843   std::vector<Address>& out_section_offsets(this->section_offsets_);
844 
845   out_sections.resize(shnum);
846   out_section_offsets.resize(shnum);
847 
848   // If we are only linking for symbols, then there is nothing else to
849   // do here.
850   if (this->input_file()->just_symbols())
851     {
852       delete sd->section_headers;
853       sd->section_headers = NULL;
854       delete sd->section_names;
855       sd->section_names = NULL;
856       return;
857     }
858 
859   // Whether we've seen a .note.GNU-stack section.
860   bool seen_gnu_stack = false;
861   // The flags of a .note.GNU-stack section.
862   uint64_t gnu_stack_flags = 0;
863 
864   // Keep track of which sections to omit.
865   std::vector<bool> omit(shnum, false);
866 
867   // Keep track of reloc sections when emitting relocations.
868   const bool relocatable = parameters->options().relocatable();
869   const bool emit_relocs = (relocatable
870 			    || parameters->options().emit_relocs());
871   std::vector<unsigned int> reloc_sections;
872 
873   // Keep track of .eh_frame sections.
874   std::vector<unsigned int> eh_frame_sections;
875 
876   // Skip the first, dummy, section.
877   pshdrs = shdrs + This::shdr_size;
878   for (unsigned int i = 1; i < shnum; ++i, pshdrs += This::shdr_size)
879     {
880       typename This::Shdr shdr(pshdrs);
881 
882       if (shdr.get_sh_name() >= sd->section_names_size)
883 	{
884 	  this->error(_("bad section name offset for section %u: %lu"),
885 		      i, static_cast<unsigned long>(shdr.get_sh_name()));
886 	  return;
887 	}
888 
889       const char* name = pnames + shdr.get_sh_name();
890 
891       if (this->handle_gnu_warning_section(name, i, symtab))
892 	{
893 	  if (!relocatable)
894 	    omit[i] = true;
895 	}
896 
897       // The .note.GNU-stack section is special.  It gives the
898       // protection flags that this object file requires for the stack
899       // in memory.
900       if (strcmp(name, ".note.GNU-stack") == 0)
901 	{
902 	  seen_gnu_stack = true;
903 	  gnu_stack_flags |= shdr.get_sh_flags();
904 	  omit[i] = true;
905 	}
906 
907       bool discard = omit[i];
908       if (!discard)
909 	{
910 	  if (shdr.get_sh_type() == elfcpp::SHT_GROUP)
911 	    {
912 	      if (!this->include_section_group(symtab, layout, i, name, shdrs,
913 					       pnames, sd->section_names_size,
914 					       &omit))
915 		discard = true;
916 	    }
917           else if ((shdr.get_sh_flags() & elfcpp::SHF_GROUP) == 0
918                    && Layout::is_linkonce(name))
919 	    {
920 	      if (!this->include_linkonce_section(layout, i, name, shdr))
921 		discard = true;
922 	    }
923 	}
924 
925       if (discard)
926 	{
927 	  // Do not include this section in the link.
928 	  out_sections[i] = NULL;
929           out_section_offsets[i] = -1U;
930 	  continue;
931 	}
932 
933       // When doing a relocatable link we are going to copy input
934       // reloc sections into the output.  We only want to copy the
935       // ones associated with sections which are not being discarded.
936       // However, we don't know that yet for all sections.  So save
937       // reloc sections and process them later.
938       if (emit_relocs
939 	  && (shdr.get_sh_type() == elfcpp::SHT_REL
940 	      || shdr.get_sh_type() == elfcpp::SHT_RELA))
941 	{
942 	  reloc_sections.push_back(i);
943 	  continue;
944 	}
945 
946       if (relocatable && shdr.get_sh_type() == elfcpp::SHT_GROUP)
947 	continue;
948 
949       // The .eh_frame section is special.  It holds exception frame
950       // information that we need to read in order to generate the
951       // exception frame header.  We process these after all the other
952       // sections so that the exception frame reader can reliably
953       // determine which sections are being discarded, and discard the
954       // corresponding information.
955       if (!relocatable
956 	  && strcmp(name, ".eh_frame") == 0
957 	  && this->check_eh_frame_flags(&shdr))
958 	{
959 	  eh_frame_sections.push_back(i);
960 	  continue;
961 	}
962 
963       off_t offset;
964       Output_section* os = layout->layout(this, i, name, shdr,
965 					  reloc_shndx[i], reloc_type[i],
966 					  &offset);
967 
968       out_sections[i] = os;
969       if (offset == -1)
970         out_section_offsets[i] = -1U;
971       else
972         out_section_offsets[i] = convert_types<Address, off_t>(offset);
973 
974       // If this section requires special handling, and if there are
975       // relocs that apply to it, then we must do the special handling
976       // before we apply the relocs.
977       if (offset == -1 && reloc_shndx[i] != 0)
978 	this->set_relocs_must_follow_section_writes();
979     }
980 
981   layout->layout_gnu_stack(seen_gnu_stack, gnu_stack_flags);
982 
983   // When doing a relocatable link handle the reloc sections at the
984   // end.
985   if (emit_relocs)
986     this->size_relocatable_relocs();
987   for (std::vector<unsigned int>::const_iterator p = reloc_sections.begin();
988        p != reloc_sections.end();
989        ++p)
990     {
991       unsigned int i = *p;
992       const unsigned char* pshdr;
993       pshdr = sd->section_headers->data() + i * This::shdr_size;
994       typename This::Shdr shdr(pshdr);
995 
996       unsigned int data_shndx = this->adjust_shndx(shdr.get_sh_info());
997       if (data_shndx >= shnum)
998 	{
999 	  // We already warned about this above.
1000 	  continue;
1001 	}
1002 
1003       Output_section* data_section = out_sections[data_shndx];
1004       if (data_section == NULL)
1005 	{
1006 	  out_sections[i] = NULL;
1007           out_section_offsets[i] = -1U;
1008 	  continue;
1009 	}
1010 
1011       Relocatable_relocs* rr = new Relocatable_relocs();
1012       this->set_relocatable_relocs(i, rr);
1013 
1014       Output_section* os = layout->layout_reloc(this, i, shdr, data_section,
1015 						rr);
1016       out_sections[i] = os;
1017       out_section_offsets[i] = -1U;
1018     }
1019 
1020   // Handle the .eh_frame sections at the end.
1021   for (std::vector<unsigned int>::const_iterator p = eh_frame_sections.begin();
1022        p != eh_frame_sections.end();
1023        ++p)
1024     {
1025       gold_assert(this->has_eh_frame_);
1026       gold_assert(sd->external_symbols_offset != 0);
1027 
1028       unsigned int i = *p;
1029       const unsigned char *pshdr;
1030       pshdr = sd->section_headers->data() + i * This::shdr_size;
1031       typename This::Shdr shdr(pshdr);
1032 
1033       off_t offset;
1034       Output_section* os = layout->layout_eh_frame(this,
1035 						   sd->symbols->data(),
1036 						   sd->symbols_size,
1037 						   sd->symbol_names->data(),
1038 						   sd->symbol_names_size,
1039 						   i, shdr,
1040 						   reloc_shndx[i],
1041 						   reloc_type[i],
1042 						   &offset);
1043       out_sections[i] = os;
1044       if (offset == -1)
1045         out_section_offsets[i] = -1U;
1046       else
1047         out_section_offsets[i] = convert_types<Address, off_t>(offset);
1048 
1049       // If this section requires special handling, and if there are
1050       // relocs that apply to it, then we must do the special handling
1051       // before we apply the relocs.
1052       if (offset == -1 && reloc_shndx[i] != 0)
1053 	this->set_relocs_must_follow_section_writes();
1054     }
1055 
1056   delete sd->section_headers;
1057   sd->section_headers = NULL;
1058   delete sd->section_names;
1059   sd->section_names = NULL;
1060 }
1061 
1062 // Add the symbols to the symbol table.
1063 
1064 template<int size, bool big_endian>
1065 void
1066 Sized_relobj<size, big_endian>::do_add_symbols(Symbol_table* symtab,
1067 					       Read_symbols_data* sd)
1068 {
1069   if (sd->symbols == NULL)
1070     {
1071       gold_assert(sd->symbol_names == NULL);
1072       return;
1073     }
1074 
1075   const int sym_size = This::sym_size;
1076   size_t symcount = ((sd->symbols_size - sd->external_symbols_offset)
1077 		     / sym_size);
1078   if (symcount * sym_size != sd->symbols_size - sd->external_symbols_offset)
1079     {
1080       this->error(_("size of symbols is not multiple of symbol size"));
1081       return;
1082     }
1083 
1084   this->symbols_.resize(symcount);
1085 
1086   const char* sym_names =
1087     reinterpret_cast<const char*>(sd->symbol_names->data());
1088   symtab->add_from_relobj(this,
1089 			  sd->symbols->data() + sd->external_symbols_offset,
1090 			  symcount, this->local_symbol_count_,
1091 			  sym_names, sd->symbol_names_size,
1092 			  &this->symbols_,
1093 			  &this->defined_count_);
1094 
1095   delete sd->symbols;
1096   sd->symbols = NULL;
1097   delete sd->symbol_names;
1098   sd->symbol_names = NULL;
1099 }
1100 
1101 // First pass over the local symbols.  Here we add their names to
1102 // *POOL and *DYNPOOL, and we store the symbol value in
1103 // THIS->LOCAL_VALUES_.  This function is always called from a
1104 // singleton thread.  This is followed by a call to
1105 // finalize_local_symbols.
1106 
1107 template<int size, bool big_endian>
1108 void
1109 Sized_relobj<size, big_endian>::do_count_local_symbols(Stringpool* pool,
1110 						       Stringpool* dynpool)
1111 {
1112   gold_assert(this->symtab_shndx_ != -1U);
1113   if (this->symtab_shndx_ == 0)
1114     {
1115       // This object has no symbols.  Weird but legal.
1116       return;
1117     }
1118 
1119   // Read the symbol table section header.
1120   const unsigned int symtab_shndx = this->symtab_shndx_;
1121   typename This::Shdr symtabshdr(this,
1122 				 this->elf_file_.section_header(symtab_shndx));
1123   gold_assert(symtabshdr.get_sh_type() == elfcpp::SHT_SYMTAB);
1124 
1125   // Read the local symbols.
1126   const int sym_size = This::sym_size;
1127   const unsigned int loccount = this->local_symbol_count_;
1128   gold_assert(loccount == symtabshdr.get_sh_info());
1129   off_t locsize = loccount * sym_size;
1130   const unsigned char* psyms = this->get_view(symtabshdr.get_sh_offset(),
1131 					      locsize, true, true);
1132 
1133   // Read the symbol names.
1134   const unsigned int strtab_shndx =
1135     this->adjust_shndx(symtabshdr.get_sh_link());
1136   section_size_type strtab_size;
1137   const unsigned char* pnamesu = this->section_contents(strtab_shndx,
1138 							&strtab_size,
1139 							true);
1140   const char* pnames = reinterpret_cast<const char*>(pnamesu);
1141 
1142   // Loop over the local symbols.
1143 
1144   const Output_sections& out_sections(this->output_sections());
1145   unsigned int shnum = this->shnum();
1146   unsigned int count = 0;
1147   unsigned int dyncount = 0;
1148   // Skip the first, dummy, symbol.
1149   psyms += sym_size;
1150   for (unsigned int i = 1; i < loccount; ++i, psyms += sym_size)
1151     {
1152       elfcpp::Sym<size, big_endian> sym(psyms);
1153 
1154       Symbol_value<size>& lv(this->local_values_[i]);
1155 
1156       bool is_ordinary;
1157       unsigned int shndx = this->adjust_sym_shndx(i, sym.get_st_shndx(),
1158 						  &is_ordinary);
1159       lv.set_input_shndx(shndx, is_ordinary);
1160 
1161       if (sym.get_st_type() == elfcpp::STT_SECTION)
1162 	lv.set_is_section_symbol();
1163       else if (sym.get_st_type() == elfcpp::STT_TLS)
1164 	lv.set_is_tls_symbol();
1165 
1166       // Save the input symbol value for use in do_finalize_local_symbols().
1167       lv.set_input_value(sym.get_st_value());
1168 
1169       // Decide whether this symbol should go into the output file.
1170 
1171       if (shndx < shnum && out_sections[shndx] == NULL)
1172         {
1173 	  lv.set_no_output_symtab_entry();
1174           gold_assert(!lv.needs_output_dynsym_entry());
1175           continue;
1176         }
1177 
1178       if (sym.get_st_type() == elfcpp::STT_SECTION)
1179 	{
1180 	  lv.set_no_output_symtab_entry();
1181           gold_assert(!lv.needs_output_dynsym_entry());
1182 	  continue;
1183 	}
1184 
1185       if (sym.get_st_name() >= strtab_size)
1186 	{
1187 	  this->error(_("local symbol %u section name out of range: %u >= %u"),
1188 		      i, sym.get_st_name(),
1189 		      static_cast<unsigned int>(strtab_size));
1190 	  lv.set_no_output_symtab_entry();
1191 	  continue;
1192 	}
1193 
1194       // Add the symbol to the symbol table string pool.
1195       const char* name = pnames + sym.get_st_name();
1196       pool->add(name, true, NULL);
1197       ++count;
1198 
1199       // If needed, add the symbol to the dynamic symbol table string pool.
1200       if (lv.needs_output_dynsym_entry())
1201         {
1202           dynpool->add(name, true, NULL);
1203           ++dyncount;
1204         }
1205     }
1206 
1207   this->output_local_symbol_count_ = count;
1208   this->output_local_dynsym_count_ = dyncount;
1209 }
1210 
1211 // Finalize the local symbols.  Here we set the final value in
1212 // THIS->LOCAL_VALUES_ and set their output symbol table indexes.
1213 // This function is always called from a singleton thread.  The actual
1214 // output of the local symbols will occur in a separate task.
1215 
1216 template<int size, bool big_endian>
1217 unsigned int
1218 Sized_relobj<size, big_endian>::do_finalize_local_symbols(unsigned int index,
1219 							  off_t off)
1220 {
1221   gold_assert(off == static_cast<off_t>(align_address(off, size >> 3)));
1222 
1223   const unsigned int loccount = this->local_symbol_count_;
1224   this->local_symbol_offset_ = off;
1225 
1226   const Output_sections& out_sections(this->output_sections());
1227   const std::vector<Address>& out_offsets(this->section_offsets_);
1228   unsigned int shnum = this->shnum();
1229 
1230   for (unsigned int i = 1; i < loccount; ++i)
1231     {
1232       Symbol_value<size>& lv(this->local_values_[i]);
1233 
1234       bool is_ordinary;
1235       unsigned int shndx = lv.input_shndx(&is_ordinary);
1236 
1237       // Set the output symbol value.
1238 
1239       if (!is_ordinary)
1240 	{
1241 	  if (shndx == elfcpp::SHN_ABS || shndx == elfcpp::SHN_COMMON)
1242 	    lv.set_output_value(lv.input_value());
1243 	  else
1244 	    {
1245 	      this->error(_("unknown section index %u for local symbol %u"),
1246 			  shndx, i);
1247 	      lv.set_output_value(0);
1248 	    }
1249 	}
1250       else
1251 	{
1252 	  if (shndx >= shnum)
1253 	    {
1254 	      this->error(_("local symbol %u section index %u out of range"),
1255 			  i, shndx);
1256 	      shndx = 0;
1257 	    }
1258 
1259 	  Output_section* os = out_sections[shndx];
1260 
1261 	  if (os == NULL)
1262 	    {
1263               // This local symbol belongs to a section we are discarding.
1264               // In some cases when applying relocations later, we will
1265               // attempt to match it to the corresponding kept section,
1266               // so we leave the input value unchanged here.
1267 	      continue;
1268 	    }
1269 	  else if (out_offsets[shndx] == -1U)
1270 	    {
1271 	      // This is a SHF_MERGE section or one which otherwise
1272 	      // requires special handling.  We get the output address
1273 	      // of the start of the merged section.  If this is not a
1274 	      // section symbol, we can then determine the final
1275 	      // value.  If it is a section symbol, we can not, as in
1276 	      // that case we have to consider the addend to determine
1277 	      // the value to use in a relocation.
1278 	      if (!lv.is_section_symbol())
1279 		lv.set_output_value(os->output_address(this, shndx,
1280                                                        lv.input_value()));
1281 	      else
1282 		{
1283                   section_offset_type start =
1284                     os->starting_output_address(this, shndx);
1285 		  Merged_symbol_value<size>* msv =
1286 		    new Merged_symbol_value<size>(lv.input_value(), start);
1287 		  lv.set_merged_symbol_value(msv);
1288 		}
1289 	    }
1290           else if (lv.is_tls_symbol())
1291 	    lv.set_output_value(os->tls_offset()
1292 				+ out_offsets[shndx]
1293 				+ lv.input_value());
1294 	  else
1295 	    lv.set_output_value(os->address()
1296 				+ out_offsets[shndx]
1297 				+ lv.input_value());
1298 	}
1299 
1300       if (lv.needs_output_symtab_entry())
1301         {
1302           lv.set_output_symtab_index(index);
1303           ++index;
1304         }
1305     }
1306   return index;
1307 }
1308 
1309 // Set the output dynamic symbol table indexes for the local variables.
1310 
1311 template<int size, bool big_endian>
1312 unsigned int
1313 Sized_relobj<size, big_endian>::do_set_local_dynsym_indexes(unsigned int index)
1314 {
1315   const unsigned int loccount = this->local_symbol_count_;
1316   for (unsigned int i = 1; i < loccount; ++i)
1317     {
1318       Symbol_value<size>& lv(this->local_values_[i]);
1319       if (lv.needs_output_dynsym_entry())
1320         {
1321           lv.set_output_dynsym_index(index);
1322           ++index;
1323         }
1324     }
1325   return index;
1326 }
1327 
1328 // Set the offset where local dynamic symbol information will be stored.
1329 // Returns the count of local symbols contributed to the symbol table by
1330 // this object.
1331 
1332 template<int size, bool big_endian>
1333 unsigned int
1334 Sized_relobj<size, big_endian>::do_set_local_dynsym_offset(off_t off)
1335 {
1336   gold_assert(off == static_cast<off_t>(align_address(off, size >> 3)));
1337   this->local_dynsym_offset_ = off;
1338   return this->output_local_dynsym_count_;
1339 }
1340 
1341 // Write out the local symbols.
1342 
1343 template<int size, bool big_endian>
1344 void
1345 Sized_relobj<size, big_endian>::write_local_symbols(
1346     Output_file* of,
1347     const Stringpool* sympool,
1348     const Stringpool* dynpool,
1349     Output_symtab_xindex* symtab_xindex,
1350     Output_symtab_xindex* dynsym_xindex)
1351 {
1352   if (parameters->options().strip_all()
1353       && this->output_local_dynsym_count_ == 0)
1354     return;
1355 
1356   gold_assert(this->symtab_shndx_ != -1U);
1357   if (this->symtab_shndx_ == 0)
1358     {
1359       // This object has no symbols.  Weird but legal.
1360       return;
1361     }
1362 
1363   // Read the symbol table section header.
1364   const unsigned int symtab_shndx = this->symtab_shndx_;
1365   typename This::Shdr symtabshdr(this,
1366 				 this->elf_file_.section_header(symtab_shndx));
1367   gold_assert(symtabshdr.get_sh_type() == elfcpp::SHT_SYMTAB);
1368   const unsigned int loccount = this->local_symbol_count_;
1369   gold_assert(loccount == symtabshdr.get_sh_info());
1370 
1371   // Read the local symbols.
1372   const int sym_size = This::sym_size;
1373   off_t locsize = loccount * sym_size;
1374   const unsigned char* psyms = this->get_view(symtabshdr.get_sh_offset(),
1375 					      locsize, true, false);
1376 
1377   // Read the symbol names.
1378   const unsigned int strtab_shndx =
1379     this->adjust_shndx(symtabshdr.get_sh_link());
1380   section_size_type strtab_size;
1381   const unsigned char* pnamesu = this->section_contents(strtab_shndx,
1382 							&strtab_size,
1383 							false);
1384   const char* pnames = reinterpret_cast<const char*>(pnamesu);
1385 
1386   // Get views into the output file for the portions of the symbol table
1387   // and the dynamic symbol table that we will be writing.
1388   off_t output_size = this->output_local_symbol_count_ * sym_size;
1389   unsigned char* oview = NULL;
1390   if (output_size > 0)
1391     oview = of->get_output_view(this->local_symbol_offset_, output_size);
1392 
1393   off_t dyn_output_size = this->output_local_dynsym_count_ * sym_size;
1394   unsigned char* dyn_oview = NULL;
1395   if (dyn_output_size > 0)
1396     dyn_oview = of->get_output_view(this->local_dynsym_offset_,
1397                                     dyn_output_size);
1398 
1399   const Output_sections out_sections(this->output_sections());
1400 
1401   gold_assert(this->local_values_.size() == loccount);
1402 
1403   unsigned char* ov = oview;
1404   unsigned char* dyn_ov = dyn_oview;
1405   psyms += sym_size;
1406   for (unsigned int i = 1; i < loccount; ++i, psyms += sym_size)
1407     {
1408       elfcpp::Sym<size, big_endian> isym(psyms);
1409 
1410       Symbol_value<size>& lv(this->local_values_[i]);
1411 
1412       bool is_ordinary;
1413       unsigned int st_shndx = this->adjust_sym_shndx(i, isym.get_st_shndx(),
1414 						     &is_ordinary);
1415       if (is_ordinary)
1416 	{
1417 	  gold_assert(st_shndx < out_sections.size());
1418 	  if (out_sections[st_shndx] == NULL)
1419 	    continue;
1420 	  st_shndx = out_sections[st_shndx]->out_shndx();
1421 	  if (st_shndx >= elfcpp::SHN_LORESERVE)
1422 	    {
1423 	      if (lv.needs_output_symtab_entry())
1424 		symtab_xindex->add(lv.output_symtab_index(), st_shndx);
1425 	      if (lv.needs_output_dynsym_entry())
1426 		dynsym_xindex->add(lv.output_dynsym_index(), st_shndx);
1427 	      st_shndx = elfcpp::SHN_XINDEX;
1428 	    }
1429 	}
1430 
1431       // Write the symbol to the output symbol table.
1432       if (!parameters->options().strip_all()
1433 	  && lv.needs_output_symtab_entry())
1434         {
1435           elfcpp::Sym_write<size, big_endian> osym(ov);
1436 
1437           gold_assert(isym.get_st_name() < strtab_size);
1438           const char* name = pnames + isym.get_st_name();
1439           osym.put_st_name(sympool->get_offset(name));
1440           osym.put_st_value(this->local_values_[i].value(this, 0));
1441           osym.put_st_size(isym.get_st_size());
1442           osym.put_st_info(isym.get_st_info());
1443           osym.put_st_other(isym.get_st_other());
1444           osym.put_st_shndx(st_shndx);
1445 
1446           ov += sym_size;
1447         }
1448 
1449       // Write the symbol to the output dynamic symbol table.
1450       if (lv.needs_output_dynsym_entry())
1451         {
1452           gold_assert(dyn_ov < dyn_oview + dyn_output_size);
1453           elfcpp::Sym_write<size, big_endian> osym(dyn_ov);
1454 
1455           gold_assert(isym.get_st_name() < strtab_size);
1456           const char* name = pnames + isym.get_st_name();
1457           osym.put_st_name(dynpool->get_offset(name));
1458           osym.put_st_value(this->local_values_[i].value(this, 0));
1459           osym.put_st_size(isym.get_st_size());
1460           osym.put_st_info(isym.get_st_info());
1461           osym.put_st_other(isym.get_st_other());
1462           osym.put_st_shndx(st_shndx);
1463 
1464           dyn_ov += sym_size;
1465         }
1466     }
1467 
1468 
1469   if (output_size > 0)
1470     {
1471       gold_assert(ov - oview == output_size);
1472       of->write_output_view(this->local_symbol_offset_, output_size, oview);
1473     }
1474 
1475   if (dyn_output_size > 0)
1476     {
1477       gold_assert(dyn_ov - dyn_oview == dyn_output_size);
1478       of->write_output_view(this->local_dynsym_offset_, dyn_output_size,
1479                             dyn_oview);
1480     }
1481 }
1482 
1483 // Set *INFO to symbolic information about the offset OFFSET in the
1484 // section SHNDX.  Return true if we found something, false if we
1485 // found nothing.
1486 
1487 template<int size, bool big_endian>
1488 bool
1489 Sized_relobj<size, big_endian>::get_symbol_location_info(
1490     unsigned int shndx,
1491     off_t offset,
1492     Symbol_location_info* info)
1493 {
1494   if (this->symtab_shndx_ == 0)
1495     return false;
1496 
1497   section_size_type symbols_size;
1498   const unsigned char* symbols = this->section_contents(this->symtab_shndx_,
1499 							&symbols_size,
1500 							false);
1501 
1502   unsigned int symbol_names_shndx =
1503     this->adjust_shndx(this->section_link(this->symtab_shndx_));
1504   section_size_type names_size;
1505   const unsigned char* symbol_names_u =
1506     this->section_contents(symbol_names_shndx, &names_size, false);
1507   const char* symbol_names = reinterpret_cast<const char*>(symbol_names_u);
1508 
1509   const int sym_size = This::sym_size;
1510   const size_t count = symbols_size / sym_size;
1511 
1512   const unsigned char* p = symbols;
1513   for (size_t i = 0; i < count; ++i, p += sym_size)
1514     {
1515       elfcpp::Sym<size, big_endian> sym(p);
1516 
1517       if (sym.get_st_type() == elfcpp::STT_FILE)
1518 	{
1519 	  if (sym.get_st_name() >= names_size)
1520 	    info->source_file = "(invalid)";
1521 	  else
1522 	    info->source_file = symbol_names + sym.get_st_name();
1523 	  continue;
1524 	}
1525 
1526       bool is_ordinary;
1527       unsigned int st_shndx = this->adjust_sym_shndx(i, sym.get_st_shndx(),
1528 						     &is_ordinary);
1529       if (is_ordinary
1530 	  && st_shndx == shndx
1531 	  && static_cast<off_t>(sym.get_st_value()) <= offset
1532 	  && (static_cast<off_t>(sym.get_st_value() + sym.get_st_size())
1533 	      > offset))
1534         {
1535           if (sym.get_st_name() > names_size)
1536 	    info->enclosing_symbol_name = "(invalid)";
1537 	  else
1538             {
1539               info->enclosing_symbol_name = symbol_names + sym.get_st_name();
1540               if (parameters->options().do_demangle())
1541                 {
1542                   char* demangled_name = cplus_demangle(
1543                       info->enclosing_symbol_name.c_str(),
1544                       DMGL_ANSI | DMGL_PARAMS);
1545                   if (demangled_name != NULL)
1546                     {
1547                       info->enclosing_symbol_name.assign(demangled_name);
1548                       free(demangled_name);
1549                     }
1550                 }
1551             }
1552 	  return true;
1553         }
1554     }
1555 
1556   return false;
1557 }
1558 
1559 // Look for a kept section corresponding to the given discarded section,
1560 // and return its output address.  This is used only for relocations in
1561 // debugging sections.  If we can't find the kept section, return 0.
1562 
1563 template<int size, bool big_endian>
1564 typename Sized_relobj<size, big_endian>::Address
1565 Sized_relobj<size, big_endian>::map_to_kept_section(
1566     unsigned int shndx,
1567     bool* found) const
1568 {
1569   Kept_comdat_section *kept = this->get_kept_comdat_section(shndx);
1570   if (kept != NULL)
1571     {
1572       gold_assert(kept->object_ != NULL);
1573       *found = true;
1574       Output_section* os = kept->object_->output_section(kept->shndx_);
1575       Address offset = kept->object_->get_output_section_offset(kept->shndx_);
1576       gold_assert(os != NULL && offset != -1U);
1577       return os->address() + offset;
1578     }
1579   *found = false;
1580   return 0;
1581 }
1582 
1583 // Get symbol counts.
1584 
1585 template<int size, bool big_endian>
1586 void
1587 Sized_relobj<size, big_endian>::do_get_global_symbol_counts(
1588     const Symbol_table*,
1589     size_t* defined,
1590     size_t* used) const
1591 {
1592   *defined = this->defined_count_;
1593   size_t count = 0;
1594   for (Symbols::const_iterator p = this->symbols_.begin();
1595        p != this->symbols_.end();
1596        ++p)
1597     if (*p != NULL
1598 	&& (*p)->source() == Symbol::FROM_OBJECT
1599 	&& (*p)->object() == this
1600 	&& (*p)->is_defined())
1601       ++count;
1602   *used = count;
1603 }
1604 
1605 // Input_objects methods.
1606 
1607 // Add a regular relocatable object to the list.  Return false if this
1608 // object should be ignored.
1609 
1610 bool
1611 Input_objects::add_object(Object* obj)
1612 {
1613   // Set the global target from the first object file we recognize.
1614   Target* target = obj->target();
1615   if (!parameters->target_valid())
1616     set_parameters_target(target);
1617   else if (target != &parameters->target())
1618     {
1619       obj->error(_("incompatible target"));
1620       return false;
1621     }
1622 
1623   // Print the filename if the -t/--trace option is selected.
1624   if (parameters->options().trace())
1625     gold_info("%s", obj->name().c_str());
1626 
1627   if (!obj->is_dynamic())
1628     this->relobj_list_.push_back(static_cast<Relobj*>(obj));
1629   else
1630     {
1631       // See if this is a duplicate SONAME.
1632       Dynobj* dynobj = static_cast<Dynobj*>(obj);
1633       const char* soname = dynobj->soname();
1634 
1635       std::pair<Unordered_set<std::string>::iterator, bool> ins =
1636 	this->sonames_.insert(soname);
1637       if (!ins.second)
1638 	{
1639 	  // We have already seen a dynamic object with this soname.
1640 	  return false;
1641 	}
1642 
1643       this->dynobj_list_.push_back(dynobj);
1644 
1645       // If this is -lc, remember the directory in which we found it.
1646       // We use this when issuing warnings about undefined symbols: as
1647       // a heuristic, we don't warn about system libraries found in
1648       // the same directory as -lc.
1649       if (strncmp(soname, "libc.so", 7) == 0)
1650 	{
1651 	  const char* object_name = dynobj->name().c_str();
1652 	  const char* base = lbasename(object_name);
1653 	  if (base != object_name)
1654 	    this->system_library_directory_.assign(object_name,
1655 						   base - 1 - object_name);
1656 	}
1657     }
1658 
1659   // Add this object to the cross-referencer if requested.
1660   if (parameters->options().user_set_print_symbol_counts())
1661     {
1662       if (this->cref_ == NULL)
1663 	this->cref_ = new Cref();
1664       this->cref_->add_object(obj);
1665     }
1666 
1667   return true;
1668 }
1669 
1670 // Return whether an object was found in the system library directory.
1671 
1672 bool
1673 Input_objects::found_in_system_library_directory(const Object* object) const
1674 {
1675   return (!this->system_library_directory_.empty()
1676 	  && object->name().compare(0,
1677 				    this->system_library_directory_.size(),
1678 				    this->system_library_directory_) == 0);
1679 }
1680 
1681 // For each dynamic object, record whether we've seen all of its
1682 // explicit dependencies.
1683 
1684 void
1685 Input_objects::check_dynamic_dependencies() const
1686 {
1687   for (Dynobj_list::const_iterator p = this->dynobj_list_.begin();
1688        p != this->dynobj_list_.end();
1689        ++p)
1690     {
1691       const Dynobj::Needed& needed((*p)->needed());
1692       bool found_all = true;
1693       for (Dynobj::Needed::const_iterator pneeded = needed.begin();
1694 	   pneeded != needed.end();
1695 	   ++pneeded)
1696 	{
1697 	  if (this->sonames_.find(*pneeded) == this->sonames_.end())
1698 	    {
1699 	      found_all = false;
1700 	      break;
1701 	    }
1702 	}
1703       (*p)->set_has_unknown_needed_entries(!found_all);
1704     }
1705 }
1706 
1707 // Start processing an archive.
1708 
1709 void
1710 Input_objects::archive_start(Archive* archive)
1711 {
1712   if (parameters->options().user_set_print_symbol_counts())
1713     {
1714       if (this->cref_ == NULL)
1715 	this->cref_ = new Cref();
1716       this->cref_->add_archive_start(archive);
1717     }
1718 }
1719 
1720 // Stop processing an archive.
1721 
1722 void
1723 Input_objects::archive_stop(Archive* archive)
1724 {
1725   if (parameters->options().user_set_print_symbol_counts())
1726     this->cref_->add_archive_stop(archive);
1727 }
1728 
1729 // Print symbol counts
1730 
1731 void
1732 Input_objects::print_symbol_counts(const Symbol_table* symtab) const
1733 {
1734   if (parameters->options().user_set_print_symbol_counts()
1735       && this->cref_ != NULL)
1736     this->cref_->print_symbol_counts(symtab);
1737 }
1738 
1739 // Relocate_info methods.
1740 
1741 // Return a string describing the location of a relocation.  This is
1742 // only used in error messages.
1743 
1744 template<int size, bool big_endian>
1745 std::string
1746 Relocate_info<size, big_endian>::location(size_t, off_t offset) const
1747 {
1748   // See if we can get line-number information from debugging sections.
1749   std::string filename;
1750   std::string file_and_lineno;   // Better than filename-only, if available.
1751 
1752   Sized_dwarf_line_info<size, big_endian> line_info(this->object);
1753   // This will be "" if we failed to parse the debug info for any reason.
1754   file_and_lineno = line_info.addr2line(this->data_shndx, offset);
1755 
1756   std::string ret(this->object->name());
1757   ret += ':';
1758   Symbol_location_info info;
1759   if (this->object->get_symbol_location_info(this->data_shndx, offset, &info))
1760     {
1761       ret += " in function ";
1762       ret += info.enclosing_symbol_name;
1763       ret += ":";
1764       filename = info.source_file;
1765     }
1766 
1767   if (!file_and_lineno.empty())
1768     ret += file_and_lineno;
1769   else
1770     {
1771       if (!filename.empty())
1772         ret += filename;
1773       ret += "(";
1774       ret += this->object->section_name(this->data_shndx);
1775       char buf[100];
1776       // Offsets into sections have to be positive.
1777       snprintf(buf, sizeof(buf), "+0x%lx", static_cast<long>(offset));
1778       ret += buf;
1779       ret += ")";
1780     }
1781   return ret;
1782 }
1783 
1784 } // End namespace gold.
1785 
1786 namespace
1787 {
1788 
1789 using namespace gold;
1790 
1791 // Read an ELF file with the header and return the appropriate
1792 // instance of Object.
1793 
1794 template<int size, bool big_endian>
1795 Object*
1796 make_elf_sized_object(const std::string& name, Input_file* input_file,
1797 		      off_t offset, const elfcpp::Ehdr<size, big_endian>& ehdr)
1798 {
1799   int et = ehdr.get_e_type();
1800   if (et == elfcpp::ET_REL)
1801     {
1802       Sized_relobj<size, big_endian>* obj =
1803 	new Sized_relobj<size, big_endian>(name, input_file, offset, ehdr);
1804       obj->setup(ehdr);
1805       return obj;
1806     }
1807   else if (et == elfcpp::ET_DYN)
1808     {
1809       Sized_dynobj<size, big_endian>* obj =
1810 	new Sized_dynobj<size, big_endian>(name, input_file, offset, ehdr);
1811       obj->setup(ehdr);
1812       return obj;
1813     }
1814   else
1815     {
1816       gold_error(_("%s: unsupported ELF file type %d"),
1817 		 name.c_str(), et);
1818       return NULL;
1819     }
1820 }
1821 
1822 } // End anonymous namespace.
1823 
1824 namespace gold
1825 {
1826 
1827 // Read an ELF file and return the appropriate instance of Object.
1828 
1829 Object*
1830 make_elf_object(const std::string& name, Input_file* input_file, off_t offset,
1831 		const unsigned char* p, section_offset_type bytes)
1832 {
1833   if (bytes < elfcpp::EI_NIDENT)
1834     {
1835       gold_error(_("%s: ELF file too short"), name.c_str());
1836       return NULL;
1837     }
1838 
1839   int v = p[elfcpp::EI_VERSION];
1840   if (v != elfcpp::EV_CURRENT)
1841     {
1842       if (v == elfcpp::EV_NONE)
1843 	gold_error(_("%s: invalid ELF version 0"), name.c_str());
1844       else
1845 	gold_error(_("%s: unsupported ELF version %d"), name.c_str(), v);
1846       return NULL;
1847     }
1848 
1849   int c = p[elfcpp::EI_CLASS];
1850   if (c == elfcpp::ELFCLASSNONE)
1851     {
1852       gold_error(_("%s: invalid ELF class 0"), name.c_str());
1853       return NULL;
1854     }
1855   else if (c != elfcpp::ELFCLASS32
1856 	   && c != elfcpp::ELFCLASS64)
1857     {
1858       gold_error(_("%s: unsupported ELF class %d"), name.c_str(), c);
1859       return NULL;
1860     }
1861 
1862   int d = p[elfcpp::EI_DATA];
1863   if (d == elfcpp::ELFDATANONE)
1864     {
1865       gold_error(_("%s: invalid ELF data encoding"), name.c_str());
1866       return NULL;
1867     }
1868   else if (d != elfcpp::ELFDATA2LSB
1869 	   && d != elfcpp::ELFDATA2MSB)
1870     {
1871       gold_error(_("%s: unsupported ELF data encoding %d"), name.c_str(), d);
1872       return NULL;
1873     }
1874 
1875   bool big_endian = d == elfcpp::ELFDATA2MSB;
1876 
1877   if (c == elfcpp::ELFCLASS32)
1878     {
1879       if (bytes < elfcpp::Elf_sizes<32>::ehdr_size)
1880 	{
1881 	  gold_error(_("%s: ELF file too short"), name.c_str());
1882 	  return NULL;
1883 	}
1884       if (big_endian)
1885 	{
1886 #ifdef HAVE_TARGET_32_BIG
1887 	  elfcpp::Ehdr<32, true> ehdr(p);
1888 	  return make_elf_sized_object<32, true>(name, input_file,
1889 						 offset, ehdr);
1890 #else
1891           gold_error(_("%s: not configured to support "
1892 		       "32-bit big-endian object"),
1893 		     name.c_str());
1894 	  return NULL;
1895 #endif
1896 	}
1897       else
1898 	{
1899 #ifdef HAVE_TARGET_32_LITTLE
1900 	  elfcpp::Ehdr<32, false> ehdr(p);
1901 	  return make_elf_sized_object<32, false>(name, input_file,
1902 						  offset, ehdr);
1903 #else
1904           gold_error(_("%s: not configured to support "
1905 		       "32-bit little-endian object"),
1906 		     name.c_str());
1907 	  return NULL;
1908 #endif
1909 	}
1910     }
1911   else
1912     {
1913       if (bytes < elfcpp::Elf_sizes<64>::ehdr_size)
1914 	{
1915 	  gold_error(_("%s: ELF file too short"), name.c_str());
1916 	  return NULL;
1917 	}
1918       if (big_endian)
1919 	{
1920 #ifdef HAVE_TARGET_64_BIG
1921 	  elfcpp::Ehdr<64, true> ehdr(p);
1922 	  return make_elf_sized_object<64, true>(name, input_file,
1923 						 offset, ehdr);
1924 #else
1925           gold_error(_("%s: not configured to support "
1926 		       "64-bit big-endian object"),
1927 		     name.c_str());
1928 	  return NULL;
1929 #endif
1930 	}
1931       else
1932 	{
1933 #ifdef HAVE_TARGET_64_LITTLE
1934 	  elfcpp::Ehdr<64, false> ehdr(p);
1935 	  return make_elf_sized_object<64, false>(name, input_file,
1936 						  offset, ehdr);
1937 #else
1938           gold_error(_("%s: not configured to support "
1939 		       "64-bit little-endian object"),
1940 		     name.c_str());
1941 	  return NULL;
1942 #endif
1943 	}
1944     }
1945 }
1946 
1947 // Instantiate the templates we need.
1948 
1949 #ifdef HAVE_TARGET_32_LITTLE
1950 template
1951 void
1952 Object::read_section_data<32, false>(elfcpp::Elf_file<32, false, Object>*,
1953 				     Read_symbols_data*);
1954 #endif
1955 
1956 #ifdef HAVE_TARGET_32_BIG
1957 template
1958 void
1959 Object::read_section_data<32, true>(elfcpp::Elf_file<32, true, Object>*,
1960 				    Read_symbols_data*);
1961 #endif
1962 
1963 #ifdef HAVE_TARGET_64_LITTLE
1964 template
1965 void
1966 Object::read_section_data<64, false>(elfcpp::Elf_file<64, false, Object>*,
1967 				     Read_symbols_data*);
1968 #endif
1969 
1970 #ifdef HAVE_TARGET_64_BIG
1971 template
1972 void
1973 Object::read_section_data<64, true>(elfcpp::Elf_file<64, true, Object>*,
1974 				    Read_symbols_data*);
1975 #endif
1976 
1977 #ifdef HAVE_TARGET_32_LITTLE
1978 template
1979 class Sized_relobj<32, false>;
1980 #endif
1981 
1982 #ifdef HAVE_TARGET_32_BIG
1983 template
1984 class Sized_relobj<32, true>;
1985 #endif
1986 
1987 #ifdef HAVE_TARGET_64_LITTLE
1988 template
1989 class Sized_relobj<64, false>;
1990 #endif
1991 
1992 #ifdef HAVE_TARGET_64_BIG
1993 template
1994 class Sized_relobj<64, true>;
1995 #endif
1996 
1997 #ifdef HAVE_TARGET_32_LITTLE
1998 template
1999 struct Relocate_info<32, false>;
2000 #endif
2001 
2002 #ifdef HAVE_TARGET_32_BIG
2003 template
2004 struct Relocate_info<32, true>;
2005 #endif
2006 
2007 #ifdef HAVE_TARGET_64_LITTLE
2008 template
2009 struct Relocate_info<64, false>;
2010 #endif
2011 
2012 #ifdef HAVE_TARGET_64_BIG
2013 template
2014 struct Relocate_info<64, true>;
2015 #endif
2016 
2017 } // End namespace gold.
2018