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