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