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