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