fc8533e817d8799600d78d252662f62708c5bfc5
[platform/upstream/binutils.git] / gold / object.cc
1 // object.cc -- support for an object file for linking in gold
2
3 // Copyright 2006, 2007, 2008, 2009, 2010, 2011, 2012
4 // Free Software Foundation, Inc.
5 // Written by Ian Lance Taylor <iant@google.com>.
6
7 // This file is part of gold.
8
9 // This program is free software; you can redistribute it and/or modify
10 // it under the terms of the GNU General Public License as published by
11 // the Free Software Foundation; either version 3 of the License, or
12 // (at your option) any later version.
13
14 // This program is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 // GNU General Public License for more details.
18
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
22 // MA 02110-1301, USA.
23
24 #include "gold.h"
25
26 #include <cerrno>
27 #include <cstring>
28 #include <cstdarg>
29 #include "demangle.h"
30 #include "libiberty.h"
31
32 #include "gc.h"
33 #include "target-select.h"
34 #include "dwarf_reader.h"
35 #include "layout.h"
36 #include "output.h"
37 #include "symtab.h"
38 #include "cref.h"
39 #include "reloc.h"
40 #include "object.h"
41 #include "dynobj.h"
42 #include "plugin.h"
43 #include "compressed_output.h"
44 #include "incremental.h"
45
46 namespace gold
47 {
48
49 // Struct Read_symbols_data.
50
51 // Destroy any remaining File_view objects.
52
53 Read_symbols_data::~Read_symbols_data()
54 {
55   if (this->section_headers != NULL)
56     delete this->section_headers;
57   if (this->section_names != NULL)
58     delete this->section_names;
59   if (this->symbols != NULL)
60     delete this->symbols;
61   if (this->symbol_names != NULL)
62     delete this->symbol_names;
63   if (this->versym != NULL)
64     delete this->versym;
65   if (this->verdef != NULL)
66     delete this->verdef;
67   if (this->verneed != NULL)
68     delete this->verneed;
69 }
70
71 // Class Xindex.
72
73 // Initialize the symtab_xindex_ array.  Find the SHT_SYMTAB_SHNDX
74 // section and read it in.  SYMTAB_SHNDX is the index of the symbol
75 // table we care about.
76
77 template<int size, bool big_endian>
78 void
79 Xindex::initialize_symtab_xindex(Object* object, unsigned int symtab_shndx)
80 {
81   if (!this->symtab_xindex_.empty())
82     return;
83
84   gold_assert(symtab_shndx != 0);
85
86   // Look through the sections in reverse order, on the theory that it
87   // is more likely to be near the end than the beginning.
88   unsigned int i = object->shnum();
89   while (i > 0)
90     {
91       --i;
92       if (object->section_type(i) == elfcpp::SHT_SYMTAB_SHNDX
93           && this->adjust_shndx(object->section_link(i)) == symtab_shndx)
94         {
95           this->read_symtab_xindex<size, big_endian>(object, i, NULL);
96           return;
97         }
98     }
99
100   object->error(_("missing SHT_SYMTAB_SHNDX section"));
101 }
102
103 // Read in the symtab_xindex_ array, given the section index of the
104 // SHT_SYMTAB_SHNDX section.  If PSHDRS is not NULL, it points at the
105 // section headers.
106
107 template<int size, bool big_endian>
108 void
109 Xindex::read_symtab_xindex(Object* object, unsigned int xindex_shndx,
110                            const unsigned char* pshdrs)
111 {
112   section_size_type bytecount;
113   const unsigned char* contents;
114   if (pshdrs == NULL)
115     contents = object->section_contents(xindex_shndx, &bytecount, false);
116   else
117     {
118       const unsigned char* p = (pshdrs
119                                 + (xindex_shndx
120                                    * elfcpp::Elf_sizes<size>::shdr_size));
121       typename elfcpp::Shdr<size, big_endian> shdr(p);
122       bytecount = convert_to_section_size_type(shdr.get_sh_size());
123       contents = object->get_view(shdr.get_sh_offset(), bytecount, true, false);
124     }
125
126   gold_assert(this->symtab_xindex_.empty());
127   this->symtab_xindex_.reserve(bytecount / 4);
128   for (section_size_type i = 0; i < bytecount; i += 4)
129     {
130       unsigned int shndx = elfcpp::Swap<32, big_endian>::readval(contents + i);
131       // We preadjust the section indexes we save.
132       this->symtab_xindex_.push_back(this->adjust_shndx(shndx));
133     }
134 }
135
136 // Symbol symndx has a section of SHN_XINDEX; return the real section
137 // index.
138
139 unsigned int
140 Xindex::sym_xindex_to_shndx(Object* object, unsigned int symndx)
141 {
142   if (symndx >= this->symtab_xindex_.size())
143     {
144       object->error(_("symbol %u out of range for SHT_SYMTAB_SHNDX section"),
145                     symndx);
146       return elfcpp::SHN_UNDEF;
147     }
148   unsigned int shndx = this->symtab_xindex_[symndx];
149   if (shndx < elfcpp::SHN_LORESERVE || shndx >= object->shnum())
150     {
151       object->error(_("extended index for symbol %u out of range: %u"),
152                     symndx, shndx);
153       return elfcpp::SHN_UNDEF;
154     }
155   return shndx;
156 }
157
158 // Class Object.
159
160 // Report an error for this object file.  This is used by the
161 // elfcpp::Elf_file interface, and also called by the Object code
162 // itself.
163
164 void
165 Object::error(const char* format, ...) const
166 {
167   va_list args;
168   va_start(args, format);
169   char* buf = NULL;
170   if (vasprintf(&buf, format, args) < 0)
171     gold_nomem();
172   va_end(args);
173   gold_error(_("%s: %s"), this->name().c_str(), buf);
174   free(buf);
175 }
176
177 // Return a view of the contents of a section.
178
179 const unsigned char*
180 Object::section_contents(unsigned int shndx, section_size_type* plen,
181                          bool cache)
182 { return this->do_section_contents(shndx, plen, cache); }
183
184 // Read the section data into SD.  This is code common to Sized_relobj_file
185 // and Sized_dynobj, so we put it into Object.
186
187 template<int size, bool big_endian>
188 void
189 Object::read_section_data(elfcpp::Elf_file<size, big_endian, Object>* elf_file,
190                           Read_symbols_data* sd)
191 {
192   const int shdr_size = elfcpp::Elf_sizes<size>::shdr_size;
193
194   // Read the section headers.
195   const off_t shoff = elf_file->shoff();
196   const unsigned int shnum = this->shnum();
197   sd->section_headers = this->get_lasting_view(shoff, shnum * shdr_size,
198                                                true, true);
199
200   // Read the section names.
201   const unsigned char* pshdrs = sd->section_headers->data();
202   const unsigned char* pshdrnames = pshdrs + elf_file->shstrndx() * shdr_size;
203   typename elfcpp::Shdr<size, big_endian> shdrnames(pshdrnames);
204
205   if (shdrnames.get_sh_type() != elfcpp::SHT_STRTAB)
206     this->error(_("section name section has wrong type: %u"),
207                 static_cast<unsigned int>(shdrnames.get_sh_type()));
208
209   sd->section_names_size =
210     convert_to_section_size_type(shdrnames.get_sh_size());
211   sd->section_names = this->get_lasting_view(shdrnames.get_sh_offset(),
212                                              sd->section_names_size, false,
213                                              false);
214 }
215
216 // If NAME is the name of a special .gnu.warning section, arrange for
217 // the warning to be issued.  SHNDX is the section index.  Return
218 // whether it is a warning section.
219
220 bool
221 Object::handle_gnu_warning_section(const char* name, unsigned int shndx,
222                                    Symbol_table* symtab)
223 {
224   const char warn_prefix[] = ".gnu.warning.";
225   const int warn_prefix_len = sizeof warn_prefix - 1;
226   if (strncmp(name, warn_prefix, warn_prefix_len) == 0)
227     {
228       // Read the section contents to get the warning text.  It would
229       // be nicer if we only did this if we have to actually issue a
230       // warning.  Unfortunately, warnings are issued as we relocate
231       // sections.  That means that we can not lock the object then,
232       // as we might try to issue the same warning multiple times
233       // simultaneously.
234       section_size_type len;
235       const unsigned char* contents = this->section_contents(shndx, &len,
236                                                              false);
237       if (len == 0)
238         {
239           const char* warning = name + warn_prefix_len;
240           contents = reinterpret_cast<const unsigned char*>(warning);
241           len = strlen(warning);
242         }
243       std::string warning(reinterpret_cast<const char*>(contents), len);
244       symtab->add_warning(name + warn_prefix_len, this, warning);
245       return true;
246     }
247   return false;
248 }
249
250 // If NAME is the name of the special section which indicates that
251 // this object was compiled with -fsplit-stack, mark it accordingly.
252
253 bool
254 Object::handle_split_stack_section(const char* name)
255 {
256   if (strcmp(name, ".note.GNU-split-stack") == 0)
257     {
258       this->uses_split_stack_ = true;
259       return true;
260     }
261   if (strcmp(name, ".note.GNU-no-split-stack") == 0)
262     {
263       this->has_no_split_stack_ = true;
264       return true;
265     }
266   return false;
267 }
268
269 // Class Relobj
270
271 // To copy the symbols data read from the file to a local data structure.
272 // This function is called from do_layout only while doing garbage
273 // collection.
274
275 void
276 Relobj::copy_symbols_data(Symbols_data* gc_sd, Read_symbols_data* sd,
277                           unsigned int section_header_size)
278 {
279   gc_sd->section_headers_data =
280          new unsigned char[(section_header_size)];
281   memcpy(gc_sd->section_headers_data, sd->section_headers->data(),
282          section_header_size);
283   gc_sd->section_names_data =
284          new unsigned char[sd->section_names_size];
285   memcpy(gc_sd->section_names_data, sd->section_names->data(),
286          sd->section_names_size);
287   gc_sd->section_names_size = sd->section_names_size;
288   if (sd->symbols != NULL)
289     {
290       gc_sd->symbols_data =
291              new unsigned char[sd->symbols_size];
292       memcpy(gc_sd->symbols_data, sd->symbols->data(),
293             sd->symbols_size);
294     }
295   else
296     {
297       gc_sd->symbols_data = NULL;
298     }
299   gc_sd->symbols_size = sd->symbols_size;
300   gc_sd->external_symbols_offset = sd->external_symbols_offset;
301   if (sd->symbol_names != NULL)
302     {
303       gc_sd->symbol_names_data =
304              new unsigned char[sd->symbol_names_size];
305       memcpy(gc_sd->symbol_names_data, sd->symbol_names->data(),
306             sd->symbol_names_size);
307     }
308   else
309     {
310       gc_sd->symbol_names_data = NULL;
311     }
312   gc_sd->symbol_names_size = sd->symbol_names_size;
313 }
314
315 // This function determines if a particular section name must be included
316 // in the link.  This is used during garbage collection to determine the
317 // roots of the worklist.
318
319 bool
320 Relobj::is_section_name_included(const char* name)
321 {
322   if (is_prefix_of(".ctors", name)
323       || is_prefix_of(".dtors", name)
324       || is_prefix_of(".note", name)
325       || is_prefix_of(".init", name)
326       || is_prefix_of(".fini", name)
327       || is_prefix_of(".gcc_except_table", name)
328       || is_prefix_of(".jcr", name)
329       || is_prefix_of(".preinit_array", name)
330       || (is_prefix_of(".text", name)
331           && strstr(name, "personality"))
332       || (is_prefix_of(".data", name)
333           &&  strstr(name, "personality"))
334       || (is_prefix_of(".gnu.linkonce.d", name)
335           && strstr(name, "personality")))
336     {
337       return true;
338     }
339   return false;
340 }
341
342 // Finalize the incremental relocation information.  Allocates a block
343 // of relocation entries for each symbol, and sets the reloc_bases_
344 // array to point to the first entry in each block.  If CLEAR_COUNTS
345 // is TRUE, also clear the per-symbol relocation counters.
346
347 void
348 Relobj::finalize_incremental_relocs(Layout* layout, bool clear_counts)
349 {
350   unsigned int nsyms = this->get_global_symbols()->size();
351   this->reloc_bases_ = new unsigned int[nsyms];
352
353   gold_assert(this->reloc_bases_ != NULL);
354   gold_assert(layout->incremental_inputs() != NULL);
355
356   unsigned int rindex = layout->incremental_inputs()->get_reloc_count();
357   for (unsigned int i = 0; i < nsyms; ++i)
358     {
359       this->reloc_bases_[i] = rindex;
360       rindex += this->reloc_counts_[i];
361       if (clear_counts)
362         this->reloc_counts_[i] = 0;
363     }
364   layout->incremental_inputs()->set_reloc_count(rindex);
365 }
366
367 // Class Sized_relobj.
368
369 // Iterate over local symbols, calling a visitor class V for each GOT offset
370 // associated with a local symbol.
371
372 template<int size, bool big_endian>
373 void
374 Sized_relobj<size, big_endian>::do_for_all_local_got_entries(
375     Got_offset_list::Visitor* v) const
376 {
377   unsigned int nsyms = this->local_symbol_count();
378   for (unsigned int i = 0; i < nsyms; i++)
379     {
380       Local_got_offsets::const_iterator p = this->local_got_offsets_.find(i);
381       if (p != this->local_got_offsets_.end())
382         {
383           const Got_offset_list* got_offsets = p->second;
384           got_offsets->for_all_got_offsets(v);
385         }
386     }
387 }
388
389 // Class Sized_relobj_file.
390
391 template<int size, bool big_endian>
392 Sized_relobj_file<size, big_endian>::Sized_relobj_file(
393     const std::string& name,
394     Input_file* input_file,
395     off_t offset,
396     const elfcpp::Ehdr<size, big_endian>& ehdr)
397   : Sized_relobj<size, big_endian>(name, input_file, offset),
398     elf_file_(this, ehdr),
399     symtab_shndx_(-1U),
400     local_symbol_count_(0),
401     output_local_symbol_count_(0),
402     output_local_dynsym_count_(0),
403     symbols_(),
404     defined_count_(0),
405     local_symbol_offset_(0),
406     local_dynsym_offset_(0),
407     local_values_(),
408     local_plt_offsets_(),
409     kept_comdat_sections_(),
410     has_eh_frame_(false),
411     discarded_eh_frame_shndx_(-1U),
412     deferred_layout_(),
413     deferred_layout_relocs_(),
414     compressed_sections_()
415 {
416   this->e_type_ = ehdr.get_e_type();
417 }
418
419 template<int size, bool big_endian>
420 Sized_relobj_file<size, big_endian>::~Sized_relobj_file()
421 {
422 }
423
424 // Set up an object file based on the file header.  This sets up the
425 // section information.
426
427 template<int size, bool big_endian>
428 void
429 Sized_relobj_file<size, big_endian>::do_setup()
430 {
431   const unsigned int shnum = this->elf_file_.shnum();
432   this->set_shnum(shnum);
433 }
434
435 // Find the SHT_SYMTAB section, given the section headers.  The ELF
436 // standard says that maybe in the future there can be more than one
437 // SHT_SYMTAB section.  Until somebody figures out how that could
438 // work, we assume there is only one.
439
440 template<int size, bool big_endian>
441 void
442 Sized_relobj_file<size, big_endian>::find_symtab(const unsigned char* pshdrs)
443 {
444   const unsigned int shnum = this->shnum();
445   this->symtab_shndx_ = 0;
446   if (shnum > 0)
447     {
448       // Look through the sections in reverse order, since gas tends
449       // to put the symbol table at the end.
450       const unsigned char* p = pshdrs + shnum * This::shdr_size;
451       unsigned int i = shnum;
452       unsigned int xindex_shndx = 0;
453       unsigned int xindex_link = 0;
454       while (i > 0)
455         {
456           --i;
457           p -= This::shdr_size;
458           typename This::Shdr shdr(p);
459           if (shdr.get_sh_type() == elfcpp::SHT_SYMTAB)
460             {
461               this->symtab_shndx_ = i;
462               if (xindex_shndx > 0 && xindex_link == i)
463                 {
464                   Xindex* xindex =
465                     new Xindex(this->elf_file_.large_shndx_offset());
466                   xindex->read_symtab_xindex<size, big_endian>(this,
467                                                                xindex_shndx,
468                                                                pshdrs);
469                   this->set_xindex(xindex);
470                 }
471               break;
472             }
473
474           // Try to pick up the SHT_SYMTAB_SHNDX section, if there is
475           // one.  This will work if it follows the SHT_SYMTAB
476           // section.
477           if (shdr.get_sh_type() == elfcpp::SHT_SYMTAB_SHNDX)
478             {
479               xindex_shndx = i;
480               xindex_link = this->adjust_shndx(shdr.get_sh_link());
481             }
482         }
483     }
484 }
485
486 // Return the Xindex structure to use for object with lots of
487 // sections.
488
489 template<int size, bool big_endian>
490 Xindex*
491 Sized_relobj_file<size, big_endian>::do_initialize_xindex()
492 {
493   gold_assert(this->symtab_shndx_ != -1U);
494   Xindex* xindex = new Xindex(this->elf_file_.large_shndx_offset());
495   xindex->initialize_symtab_xindex<size, big_endian>(this, this->symtab_shndx_);
496   return xindex;
497 }
498
499 // Return whether SHDR has the right type and flags to be a GNU
500 // .eh_frame section.
501
502 template<int size, bool big_endian>
503 bool
504 Sized_relobj_file<size, big_endian>::check_eh_frame_flags(
505     const elfcpp::Shdr<size, big_endian>* shdr) const
506 {
507   elfcpp::Elf_Word sh_type = shdr->get_sh_type();
508   return ((sh_type == elfcpp::SHT_PROGBITS
509            || sh_type == elfcpp::SHT_X86_64_UNWIND)
510           && (shdr->get_sh_flags() & elfcpp::SHF_ALLOC) != 0);
511 }
512
513 // Find the section header with the given name.
514
515 template<int size, bool big_endian>
516 const unsigned char*
517 Sized_relobj_file<size, big_endian>::find_shdr(
518     const unsigned char* pshdrs,
519     const char* name,
520     const char* names,
521     section_size_type names_size,
522     const unsigned char* hdr) const
523 {
524   const unsigned int shnum = this->shnum();
525   const unsigned char* hdr_end = pshdrs + This::shdr_size * shnum;
526   size_t sh_name = 0;
527
528   while (1)
529     {
530       if (hdr)
531         {
532           // We found HDR last time we were called, continue looking.
533           typename This::Shdr shdr(hdr);
534           sh_name = shdr.get_sh_name();
535         }
536       else
537         {
538           // Look for the next occurrence of NAME in NAMES.
539           // The fact that .shstrtab produced by current GNU tools is
540           // string merged means we shouldn't have both .not.foo and
541           // .foo in .shstrtab, and multiple .foo sections should all
542           // have the same sh_name.  However, this is not guaranteed
543           // by the ELF spec and not all ELF object file producers may
544           // be so clever.
545           size_t len = strlen(name) + 1;
546           const char *p = sh_name ? names + sh_name + len : names;
547           p = reinterpret_cast<const char*>(memmem(p, names_size - (p - names),
548                                                    name, len));
549           if (p == NULL)
550             return NULL;
551           sh_name = p - names;
552           hdr = pshdrs;
553           if (sh_name == 0)
554             return hdr;
555         }
556
557       hdr += This::shdr_size;
558       while (hdr < hdr_end)
559         {
560           typename This::Shdr shdr(hdr);
561           if (shdr.get_sh_name() == sh_name)
562             return hdr;
563           hdr += This::shdr_size;
564         }
565       hdr = NULL;
566       if (sh_name == 0)
567         return hdr;
568     }
569 }
570
571 // Return whether there is a GNU .eh_frame section, given the section
572 // headers and the section names.
573
574 template<int size, bool big_endian>
575 bool
576 Sized_relobj_file<size, big_endian>::find_eh_frame(
577     const unsigned char* pshdrs,
578     const char* names,
579     section_size_type names_size) const
580 {
581   const unsigned char* s = NULL;
582
583   while (1)
584     {
585       s = this->find_shdr(pshdrs, ".eh_frame", names, names_size, s);
586       if (s == NULL)
587         return false;
588
589       typename This::Shdr shdr(s);
590       if (this->check_eh_frame_flags(&shdr))
591         return true;
592     }
593 }
594
595 // Return TRUE if this is a section whose contents will be needed in the
596 // Add_symbols task.  This function is only called for sections that have
597 // already passed the test in is_compressed_debug_section(), so we know
598 // that the section name begins with ".zdebug".
599
600 static bool
601 need_decompressed_section(const char* name)
602 {
603   // Skip over the ".zdebug" and a quick check for the "_".
604   name += 7;
605   if (*name++ != '_')
606     return false;
607
608 #ifdef ENABLE_THREADS
609   // Decompressing these sections now will help only if we're
610   // multithreaded.
611   if (parameters->options().threads())
612     {
613       // We will need .zdebug_str if this is not an incremental link
614       // (i.e., we are processing string merge sections) or if we need
615       // to build a gdb index.
616       if ((!parameters->incremental() || parameters->options().gdb_index())
617           && strcmp(name, "str") == 0)
618         return true;
619
620       // We will need these other sections when building a gdb index.
621       if (parameters->options().gdb_index()
622           && (strcmp(name, "info") == 0
623               || strcmp(name, "types") == 0
624               || strcmp(name, "pubnames") == 0
625               || strcmp(name, "pubtypes") == 0
626               || strcmp(name, "ranges") == 0
627               || strcmp(name, "abbrev") == 0))
628         return true;
629     }
630 #endif
631
632   // Even when single-threaded, we will need .zdebug_str if this is
633   // not an incremental link and we are building a gdb index.
634   // Otherwise, we would decompress the section twice: once for
635   // string merge processing, and once for building the gdb index.
636   if (!parameters->incremental()
637       && parameters->options().gdb_index()
638       && strcmp(name, "str") == 0)
639     return true;
640
641   return false;
642 }
643
644 // Build a table for any compressed debug sections, mapping each section index
645 // to the uncompressed size and (if needed) the decompressed contents.
646
647 template<int size, bool big_endian>
648 Compressed_section_map*
649 build_compressed_section_map(
650     const unsigned char* pshdrs,
651     unsigned int shnum,
652     const char* names,
653     section_size_type names_size,
654     Sized_relobj_file<size, big_endian>* obj)
655 {
656   Compressed_section_map* uncompressed_map = new Compressed_section_map();
657   const unsigned int shdr_size = elfcpp::Elf_sizes<size>::shdr_size;
658   const unsigned char* p = pshdrs + shdr_size;
659
660   for (unsigned int i = 1; i < shnum; ++i, p += shdr_size)
661     {
662       typename elfcpp::Shdr<size, big_endian> shdr(p);
663       if (shdr.get_sh_type() == elfcpp::SHT_PROGBITS
664           && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
665         {
666           if (shdr.get_sh_name() >= names_size)
667             {
668               obj->error(_("bad section name offset for section %u: %lu"),
669                          i, static_cast<unsigned long>(shdr.get_sh_name()));
670               continue;
671             }
672
673           const char* name = names + shdr.get_sh_name();
674           if (is_compressed_debug_section(name))
675             {
676               section_size_type len;
677               const unsigned char* contents =
678                   obj->section_contents(i, &len, false);
679               uint64_t uncompressed_size = get_uncompressed_size(contents, len);
680               Compressed_section_info info;
681               info.size = convert_to_section_size_type(uncompressed_size);
682               info.contents = NULL;
683               if (uncompressed_size != -1ULL)
684                 {
685                   unsigned char* uncompressed_data = NULL;
686                   if (need_decompressed_section(name))
687                     {
688                       uncompressed_data = new unsigned char[uncompressed_size];
689                       if (decompress_input_section(contents, len,
690                                                    uncompressed_data,
691                                                    uncompressed_size))
692                         info.contents = uncompressed_data;
693                       else
694                         delete[] uncompressed_data;
695                     }
696                   (*uncompressed_map)[i] = info;
697                 }
698             }
699         }
700     }
701   return uncompressed_map;
702 }
703
704 // Stash away info for a number of special sections.
705 // Return true if any of the sections found require local symbols to be read.
706
707 template<int size, bool big_endian>
708 bool
709 Sized_relobj_file<size, big_endian>::do_find_special_sections(
710     Read_symbols_data* sd)
711 {
712   const unsigned char* const pshdrs = sd->section_headers->data();
713   const unsigned char* namesu = sd->section_names->data();
714   const char* names = reinterpret_cast<const char*>(namesu);
715
716   if (this->find_eh_frame(pshdrs, names, sd->section_names_size))
717     this->has_eh_frame_ = true;
718
719   if (memmem(names, sd->section_names_size, ".zdebug_", 8) != NULL)
720     this->compressed_sections_
721       = build_compressed_section_map(pshdrs, this->shnum(), names,
722                                      sd->section_names_size, this);
723   return (this->has_eh_frame_
724           || (!parameters->options().relocatable()
725               && parameters->options().gdb_index()
726               && (memmem(names, sd->section_names_size, "debug_info", 12) == 0
727                   || memmem(names, sd->section_names_size, "debug_types",
728                             13) == 0)));
729 }
730
731 // Read the sections and symbols from an object file.
732
733 template<int size, bool big_endian>
734 void
735 Sized_relobj_file<size, big_endian>::do_read_symbols(Read_symbols_data* sd)
736 {
737   this->read_section_data(&this->elf_file_, sd);
738
739   const unsigned char* const pshdrs = sd->section_headers->data();
740
741   this->find_symtab(pshdrs);
742
743   bool need_local_symbols = this->do_find_special_sections(sd);
744
745   sd->symbols = NULL;
746   sd->symbols_size = 0;
747   sd->external_symbols_offset = 0;
748   sd->symbol_names = NULL;
749   sd->symbol_names_size = 0;
750
751   if (this->symtab_shndx_ == 0)
752     {
753       // No symbol table.  Weird but legal.
754       return;
755     }
756
757   // Get the symbol table section header.
758   typename This::Shdr symtabshdr(pshdrs
759                                  + this->symtab_shndx_ * This::shdr_size);
760   gold_assert(symtabshdr.get_sh_type() == elfcpp::SHT_SYMTAB);
761
762   // If this object has a .eh_frame section, or if building a .gdb_index
763   // section and there is debug info, we need all the symbols.
764   // Otherwise we only need the external symbols.  While it would be
765   // simpler to just always read all the symbols, I've seen object
766   // files with well over 2000 local symbols, which for a 64-bit
767   // object file format is over 5 pages that we don't need to read
768   // now.
769
770   const int sym_size = This::sym_size;
771   const unsigned int loccount = symtabshdr.get_sh_info();
772   this->local_symbol_count_ = loccount;
773   this->local_values_.resize(loccount);
774   section_offset_type locsize = loccount * sym_size;
775   off_t dataoff = symtabshdr.get_sh_offset();
776   section_size_type datasize =
777     convert_to_section_size_type(symtabshdr.get_sh_size());
778   off_t extoff = dataoff + locsize;
779   section_size_type extsize = datasize - locsize;
780
781   off_t readoff = need_local_symbols ? dataoff : extoff;
782   section_size_type readsize = need_local_symbols ? datasize : extsize;
783
784   if (readsize == 0)
785     {
786       // No external symbols.  Also weird but also legal.
787       return;
788     }
789
790   File_view* fvsymtab = this->get_lasting_view(readoff, readsize, true, false);
791
792   // Read the section header for the symbol names.
793   unsigned int strtab_shndx = this->adjust_shndx(symtabshdr.get_sh_link());
794   if (strtab_shndx >= this->shnum())
795     {
796       this->error(_("invalid symbol table name index: %u"), strtab_shndx);
797       return;
798     }
799   typename This::Shdr strtabshdr(pshdrs + strtab_shndx * This::shdr_size);
800   if (strtabshdr.get_sh_type() != elfcpp::SHT_STRTAB)
801     {
802       this->error(_("symbol table name section has wrong type: %u"),
803                   static_cast<unsigned int>(strtabshdr.get_sh_type()));
804       return;
805     }
806
807   // Read the symbol names.
808   File_view* fvstrtab = this->get_lasting_view(strtabshdr.get_sh_offset(),
809                                                strtabshdr.get_sh_size(),
810                                                false, true);
811
812   sd->symbols = fvsymtab;
813   sd->symbols_size = readsize;
814   sd->external_symbols_offset = need_local_symbols ? locsize : 0;
815   sd->symbol_names = fvstrtab;
816   sd->symbol_names_size =
817     convert_to_section_size_type(strtabshdr.get_sh_size());
818 }
819
820 // Return the section index of symbol SYM.  Set *VALUE to its value in
821 // the object file.  Set *IS_ORDINARY if this is an ordinary section
822 // index, not a special code between SHN_LORESERVE and SHN_HIRESERVE.
823 // Note that for a symbol which is not defined in this object file,
824 // this will set *VALUE to 0 and return SHN_UNDEF; it will not return
825 // the final value of the symbol in the link.
826
827 template<int size, bool big_endian>
828 unsigned int
829 Sized_relobj_file<size, big_endian>::symbol_section_and_value(unsigned int sym,
830                                                               Address* value,
831                                                               bool* is_ordinary)
832 {
833   section_size_type symbols_size;
834   const unsigned char* symbols = this->section_contents(this->symtab_shndx_,
835                                                         &symbols_size,
836                                                         false);
837
838   const size_t count = symbols_size / This::sym_size;
839   gold_assert(sym < count);
840
841   elfcpp::Sym<size, big_endian> elfsym(symbols + sym * This::sym_size);
842   *value = elfsym.get_st_value();
843
844   return this->adjust_sym_shndx(sym, elfsym.get_st_shndx(), is_ordinary);
845 }
846
847 // Return whether to include a section group in the link.  LAYOUT is
848 // used to keep track of which section groups we have already seen.
849 // INDEX is the index of the section group and SHDR is the section
850 // header.  If we do not want to include this group, we set bits in
851 // OMIT for each section which should be discarded.
852
853 template<int size, bool big_endian>
854 bool
855 Sized_relobj_file<size, big_endian>::include_section_group(
856     Symbol_table* symtab,
857     Layout* layout,
858     unsigned int index,
859     const char* name,
860     const unsigned char* shdrs,
861     const char* section_names,
862     section_size_type section_names_size,
863     std::vector<bool>* omit)
864 {
865   // Read the section contents.
866   typename This::Shdr shdr(shdrs + index * This::shdr_size);
867   const unsigned char* pcon = this->get_view(shdr.get_sh_offset(),
868                                              shdr.get_sh_size(), true, false);
869   const elfcpp::Elf_Word* pword =
870     reinterpret_cast<const elfcpp::Elf_Word*>(pcon);
871
872   // The first word contains flags.  We only care about COMDAT section
873   // groups.  Other section groups are always included in the link
874   // just like ordinary sections.
875   elfcpp::Elf_Word flags = elfcpp::Swap<32, big_endian>::readval(pword);
876
877   // Look up the group signature, which is the name of a symbol.  ELF
878   // uses a symbol name because some group signatures are long, and
879   // the name is generally already in the symbol table, so it makes
880   // sense to put the long string just once in .strtab rather than in
881   // both .strtab and .shstrtab.
882
883   // Get the appropriate symbol table header (this will normally be
884   // the single SHT_SYMTAB section, but in principle it need not be).
885   const unsigned int link = this->adjust_shndx(shdr.get_sh_link());
886   typename This::Shdr symshdr(this, this->elf_file_.section_header(link));
887
888   // Read the symbol table entry.
889   unsigned int symndx = shdr.get_sh_info();
890   if (symndx >= symshdr.get_sh_size() / This::sym_size)
891     {
892       this->error(_("section group %u info %u out of range"),
893                   index, symndx);
894       return false;
895     }
896   off_t symoff = symshdr.get_sh_offset() + symndx * This::sym_size;
897   const unsigned char* psym = this->get_view(symoff, This::sym_size, true,
898                                              false);
899   elfcpp::Sym<size, big_endian> sym(psym);
900
901   // Read the symbol table names.
902   section_size_type symnamelen;
903   const unsigned char* psymnamesu;
904   psymnamesu = this->section_contents(this->adjust_shndx(symshdr.get_sh_link()),
905                                       &symnamelen, true);
906   const char* psymnames = reinterpret_cast<const char*>(psymnamesu);
907
908   // Get the section group signature.
909   if (sym.get_st_name() >= symnamelen)
910     {
911       this->error(_("symbol %u name offset %u out of range"),
912                   symndx, sym.get_st_name());
913       return false;
914     }
915
916   std::string signature(psymnames + sym.get_st_name());
917
918   // It seems that some versions of gas will create a section group
919   // associated with a section symbol, and then fail to give a name to
920   // the section symbol.  In such a case, use the name of the section.
921   if (signature[0] == '\0' && sym.get_st_type() == elfcpp::STT_SECTION)
922     {
923       bool is_ordinary;
924       unsigned int sym_shndx = this->adjust_sym_shndx(symndx,
925                                                       sym.get_st_shndx(),
926                                                       &is_ordinary);
927       if (!is_ordinary || sym_shndx >= this->shnum())
928         {
929           this->error(_("symbol %u invalid section index %u"),
930                       symndx, sym_shndx);
931           return false;
932         }
933       typename This::Shdr member_shdr(shdrs + sym_shndx * This::shdr_size);
934       if (member_shdr.get_sh_name() < section_names_size)
935         signature = section_names + member_shdr.get_sh_name();
936     }
937
938   // Record this section group in the layout, and see whether we've already
939   // seen one with the same signature.
940   bool include_group;
941   bool is_comdat;
942   Kept_section* kept_section = NULL;
943
944   if ((flags & elfcpp::GRP_COMDAT) == 0)
945     {
946       include_group = true;
947       is_comdat = false;
948     }
949   else
950     {
951       include_group = layout->find_or_add_kept_section(signature,
952                                                        this, index, true,
953                                                        true, &kept_section);
954       is_comdat = true;
955     }
956
957   if (is_comdat && include_group)
958     {
959       Incremental_inputs* incremental_inputs = layout->incremental_inputs();
960       if (incremental_inputs != NULL)
961         incremental_inputs->report_comdat_group(this, signature.c_str());
962     }
963
964   size_t count = shdr.get_sh_size() / sizeof(elfcpp::Elf_Word);
965
966   std::vector<unsigned int> shndxes;
967   bool relocate_group = include_group && parameters->options().relocatable();
968   if (relocate_group)
969     shndxes.reserve(count - 1);
970
971   for (size_t i = 1; i < count; ++i)
972     {
973       elfcpp::Elf_Word shndx =
974         this->adjust_shndx(elfcpp::Swap<32, big_endian>::readval(pword + i));
975
976       if (relocate_group)
977         shndxes.push_back(shndx);
978
979       if (shndx >= this->shnum())
980         {
981           this->error(_("section %u in section group %u out of range"),
982                       shndx, index);
983           continue;
984         }
985
986       // Check for an earlier section number, since we're going to get
987       // it wrong--we may have already decided to include the section.
988       if (shndx < index)
989         this->error(_("invalid section group %u refers to earlier section %u"),
990                     index, shndx);
991
992       // Get the name of the member section.
993       typename This::Shdr member_shdr(shdrs + shndx * This::shdr_size);
994       if (member_shdr.get_sh_name() >= section_names_size)
995         {
996           // This is an error, but it will be diagnosed eventually
997           // in do_layout, so we don't need to do anything here but
998           // ignore it.
999           continue;
1000         }
1001       std::string mname(section_names + member_shdr.get_sh_name());
1002
1003       if (include_group)
1004         {
1005           if (is_comdat)
1006             kept_section->add_comdat_section(mname, shndx,
1007                                              member_shdr.get_sh_size());
1008         }
1009       else
1010         {
1011           (*omit)[shndx] = true;
1012
1013           if (is_comdat)
1014             {
1015               Relobj* kept_object = kept_section->object();
1016               if (kept_section->is_comdat())
1017                 {
1018                   // Find the corresponding kept section, and store
1019                   // that info in the discarded section table.
1020                   unsigned int kept_shndx;
1021                   uint64_t kept_size;
1022                   if (kept_section->find_comdat_section(mname, &kept_shndx,
1023                                                         &kept_size))
1024                     {
1025                       // We don't keep a mapping for this section if
1026                       // it has a different size.  The mapping is only
1027                       // used for relocation processing, and we don't
1028                       // want to treat the sections as similar if the
1029                       // sizes are different.  Checking the section
1030                       // size is the approach used by the GNU linker.
1031                       if (kept_size == member_shdr.get_sh_size())
1032                         this->set_kept_comdat_section(shndx, kept_object,
1033                                                       kept_shndx);
1034                     }
1035                 }
1036               else
1037                 {
1038                   // The existing section is a linkonce section.  Add
1039                   // a mapping if there is exactly one section in the
1040                   // group (which is true when COUNT == 2) and if it
1041                   // is the same size.
1042                   if (count == 2
1043                       && (kept_section->linkonce_size()
1044                           == member_shdr.get_sh_size()))
1045                     this->set_kept_comdat_section(shndx, kept_object,
1046                                                   kept_section->shndx());
1047                 }
1048             }
1049         }
1050     }
1051
1052   if (relocate_group)
1053     layout->layout_group(symtab, this, index, name, signature.c_str(),
1054                          shdr, flags, &shndxes);
1055
1056   return include_group;
1057 }
1058
1059 // Whether to include a linkonce section in the link.  NAME is the
1060 // name of the section and SHDR is the section header.
1061
1062 // Linkonce sections are a GNU extension implemented in the original
1063 // GNU linker before section groups were defined.  The semantics are
1064 // that we only include one linkonce section with a given name.  The
1065 // name of a linkonce section is normally .gnu.linkonce.T.SYMNAME,
1066 // where T is the type of section and SYMNAME is the name of a symbol.
1067 // In an attempt to make linkonce sections interact well with section
1068 // groups, we try to identify SYMNAME and use it like a section group
1069 // signature.  We want to block section groups with that signature,
1070 // but not other linkonce sections with that signature.  We also use
1071 // the full name of the linkonce section as a normal section group
1072 // signature.
1073
1074 template<int size, bool big_endian>
1075 bool
1076 Sized_relobj_file<size, big_endian>::include_linkonce_section(
1077     Layout* layout,
1078     unsigned int index,
1079     const char* name,
1080     const elfcpp::Shdr<size, big_endian>& shdr)
1081 {
1082   typename elfcpp::Elf_types<size>::Elf_WXword sh_size = shdr.get_sh_size();
1083   // In general the symbol name we want will be the string following
1084   // the last '.'.  However, we have to handle the case of
1085   // .gnu.linkonce.t.__i686.get_pc_thunk.bx, which was generated by
1086   // some versions of gcc.  So we use a heuristic: if the name starts
1087   // with ".gnu.linkonce.t.", we use everything after that.  Otherwise
1088   // we look for the last '.'.  We can't always simply skip
1089   // ".gnu.linkonce.X", because we have to deal with cases like
1090   // ".gnu.linkonce.d.rel.ro.local".
1091   const char* const linkonce_t = ".gnu.linkonce.t.";
1092   const char* symname;
1093   if (strncmp(name, linkonce_t, strlen(linkonce_t)) == 0)
1094     symname = name + strlen(linkonce_t);
1095   else
1096     symname = strrchr(name, '.') + 1;
1097   std::string sig1(symname);
1098   std::string sig2(name);
1099   Kept_section* kept1;
1100   Kept_section* kept2;
1101   bool include1 = layout->find_or_add_kept_section(sig1, this, index, false,
1102                                                    false, &kept1);
1103   bool include2 = layout->find_or_add_kept_section(sig2, this, index, false,
1104                                                    true, &kept2);
1105
1106   if (!include2)
1107     {
1108       // We are not including this section because we already saw the
1109       // name of the section as a signature.  This normally implies
1110       // that the kept section is another linkonce section.  If it is
1111       // the same size, record it as the section which corresponds to
1112       // this one.
1113       if (kept2->object() != NULL
1114           && !kept2->is_comdat()
1115           && kept2->linkonce_size() == sh_size)
1116         this->set_kept_comdat_section(index, kept2->object(), kept2->shndx());
1117     }
1118   else if (!include1)
1119     {
1120       // The section is being discarded on the basis of its symbol
1121       // name.  This means that the corresponding kept section was
1122       // part of a comdat group, and it will be difficult to identify
1123       // the specific section within that group that corresponds to
1124       // this linkonce section.  We'll handle the simple case where
1125       // the group has only one member section.  Otherwise, it's not
1126       // worth the effort.
1127       unsigned int kept_shndx;
1128       uint64_t kept_size;
1129       if (kept1->object() != NULL
1130           && kept1->is_comdat()
1131           && kept1->find_single_comdat_section(&kept_shndx, &kept_size)
1132           && kept_size == sh_size)
1133         this->set_kept_comdat_section(index, kept1->object(), kept_shndx);
1134     }
1135   else
1136     {
1137       kept1->set_linkonce_size(sh_size);
1138       kept2->set_linkonce_size(sh_size);
1139     }
1140
1141   return include1 && include2;
1142 }
1143
1144 // Layout an input section.
1145
1146 template<int size, bool big_endian>
1147 inline void
1148 Sized_relobj_file<size, big_endian>::layout_section(
1149     Layout* layout,
1150     unsigned int shndx,
1151     const char* name,
1152     const typename This::Shdr& shdr,
1153     unsigned int reloc_shndx,
1154     unsigned int reloc_type)
1155 {
1156   off_t offset;
1157   Output_section* os = layout->layout(this, shndx, name, shdr,
1158                                           reloc_shndx, reloc_type, &offset);
1159
1160   this->output_sections()[shndx] = os;
1161   if (offset == -1)
1162     this->section_offsets()[shndx] = invalid_address;
1163   else
1164     this->section_offsets()[shndx] = convert_types<Address, off_t>(offset);
1165
1166   // If this section requires special handling, and if there are
1167   // relocs that apply to it, then we must do the special handling
1168   // before we apply the relocs.
1169   if (offset == -1 && reloc_shndx != 0)
1170     this->set_relocs_must_follow_section_writes();
1171 }
1172
1173 // Layout an input .eh_frame section.
1174
1175 template<int size, bool big_endian>
1176 void
1177 Sized_relobj_file<size, big_endian>::layout_eh_frame_section(
1178     Layout* layout,
1179     const unsigned char* symbols_data,
1180     section_size_type symbols_size,
1181     const unsigned char* symbol_names_data,
1182     section_size_type symbol_names_size,
1183     unsigned int shndx,
1184     const typename This::Shdr& shdr,
1185     unsigned int reloc_shndx,
1186     unsigned int reloc_type)
1187 {
1188   gold_assert(this->has_eh_frame_);
1189
1190   off_t offset;
1191   Output_section* os = layout->layout_eh_frame(this,
1192                                                symbols_data,
1193                                                symbols_size,
1194                                                symbol_names_data,
1195                                                symbol_names_size,
1196                                                shndx,
1197                                                shdr,
1198                                                reloc_shndx,
1199                                                reloc_type,
1200                                                &offset);
1201   this->output_sections()[shndx] = os;
1202   if (os == NULL || offset == -1)
1203     {
1204       // An object can contain at most one section holding exception
1205       // frame information.
1206       gold_assert(this->discarded_eh_frame_shndx_ == -1U);
1207       this->discarded_eh_frame_shndx_ = shndx;
1208       this->section_offsets()[shndx] = invalid_address;
1209     }
1210   else
1211     this->section_offsets()[shndx] = convert_types<Address, off_t>(offset);
1212
1213   // If this section requires special handling, and if there are
1214   // relocs that aply to it, then we must do the special handling
1215   // before we apply the relocs.
1216   if (os != NULL && offset == -1 && reloc_shndx != 0)
1217     this->set_relocs_must_follow_section_writes();
1218 }
1219
1220 // Lay out the input sections.  We walk through the sections and check
1221 // whether they should be included in the link.  If they should, we
1222 // pass them to the Layout object, which will return an output section
1223 // and an offset.
1224 // During garbage collection (--gc-sections) and identical code folding
1225 // (--icf), this function is called twice.  When it is called the first
1226 // time, it is for setting up some sections as roots to a work-list for
1227 // --gc-sections and to do comdat processing.  Actual layout happens the
1228 // second time around after all the relevant sections have been determined.
1229 // The first time, is_worklist_ready or is_icf_ready is false. It is then
1230 // set to true after the garbage collection worklist or identical code
1231 // folding is processed and the relevant sections to be kept are
1232 // determined.  Then, this function is called again to layout the sections.
1233
1234 template<int size, bool big_endian>
1235 void
1236 Sized_relobj_file<size, big_endian>::do_layout(Symbol_table* symtab,
1237                                                Layout* layout,
1238                                                Read_symbols_data* sd)
1239 {
1240   const unsigned int shnum = this->shnum();
1241   bool is_gc_pass_one = ((parameters->options().gc_sections()
1242                           && !symtab->gc()->is_worklist_ready())
1243                          || (parameters->options().icf_enabled()
1244                              && !symtab->icf()->is_icf_ready()));
1245
1246   bool is_gc_pass_two = ((parameters->options().gc_sections()
1247                           && symtab->gc()->is_worklist_ready())
1248                          || (parameters->options().icf_enabled()
1249                              && symtab->icf()->is_icf_ready()));
1250
1251   bool is_gc_or_icf = (parameters->options().gc_sections()
1252                        || parameters->options().icf_enabled());
1253
1254   // Both is_gc_pass_one and is_gc_pass_two should not be true.
1255   gold_assert(!(is_gc_pass_one  && is_gc_pass_two));
1256
1257   if (shnum == 0)
1258     return;
1259   Symbols_data* gc_sd = NULL;
1260   if (is_gc_pass_one)
1261     {
1262       // During garbage collection save the symbols data to use it when
1263       // re-entering this function.
1264       gc_sd = new Symbols_data;
1265       this->copy_symbols_data(gc_sd, sd, This::shdr_size * shnum);
1266       this->set_symbols_data(gc_sd);
1267     }
1268   else if (is_gc_pass_two)
1269     {
1270       gc_sd = this->get_symbols_data();
1271     }
1272
1273   const unsigned char* section_headers_data = NULL;
1274   section_size_type section_names_size;
1275   const unsigned char* symbols_data = NULL;
1276   section_size_type symbols_size;
1277   const unsigned char* symbol_names_data = NULL;
1278   section_size_type symbol_names_size;
1279
1280   if (is_gc_or_icf)
1281     {
1282       section_headers_data = gc_sd->section_headers_data;
1283       section_names_size = gc_sd->section_names_size;
1284       symbols_data = gc_sd->symbols_data;
1285       symbols_size = gc_sd->symbols_size;
1286       symbol_names_data = gc_sd->symbol_names_data;
1287       symbol_names_size = gc_sd->symbol_names_size;
1288     }
1289   else
1290     {
1291       section_headers_data = sd->section_headers->data();
1292       section_names_size = sd->section_names_size;
1293       if (sd->symbols != NULL)
1294         symbols_data = sd->symbols->data();
1295       symbols_size = sd->symbols_size;
1296       if (sd->symbol_names != NULL)
1297         symbol_names_data = sd->symbol_names->data();
1298       symbol_names_size = sd->symbol_names_size;
1299     }
1300
1301   // Get the section headers.
1302   const unsigned char* shdrs = section_headers_data;
1303   const unsigned char* pshdrs;
1304
1305   // Get the section names.
1306   const unsigned char* pnamesu = (is_gc_or_icf)
1307                                  ? gc_sd->section_names_data
1308                                  : sd->section_names->data();
1309
1310   const char* pnames = reinterpret_cast<const char*>(pnamesu);
1311
1312   // If any input files have been claimed by plugins, we need to defer
1313   // actual layout until the replacement files have arrived.
1314   const bool should_defer_layout =
1315       (parameters->options().has_plugins()
1316        && parameters->options().plugins()->should_defer_layout());
1317   unsigned int num_sections_to_defer = 0;
1318
1319   // For each section, record the index of the reloc section if any.
1320   // Use 0 to mean that there is no reloc section, -1U to mean that
1321   // there is more than one.
1322   std::vector<unsigned int> reloc_shndx(shnum, 0);
1323   std::vector<unsigned int> reloc_type(shnum, elfcpp::SHT_NULL);
1324   // Skip the first, dummy, section.
1325   pshdrs = shdrs + This::shdr_size;
1326   for (unsigned int i = 1; i < shnum; ++i, pshdrs += This::shdr_size)
1327     {
1328       typename This::Shdr shdr(pshdrs);
1329
1330       // Count the number of sections whose layout will be deferred.
1331       if (should_defer_layout && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC))
1332         ++num_sections_to_defer;
1333
1334       unsigned int sh_type = shdr.get_sh_type();
1335       if (sh_type == elfcpp::SHT_REL || sh_type == elfcpp::SHT_RELA)
1336         {
1337           unsigned int target_shndx = this->adjust_shndx(shdr.get_sh_info());
1338           if (target_shndx == 0 || target_shndx >= shnum)
1339             {
1340               this->error(_("relocation section %u has bad info %u"),
1341                           i, target_shndx);
1342               continue;
1343             }
1344
1345           if (reloc_shndx[target_shndx] != 0)
1346             reloc_shndx[target_shndx] = -1U;
1347           else
1348             {
1349               reloc_shndx[target_shndx] = i;
1350               reloc_type[target_shndx] = sh_type;
1351             }
1352         }
1353     }
1354
1355   Output_sections& out_sections(this->output_sections());
1356   std::vector<Address>& out_section_offsets(this->section_offsets());
1357
1358   if (!is_gc_pass_two)
1359     {
1360       out_sections.resize(shnum);
1361       out_section_offsets.resize(shnum);
1362     }
1363
1364   // If we are only linking for symbols, then there is nothing else to
1365   // do here.
1366   if (this->input_file()->just_symbols())
1367     {
1368       if (!is_gc_pass_two)
1369         {
1370           delete sd->section_headers;
1371           sd->section_headers = NULL;
1372           delete sd->section_names;
1373           sd->section_names = NULL;
1374         }
1375       return;
1376     }
1377
1378   if (num_sections_to_defer > 0)
1379     {
1380       parameters->options().plugins()->add_deferred_layout_object(this);
1381       this->deferred_layout_.reserve(num_sections_to_defer);
1382     }
1383
1384   // Whether we've seen a .note.GNU-stack section.
1385   bool seen_gnu_stack = false;
1386   // The flags of a .note.GNU-stack section.
1387   uint64_t gnu_stack_flags = 0;
1388
1389   // Keep track of which sections to omit.
1390   std::vector<bool> omit(shnum, false);
1391
1392   // Keep track of reloc sections when emitting relocations.
1393   const bool relocatable = parameters->options().relocatable();
1394   const bool emit_relocs = (relocatable
1395                             || parameters->options().emit_relocs());
1396   std::vector<unsigned int> reloc_sections;
1397
1398   // Keep track of .eh_frame sections.
1399   std::vector<unsigned int> eh_frame_sections;
1400
1401   // Keep track of .debug_info and .debug_types sections.
1402   std::vector<unsigned int> debug_info_sections;
1403   std::vector<unsigned int> debug_types_sections;
1404
1405   // Skip the first, dummy, section.
1406   pshdrs = shdrs + This::shdr_size;
1407   for (unsigned int i = 1; i < shnum; ++i, pshdrs += This::shdr_size)
1408     {
1409       typename This::Shdr shdr(pshdrs);
1410
1411       if (shdr.get_sh_name() >= section_names_size)
1412         {
1413           this->error(_("bad section name offset for section %u: %lu"),
1414                       i, static_cast<unsigned long>(shdr.get_sh_name()));
1415           return;
1416         }
1417
1418       const char* name = pnames + shdr.get_sh_name();
1419
1420       if (!is_gc_pass_two)
1421         {
1422           if (this->handle_gnu_warning_section(name, i, symtab))
1423             {
1424               if (!relocatable && !parameters->options().shared())
1425                 omit[i] = true;
1426             }
1427
1428           // The .note.GNU-stack section is special.  It gives the
1429           // protection flags that this object file requires for the stack
1430           // in memory.
1431           if (strcmp(name, ".note.GNU-stack") == 0)
1432             {
1433               seen_gnu_stack = true;
1434               gnu_stack_flags |= shdr.get_sh_flags();
1435               omit[i] = true;
1436             }
1437
1438           // The .note.GNU-split-stack section is also special.  It
1439           // indicates that the object was compiled with
1440           // -fsplit-stack.
1441           if (this->handle_split_stack_section(name))
1442             {
1443               if (!relocatable && !parameters->options().shared())
1444                 omit[i] = true;
1445             }
1446
1447           // Skip attributes section.
1448           if (parameters->target().is_attributes_section(name))
1449             {
1450               omit[i] = true;
1451             }
1452
1453           bool discard = omit[i];
1454           if (!discard)
1455             {
1456               if (shdr.get_sh_type() == elfcpp::SHT_GROUP)
1457                 {
1458                   if (!this->include_section_group(symtab, layout, i, name,
1459                                                    shdrs, pnames,
1460                                                    section_names_size,
1461                                                    &omit))
1462                     discard = true;
1463                 }
1464               else if ((shdr.get_sh_flags() & elfcpp::SHF_GROUP) == 0
1465                        && Layout::is_linkonce(name))
1466                 {
1467                   if (!this->include_linkonce_section(layout, i, name, shdr))
1468                     discard = true;
1469                 }
1470             }
1471
1472           // Add the section to the incremental inputs layout.
1473           Incremental_inputs* incremental_inputs = layout->incremental_inputs();
1474           if (incremental_inputs != NULL
1475               && !discard
1476               && can_incremental_update(shdr.get_sh_type()))
1477             {
1478               off_t sh_size = shdr.get_sh_size();
1479               section_size_type uncompressed_size;
1480               if (this->section_is_compressed(i, &uncompressed_size))
1481                 sh_size = uncompressed_size;
1482               incremental_inputs->report_input_section(this, i, name, sh_size);
1483             }
1484
1485           if (discard)
1486             {
1487               // Do not include this section in the link.
1488               out_sections[i] = NULL;
1489               out_section_offsets[i] = invalid_address;
1490               continue;
1491             }
1492         }
1493
1494       if (is_gc_pass_one && parameters->options().gc_sections())
1495         {
1496           if (this->is_section_name_included(name)
1497               || shdr.get_sh_type() == elfcpp::SHT_INIT_ARRAY
1498               || shdr.get_sh_type() == elfcpp::SHT_FINI_ARRAY)
1499             {
1500               symtab->gc()->worklist().push(Section_id(this, i));
1501             }
1502           // If the section name XXX can be represented as a C identifier
1503           // it cannot be discarded if there are references to
1504           // __start_XXX and __stop_XXX symbols.  These need to be
1505           // specially handled.
1506           if (is_cident(name))
1507             {
1508               symtab->gc()->add_cident_section(name, Section_id(this, i));
1509             }
1510         }
1511
1512       // When doing a relocatable link we are going to copy input
1513       // reloc sections into the output.  We only want to copy the
1514       // ones associated with sections which are not being discarded.
1515       // However, we don't know that yet for all sections.  So save
1516       // reloc sections and process them later. Garbage collection is
1517       // not triggered when relocatable code is desired.
1518       if (emit_relocs
1519           && (shdr.get_sh_type() == elfcpp::SHT_REL
1520               || shdr.get_sh_type() == elfcpp::SHT_RELA))
1521         {
1522           reloc_sections.push_back(i);
1523           continue;
1524         }
1525
1526       if (relocatable && shdr.get_sh_type() == elfcpp::SHT_GROUP)
1527         continue;
1528
1529       // The .eh_frame section is special.  It holds exception frame
1530       // information that we need to read in order to generate the
1531       // exception frame header.  We process these after all the other
1532       // sections so that the exception frame reader can reliably
1533       // determine which sections are being discarded, and discard the
1534       // corresponding information.
1535       if (!relocatable
1536           && strcmp(name, ".eh_frame") == 0
1537           && this->check_eh_frame_flags(&shdr))
1538         {
1539           if (is_gc_pass_one)
1540             {
1541               out_sections[i] = reinterpret_cast<Output_section*>(1);
1542               out_section_offsets[i] = invalid_address;
1543             }
1544           else if (should_defer_layout)
1545             this->deferred_layout_.push_back(Deferred_layout(i, name,
1546                                                              pshdrs,
1547                                                              reloc_shndx[i],
1548                                                              reloc_type[i]));
1549           else
1550             eh_frame_sections.push_back(i);
1551           continue;
1552         }
1553
1554       if (is_gc_pass_two && parameters->options().gc_sections())
1555         {
1556           // This is executed during the second pass of garbage
1557           // collection. do_layout has been called before and some
1558           // sections have been already discarded. Simply ignore
1559           // such sections this time around.
1560           if (out_sections[i] == NULL)
1561             {
1562               gold_assert(out_section_offsets[i] == invalid_address);
1563               continue;
1564             }
1565           if (((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0)
1566               && symtab->gc()->is_section_garbage(this, i))
1567               {
1568                 if (parameters->options().print_gc_sections())
1569                   gold_info(_("%s: removing unused section from '%s'"
1570                               " in file '%s'"),
1571                             program_name, this->section_name(i).c_str(),
1572                             this->name().c_str());
1573                 out_sections[i] = NULL;
1574                 out_section_offsets[i] = invalid_address;
1575                 continue;
1576               }
1577         }
1578
1579       if (is_gc_pass_two && parameters->options().icf_enabled())
1580         {
1581           if (out_sections[i] == NULL)
1582             {
1583               gold_assert(out_section_offsets[i] == invalid_address);
1584               continue;
1585             }
1586           if (((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0)
1587               && symtab->icf()->is_section_folded(this, i))
1588               {
1589                 if (parameters->options().print_icf_sections())
1590                   {
1591                     Section_id folded =
1592                                 symtab->icf()->get_folded_section(this, i);
1593                     Relobj* folded_obj =
1594                                 reinterpret_cast<Relobj*>(folded.first);
1595                     gold_info(_("%s: ICF folding section '%s' in file '%s'"
1596                                 "into '%s' in file '%s'"),
1597                               program_name, this->section_name(i).c_str(),
1598                               this->name().c_str(),
1599                               folded_obj->section_name(folded.second).c_str(),
1600                               folded_obj->name().c_str());
1601                   }
1602                 out_sections[i] = NULL;
1603                 out_section_offsets[i] = invalid_address;
1604                 continue;
1605               }
1606         }
1607
1608       // Defer layout here if input files are claimed by plugins.  When gc
1609       // is turned on this function is called twice.  For the second call
1610       // should_defer_layout should be false.
1611       if (should_defer_layout && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC))
1612         {
1613           gold_assert(!is_gc_pass_two);
1614           this->deferred_layout_.push_back(Deferred_layout(i, name,
1615                                                            pshdrs,
1616                                                            reloc_shndx[i],
1617                                                            reloc_type[i]));
1618           // Put dummy values here; real values will be supplied by
1619           // do_layout_deferred_sections.
1620           out_sections[i] = reinterpret_cast<Output_section*>(2);
1621           out_section_offsets[i] = invalid_address;
1622           continue;
1623         }
1624
1625       // During gc_pass_two if a section that was previously deferred is
1626       // found, do not layout the section as layout_deferred_sections will
1627       // do it later from gold.cc.
1628       if (is_gc_pass_two
1629           && (out_sections[i] == reinterpret_cast<Output_section*>(2)))
1630         continue;
1631
1632       if (is_gc_pass_one)
1633         {
1634           // This is during garbage collection. The out_sections are
1635           // assigned in the second call to this function.
1636           out_sections[i] = reinterpret_cast<Output_section*>(1);
1637           out_section_offsets[i] = invalid_address;
1638         }
1639       else
1640         {
1641           // When garbage collection is switched on the actual layout
1642           // only happens in the second call.
1643           this->layout_section(layout, i, name, shdr, reloc_shndx[i],
1644                                reloc_type[i]);
1645
1646           // When generating a .gdb_index section, we do additional
1647           // processing of .debug_info and .debug_types sections after all
1648           // the other sections for the same reason as above.
1649           if (!relocatable
1650               && parameters->options().gdb_index()
1651               && !(shdr.get_sh_flags() & elfcpp::SHF_ALLOC))
1652             {
1653               if (strcmp(name, ".debug_info") == 0
1654                   || strcmp(name, ".zdebug_info") == 0)
1655                 debug_info_sections.push_back(i);
1656               else if (strcmp(name, ".debug_types") == 0
1657                        || strcmp(name, ".zdebug_types") == 0)
1658                 debug_types_sections.push_back(i);
1659             }
1660         }
1661     }
1662
1663   if (!is_gc_pass_two)
1664     layout->layout_gnu_stack(seen_gnu_stack, gnu_stack_flags, this);
1665
1666   // When doing a relocatable link handle the reloc sections at the
1667   // end.  Garbage collection  and Identical Code Folding is not
1668   // turned on for relocatable code.
1669   if (emit_relocs)
1670     this->size_relocatable_relocs();
1671
1672   gold_assert(!(is_gc_or_icf) || reloc_sections.empty());
1673
1674   for (std::vector<unsigned int>::const_iterator p = reloc_sections.begin();
1675        p != reloc_sections.end();
1676        ++p)
1677     {
1678       unsigned int i = *p;
1679       const unsigned char* pshdr;
1680       pshdr = section_headers_data + i * This::shdr_size;
1681       typename This::Shdr shdr(pshdr);
1682
1683       unsigned int data_shndx = this->adjust_shndx(shdr.get_sh_info());
1684       if (data_shndx >= shnum)
1685         {
1686           // We already warned about this above.
1687           continue;
1688         }
1689
1690       Output_section* data_section = out_sections[data_shndx];
1691       if (data_section == reinterpret_cast<Output_section*>(2))
1692         {
1693           // The layout for the data section was deferred, so we need
1694           // to defer the relocation section, too.
1695           const char* name = pnames + shdr.get_sh_name();
1696           this->deferred_layout_relocs_.push_back(
1697               Deferred_layout(i, name, pshdr, 0, elfcpp::SHT_NULL));
1698           out_sections[i] = reinterpret_cast<Output_section*>(2);
1699           out_section_offsets[i] = invalid_address;
1700           continue;
1701         }
1702       if (data_section == NULL)
1703         {
1704           out_sections[i] = NULL;
1705           out_section_offsets[i] = invalid_address;
1706           continue;
1707         }
1708
1709       Relocatable_relocs* rr = new Relocatable_relocs();
1710       this->set_relocatable_relocs(i, rr);
1711
1712       Output_section* os = layout->layout_reloc(this, i, shdr, data_section,
1713                                                 rr);
1714       out_sections[i] = os;
1715       out_section_offsets[i] = invalid_address;
1716     }
1717
1718   // Handle the .eh_frame sections at the end.
1719   gold_assert(!is_gc_pass_one || eh_frame_sections.empty());
1720   for (std::vector<unsigned int>::const_iterator p = eh_frame_sections.begin();
1721        p != eh_frame_sections.end();
1722        ++p)
1723     {
1724       unsigned int i = *p;
1725       const unsigned char* pshdr;
1726       pshdr = section_headers_data + i * This::shdr_size;
1727       typename This::Shdr shdr(pshdr);
1728
1729       this->layout_eh_frame_section(layout,
1730                                     symbols_data,
1731                                     symbols_size,
1732                                     symbol_names_data,
1733                                     symbol_names_size,
1734                                     i,
1735                                     shdr,
1736                                     reloc_shndx[i],
1737                                     reloc_type[i]);
1738     }
1739
1740   // When building a .gdb_index section, scan the .debug_info and
1741   // .debug_types sections.
1742   gold_assert(!is_gc_pass_one
1743               || (debug_info_sections.empty() && debug_types_sections.empty()));
1744   for (std::vector<unsigned int>::const_iterator p
1745            = debug_info_sections.begin();
1746        p != debug_info_sections.end();
1747        ++p)
1748     {
1749       unsigned int i = *p;
1750       layout->add_to_gdb_index(false, this, symbols_data, symbols_size,
1751                                i, reloc_shndx[i], reloc_type[i]);
1752     }
1753   for (std::vector<unsigned int>::const_iterator p
1754            = debug_types_sections.begin();
1755        p != debug_types_sections.end();
1756        ++p)
1757     {
1758       unsigned int i = *p;
1759       layout->add_to_gdb_index(true, this, symbols_data, symbols_size,
1760                                i, reloc_shndx[i], reloc_type[i]);
1761     }
1762
1763   if (is_gc_pass_two)
1764     {
1765       delete[] gc_sd->section_headers_data;
1766       delete[] gc_sd->section_names_data;
1767       delete[] gc_sd->symbols_data;
1768       delete[] gc_sd->symbol_names_data;
1769       this->set_symbols_data(NULL);
1770     }
1771   else
1772     {
1773       delete sd->section_headers;
1774       sd->section_headers = NULL;
1775       delete sd->section_names;
1776       sd->section_names = NULL;
1777     }
1778 }
1779
1780 // Layout sections whose layout was deferred while waiting for
1781 // input files from a plugin.
1782
1783 template<int size, bool big_endian>
1784 void
1785 Sized_relobj_file<size, big_endian>::do_layout_deferred_sections(Layout* layout)
1786 {
1787   typename std::vector<Deferred_layout>::iterator deferred;
1788
1789   for (deferred = this->deferred_layout_.begin();
1790        deferred != this->deferred_layout_.end();
1791        ++deferred)
1792     {
1793       typename This::Shdr shdr(deferred->shdr_data_);
1794       // If the section is not included, it is because the garbage collector
1795       // decided it is not needed.  Avoid reverting that decision.
1796       if (!this->is_section_included(deferred->shndx_))
1797         continue;
1798
1799       if (parameters->options().relocatable()
1800           || deferred->name_ != ".eh_frame"
1801           || !this->check_eh_frame_flags(&shdr))
1802         this->layout_section(layout, deferred->shndx_, deferred->name_.c_str(),
1803                              shdr, deferred->reloc_shndx_,
1804                              deferred->reloc_type_);
1805       else
1806         {
1807           // Reading the symbols again here may be slow.
1808           Read_symbols_data sd;
1809           this->read_symbols(&sd);
1810           this->layout_eh_frame_section(layout,
1811                                         sd.symbols->data(),
1812                                         sd.symbols_size,
1813                                         sd.symbol_names->data(),
1814                                         sd.symbol_names_size,
1815                                         deferred->shndx_,
1816                                         shdr,
1817                                         deferred->reloc_shndx_,
1818                                         deferred->reloc_type_);
1819         }
1820     }
1821
1822   this->deferred_layout_.clear();
1823
1824   // Now handle the deferred relocation sections.
1825
1826   Output_sections& out_sections(this->output_sections());
1827   std::vector<Address>& out_section_offsets(this->section_offsets());
1828
1829   for (deferred = this->deferred_layout_relocs_.begin();
1830        deferred != this->deferred_layout_relocs_.end();
1831        ++deferred)
1832     {
1833       unsigned int shndx = deferred->shndx_;
1834       typename This::Shdr shdr(deferred->shdr_data_);
1835       unsigned int data_shndx = this->adjust_shndx(shdr.get_sh_info());
1836
1837       Output_section* data_section = out_sections[data_shndx];
1838       if (data_section == NULL)
1839         {
1840           out_sections[shndx] = NULL;
1841           out_section_offsets[shndx] = invalid_address;
1842           continue;
1843         }
1844
1845       Relocatable_relocs* rr = new Relocatable_relocs();
1846       this->set_relocatable_relocs(shndx, rr);
1847
1848       Output_section* os = layout->layout_reloc(this, shndx, shdr,
1849                                                 data_section, rr);
1850       out_sections[shndx] = os;
1851       out_section_offsets[shndx] = invalid_address;
1852     }
1853 }
1854
1855 // Add the symbols to the symbol table.
1856
1857 template<int size, bool big_endian>
1858 void
1859 Sized_relobj_file<size, big_endian>::do_add_symbols(Symbol_table* symtab,
1860                                                     Read_symbols_data* sd,
1861                                                     Layout*)
1862 {
1863   if (sd->symbols == NULL)
1864     {
1865       gold_assert(sd->symbol_names == NULL);
1866       return;
1867     }
1868
1869   const int sym_size = This::sym_size;
1870   size_t symcount = ((sd->symbols_size - sd->external_symbols_offset)
1871                      / sym_size);
1872   if (symcount * sym_size != sd->symbols_size - sd->external_symbols_offset)
1873     {
1874       this->error(_("size of symbols is not multiple of symbol size"));
1875       return;
1876     }
1877
1878   this->symbols_.resize(symcount);
1879
1880   const char* sym_names =
1881     reinterpret_cast<const char*>(sd->symbol_names->data());
1882   symtab->add_from_relobj(this,
1883                           sd->symbols->data() + sd->external_symbols_offset,
1884                           symcount, this->local_symbol_count_,
1885                           sym_names, sd->symbol_names_size,
1886                           &this->symbols_,
1887                           &this->defined_count_);
1888
1889   delete sd->symbols;
1890   sd->symbols = NULL;
1891   delete sd->symbol_names;
1892   sd->symbol_names = NULL;
1893 }
1894
1895 // Find out if this object, that is a member of a lib group, should be included
1896 // in the link. We check every symbol defined by this object. If the symbol
1897 // table has a strong undefined reference to that symbol, we have to include
1898 // the object.
1899
1900 template<int size, bool big_endian>
1901 Archive::Should_include
1902 Sized_relobj_file<size, big_endian>::do_should_include_member(
1903     Symbol_table* symtab,
1904     Layout* layout,
1905     Read_symbols_data* sd,
1906     std::string* why)
1907 {
1908   char* tmpbuf = NULL;
1909   size_t tmpbuflen = 0;
1910   const char* sym_names =
1911       reinterpret_cast<const char*>(sd->symbol_names->data());
1912   const unsigned char* syms =
1913       sd->symbols->data() + sd->external_symbols_offset;
1914   const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
1915   size_t symcount = ((sd->symbols_size - sd->external_symbols_offset)
1916                          / sym_size);
1917
1918   const unsigned char* p = syms;
1919
1920   for (size_t i = 0; i < symcount; ++i, p += sym_size)
1921     {
1922       elfcpp::Sym<size, big_endian> sym(p);
1923       unsigned int st_shndx = sym.get_st_shndx();
1924       if (st_shndx == elfcpp::SHN_UNDEF)
1925         continue;
1926
1927       unsigned int st_name = sym.get_st_name();
1928       const char* name = sym_names + st_name;
1929       Symbol* symbol;
1930       Archive::Should_include t = Archive::should_include_member(symtab,
1931                                                                  layout,
1932                                                                  name,
1933                                                                  &symbol, why,
1934                                                                  &tmpbuf,
1935                                                                  &tmpbuflen);
1936       if (t == Archive::SHOULD_INCLUDE_YES)
1937         {
1938           if (tmpbuf != NULL)
1939             free(tmpbuf);
1940           return t;
1941         }
1942     }
1943   if (tmpbuf != NULL)
1944     free(tmpbuf);
1945   return Archive::SHOULD_INCLUDE_UNKNOWN;
1946 }
1947
1948 // Iterate over global defined symbols, calling a visitor class V for each.
1949
1950 template<int size, bool big_endian>
1951 void
1952 Sized_relobj_file<size, big_endian>::do_for_all_global_symbols(
1953     Read_symbols_data* sd,
1954     Library_base::Symbol_visitor_base* v)
1955 {
1956   const char* sym_names =
1957       reinterpret_cast<const char*>(sd->symbol_names->data());
1958   const unsigned char* syms =
1959       sd->symbols->data() + sd->external_symbols_offset;
1960   const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
1961   size_t symcount = ((sd->symbols_size - sd->external_symbols_offset)
1962                      / sym_size);
1963   const unsigned char* p = syms;
1964
1965   for (size_t i = 0; i < symcount; ++i, p += sym_size)
1966     {
1967       elfcpp::Sym<size, big_endian> sym(p);
1968       if (sym.get_st_shndx() != elfcpp::SHN_UNDEF)
1969         v->visit(sym_names + sym.get_st_name());
1970     }
1971 }
1972
1973 // Return whether the local symbol SYMNDX has a PLT offset.
1974
1975 template<int size, bool big_endian>
1976 bool
1977 Sized_relobj_file<size, big_endian>::local_has_plt_offset(
1978     unsigned int symndx) const
1979 {
1980   typename Local_plt_offsets::const_iterator p =
1981     this->local_plt_offsets_.find(symndx);
1982   return p != this->local_plt_offsets_.end();
1983 }
1984
1985 // Get the PLT offset of a local symbol.
1986
1987 template<int size, bool big_endian>
1988 unsigned int
1989 Sized_relobj_file<size, big_endian>::do_local_plt_offset(
1990     unsigned int symndx) const
1991 {
1992   typename Local_plt_offsets::const_iterator p =
1993     this->local_plt_offsets_.find(symndx);
1994   gold_assert(p != this->local_plt_offsets_.end());
1995   return p->second;
1996 }
1997
1998 // Set the PLT offset of a local symbol.
1999
2000 template<int size, bool big_endian>
2001 void
2002 Sized_relobj_file<size, big_endian>::set_local_plt_offset(
2003     unsigned int symndx, unsigned int plt_offset)
2004 {
2005   std::pair<typename Local_plt_offsets::iterator, bool> ins =
2006     this->local_plt_offsets_.insert(std::make_pair(symndx, plt_offset));
2007   gold_assert(ins.second);
2008 }
2009
2010 // First pass over the local symbols.  Here we add their names to
2011 // *POOL and *DYNPOOL, and we store the symbol value in
2012 // THIS->LOCAL_VALUES_.  This function is always called from a
2013 // singleton thread.  This is followed by a call to
2014 // finalize_local_symbols.
2015
2016 template<int size, bool big_endian>
2017 void
2018 Sized_relobj_file<size, big_endian>::do_count_local_symbols(Stringpool* pool,
2019                                                             Stringpool* dynpool)
2020 {
2021   gold_assert(this->symtab_shndx_ != -1U);
2022   if (this->symtab_shndx_ == 0)
2023     {
2024       // This object has no symbols.  Weird but legal.
2025       return;
2026     }
2027
2028   // Read the symbol table section header.
2029   const unsigned int symtab_shndx = this->symtab_shndx_;
2030   typename This::Shdr symtabshdr(this,
2031                                  this->elf_file_.section_header(symtab_shndx));
2032   gold_assert(symtabshdr.get_sh_type() == elfcpp::SHT_SYMTAB);
2033
2034   // Read the local symbols.
2035   const int sym_size = This::sym_size;
2036   const unsigned int loccount = this->local_symbol_count_;
2037   gold_assert(loccount == symtabshdr.get_sh_info());
2038   off_t locsize = loccount * sym_size;
2039   const unsigned char* psyms = this->get_view(symtabshdr.get_sh_offset(),
2040                                               locsize, true, true);
2041
2042   // Read the symbol names.
2043   const unsigned int strtab_shndx =
2044     this->adjust_shndx(symtabshdr.get_sh_link());
2045   section_size_type strtab_size;
2046   const unsigned char* pnamesu = this->section_contents(strtab_shndx,
2047                                                         &strtab_size,
2048                                                         true);
2049   const char* pnames = reinterpret_cast<const char*>(pnamesu);
2050
2051   // Loop over the local symbols.
2052
2053   const Output_sections& out_sections(this->output_sections());
2054   unsigned int shnum = this->shnum();
2055   unsigned int count = 0;
2056   unsigned int dyncount = 0;
2057   // Skip the first, dummy, symbol.
2058   psyms += sym_size;
2059   bool strip_all = parameters->options().strip_all();
2060   bool discard_all = parameters->options().discard_all();
2061   bool discard_locals = parameters->options().discard_locals();
2062   for (unsigned int i = 1; i < loccount; ++i, psyms += sym_size)
2063     {
2064       elfcpp::Sym<size, big_endian> sym(psyms);
2065
2066       Symbol_value<size>& lv(this->local_values_[i]);
2067
2068       bool is_ordinary;
2069       unsigned int shndx = this->adjust_sym_shndx(i, sym.get_st_shndx(),
2070                                                   &is_ordinary);
2071       lv.set_input_shndx(shndx, is_ordinary);
2072
2073       if (sym.get_st_type() == elfcpp::STT_SECTION)
2074         lv.set_is_section_symbol();
2075       else if (sym.get_st_type() == elfcpp::STT_TLS)
2076         lv.set_is_tls_symbol();
2077       else if (sym.get_st_type() == elfcpp::STT_GNU_IFUNC)
2078         lv.set_is_ifunc_symbol();
2079
2080       // Save the input symbol value for use in do_finalize_local_symbols().
2081       lv.set_input_value(sym.get_st_value());
2082
2083       // Decide whether this symbol should go into the output file.
2084
2085       if ((shndx < shnum && out_sections[shndx] == NULL)
2086           || shndx == this->discarded_eh_frame_shndx_)
2087         {
2088           lv.set_no_output_symtab_entry();
2089           gold_assert(!lv.needs_output_dynsym_entry());
2090           continue;
2091         }
2092
2093       if (sym.get_st_type() == elfcpp::STT_SECTION)
2094         {
2095           lv.set_no_output_symtab_entry();
2096           gold_assert(!lv.needs_output_dynsym_entry());
2097           continue;
2098         }
2099
2100       if (sym.get_st_name() >= strtab_size)
2101         {
2102           this->error(_("local symbol %u section name out of range: %u >= %u"),
2103                       i, sym.get_st_name(),
2104                       static_cast<unsigned int>(strtab_size));
2105           lv.set_no_output_symtab_entry();
2106           continue;
2107         }
2108
2109       const char* name = pnames + sym.get_st_name();
2110
2111       // If needed, add the symbol to the dynamic symbol table string pool.
2112       if (lv.needs_output_dynsym_entry())
2113         {
2114           dynpool->add(name, true, NULL);
2115           ++dyncount;
2116         }
2117
2118       if (strip_all
2119           || (discard_all && lv.may_be_discarded_from_output_symtab()))
2120         {
2121           lv.set_no_output_symtab_entry();
2122           continue;
2123         }
2124
2125       // If --discard-locals option is used, discard all temporary local
2126       // symbols.  These symbols start with system-specific local label
2127       // prefixes, typically .L for ELF system.  We want to be compatible
2128       // with GNU ld so here we essentially use the same check in
2129       // bfd_is_local_label().  The code is different because we already
2130       // know that:
2131       //
2132       //   - the symbol is local and thus cannot have global or weak binding.
2133       //   - the symbol is not a section symbol.
2134       //   - the symbol has a name.
2135       //
2136       // We do not discard a symbol if it needs a dynamic symbol entry.
2137       if (discard_locals
2138           && sym.get_st_type() != elfcpp::STT_FILE
2139           && !lv.needs_output_dynsym_entry()
2140           && lv.may_be_discarded_from_output_symtab()
2141           && parameters->target().is_local_label_name(name))
2142         {
2143           lv.set_no_output_symtab_entry();
2144           continue;
2145         }
2146
2147       // Discard the local symbol if -retain_symbols_file is specified
2148       // and the local symbol is not in that file.
2149       if (!parameters->options().should_retain_symbol(name))
2150         {
2151           lv.set_no_output_symtab_entry();
2152           continue;
2153         }
2154
2155       // Add the symbol to the symbol table string pool.
2156       pool->add(name, true, NULL);
2157       ++count;
2158     }
2159
2160   this->output_local_symbol_count_ = count;
2161   this->output_local_dynsym_count_ = dyncount;
2162 }
2163
2164 // Compute the final value of a local symbol.
2165
2166 template<int size, bool big_endian>
2167 typename Sized_relobj_file<size, big_endian>::Compute_final_local_value_status
2168 Sized_relobj_file<size, big_endian>::compute_final_local_value_internal(
2169     unsigned int r_sym,
2170     const Symbol_value<size>* lv_in,
2171     Symbol_value<size>* lv_out,
2172     bool relocatable,
2173     const Output_sections& out_sections,
2174     const std::vector<Address>& out_offsets,
2175     const Symbol_table* symtab)
2176 {
2177   // We are going to overwrite *LV_OUT, if it has a merged symbol value,
2178   // we may have a memory leak.
2179   gold_assert(lv_out->has_output_value());
2180
2181   bool is_ordinary;
2182   unsigned int shndx = lv_in->input_shndx(&is_ordinary);
2183
2184   // Set the output symbol value.
2185
2186   if (!is_ordinary)
2187     {
2188       if (shndx == elfcpp::SHN_ABS || Symbol::is_common_shndx(shndx))
2189         lv_out->set_output_value(lv_in->input_value());
2190       else
2191         {
2192           this->error(_("unknown section index %u for local symbol %u"),
2193                       shndx, r_sym);
2194           lv_out->set_output_value(0);
2195           return This::CFLV_ERROR;
2196         }
2197     }
2198   else
2199     {
2200       if (shndx >= this->shnum())
2201         {
2202           this->error(_("local symbol %u section index %u out of range"),
2203                       r_sym, shndx);
2204           lv_out->set_output_value(0);
2205           return This::CFLV_ERROR;
2206         }
2207
2208       Output_section* os = out_sections[shndx];
2209       Address secoffset = out_offsets[shndx];
2210       if (symtab->is_section_folded(this, shndx))
2211         {
2212           gold_assert(os == NULL && secoffset == invalid_address);
2213           // Get the os of the section it is folded onto.
2214           Section_id folded = symtab->icf()->get_folded_section(this,
2215                                                                 shndx);
2216           gold_assert(folded.first != NULL);
2217           Sized_relobj_file<size, big_endian>* folded_obj = reinterpret_cast
2218             <Sized_relobj_file<size, big_endian>*>(folded.first);
2219           os = folded_obj->output_section(folded.second);
2220           gold_assert(os != NULL);
2221           secoffset = folded_obj->get_output_section_offset(folded.second);
2222
2223           // This could be a relaxed input section.
2224           if (secoffset == invalid_address)
2225             {
2226               const Output_relaxed_input_section* relaxed_section =
2227                 os->find_relaxed_input_section(folded_obj, folded.second);
2228               gold_assert(relaxed_section != NULL);
2229               secoffset = relaxed_section->address() - os->address();
2230             }
2231         }
2232
2233       if (os == NULL)
2234         {
2235           // This local symbol belongs to a section we are discarding.
2236           // In some cases when applying relocations later, we will
2237           // attempt to match it to the corresponding kept section,
2238           // so we leave the input value unchanged here.
2239           return This::CFLV_DISCARDED;
2240         }
2241       else if (secoffset == invalid_address)
2242         {
2243           uint64_t start;
2244
2245           // This is a SHF_MERGE section or one which otherwise
2246           // requires special handling.
2247           if (shndx == this->discarded_eh_frame_shndx_)
2248             {
2249               // This local symbol belongs to a discarded .eh_frame
2250               // section.  Just treat it like the case in which
2251               // os == NULL above.
2252               gold_assert(this->has_eh_frame_);
2253               return This::CFLV_DISCARDED;
2254             }
2255           else if (!lv_in->is_section_symbol())
2256             {
2257               // This is not a section symbol.  We can determine
2258               // the final value now.
2259               lv_out->set_output_value(
2260                   os->output_address(this, shndx, lv_in->input_value()));
2261             }
2262           else if (!os->find_starting_output_address(this, shndx, &start))
2263             {
2264               // This is a section symbol, but apparently not one in a
2265               // merged section.  First check to see if this is a relaxed
2266               // input section.  If so, use its address.  Otherwise just
2267               // use the start of the output section.  This happens with
2268               // relocatable links when the input object has section
2269               // symbols for arbitrary non-merge sections.
2270               const Output_section_data* posd =
2271                 os->find_relaxed_input_section(this, shndx);
2272               if (posd != NULL)
2273                 {
2274                   Address relocatable_link_adjustment =
2275                     relocatable ? os->address() : 0;
2276                   lv_out->set_output_value(posd->address()
2277                                            - relocatable_link_adjustment);
2278                 }
2279               else
2280                 lv_out->set_output_value(os->address());
2281             }
2282           else
2283             {
2284               // We have to consider the addend to determine the
2285               // value to use in a relocation.  START is the start
2286               // of this input section.  If we are doing a relocatable
2287               // link, use offset from start output section instead of
2288               // address.
2289               Address adjusted_start =
2290                 relocatable ? start - os->address() : start;
2291               Merged_symbol_value<size>* msv =
2292                 new Merged_symbol_value<size>(lv_in->input_value(),
2293                                               adjusted_start);
2294               lv_out->set_merged_symbol_value(msv);
2295             }
2296         }
2297       else if (lv_in->is_tls_symbol())
2298         lv_out->set_output_value(os->tls_offset()
2299                                  + secoffset
2300                                  + lv_in->input_value());
2301       else
2302         lv_out->set_output_value((relocatable ? 0 : os->address())
2303                                  + secoffset
2304                                  + lv_in->input_value());
2305     }
2306   return This::CFLV_OK;
2307 }
2308
2309 // Compute final local symbol value.  R_SYM is the index of a local
2310 // symbol in symbol table.  LV points to a symbol value, which is
2311 // expected to hold the input value and to be over-written by the
2312 // final value.  SYMTAB points to a symbol table.  Some targets may want
2313 // to know would-be-finalized local symbol values in relaxation.
2314 // Hence we provide this method.  Since this method updates *LV, a
2315 // callee should make a copy of the original local symbol value and
2316 // use the copy instead of modifying an object's local symbols before
2317 // everything is finalized.  The caller should also free up any allocated
2318 // memory in the return value in *LV.
2319 template<int size, bool big_endian>
2320 typename Sized_relobj_file<size, big_endian>::Compute_final_local_value_status
2321 Sized_relobj_file<size, big_endian>::compute_final_local_value(
2322     unsigned int r_sym,
2323     const Symbol_value<size>* lv_in,
2324     Symbol_value<size>* lv_out,
2325     const Symbol_table* symtab)
2326 {
2327   // This is just a wrapper of compute_final_local_value_internal.
2328   const bool relocatable = parameters->options().relocatable();
2329   const Output_sections& out_sections(this->output_sections());
2330   const std::vector<Address>& out_offsets(this->section_offsets());
2331   return this->compute_final_local_value_internal(r_sym, lv_in, lv_out,
2332                                                   relocatable, out_sections,
2333                                                   out_offsets, symtab);
2334 }
2335
2336 // Finalize the local symbols.  Here we set the final value in
2337 // THIS->LOCAL_VALUES_ and set their output symbol table indexes.
2338 // This function is always called from a singleton thread.  The actual
2339 // output of the local symbols will occur in a separate task.
2340
2341 template<int size, bool big_endian>
2342 unsigned int
2343 Sized_relobj_file<size, big_endian>::do_finalize_local_symbols(
2344     unsigned int index,
2345     off_t off,
2346     Symbol_table* symtab)
2347 {
2348   gold_assert(off == static_cast<off_t>(align_address(off, size >> 3)));
2349
2350   const unsigned int loccount = this->local_symbol_count_;
2351   this->local_symbol_offset_ = off;
2352
2353   const bool relocatable = parameters->options().relocatable();
2354   const Output_sections& out_sections(this->output_sections());
2355   const std::vector<Address>& out_offsets(this->section_offsets());
2356
2357   for (unsigned int i = 1; i < loccount; ++i)
2358     {
2359       Symbol_value<size>* lv = &this->local_values_[i];
2360
2361       Compute_final_local_value_status cflv_status =
2362         this->compute_final_local_value_internal(i, lv, lv, relocatable,
2363                                                  out_sections, out_offsets,
2364                                                  symtab);
2365       switch (cflv_status)
2366         {
2367         case CFLV_OK:
2368           if (!lv->is_output_symtab_index_set())
2369             {
2370               lv->set_output_symtab_index(index);
2371               ++index;
2372             }
2373           break;
2374         case CFLV_DISCARDED:
2375         case CFLV_ERROR:
2376           // Do nothing.
2377           break;
2378         default:
2379           gold_unreachable();
2380         }
2381     }
2382   return index;
2383 }
2384
2385 // Set the output dynamic symbol table indexes for the local variables.
2386
2387 template<int size, bool big_endian>
2388 unsigned int
2389 Sized_relobj_file<size, big_endian>::do_set_local_dynsym_indexes(
2390     unsigned int index)
2391 {
2392   const unsigned int loccount = this->local_symbol_count_;
2393   for (unsigned int i = 1; i < loccount; ++i)
2394     {
2395       Symbol_value<size>& lv(this->local_values_[i]);
2396       if (lv.needs_output_dynsym_entry())
2397         {
2398           lv.set_output_dynsym_index(index);
2399           ++index;
2400         }
2401     }
2402   return index;
2403 }
2404
2405 // Set the offset where local dynamic symbol information will be stored.
2406 // Returns the count of local symbols contributed to the symbol table by
2407 // this object.
2408
2409 template<int size, bool big_endian>
2410 unsigned int
2411 Sized_relobj_file<size, big_endian>::do_set_local_dynsym_offset(off_t off)
2412 {
2413   gold_assert(off == static_cast<off_t>(align_address(off, size >> 3)));
2414   this->local_dynsym_offset_ = off;
2415   return this->output_local_dynsym_count_;
2416 }
2417
2418 // If Symbols_data is not NULL get the section flags from here otherwise
2419 // get it from the file.
2420
2421 template<int size, bool big_endian>
2422 uint64_t
2423 Sized_relobj_file<size, big_endian>::do_section_flags(unsigned int shndx)
2424 {
2425   Symbols_data* sd = this->get_symbols_data();
2426   if (sd != NULL)
2427     {
2428       const unsigned char* pshdrs = sd->section_headers_data
2429                                     + This::shdr_size * shndx;
2430       typename This::Shdr shdr(pshdrs);
2431       return shdr.get_sh_flags();
2432     }
2433   // If sd is NULL, read the section header from the file.
2434   return this->elf_file_.section_flags(shndx);
2435 }
2436
2437 // Get the section's ent size from Symbols_data.  Called by get_section_contents
2438 // in icf.cc
2439
2440 template<int size, bool big_endian>
2441 uint64_t
2442 Sized_relobj_file<size, big_endian>::do_section_entsize(unsigned int shndx)
2443 {
2444   Symbols_data* sd = this->get_symbols_data();
2445   gold_assert(sd != NULL);
2446
2447   const unsigned char* pshdrs = sd->section_headers_data
2448                                 + This::shdr_size * shndx;
2449   typename This::Shdr shdr(pshdrs);
2450   return shdr.get_sh_entsize();
2451 }
2452
2453 // Write out the local symbols.
2454
2455 template<int size, bool big_endian>
2456 void
2457 Sized_relobj_file<size, big_endian>::write_local_symbols(
2458     Output_file* of,
2459     const Stringpool* sympool,
2460     const Stringpool* dynpool,
2461     Output_symtab_xindex* symtab_xindex,
2462     Output_symtab_xindex* dynsym_xindex,
2463     off_t symtab_off)
2464 {
2465   const bool strip_all = parameters->options().strip_all();
2466   if (strip_all)
2467     {
2468       if (this->output_local_dynsym_count_ == 0)
2469         return;
2470       this->output_local_symbol_count_ = 0;
2471     }
2472
2473   gold_assert(this->symtab_shndx_ != -1U);
2474   if (this->symtab_shndx_ == 0)
2475     {
2476       // This object has no symbols.  Weird but legal.
2477       return;
2478     }
2479
2480   // Read the symbol table section header.
2481   const unsigned int symtab_shndx = this->symtab_shndx_;
2482   typename This::Shdr symtabshdr(this,
2483                                  this->elf_file_.section_header(symtab_shndx));
2484   gold_assert(symtabshdr.get_sh_type() == elfcpp::SHT_SYMTAB);
2485   const unsigned int loccount = this->local_symbol_count_;
2486   gold_assert(loccount == symtabshdr.get_sh_info());
2487
2488   // Read the local symbols.
2489   const int sym_size = This::sym_size;
2490   off_t locsize = loccount * sym_size;
2491   const unsigned char* psyms = this->get_view(symtabshdr.get_sh_offset(),
2492                                               locsize, true, false);
2493
2494   // Read the symbol names.
2495   const unsigned int strtab_shndx =
2496     this->adjust_shndx(symtabshdr.get_sh_link());
2497   section_size_type strtab_size;
2498   const unsigned char* pnamesu = this->section_contents(strtab_shndx,
2499                                                         &strtab_size,
2500                                                         false);
2501   const char* pnames = reinterpret_cast<const char*>(pnamesu);
2502
2503   // Get views into the output file for the portions of the symbol table
2504   // and the dynamic symbol table that we will be writing.
2505   off_t output_size = this->output_local_symbol_count_ * sym_size;
2506   unsigned char* oview = NULL;
2507   if (output_size > 0)
2508     oview = of->get_output_view(symtab_off + this->local_symbol_offset_,
2509                                 output_size);
2510
2511   off_t dyn_output_size = this->output_local_dynsym_count_ * sym_size;
2512   unsigned char* dyn_oview = NULL;
2513   if (dyn_output_size > 0)
2514     dyn_oview = of->get_output_view(this->local_dynsym_offset_,
2515                                     dyn_output_size);
2516
2517   const Output_sections out_sections(this->output_sections());
2518
2519   gold_assert(this->local_values_.size() == loccount);
2520
2521   unsigned char* ov = oview;
2522   unsigned char* dyn_ov = dyn_oview;
2523   psyms += sym_size;
2524   for (unsigned int i = 1; i < loccount; ++i, psyms += sym_size)
2525     {
2526       elfcpp::Sym<size, big_endian> isym(psyms);
2527
2528       Symbol_value<size>& lv(this->local_values_[i]);
2529
2530       bool is_ordinary;
2531       unsigned int st_shndx = this->adjust_sym_shndx(i, isym.get_st_shndx(),
2532                                                      &is_ordinary);
2533       if (is_ordinary)
2534         {
2535           gold_assert(st_shndx < out_sections.size());
2536           if (out_sections[st_shndx] == NULL)
2537             continue;
2538           st_shndx = out_sections[st_shndx]->out_shndx();
2539           if (st_shndx >= elfcpp::SHN_LORESERVE)
2540             {
2541               if (lv.has_output_symtab_entry())
2542                 symtab_xindex->add(lv.output_symtab_index(), st_shndx);
2543               if (lv.has_output_dynsym_entry())
2544                 dynsym_xindex->add(lv.output_dynsym_index(), st_shndx);
2545               st_shndx = elfcpp::SHN_XINDEX;
2546             }
2547         }
2548
2549       // Write the symbol to the output symbol table.
2550       if (lv.has_output_symtab_entry())
2551         {
2552           elfcpp::Sym_write<size, big_endian> osym(ov);
2553
2554           gold_assert(isym.get_st_name() < strtab_size);
2555           const char* name = pnames + isym.get_st_name();
2556           osym.put_st_name(sympool->get_offset(name));
2557           osym.put_st_value(this->local_values_[i].value(this, 0));
2558           osym.put_st_size(isym.get_st_size());
2559           osym.put_st_info(isym.get_st_info());
2560           osym.put_st_other(isym.get_st_other());
2561           osym.put_st_shndx(st_shndx);
2562
2563           ov += sym_size;
2564         }
2565
2566       // Write the symbol to the output dynamic symbol table.
2567       if (lv.has_output_dynsym_entry())
2568         {
2569           gold_assert(dyn_ov < dyn_oview + dyn_output_size);
2570           elfcpp::Sym_write<size, big_endian> osym(dyn_ov);
2571
2572           gold_assert(isym.get_st_name() < strtab_size);
2573           const char* name = pnames + isym.get_st_name();
2574           osym.put_st_name(dynpool->get_offset(name));
2575           osym.put_st_value(this->local_values_[i].value(this, 0));
2576           osym.put_st_size(isym.get_st_size());
2577           osym.put_st_info(isym.get_st_info());
2578           osym.put_st_other(isym.get_st_other());
2579           osym.put_st_shndx(st_shndx);
2580
2581           dyn_ov += sym_size;
2582         }
2583     }
2584
2585
2586   if (output_size > 0)
2587     {
2588       gold_assert(ov - oview == output_size);
2589       of->write_output_view(symtab_off + this->local_symbol_offset_,
2590                             output_size, oview);
2591     }
2592
2593   if (dyn_output_size > 0)
2594     {
2595       gold_assert(dyn_ov - dyn_oview == dyn_output_size);
2596       of->write_output_view(this->local_dynsym_offset_, dyn_output_size,
2597                             dyn_oview);
2598     }
2599 }
2600
2601 // Set *INFO to symbolic information about the offset OFFSET in the
2602 // section SHNDX.  Return true if we found something, false if we
2603 // found nothing.
2604
2605 template<int size, bool big_endian>
2606 bool
2607 Sized_relobj_file<size, big_endian>::get_symbol_location_info(
2608     unsigned int shndx,
2609     off_t offset,
2610     Symbol_location_info* info)
2611 {
2612   if (this->symtab_shndx_ == 0)
2613     return false;
2614
2615   section_size_type symbols_size;
2616   const unsigned char* symbols = this->section_contents(this->symtab_shndx_,
2617                                                         &symbols_size,
2618                                                         false);
2619
2620   unsigned int symbol_names_shndx =
2621     this->adjust_shndx(this->section_link(this->symtab_shndx_));
2622   section_size_type names_size;
2623   const unsigned char* symbol_names_u =
2624     this->section_contents(symbol_names_shndx, &names_size, false);
2625   const char* symbol_names = reinterpret_cast<const char*>(symbol_names_u);
2626
2627   const int sym_size = This::sym_size;
2628   const size_t count = symbols_size / sym_size;
2629
2630   const unsigned char* p = symbols;
2631   for (size_t i = 0; i < count; ++i, p += sym_size)
2632     {
2633       elfcpp::Sym<size, big_endian> sym(p);
2634
2635       if (sym.get_st_type() == elfcpp::STT_FILE)
2636         {
2637           if (sym.get_st_name() >= names_size)
2638             info->source_file = "(invalid)";
2639           else
2640             info->source_file = symbol_names + sym.get_st_name();
2641           continue;
2642         }
2643
2644       bool is_ordinary;
2645       unsigned int st_shndx = this->adjust_sym_shndx(i, sym.get_st_shndx(),
2646                                                      &is_ordinary);
2647       if (is_ordinary
2648           && st_shndx == shndx
2649           && static_cast<off_t>(sym.get_st_value()) <= offset
2650           && (static_cast<off_t>(sym.get_st_value() + sym.get_st_size())
2651               > offset))
2652         {
2653           if (sym.get_st_name() > names_size)
2654             info->enclosing_symbol_name = "(invalid)";
2655           else
2656             {
2657               info->enclosing_symbol_name = symbol_names + sym.get_st_name();
2658               if (parameters->options().do_demangle())
2659                 {
2660                   char* demangled_name = cplus_demangle(
2661                       info->enclosing_symbol_name.c_str(),
2662                       DMGL_ANSI | DMGL_PARAMS);
2663                   if (demangled_name != NULL)
2664                     {
2665                       info->enclosing_symbol_name.assign(demangled_name);
2666                       free(demangled_name);
2667                     }
2668                 }
2669             }
2670           return true;
2671         }
2672     }
2673
2674   return false;
2675 }
2676
2677 // Look for a kept section corresponding to the given discarded section,
2678 // and return its output address.  This is used only for relocations in
2679 // debugging sections.  If we can't find the kept section, return 0.
2680
2681 template<int size, bool big_endian>
2682 typename Sized_relobj_file<size, big_endian>::Address
2683 Sized_relobj_file<size, big_endian>::map_to_kept_section(
2684     unsigned int shndx,
2685     bool* found) const
2686 {
2687   Relobj* kept_object;
2688   unsigned int kept_shndx;
2689   if (this->get_kept_comdat_section(shndx, &kept_object, &kept_shndx))
2690     {
2691       Sized_relobj_file<size, big_endian>* kept_relobj =
2692         static_cast<Sized_relobj_file<size, big_endian>*>(kept_object);
2693       Output_section* os = kept_relobj->output_section(kept_shndx);
2694       Address offset = kept_relobj->get_output_section_offset(kept_shndx);
2695       if (os != NULL && offset != invalid_address)
2696         {
2697           *found = true;
2698           return os->address() + offset;
2699         }
2700     }
2701   *found = false;
2702   return 0;
2703 }
2704
2705 // Get symbol counts.
2706
2707 template<int size, bool big_endian>
2708 void
2709 Sized_relobj_file<size, big_endian>::do_get_global_symbol_counts(
2710     const Symbol_table*,
2711     size_t* defined,
2712     size_t* used) const
2713 {
2714   *defined = this->defined_count_;
2715   size_t count = 0;
2716   for (typename Symbols::const_iterator p = this->symbols_.begin();
2717        p != this->symbols_.end();
2718        ++p)
2719     if (*p != NULL
2720         && (*p)->source() == Symbol::FROM_OBJECT
2721         && (*p)->object() == this
2722         && (*p)->is_defined())
2723       ++count;
2724   *used = count;
2725 }
2726
2727 // Return a view of the decompressed contents of a section.  Set *PLEN
2728 // to the size.  Set *IS_NEW to true if the contents need to be freed
2729 // by the caller.
2730
2731 template<int size, bool big_endian>
2732 const unsigned char*
2733 Sized_relobj_file<size, big_endian>::do_decompressed_section_contents(
2734     unsigned int shndx,
2735     section_size_type* plen,
2736     bool* is_new)
2737 {
2738   section_size_type buffer_size;
2739   const unsigned char* buffer = this->do_section_contents(shndx, &buffer_size,
2740                                                           false);
2741
2742   if (this->compressed_sections_ == NULL)
2743     {
2744       *plen = buffer_size;
2745       *is_new = false;
2746       return buffer;
2747     }
2748
2749   Compressed_section_map::const_iterator p =
2750       this->compressed_sections_->find(shndx);
2751   if (p == this->compressed_sections_->end())
2752     {
2753       *plen = buffer_size;
2754       *is_new = false;
2755       return buffer;
2756     }
2757
2758   section_size_type uncompressed_size = p->second.size;
2759   if (p->second.contents != NULL)
2760     {
2761       *plen = uncompressed_size;
2762       *is_new = false;
2763       return p->second.contents;
2764     }
2765
2766   unsigned char* uncompressed_data = new unsigned char[uncompressed_size];
2767   if (!decompress_input_section(buffer,
2768                                 buffer_size,
2769                                 uncompressed_data,
2770                                 uncompressed_size))
2771     this->error(_("could not decompress section %s"),
2772                 this->do_section_name(shndx).c_str());
2773
2774   // We could cache the results in p->second.contents and store
2775   // false in *IS_NEW, but build_compressed_section_map() would
2776   // have done so if it had expected it to be profitable.  If
2777   // we reach this point, we expect to need the contents only
2778   // once in this pass.
2779   *plen = uncompressed_size;
2780   *is_new = true;
2781   return uncompressed_data;
2782 }
2783
2784 // Discard any buffers of uncompressed sections.  This is done
2785 // at the end of the Add_symbols task.
2786
2787 template<int size, bool big_endian>
2788 void
2789 Sized_relobj_file<size, big_endian>::do_discard_decompressed_sections()
2790 {
2791   if (this->compressed_sections_ == NULL)
2792     return;
2793
2794   for (Compressed_section_map::iterator p = this->compressed_sections_->begin();
2795        p != this->compressed_sections_->end();
2796        ++p)
2797     {
2798       if (p->second.contents != NULL)
2799         {
2800           delete[] p->second.contents;
2801           p->second.contents = NULL;
2802         }
2803     }
2804 }
2805
2806 // Input_objects methods.
2807
2808 // Add a regular relocatable object to the list.  Return false if this
2809 // object should be ignored.
2810
2811 bool
2812 Input_objects::add_object(Object* obj)
2813 {
2814   // Print the filename if the -t/--trace option is selected.
2815   if (parameters->options().trace())
2816     gold_info("%s", obj->name().c_str());
2817
2818   if (!obj->is_dynamic())
2819     this->relobj_list_.push_back(static_cast<Relobj*>(obj));
2820   else
2821     {
2822       // See if this is a duplicate SONAME.
2823       Dynobj* dynobj = static_cast<Dynobj*>(obj);
2824       const char* soname = dynobj->soname();
2825
2826       std::pair<Unordered_set<std::string>::iterator, bool> ins =
2827         this->sonames_.insert(soname);
2828       if (!ins.second)
2829         {
2830           // We have already seen a dynamic object with this soname.
2831           return false;
2832         }
2833
2834       this->dynobj_list_.push_back(dynobj);
2835     }
2836
2837   // Add this object to the cross-referencer if requested.
2838   if (parameters->options().user_set_print_symbol_counts()
2839       || parameters->options().cref())
2840     {
2841       if (this->cref_ == NULL)
2842         this->cref_ = new Cref();
2843       this->cref_->add_object(obj);
2844     }
2845
2846   return true;
2847 }
2848
2849 // For each dynamic object, record whether we've seen all of its
2850 // explicit dependencies.
2851
2852 void
2853 Input_objects::check_dynamic_dependencies() const
2854 {
2855   bool issued_copy_dt_needed_error = false;
2856   for (Dynobj_list::const_iterator p = this->dynobj_list_.begin();
2857        p != this->dynobj_list_.end();
2858        ++p)
2859     {
2860       const Dynobj::Needed& needed((*p)->needed());
2861       bool found_all = true;
2862       Dynobj::Needed::const_iterator pneeded;
2863       for (pneeded = needed.begin(); pneeded != needed.end(); ++pneeded)
2864         {
2865           if (this->sonames_.find(*pneeded) == this->sonames_.end())
2866             {
2867               found_all = false;
2868               break;
2869             }
2870         }
2871       (*p)->set_has_unknown_needed_entries(!found_all);
2872
2873       // --copy-dt-needed-entries aka --add-needed is a GNU ld option
2874       // that gold does not support.  However, they cause no trouble
2875       // unless there is a DT_NEEDED entry that we don't know about;
2876       // warn only in that case.
2877       if (!found_all
2878           && !issued_copy_dt_needed_error
2879           && (parameters->options().copy_dt_needed_entries()
2880               || parameters->options().add_needed()))
2881         {
2882           const char* optname;
2883           if (parameters->options().copy_dt_needed_entries())
2884             optname = "--copy-dt-needed-entries";
2885           else
2886             optname = "--add-needed";
2887           gold_error(_("%s is not supported but is required for %s in %s"),
2888                      optname, (*pneeded).c_str(), (*p)->name().c_str());
2889           issued_copy_dt_needed_error = true;
2890         }
2891     }
2892 }
2893
2894 // Start processing an archive.
2895
2896 void
2897 Input_objects::archive_start(Archive* archive)
2898 {
2899   if (parameters->options().user_set_print_symbol_counts()
2900       || parameters->options().cref())
2901     {
2902       if (this->cref_ == NULL)
2903         this->cref_ = new Cref();
2904       this->cref_->add_archive_start(archive);
2905     }
2906 }
2907
2908 // Stop processing an archive.
2909
2910 void
2911 Input_objects::archive_stop(Archive* archive)
2912 {
2913   if (parameters->options().user_set_print_symbol_counts()
2914       || parameters->options().cref())
2915     this->cref_->add_archive_stop(archive);
2916 }
2917
2918 // Print symbol counts
2919
2920 void
2921 Input_objects::print_symbol_counts(const Symbol_table* symtab) const
2922 {
2923   if (parameters->options().user_set_print_symbol_counts()
2924       && this->cref_ != NULL)
2925     this->cref_->print_symbol_counts(symtab);
2926 }
2927
2928 // Print a cross reference table.
2929
2930 void
2931 Input_objects::print_cref(const Symbol_table* symtab, FILE* f) const
2932 {
2933   if (parameters->options().cref() && this->cref_ != NULL)
2934     this->cref_->print_cref(symtab, f);
2935 }
2936
2937 // Relocate_info methods.
2938
2939 // Return a string describing the location of a relocation when file
2940 // and lineno information is not available.  This is only used in
2941 // error messages.
2942
2943 template<int size, bool big_endian>
2944 std::string
2945 Relocate_info<size, big_endian>::location(size_t, off_t offset) const
2946 {
2947   Sized_dwarf_line_info<size, big_endian> line_info(this->object);
2948   std::string ret = line_info.addr2line(this->data_shndx, offset, NULL);
2949   if (!ret.empty())
2950     return ret;
2951
2952   ret = this->object->name();
2953
2954   Symbol_location_info info;
2955   if (this->object->get_symbol_location_info(this->data_shndx, offset, &info))
2956     {
2957       if (!info.source_file.empty())
2958         {
2959           ret += ":";
2960           ret += info.source_file;
2961         }
2962       size_t len = info.enclosing_symbol_name.length() + 100;
2963       char* buf = new char[len];
2964       snprintf(buf, len, _(":function %s"),
2965                info.enclosing_symbol_name.c_str());
2966       ret += buf;
2967       delete[] buf;
2968       return ret;
2969     }
2970
2971   ret += "(";
2972   ret += this->object->section_name(this->data_shndx);
2973   char buf[100];
2974   snprintf(buf, sizeof buf, "+0x%lx)", static_cast<long>(offset));
2975   ret += buf;
2976   return ret;
2977 }
2978
2979 } // End namespace gold.
2980
2981 namespace
2982 {
2983
2984 using namespace gold;
2985
2986 // Read an ELF file with the header and return the appropriate
2987 // instance of Object.
2988
2989 template<int size, bool big_endian>
2990 Object*
2991 make_elf_sized_object(const std::string& name, Input_file* input_file,
2992                       off_t offset, const elfcpp::Ehdr<size, big_endian>& ehdr,
2993                       bool* punconfigured)
2994 {
2995   Target* target = select_target(input_file, offset,
2996                                  ehdr.get_e_machine(), size, big_endian,
2997                                  ehdr.get_e_ident()[elfcpp::EI_OSABI],
2998                                  ehdr.get_e_ident()[elfcpp::EI_ABIVERSION]);
2999   if (target == NULL)
3000     gold_fatal(_("%s: unsupported ELF machine number %d"),
3001                name.c_str(), ehdr.get_e_machine());
3002
3003   if (!parameters->target_valid())
3004     set_parameters_target(target);
3005   else if (target != &parameters->target())
3006     {
3007       if (punconfigured != NULL)
3008         *punconfigured = true;
3009       else
3010         gold_error(_("%s: incompatible target"), name.c_str());
3011       return NULL;
3012     }
3013
3014   return target->make_elf_object<size, big_endian>(name, input_file, offset,
3015                                                    ehdr);
3016 }
3017
3018 } // End anonymous namespace.
3019
3020 namespace gold
3021 {
3022
3023 // Return whether INPUT_FILE is an ELF object.
3024
3025 bool
3026 is_elf_object(Input_file* input_file, off_t offset,
3027               const unsigned char** start, int* read_size)
3028 {
3029   off_t filesize = input_file->file().filesize();
3030   int want = elfcpp::Elf_recognizer::max_header_size;
3031   if (filesize - offset < want)
3032     want = filesize - offset;
3033
3034   const unsigned char* p = input_file->file().get_view(offset, 0, want,
3035                                                        true, false);
3036   *start = p;
3037   *read_size = want;
3038
3039   return elfcpp::Elf_recognizer::is_elf_file(p, want);
3040 }
3041
3042 // Read an ELF file and return the appropriate instance of Object.
3043
3044 Object*
3045 make_elf_object(const std::string& name, Input_file* input_file, off_t offset,
3046                 const unsigned char* p, section_offset_type bytes,
3047                 bool* punconfigured)
3048 {
3049   if (punconfigured != NULL)
3050     *punconfigured = false;
3051
3052   std::string error;
3053   bool big_endian = false;
3054   int size = 0;
3055   if (!elfcpp::Elf_recognizer::is_valid_header(p, bytes, &size,
3056                                                &big_endian, &error))
3057     {
3058       gold_error(_("%s: %s"), name.c_str(), error.c_str());
3059       return NULL;
3060     }
3061
3062   if (size == 32)
3063     {
3064       if (big_endian)
3065         {
3066 #ifdef HAVE_TARGET_32_BIG
3067           elfcpp::Ehdr<32, true> ehdr(p);
3068           return make_elf_sized_object<32, true>(name, input_file,
3069                                                  offset, ehdr, punconfigured);
3070 #else
3071           if (punconfigured != NULL)
3072             *punconfigured = true;
3073           else
3074             gold_error(_("%s: not configured to support "
3075                          "32-bit big-endian object"),
3076                        name.c_str());
3077           return NULL;
3078 #endif
3079         }
3080       else
3081         {
3082 #ifdef HAVE_TARGET_32_LITTLE
3083           elfcpp::Ehdr<32, false> ehdr(p);
3084           return make_elf_sized_object<32, false>(name, input_file,
3085                                                   offset, ehdr, punconfigured);
3086 #else
3087           if (punconfigured != NULL)
3088             *punconfigured = true;
3089           else
3090             gold_error(_("%s: not configured to support "
3091                          "32-bit little-endian object"),
3092                        name.c_str());
3093           return NULL;
3094 #endif
3095         }
3096     }
3097   else if (size == 64)
3098     {
3099       if (big_endian)
3100         {
3101 #ifdef HAVE_TARGET_64_BIG
3102           elfcpp::Ehdr<64, true> ehdr(p);
3103           return make_elf_sized_object<64, true>(name, input_file,
3104                                                  offset, ehdr, punconfigured);
3105 #else
3106           if (punconfigured != NULL)
3107             *punconfigured = true;
3108           else
3109             gold_error(_("%s: not configured to support "
3110                          "64-bit big-endian object"),
3111                        name.c_str());
3112           return NULL;
3113 #endif
3114         }
3115       else
3116         {
3117 #ifdef HAVE_TARGET_64_LITTLE
3118           elfcpp::Ehdr<64, false> ehdr(p);
3119           return make_elf_sized_object<64, false>(name, input_file,
3120                                                   offset, ehdr, punconfigured);
3121 #else
3122           if (punconfigured != NULL)
3123             *punconfigured = true;
3124           else
3125             gold_error(_("%s: not configured to support "
3126                          "64-bit little-endian object"),
3127                        name.c_str());
3128           return NULL;
3129 #endif
3130         }
3131     }
3132   else
3133     gold_unreachable();
3134 }
3135
3136 // Instantiate the templates we need.
3137
3138 #ifdef HAVE_TARGET_32_LITTLE
3139 template
3140 void
3141 Object::read_section_data<32, false>(elfcpp::Elf_file<32, false, Object>*,
3142                                      Read_symbols_data*);
3143 #endif
3144
3145 #ifdef HAVE_TARGET_32_BIG
3146 template
3147 void
3148 Object::read_section_data<32, true>(elfcpp::Elf_file<32, true, Object>*,
3149                                     Read_symbols_data*);
3150 #endif
3151
3152 #ifdef HAVE_TARGET_64_LITTLE
3153 template
3154 void
3155 Object::read_section_data<64, false>(elfcpp::Elf_file<64, false, Object>*,
3156                                      Read_symbols_data*);
3157 #endif
3158
3159 #ifdef HAVE_TARGET_64_BIG
3160 template
3161 void
3162 Object::read_section_data<64, true>(elfcpp::Elf_file<64, true, Object>*,
3163                                     Read_symbols_data*);
3164 #endif
3165
3166 #ifdef HAVE_TARGET_32_LITTLE
3167 template
3168 class Sized_relobj_file<32, false>;
3169 #endif
3170
3171 #ifdef HAVE_TARGET_32_BIG
3172 template
3173 class Sized_relobj_file<32, true>;
3174 #endif
3175
3176 #ifdef HAVE_TARGET_64_LITTLE
3177 template
3178 class Sized_relobj_file<64, false>;
3179 #endif
3180
3181 #ifdef HAVE_TARGET_64_BIG
3182 template
3183 class Sized_relobj_file<64, true>;
3184 #endif
3185
3186 #ifdef HAVE_TARGET_32_LITTLE
3187 template
3188 struct Relocate_info<32, false>;
3189 #endif
3190
3191 #ifdef HAVE_TARGET_32_BIG
3192 template
3193 struct Relocate_info<32, true>;
3194 #endif
3195
3196 #ifdef HAVE_TARGET_64_LITTLE
3197 template
3198 struct Relocate_info<64, false>;
3199 #endif
3200
3201 #ifdef HAVE_TARGET_64_BIG
3202 template
3203 struct Relocate_info<64, true>;
3204 #endif
3205
3206 #ifdef HAVE_TARGET_32_LITTLE
3207 template
3208 void
3209 Xindex::initialize_symtab_xindex<32, false>(Object*, unsigned int);
3210
3211 template
3212 void
3213 Xindex::read_symtab_xindex<32, false>(Object*, unsigned int,
3214                                       const unsigned char*);
3215 #endif
3216
3217 #ifdef HAVE_TARGET_32_BIG
3218 template
3219 void
3220 Xindex::initialize_symtab_xindex<32, true>(Object*, unsigned int);
3221
3222 template
3223 void
3224 Xindex::read_symtab_xindex<32, true>(Object*, unsigned int,
3225                                      const unsigned char*);
3226 #endif
3227
3228 #ifdef HAVE_TARGET_64_LITTLE
3229 template
3230 void
3231 Xindex::initialize_symtab_xindex<64, false>(Object*, unsigned int);
3232
3233 template
3234 void
3235 Xindex::read_symtab_xindex<64, false>(Object*, unsigned int,
3236                                       const unsigned char*);
3237 #endif
3238
3239 #ifdef HAVE_TARGET_64_BIG
3240 template
3241 void
3242 Xindex::initialize_symtab_xindex<64, true>(Object*, unsigned int);
3243
3244 template
3245 void
3246 Xindex::read_symtab_xindex<64, true>(Object*, unsigned int,
3247                                      const unsigned char*);
3248 #endif
3249
3250 } // End namespace gold.