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