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