Add --verify-only option to DWP.
[platform/upstream/binutils.git] / gold / dwp.cc
1 // dwp.cc -- DWARF packaging utility
2
3 // Copyright 2012 Free Software Foundation, Inc.
4 // Written by Cary Coutant <ccoutant@google.com>.
5
6 // This file is part of dwp, the DWARF packaging utility.
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 "dwp.h"
24
25 #include <cstdarg>
26 #include <cstddef>
27 #include <cstdio>
28 #include <cstdlib>
29 #include <cstring>
30 #include <cerrno>
31
32 #include <vector>
33 #include <algorithm>
34
35 #include "getopt.h"
36 #include "libiberty.h"
37 #include "../bfd/bfdver.h"
38
39 #include "elfcpp.h"
40 #include "elfcpp_file.h"
41 #include "dwarf.h"
42 #include "dirsearch.h"
43 #include "fileread.h"
44 #include "object.h"
45 #include "compressed_output.h"
46 #include "stringpool.h"
47 #include "dwarf_reader.h"
48
49 static void
50 usage(FILE* fd, int) ATTRIBUTE_NORETURN;
51
52 static void
53 print_version() ATTRIBUTE_NORETURN;
54
55 namespace gold {
56
57 class Dwp_output_file;
58
59 template <int size, bool big_endian>
60 class Sized_relobj_dwo;
61
62 // List of .dwo files to process.
63 struct Dwo_file_entry
64 {
65   Dwo_file_entry(uint64_t id, std::string name)
66     : dwo_id(id), dwo_name(name)
67   { }
68   uint64_t dwo_id;
69   std::string dwo_name;
70 };
71 typedef std::vector<Dwo_file_entry> File_list;
72
73 // Type to hold the offset and length of an input section
74 // within an output section.
75
76 struct Section_bounds
77 {
78   section_offset_type offset;
79   section_size_type size;
80
81   Section_bounds()
82     : offset(0), size(0)
83   { }
84
85   Section_bounds(section_offset_type o, section_size_type s)
86     : offset(o), size(s)
87   { }
88 };
89
90 // A set of sections for a compilation unit or type unit.
91
92 struct Unit_set
93 {
94   uint64_t signature;
95   Section_bounds sections[elfcpp::DW_SECT_MAX + 1];
96
97   Unit_set()
98     : signature(0), sections()
99   { }
100 };
101
102 // An input file.
103 // This class may represent a .dwo file, a .dwp file
104 // produced by an earlier run, or an executable file whose
105 // debug section identifies a set of .dwo files to read.
106
107 class Dwo_file
108 {
109  public:
110   Dwo_file(const char* name)
111     : name_(name), obj_(NULL), input_file_(NULL), is_compressed_(),
112       sect_offsets_(), str_offset_map_()
113   { }
114
115   ~Dwo_file();
116
117   // Read the input executable file and extract the list of .dwo files
118   // that it references.
119   void
120   read_executable(File_list* files);
121
122   // Read the input file and send its contents to OUTPUT_FILE.
123   void
124   read(Dwp_output_file* output_file);
125
126   // Verify a .dwp file given a list of .dwo files referenced by the
127   // corresponding executable file.  Returns true if no problems
128   // were found.
129   bool
130   verify(const File_list& files);
131
132  private:
133   // Types for mapping input string offsets to output string offsets.
134   typedef std::pair<section_offset_type, section_offset_type>
135       Str_offset_map_entry;
136   typedef std::vector<Str_offset_map_entry> Str_offset_map;
137
138   // A less-than comparison routine for Str_offset_map.
139   struct Offset_compare
140   {
141     bool
142     operator()(const Str_offset_map_entry& i1,
143                const Str_offset_map_entry& i2) const
144     { return i1.first < i2.first; }
145   };
146
147   // Create a Sized_relobj_dwo of the given size and endianness,
148   // and record the target info.  P is a pointer to the ELF header
149   // in memory.
150   Relobj*
151   make_object(Dwp_output_file* output_file);
152
153   template <int size, bool big_endian>
154   Relobj*
155   sized_make_object(const unsigned char* p, Input_file* input_file,
156                     Dwp_output_file* output_file);
157
158   // Return the number of sections in the input object file.
159   unsigned int
160   shnum() const
161   { return this->obj_->shnum(); }
162
163   // Return section type.
164   unsigned int
165   section_type(unsigned int shndx)
166   { return this->obj_->section_type(shndx); }
167
168   // Get the name of a section.
169   std::string
170   section_name(unsigned int shndx)
171   { return this->obj_->section_name(shndx); }
172
173   // Return a view of the contents of a section, decompressed if necessary.
174   // Set *PLEN to the size.  Set *IS_NEW to true if the contents need to be
175   // deleted by the caller.
176   const unsigned char*
177   section_contents(unsigned int shndx, section_size_type* plen, bool* is_new)
178   { return this->obj_->decompressed_section_contents(shndx, plen, is_new); }
179
180   // Read the .debug_cu_index or .debug_tu_index section of a .dwp file,
181   // and process the CU or TU sets.
182   void
183   read_unit_index(unsigned int, unsigned int *, Dwp_output_file*,
184                   bool is_tu_index);
185
186   template <bool big_endian>
187   void
188   sized_read_unit_index(unsigned int, unsigned int *, Dwp_output_file*,
189                         bool is_tu_index);
190
191   // Verify the .debug_cu_index section of a .dwp file, comparing it
192   // against the list of .dwo files referenced by the corresponding
193   // executable file.
194   bool
195   verify_dwo_list(unsigned int, const File_list& files);
196
197   template <bool big_endian>
198   bool
199   sized_verify_dwo_list(unsigned int, const File_list& files);
200
201   // Merge the input string table section into the output file.
202   void
203   add_strings(Dwp_output_file*, unsigned int);
204
205   // Copy a section from the input file to the output file.
206   Section_bounds
207   copy_section(Dwp_output_file* output_file, unsigned int shndx,
208                elfcpp::DW_SECT section_id);
209
210   // Remap the string offsets in the .debug_str_offsets.dwo section.
211   const unsigned char*
212   remap_str_offsets(const unsigned char* contents, section_size_type len);
213
214   template <bool big_endian>
215   const unsigned char*
216   sized_remap_str_offsets(const unsigned char* contents, section_size_type len);
217
218   // Remap a single string offsets from an offset in the input string table
219   // to an offset in the output string table.
220   unsigned int
221   remap_str_offset(section_offset_type val);
222
223   // Add a set of .debug_info.dwo or .debug_types.dwo and related sections
224   // to OUTPUT_FILE.
225   void
226   add_unit_set(Dwp_output_file* output_file, unsigned int *debug_shndx,
227                bool is_debug_types);
228
229   // The filename.
230   const char* name_;
231   // The ELF file, represented as a gold Relobj instance.
232   Relobj* obj_;
233   // The Input_file object.
234   Input_file* input_file_;
235   // Flags indicating which sections are compressed.
236   std::vector<bool> is_compressed_;
237   // Map input section index onto output section offset and size.
238   std::vector<Section_bounds> sect_offsets_;
239   // Map input string offsets to output string offsets.
240   Str_offset_map str_offset_map_;
241 };
242
243 // An ELF input file.
244 // We derive from Sized_relobj so that we can use interfaces
245 // in libgold to access the file.
246
247 template <int size, bool big_endian>
248 class Sized_relobj_dwo : public Sized_relobj<size, big_endian>
249 {
250  public:
251   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
252   typedef typename Sized_relobj<size, big_endian>::Symbols Symbols;
253
254   Sized_relobj_dwo(const char* name, Input_file* input_file,
255                    const elfcpp::Ehdr<size, big_endian>& ehdr)
256     : Sized_relobj<size, big_endian>(name, input_file),
257       elf_file_(this, ehdr)
258   { }
259
260   ~Sized_relobj_dwo()
261   { }
262
263   // Setup the section information.
264   void
265   setup();
266
267  protected:
268   // Return section type.
269   unsigned int
270   do_section_type(unsigned int shndx)
271   { return this->elf_file_.section_type(shndx); }
272
273   // Get the name of a section.
274   std::string
275   do_section_name(unsigned int shndx)
276   { return this->elf_file_.section_name(shndx); }
277
278   // Get the size of a section.
279   uint64_t
280   do_section_size(unsigned int shndx)
281   { return this->elf_file_.section_size(shndx); }
282
283   // Return a view of the contents of a section.
284   const unsigned char*
285   do_section_contents(unsigned int, section_size_type*, bool);
286
287   // Return a view of the uncompressed contents of a section.  Set *PLEN
288   // to the size.  Set *IS_NEW to true if the contents need to be deleted
289   // by the caller.
290   const unsigned char*
291   do_decompressed_section_contents(unsigned int shndx,
292                                    section_size_type* plen,
293                                    bool* is_new);
294
295   // The following virtual functions are abstract in the base classes,
296   // but are not used here.
297
298   // Read the symbols.
299   void
300   do_read_symbols(Read_symbols_data*)
301   { gold_unreachable(); }
302
303   // Lay out the input sections.
304   void
305   do_layout(Symbol_table*, Layout*, Read_symbols_data*)
306   { gold_unreachable(); }
307
308   // Layout sections whose layout was deferred while waiting for
309   // input files from a plugin.
310   void
311   do_layout_deferred_sections(Layout*)
312   { gold_unreachable(); }
313
314   // Add the symbols to the symbol table.
315   void
316   do_add_symbols(Symbol_table*, Read_symbols_data*, Layout*)
317   { gold_unreachable(); }
318
319   Archive::Should_include
320   do_should_include_member(Symbol_table*, Layout*, Read_symbols_data*,
321                            std::string*)
322   { gold_unreachable(); }
323
324   // Iterate over global symbols, calling a visitor class V for each.
325   void
326   do_for_all_global_symbols(Read_symbols_data*,
327                             Library_base::Symbol_visitor_base*)
328   { gold_unreachable(); }
329
330   // Return section flags.
331   uint64_t
332   do_section_flags(unsigned int)
333   { gold_unreachable(); }
334
335   // Return section entsize.
336   uint64_t
337   do_section_entsize(unsigned int)
338   { gold_unreachable(); }
339
340   // Return section address.
341   uint64_t
342   do_section_address(unsigned int)
343   { gold_unreachable(); }
344
345   // Return the section link field.
346   unsigned int
347   do_section_link(unsigned int)
348   { gold_unreachable(); }
349
350   // Return the section link field.
351   unsigned int
352   do_section_info(unsigned int)
353   { gold_unreachable(); }
354
355   // Return the section alignment.
356   uint64_t
357   do_section_addralign(unsigned int)
358   { gold_unreachable(); }
359
360   // Return the Xindex structure to use.
361   Xindex*
362   do_initialize_xindex()
363   { gold_unreachable(); }
364
365   // Get symbol counts.
366   void
367   do_get_global_symbol_counts(const Symbol_table*, size_t*, size_t*) const
368   { gold_unreachable(); }
369
370   // Get global symbols.
371   const Symbols*
372   do_get_global_symbols() const
373   { return NULL; }
374
375   // Return the value of a local symbol.
376   uint64_t
377   do_local_symbol_value(unsigned int, uint64_t) const
378   { gold_unreachable(); }
379
380   unsigned int
381   do_local_plt_offset(unsigned int) const
382   { gold_unreachable(); }
383
384   // Return whether local symbol SYMNDX is a TLS symbol.
385   bool
386   do_local_is_tls(unsigned int) const
387   { gold_unreachable(); }
388
389   // Return the number of local symbols.
390   unsigned int
391   do_local_symbol_count() const
392   { gold_unreachable(); }
393
394   // Return the number of local symbols in the output symbol table.
395   unsigned int
396   do_output_local_symbol_count() const
397   { gold_unreachable(); }
398
399   // Return the file offset for local symbols in the output symbol table.
400   off_t
401   do_local_symbol_offset() const
402   { gold_unreachable(); }
403
404   // Read the relocs.
405   void
406   do_read_relocs(Read_relocs_data*)
407   { gold_unreachable(); }
408
409   // Process the relocs to find list of referenced sections. Used only
410   // during garbage collection.
411   void
412   do_gc_process_relocs(Symbol_table*, Layout*, Read_relocs_data*)
413   { gold_unreachable(); }
414
415   // Scan the relocs and adjust the symbol table.
416   void
417   do_scan_relocs(Symbol_table*, Layout*, Read_relocs_data*)
418   { gold_unreachable(); }
419
420   // Count the local symbols.
421   void
422   do_count_local_symbols(Stringpool_template<char>*,
423                          Stringpool_template<char>*)
424   { gold_unreachable(); }
425
426   // Finalize the local symbols.
427   unsigned int
428   do_finalize_local_symbols(unsigned int, off_t, Symbol_table*)
429   { gold_unreachable(); }
430
431   // Set the offset where local dynamic symbol information will be stored.
432   unsigned int
433   do_set_local_dynsym_indexes(unsigned int)
434   { gold_unreachable(); }
435
436   // Set the offset where local dynamic symbol information will be stored.
437   unsigned int
438   do_set_local_dynsym_offset(off_t)
439   { gold_unreachable(); }
440
441   // Relocate the input sections and write out the local symbols.
442   void
443   do_relocate(const Symbol_table*, const Layout*, Output_file*)
444   { gold_unreachable(); }
445
446  private:
447   // General access to the ELF file.
448   elfcpp::Elf_file<size, big_endian, Object> elf_file_;
449 };
450
451 // The output file.
452 // This class is responsible for collecting the debug index information
453 // and writing the .dwp file in ELF format.
454
455 class Dwp_output_file
456 {
457  public:
458   Dwp_output_file(const char* name)
459     : name_(name), machine_(0), size_(0), big_endian_(false), osabi_(0),
460       abiversion_(0), fd_(NULL), next_file_offset_(0), shnum_(1), sections_(),
461       section_id_map_(), shoff_(0), shstrndx_(0), have_strings_(false),
462       stringpool_(), shstrtab_(), cu_index_(), tu_index_(), last_type_sig_(0),
463       last_tu_slot_(0)
464   {
465     this->section_id_map_.resize(elfcpp::DW_SECT_MAX + 1);
466     this->stringpool_.set_no_zero_null();
467   }
468
469   // Record the target info from an input file.
470   void
471   record_target_info(const char* name, int machine, int size, bool big_endian,
472                      int osabi, int abiversion);
473
474   // Add a string to the debug strings section.
475   section_offset_type
476   add_string(const char* str, size_t len);
477
478   // Add a section to the output file, and return the new section offset.
479   section_offset_type
480   add_contribution(elfcpp::DW_SECT section_id, const unsigned char* contents,
481                    section_size_type len, int align);
482
483   // Add a set of .debug_info and related sections to the output file.
484   void
485   add_cu_set(Unit_set* cu_set);
486
487   // Lookup a type signature and return TRUE if we have already seen it.
488   bool
489   lookup_tu(uint64_t type_sig);
490
491   // Add a set of .debug_types and related sections to the output file.
492   void
493   add_tu_set(Unit_set* tu_set);
494
495   // Finalize the file, write the string tables and index sections,
496   // and close the file.
497   void
498   finalize();
499
500  private:
501   // Contributions to output sections.
502   struct Contribution
503   {
504     section_offset_type output_offset;
505     section_size_type size;
506     const unsigned char* contents;
507   };
508
509   // Sections in the output file.
510   struct Section
511   {
512     const char* name;
513     off_t offset;
514     section_size_type size;
515     int align;
516     std::vector<Contribution> contributions;
517
518     Section(const char* n, int a)
519       : name(n), offset(0), size(0), align(a), contributions()
520     { }
521   };
522
523   // The index sections defined by the DWARF Package File Format spec.
524   class Dwp_index
525   {
526    public:
527     // Vector for the section table.
528     typedef std::vector<const Unit_set*> Section_table;
529
530     Dwp_index()
531       : capacity_(0), used_(0), hash_table_(NULL), section_table_(),
532         section_mask_(0)
533     { }
534
535     ~Dwp_index()
536     { }
537
538     // Find a slot in the hash table for SIGNATURE.  Return TRUE
539     // if the entry already exists.
540     bool
541     find_or_add(uint64_t signature, unsigned int* slotp);
542
543     // Enter a CU or TU set at the given SLOT in the hash table.
544     void
545     enter_set(unsigned int slot, const Unit_set* set);
546
547     // Return the contents of the given SLOT in the hash table of signatures.
548     uint64_t
549     hash_table(unsigned int slot) const
550     { return this->hash_table_[slot]; }
551
552     // Return the contents of the given SLOT in the parallel table of
553     // shndx pool indexes.
554     uint32_t
555     index_table(unsigned int slot) const
556     { return this->index_table_[slot]; }
557
558     // Return the total number of slots in the hash table.
559     unsigned int
560     hash_table_total_slots() const
561     { return this->capacity_; }
562
563     // Return the number of used slots in the hash table.
564     unsigned int
565     hash_table_used_slots() const
566     { return this->used_; }
567
568     // Return an iterator into the shndx pool.
569     Section_table::const_iterator
570     section_table() const
571     { return this->section_table_.begin(); }
572
573     Section_table::const_iterator
574     section_table_end() const
575     { return this->section_table_.end(); }
576
577     // Return the number of rows in the section table.
578     unsigned int
579     section_table_rows() const
580     { return this->section_table_.size(); }
581
582     // Return the mask indicating which columns will be used
583     // in the section table.
584     int
585     section_table_cols() const
586     { return this->section_mask_; }
587
588    private:
589     // Initialize the hash table.
590     void
591     initialize();
592
593     // Grow the hash table when we reach 2/3 capacity.
594     void
595     grow();
596
597     // The number of slots in the table, a power of 2 such that
598     // capacity > 3 * size / 2.
599     unsigned int capacity_;
600     // The current number of used slots in the hash table.
601     unsigned int used_;
602     // The storage for the hash table of signatures.
603     uint64_t* hash_table_;
604     // The storage for the parallel table of shndx pool indexes.
605     uint32_t* index_table_;
606     // The table of section offsets and sizes.
607     Section_table section_table_;
608     // Bit mask to indicate which debug sections are present in the file.
609     int section_mask_;
610   };  // End class Dwp_output_file::Dwp_index.
611
612   // Add a new output section and return the section index.
613   unsigned int
614   add_output_section(const char* section_name, int align);
615
616   // Write a new section to the output file.
617   void
618   write_new_section(const char* section_name, const unsigned char* contents,
619                     section_size_type len, int align);
620
621   // Write the ELF header.
622   void
623   write_ehdr();
624
625   template<unsigned int size, bool big_endian>
626   void
627   sized_write_ehdr();
628
629   // Write a section header.
630   void
631   write_shdr(const char* name, unsigned int type, unsigned int flags,
632              uint64_t addr, off_t offset, section_size_type sect_size,
633              unsigned int link, unsigned int info,
634              unsigned int align, unsigned int ent_size);
635
636   template<unsigned int size, bool big_endian>
637   void
638   sized_write_shdr(const char* name, unsigned int type, unsigned int flags,
639                    uint64_t addr, off_t offset, section_size_type sect_size,
640                    unsigned int link, unsigned int info,
641                    unsigned int align, unsigned int ent_size);
642
643   // Write the contributions to an output section.
644   void
645   write_contributions(const Section& sect);
646
647   // Write a CU or TU index section.
648   template<bool big_endian>
649   void
650   write_index(const char* sect_name, const Dwp_index& index);
651
652   // The output filename.
653   const char* name_;
654   // ELF header parameters.
655   int machine_;
656   int size_;
657   int big_endian_;
658   int osabi_;
659   int abiversion_;
660   // The output file descriptor.
661   FILE* fd_;
662   // Next available file offset.
663   off_t next_file_offset_;
664   // The number of sections.
665   unsigned int shnum_;
666   // Section table. The first entry is shndx 1.
667   std::vector<Section> sections_;
668   // Section id map. This maps a DW_SECT enum to an shndx.
669   std::vector<unsigned int> section_id_map_;
670   // File offset of the section header table.
671   off_t shoff_;
672   // Section index of the section string table.
673   unsigned int shstrndx_;
674   // TRUE if we have added any strings to the string pool.
675   bool have_strings_;
676   // String pool for the output .debug_str.dwo section.
677   Stringpool stringpool_;
678   // String pool for the .shstrtab section.
679   Stringpool shstrtab_;
680   // The compilation unit index.
681   Dwp_index cu_index_;
682   // The type unit index.
683   Dwp_index tu_index_;
684   // Cache of the last type signature looked up.
685   uint64_t last_type_sig_;
686   // Cache of the slot index for the last type signature.
687   unsigned int last_tu_slot_;
688 };
689
690 // A specialization of Dwarf_info_reader, for reading dwo_names from
691 // DWARF CUs.
692
693 class Dwo_name_info_reader : public Dwarf_info_reader
694 {
695  public:
696   Dwo_name_info_reader(Relobj* object, unsigned int shndx)
697     : Dwarf_info_reader(false, object, NULL, 0, shndx, 0, 0),
698       files_(NULL)
699   { }
700
701   ~Dwo_name_info_reader()
702   { }
703
704   // Get the dwo_names from the DWARF compilation unit DIEs.
705   void
706   get_dwo_names(File_list* files)
707   { 
708     this->files_ = files;
709     this->parse();
710   }
711
712  protected:
713   // Visit a compilation unit.
714   virtual void
715   visit_compilation_unit(off_t cu_offset, off_t cu_length, Dwarf_die*);
716
717  private:
718   // The list of files to populate.
719   File_list* files_;
720 };
721
722 // A specialization of Dwarf_info_reader, for reading DWARF CUs and TUs
723 // and adding them to the output file.
724
725 class Unit_reader : public Dwarf_info_reader
726 {
727  public:
728   Unit_reader(bool is_type_unit, Relobj* object, unsigned int shndx)
729     : Dwarf_info_reader(is_type_unit, object, NULL, 0, shndx, 0, 0),
730       output_file_(NULL), sections_(NULL)
731   { }
732
733   ~Unit_reader()
734   { }
735
736   // Read the CUs or TUs and add them to the output file.
737   void
738   add_units(Dwp_output_file*, unsigned int debug_abbrev, Section_bounds*);
739
740  protected:
741   // Visit a compilation unit.
742   virtual void
743   visit_compilation_unit(off_t cu_offset, off_t cu_length, Dwarf_die*);
744
745   // Visit a type unit.
746   virtual void
747   visit_type_unit(off_t tu_offset, off_t tu_length, off_t type_offset,
748                   uint64_t signature, Dwarf_die*);
749
750  private:
751   Dwp_output_file* output_file_;
752   Section_bounds* sections_;
753 };
754
755 // Return the name of a DWARF .dwo section.
756
757 static const char*
758 get_dwarf_section_name(elfcpp::DW_SECT section_id)
759 {
760   static const char* dwarf_section_names[] = {
761     NULL, // unused
762     ".debug_info.dwo",         // DW_SECT_INFO = 1
763     ".debug_types.dwo",        // DW_SECT_TYPES = 2
764     ".debug_abbrev.dwo",       // DW_SECT_ABBREV = 3
765     ".debug_line.dwo",         // DW_SECT_LINE = 4
766     ".debug_loc.dwo",          // DW_SECT_LOC = 5
767     ".debug_str_offsets.dwo",  // DW_SECT_STR_OFFSETS = 6
768     ".debug_macinfo.dwo",      // DW_SECT_MACINFO = 7
769     ".debug_macro.dwo",        // DW_SECT_MACRO = 8
770   };
771
772   gold_assert(section_id > 0 && section_id <= elfcpp::DW_SECT_MAX);
773   return dwarf_section_names[section_id];
774 }
775
776 // Class Sized_relobj_dwo.
777
778 // Setup the section information.
779
780 template <int size, bool big_endian>
781 void
782 Sized_relobj_dwo<size, big_endian>::setup()
783 {
784   const unsigned int shnum = this->elf_file_.shnum();
785   this->set_shnum(shnum);
786   this->section_offsets().resize(shnum);
787 }
788
789 // Return a view of the contents of a section.
790
791 template <int size, bool big_endian>
792 const unsigned char*
793 Sized_relobj_dwo<size, big_endian>::do_section_contents(
794     unsigned int shndx,
795     section_size_type* plen,
796     bool cache)
797 {
798   Object::Location loc(this->elf_file_.section_contents(shndx));
799   *plen = convert_to_section_size_type(loc.data_size);
800   if (*plen == 0)
801     {
802       static const unsigned char empty[1] = { '\0' };
803       return empty;
804     }
805   return this->get_view(loc.file_offset, *plen, true, cache);
806 }
807
808 // Return a view of the uncompressed contents of a section.  Set *PLEN
809 // to the size.  Set *IS_NEW to true if the contents need to be deleted
810 // by the caller.
811
812 template <int size, bool big_endian>
813 const unsigned char*
814 Sized_relobj_dwo<size, big_endian>::do_decompressed_section_contents(
815     unsigned int shndx,
816     section_size_type* plen,
817     bool* is_new)
818 {
819   section_size_type buffer_size;
820   const unsigned char* buffer = this->do_section_contents(shndx, &buffer_size,
821                                                           false);
822
823   std::string sect_name = this->do_section_name(shndx);
824   if (!is_prefix_of(".zdebug_", sect_name.c_str()))
825     {
826       *plen = buffer_size;
827       *is_new = false;
828       return buffer;
829     }
830
831   section_size_type uncompressed_size = get_uncompressed_size(buffer,
832                                                               buffer_size);
833   unsigned char* uncompressed_data = new unsigned char[uncompressed_size];
834   if (!decompress_input_section(buffer,
835                                 buffer_size,
836                                 uncompressed_data,
837                                 uncompressed_size))
838     this->error(_("could not decompress section %s"),
839                 this->section_name(shndx).c_str());
840   *plen = uncompressed_size;
841   *is_new = true;
842   return uncompressed_data;
843 }
844
845 // Class Dwo_file.
846
847 Dwo_file::~Dwo_file()
848 {
849   if (this->obj_ != NULL)
850     delete this->obj_;
851   if (this->input_file_ != NULL)
852     delete this->input_file_;
853 }
854
855 // Read the input executable file and extract the list of .dwo files
856 // that it references.
857
858 void
859 Dwo_file::read_executable(File_list* files)
860 {
861   this->obj_ = this->make_object(NULL);
862
863   unsigned int shnum = this->shnum();
864   this->is_compressed_.resize(shnum);
865   this->sect_offsets_.resize(shnum);
866
867   unsigned int debug_info = 0;
868   unsigned int debug_abbrev = 0;
869
870   // Scan the section table and collect the debug sections we need.
871   // (Section index 0 is a dummy section; skip it.)
872   for (unsigned int i = 1; i < shnum; i++)
873     {
874       if (this->section_type(i) != elfcpp::SHT_PROGBITS)
875         continue;
876       std::string sect_name = this->section_name(i);
877       const char* suffix = sect_name.c_str();
878       if (is_prefix_of(".debug_", suffix))
879         suffix += 7;
880       else if (is_prefix_of(".zdebug_", suffix))
881         {
882           this->is_compressed_[i] = true;
883           suffix += 8;
884         }
885       else
886         continue;
887       if (strcmp(suffix, "info") == 0)
888         debug_info = i;
889       else if (strcmp(suffix, "abbrev") == 0)
890         debug_abbrev = i;
891     }
892
893   if (debug_info > 0)
894     {
895       Dwo_name_info_reader dwarf_reader(this->obj_, debug_info);
896       dwarf_reader.set_abbrev_shndx(debug_abbrev);
897       dwarf_reader.get_dwo_names(files);
898     }
899 }
900
901 // Read the input file and send its contents to OUTPUT_FILE.
902
903 void
904 Dwo_file::read(Dwp_output_file* output_file)
905 {
906   this->obj_ = this->make_object(output_file);
907
908   unsigned int shnum = this->shnum();
909   this->is_compressed_.resize(shnum);
910   this->sect_offsets_.resize(shnum);
911
912   typedef std::vector<unsigned int> Types_list;
913   Types_list debug_types;
914   unsigned int debug_shndx[elfcpp::DW_SECT_MAX + 1];
915   for (unsigned int i = 0; i <= elfcpp::DW_SECT_MAX; i++)
916     debug_shndx[i] = 0;
917   unsigned int debug_str = 0;
918   unsigned int debug_cu_index = 0;
919   unsigned int debug_tu_index = 0;
920
921   // Scan the section table and collect debug sections.
922   // (Section index 0 is a dummy section; skip it.)
923   for (unsigned int i = 1; i < shnum; i++)
924     {
925       if (this->section_type(i) != elfcpp::SHT_PROGBITS)
926         continue;
927       std::string sect_name = this->section_name(i);
928       const char* suffix = sect_name.c_str();
929       if (is_prefix_of(".debug_", suffix))
930         suffix += 7;
931       else if (is_prefix_of(".zdebug_", suffix))
932         {
933           this->is_compressed_[i] = true;
934           suffix += 8;
935         }
936       else
937         continue;
938       if (strcmp(suffix, "info.dwo") == 0)
939         debug_shndx[elfcpp::DW_SECT_INFO] = i;
940       else if (strcmp(suffix, "types.dwo") == 0)
941         debug_types.push_back(i);
942       else if (strcmp(suffix, "abbrev.dwo") == 0)
943         debug_shndx[elfcpp::DW_SECT_ABBREV] = i;
944       else if (strcmp(suffix, "line.dwo") == 0)
945         debug_shndx[elfcpp::DW_SECT_LINE] = i;
946       else if (strcmp(suffix, "loc.dwo") == 0)
947         debug_shndx[elfcpp::DW_SECT_LOC] = i;
948       else if (strcmp(suffix, "str.dwo") == 0)
949         debug_str = i;
950       else if (strcmp(suffix, "str_offsets.dwo") == 0)
951         debug_shndx[elfcpp::DW_SECT_STR_OFFSETS] = i;
952       else if (strcmp(suffix, "macinfo.dwo") == 0)
953         debug_shndx[elfcpp::DW_SECT_MACINFO] = i;
954       else if (strcmp(suffix, "macro.dwo") == 0)
955         debug_shndx[elfcpp::DW_SECT_MACRO] = i;
956       else if (strcmp(suffix, "cu_index") == 0)
957         debug_cu_index = i;
958       else if (strcmp(suffix, "tu_index") == 0)
959         debug_tu_index = i;
960     }
961
962   // Merge the input string table into the output string table.
963   this->add_strings(output_file, debug_str);
964
965   // If we found any .dwp index sections, read those and add the section
966   // sets to the output file.
967   if (debug_cu_index > 0 || debug_tu_index > 0)
968     {
969       if (debug_cu_index > 0)
970         this->read_unit_index(debug_cu_index, debug_shndx, output_file, false);
971       if (debug_tu_index > 0)
972         {
973           if (debug_types.size() != 1)
974             gold_fatal(_("%s: .dwp file must have exactly one "
975                          ".debug_types.dwo section"), this->name_);
976           debug_shndx[elfcpp::DW_SECT_TYPES] = debug_types[0];
977           this->read_unit_index(debug_tu_index, debug_shndx, output_file, true);
978         }
979       return;
980     }
981
982   // If we found no index sections, this is a .dwo file.
983   if (debug_shndx[elfcpp::DW_SECT_INFO] > 0)
984     this->add_unit_set(output_file, debug_shndx, false);
985
986   debug_shndx[elfcpp::DW_SECT_INFO] = 0;
987   for (Types_list::const_iterator tp = debug_types.begin();
988        tp != debug_types.end();
989        ++tp)
990     {
991       debug_shndx[elfcpp::DW_SECT_TYPES] = *tp;
992       this->add_unit_set(output_file, debug_shndx, true);
993     }
994 }
995
996 // Verify a .dwp file given a list of .dwo files referenced by the
997 // corresponding executable file.  Returns true if no problems
998 // were found.
999
1000 bool
1001 Dwo_file::verify(const File_list& files)
1002 {
1003   this->obj_ = this->make_object(NULL);
1004
1005   unsigned int shnum = this->shnum();
1006   this->is_compressed_.resize(shnum);
1007   this->sect_offsets_.resize(shnum);
1008
1009   unsigned int debug_cu_index = 0;
1010
1011   // Scan the section table and collect debug sections.
1012   // (Section index 0 is a dummy section; skip it.)
1013   for (unsigned int i = 1; i < shnum; i++)
1014     {
1015       if (this->section_type(i) != elfcpp::SHT_PROGBITS)
1016         continue;
1017       std::string sect_name = this->section_name(i);
1018       const char* suffix = sect_name.c_str();
1019       if (is_prefix_of(".debug_", suffix))
1020         suffix += 7;
1021       else if (is_prefix_of(".zdebug_", suffix))
1022         {
1023           this->is_compressed_[i] = true;
1024           suffix += 8;
1025         }
1026       else
1027         continue;
1028       if (strcmp(suffix, "cu_index") == 0)
1029         debug_cu_index = i;
1030     }
1031
1032   if (debug_cu_index == 0)
1033     gold_fatal(_("%s: no .debug_cu_index section found"), this->name_);
1034
1035   return this->verify_dwo_list(debug_cu_index, files);
1036 }
1037
1038 // Create a Sized_relobj_dwo of the given size and endianness,
1039 // and record the target info.
1040
1041 Relobj*
1042 Dwo_file::make_object(Dwp_output_file* output_file)
1043 {
1044   // Open the input file.
1045   Input_file* input_file = new Input_file(this->name_);
1046   this->input_file_ = input_file;
1047   Dirsearch dirpath;
1048   int index;
1049   if (!input_file->open(dirpath, NULL, &index))
1050     gold_fatal(_("%s: can't open"), this->name_);
1051   
1052   // Check that it's an ELF file.
1053   off_t filesize = input_file->file().filesize();
1054   int hdrsize = elfcpp::Elf_recognizer::max_header_size;
1055   if (filesize < hdrsize)
1056     hdrsize = filesize;
1057   const unsigned char* elf_header =
1058       input_file->file().get_view(0, 0, hdrsize, true, false);
1059   if (!elfcpp::Elf_recognizer::is_elf_file(elf_header, hdrsize))
1060     gold_fatal(_("%s: not an ELF object file"), this->name_);
1061   
1062   // Get the size, endianness, machine, etc. info from the header,
1063   // make an appropriately-sized Relobj, and pass the target info
1064   // to the output object.
1065   int size;
1066   bool big_endian;
1067   std::string error;
1068   if (!elfcpp::Elf_recognizer::is_valid_header(elf_header, hdrsize, &size,
1069                                                &big_endian, &error))
1070     gold_fatal(_("%s: %s"), this->name_, error.c_str());
1071
1072   if (size == 32)
1073     {
1074       if (big_endian)
1075 #ifdef HAVE_TARGET_32_BIG
1076         return this->sized_make_object<32, true>(elf_header, input_file,
1077                                                  output_file);
1078 #else
1079         gold_unreachable();
1080 #endif
1081       else
1082 #ifdef HAVE_TARGET_32_LITTLE
1083         return this->sized_make_object<32, false>(elf_header, input_file,
1084                                                   output_file);
1085 #else
1086         gold_unreachable();
1087 #endif
1088     }
1089   else if (size == 64)
1090     {
1091       if (big_endian)
1092 #ifdef HAVE_TARGET_64_BIG
1093         return this->sized_make_object<64, true>(elf_header, input_file,
1094                                                  output_file);
1095 #else
1096         gold_unreachable();
1097 #endif
1098       else
1099 #ifdef HAVE_TARGET_64_LITTLE
1100         return this->sized_make_object<64, false>(elf_header, input_file,
1101                                                   output_file);
1102 #else
1103         gold_unreachable();
1104 #endif
1105     }
1106   else
1107     gold_unreachable();
1108 }
1109
1110 // Function template to create a Sized_relobj_dwo and record the target info.
1111 // P is a pointer to the ELF header in memory.
1112
1113 template <int size, bool big_endian>
1114 Relobj*
1115 Dwo_file::sized_make_object(const unsigned char* p, Input_file* input_file,
1116                             Dwp_output_file* output_file)
1117 {
1118   elfcpp::Ehdr<size, big_endian> ehdr(p);
1119   Sized_relobj_dwo<size, big_endian>* obj =
1120       new Sized_relobj_dwo<size, big_endian>(this->name_, input_file, ehdr);
1121   obj->setup();
1122   if (output_file != NULL)
1123     output_file->record_target_info(
1124         this->name_, ehdr.get_e_machine(), size, big_endian,
1125         ehdr.get_e_ident()[elfcpp::EI_OSABI],
1126         ehdr.get_e_ident()[elfcpp::EI_ABIVERSION]);
1127   return obj;
1128 }
1129
1130 // Read the .debug_cu_index or .debug_tu_index section of a .dwp file,
1131 // and process the CU or TU sets.
1132
1133 void
1134 Dwo_file::read_unit_index(unsigned int shndx, unsigned int *debug_shndx,
1135                           Dwp_output_file* output_file, bool is_tu_index)
1136 {
1137   if (this->obj_->is_big_endian())
1138     this->sized_read_unit_index<true>(shndx, debug_shndx, output_file,
1139                                       is_tu_index);
1140   else
1141     this->sized_read_unit_index<false>(shndx, debug_shndx, output_file,
1142                                        is_tu_index);
1143 }
1144
1145 template <bool big_endian>
1146 void
1147 Dwo_file::sized_read_unit_index(unsigned int shndx,
1148                                 unsigned int *debug_shndx,
1149                                 Dwp_output_file* output_file,
1150                                 bool is_tu_index)
1151 {
1152   elfcpp::DW_SECT info_sect = (is_tu_index
1153                                ? elfcpp::DW_SECT_TYPES
1154                                : elfcpp::DW_SECT_INFO);
1155   unsigned int info_shndx = debug_shndx[info_sect];
1156
1157   gold_assert(shndx > 0 && info_shndx > 0);
1158
1159   section_size_type index_len;
1160   bool index_is_new;
1161   const unsigned char* contents =
1162       this->section_contents(shndx, &index_len, &index_is_new);
1163
1164   unsigned int version =
1165       elfcpp::Swap_unaligned<32, big_endian>::readval(contents);
1166
1167   // We don't support version 1 anymore because it was experimental
1168   // and because in normal use, dwp is not expected to read .dwp files
1169   // produced by an earlier version of the tool.
1170   if (version != 2)
1171     gold_fatal(_("%s: section %s has unsupported version number %d"),
1172                this->name_, this->section_name(shndx).c_str(), version);
1173
1174   unsigned int ncols =
1175       elfcpp::Swap_unaligned<32, big_endian>::readval(contents
1176                                                       + sizeof(uint32_t));
1177   unsigned int nused =
1178       elfcpp::Swap_unaligned<32, big_endian>::readval(contents
1179                                                       + 2 * sizeof(uint32_t));
1180   if (ncols == 0 || nused == 0)
1181     return;
1182
1183   unsigned int nslots =
1184       elfcpp::Swap_unaligned<32, big_endian>::readval(contents
1185                                                       + 3 * sizeof(uint32_t));
1186
1187   const unsigned char* phash = contents + 4 * sizeof(uint32_t);
1188   const unsigned char* pindex = phash + nslots * sizeof(uint64_t);
1189   const unsigned char* pcolhdrs = pindex + nslots * sizeof(uint32_t);
1190   const unsigned char* poffsets = pcolhdrs + ncols * sizeof(uint32_t);
1191   const unsigned char* psizes = poffsets + nused * ncols * sizeof(uint32_t);
1192   const unsigned char* pend = psizes + nused * ncols * sizeof(uint32_t);
1193
1194   if (pend > contents + index_len)
1195     gold_fatal(_("%s: section %s is corrupt"), this->name_,
1196                this->section_name(shndx).c_str());
1197
1198   // Copy the related sections and track the section offsets and sizes.
1199   Section_bounds sections[elfcpp::DW_SECT_MAX + 1];
1200   for (int i = elfcpp::DW_SECT_ABBREV; i <= elfcpp::DW_SECT_MAX; ++i)
1201     {
1202       if (debug_shndx[i] > 0)
1203         sections[i] = this->copy_section(output_file, debug_shndx[i],
1204                                          static_cast<elfcpp::DW_SECT>(i));
1205     }
1206
1207   // Get the contents of the .debug_info.dwo or .debug_types.dwo section.
1208   section_size_type info_len;
1209   bool info_is_new;
1210   const unsigned char* info_contents =
1211       this->section_contents(info_shndx, &info_len, &info_is_new);
1212
1213   // Loop over the slots of the hash table.
1214   for (unsigned int i = 0; i < nslots; ++i)
1215     {
1216       uint64_t signature =
1217           elfcpp::Swap_unaligned<64, big_endian>::readval(phash);
1218       unsigned int index =
1219           elfcpp::Swap_unaligned<32, big_endian>::readval(pindex);
1220       if (index != 0 && (!is_tu_index || !output_file->lookup_tu(signature)))
1221         {
1222           Unit_set* unit_set = new Unit_set();
1223           unit_set->signature = signature;
1224           const unsigned char* pch = pcolhdrs;
1225           const unsigned char* porow =
1226               poffsets + (index - 1) * ncols * sizeof(uint32_t);
1227           const unsigned char* psrow =
1228               psizes + (index - 1) * ncols * sizeof(uint32_t);
1229
1230           // Adjust the offset of each contribution within the input section
1231           // by the offset of the input section within the output section.
1232           for (unsigned int j = 0; j <= ncols; j++)
1233             {
1234               unsigned int dw_sect =
1235                   elfcpp::Swap_unaligned<64, big_endian>::readval(pch);
1236               unsigned int offset =
1237                   elfcpp::Swap_unaligned<64, big_endian>::readval(porow);
1238               unsigned int size =
1239                   elfcpp::Swap_unaligned<64, big_endian>::readval(psrow);
1240               unit_set->sections[dw_sect].offset = (sections[dw_sect].offset
1241                                                     + offset);
1242               unit_set->sections[dw_sect].size = size;
1243               pch += sizeof(uint32_t);
1244               porow += sizeof(uint32_t);
1245               psrow += sizeof(uint32_t);
1246             }
1247
1248           const unsigned char* unit_start =
1249               info_contents + unit_set->sections[info_sect].offset;
1250           section_size_type unit_length = unit_set->sections[info_sect].size;
1251
1252           // Dwp_output_file::add_contribution writes the .debug_info.dwo
1253           // section directly to the output file, so we only need to
1254           // duplicate contributions for .debug_types.dwo section.
1255           if (is_tu_index)
1256             {
1257               unsigned char *copy = new unsigned char[unit_length];
1258               memcpy(copy, unit_start, unit_length);
1259               unit_start = copy;
1260             }
1261           section_offset_type off =
1262               output_file->add_contribution(info_sect, unit_start,
1263                                             unit_length, 1);
1264           unit_set->sections[info_sect].offset = off;
1265           if (is_tu_index)
1266             output_file->add_tu_set(unit_set);
1267           else
1268             output_file->add_cu_set(unit_set);
1269         }
1270       phash += sizeof(uint64_t);
1271       pindex += sizeof(uint32_t);
1272     }
1273
1274   if (index_is_new)
1275     delete[] contents;
1276   if (info_is_new)
1277     delete[] info_contents;
1278 }
1279
1280 // Verify the .debug_cu_index section of a .dwp file, comparing it
1281 // against the list of .dwo files referenced by the corresponding
1282 // executable file.
1283
1284 bool
1285 Dwo_file::verify_dwo_list(unsigned int shndx, const File_list& files)
1286 {
1287   if (this->obj_->is_big_endian())
1288     return this->sized_verify_dwo_list<true>(shndx, files);
1289   else
1290     return this->sized_verify_dwo_list<false>(shndx, files);
1291 }
1292
1293 template <bool big_endian>
1294 bool
1295 Dwo_file::sized_verify_dwo_list(unsigned int shndx, const File_list& files)
1296 {
1297   gold_assert(shndx > 0);
1298
1299   section_size_type index_len;
1300   bool index_is_new;
1301   const unsigned char* contents =
1302       this->section_contents(shndx, &index_len, &index_is_new);
1303
1304   unsigned int version =
1305       elfcpp::Swap_unaligned<32, big_endian>::readval(contents);
1306
1307   // We don't support version 1 anymore because it was experimental
1308   // and because in normal use, dwp is not expected to read .dwp files
1309   // produced by an earlier version of the tool.
1310   if (version != 2)
1311     gold_fatal(_("%s: section %s has unsupported version number %d"),
1312                this->name_, this->section_name(shndx).c_str(), version);
1313
1314   unsigned int ncols =
1315       elfcpp::Swap_unaligned<32, big_endian>::readval(contents
1316                                                       + sizeof(uint32_t));
1317   unsigned int nused =
1318       elfcpp::Swap_unaligned<32, big_endian>::readval(contents
1319                                                       + 2 * sizeof(uint32_t));
1320   if (ncols == 0 || nused == 0)
1321     return true;
1322
1323   unsigned int nslots =
1324       elfcpp::Swap_unaligned<32, big_endian>::readval(contents
1325                                                       + 3 * sizeof(uint32_t));
1326
1327   const unsigned char* phash = contents + 4 * sizeof(uint32_t);
1328   const unsigned char* pindex = phash + nslots * sizeof(uint64_t);
1329   const unsigned char* pcolhdrs = pindex + nslots * sizeof(uint32_t);
1330   const unsigned char* poffsets = pcolhdrs + ncols * sizeof(uint32_t);
1331   const unsigned char* psizes = poffsets + nused * ncols * sizeof(uint32_t);
1332   const unsigned char* pend = psizes + nused * ncols * sizeof(uint32_t);
1333
1334   if (pend > contents + index_len)
1335     gold_fatal(_("%s: section %s is corrupt"), this->name_,
1336                this->section_name(shndx).c_str());
1337
1338   int nmissing = 0;
1339   for (File_list::const_iterator f = files.begin(); f != files.end(); ++f)
1340     {
1341       uint64_t dwo_id = f->dwo_id;
1342       unsigned int slot = static_cast<unsigned int>(dwo_id) & (nslots - 1);
1343       const unsigned char* ph = phash + slot * sizeof(uint64_t);
1344       const unsigned char* pi = pindex + slot * sizeof(uint32_t);
1345       uint64_t probe = elfcpp::Swap_unaligned<64, big_endian>::readval(ph);
1346       uint32_t row_index = elfcpp::Swap_unaligned<32, big_endian>::readval(pi);
1347       if (row_index != 0 && probe != dwo_id)
1348         {
1349           unsigned int h2 = ((static_cast<unsigned int>(dwo_id >> 32)
1350                               & (nslots - 1)) | 1);
1351           do
1352             {
1353               slot = (slot + h2) & (nslots - 1);
1354               ph = phash + slot * sizeof(uint64_t);
1355               pi = pindex + slot * sizeof(uint32_t);
1356               probe = elfcpp::Swap_unaligned<64, big_endian>::readval(ph);
1357               row_index = elfcpp::Swap_unaligned<32, big_endian>::readval(pi);
1358             } while (row_index != 0 && probe != dwo_id);
1359         }
1360       if (row_index == 0)
1361         {
1362           printf(_("missing .dwo file: %016llx %s\n"),
1363                  static_cast<long long>(dwo_id), f->dwo_name.c_str());
1364           ++nmissing;
1365         }
1366     }
1367
1368   gold_info(_("Found %d missing .dwo files"), nmissing);
1369
1370   if (index_is_new)
1371     delete[] contents;
1372
1373   return nmissing == 0;
1374 }
1375
1376 // Merge the input string table section into the output file.
1377
1378 void
1379 Dwo_file::add_strings(Dwp_output_file* output_file, unsigned int debug_str)
1380 {
1381   section_size_type len;
1382   bool is_new;
1383   const unsigned char* pdata = this->section_contents(debug_str, &len, &is_new);
1384   const char* p = reinterpret_cast<const char*>(pdata);
1385   const char* pend = p + len;
1386
1387   // Check that the last string is null terminated.
1388   if (pend[-1] != '\0')
1389     gold_fatal(_("%s: last entry in string section '%s' "
1390                  "is not null terminated"),
1391                this->name_,
1392                this->section_name(debug_str).c_str());
1393
1394   // Count the number of strings in the section, and size the map.
1395   size_t count = 0;
1396   for (const char* pt = p; pt < pend; pt += strlen(pt) + 1)
1397     ++count;
1398   this->str_offset_map_.reserve(count + 1);
1399
1400   // Add the strings to the output string table, and record the new offsets
1401   // in the map.
1402   section_offset_type i = 0;
1403   section_offset_type new_offset;
1404   while (p < pend)
1405     {
1406       size_t len = strlen(p);
1407       new_offset = output_file->add_string(p, len);
1408       this->str_offset_map_.push_back(std::make_pair(i, new_offset));
1409       p += len + 1;
1410       i += len + 1;
1411     }
1412   new_offset = 0;
1413   this->str_offset_map_.push_back(std::make_pair(i, new_offset));
1414   if (is_new)
1415     delete[] pdata;
1416 }
1417
1418 // Copy a section from the input file to the output file.
1419 // Return the offset and length of this input section's contribution
1420 // in the output section.  If copying .debug_str_offsets.dwo, remap
1421 // the string offsets for the output string table.
1422
1423 Section_bounds
1424 Dwo_file::copy_section(Dwp_output_file* output_file, unsigned int shndx,
1425                        elfcpp::DW_SECT section_id)
1426 {
1427   // Some sections may be referenced from more than one set.
1428   // Don't copy a section more than once.
1429   if (this->sect_offsets_[shndx].size > 0)
1430     return this->sect_offsets_[shndx];
1431
1432   // Get the section contents. Upon return, if IS_NEW is true, the memory
1433   // has been allocated via new; if false, the memory is part of the mapped
1434   // input file, and we will need to duplicate it so that it will persist
1435   // after we close the input file.
1436   section_size_type len;
1437   bool is_new;
1438   const unsigned char* contents = this->section_contents(shndx, &len, &is_new);
1439
1440   if (section_id == elfcpp::DW_SECT_STR_OFFSETS)
1441     {
1442       const unsigned char* remapped = this->remap_str_offsets(contents, len);
1443       if (is_new)
1444         delete[] contents;
1445       contents = remapped;
1446     }
1447   else if (!is_new)
1448     {
1449       unsigned char* copy = new unsigned char[len];
1450       memcpy(copy, contents, len);
1451       contents = copy;
1452     }
1453
1454   // Add the contents of the input section to the output section.
1455   // The output file takes ownership of the memory pointed to by CONTENTS.
1456   section_offset_type off = output_file->add_contribution(section_id, contents,
1457                                                           len, 1);
1458
1459   // Store the output section bounds.
1460   Section_bounds bounds(off, len);
1461   this->sect_offsets_[shndx] = bounds;
1462
1463   return bounds;
1464 }
1465
1466 // Remap the 
1467 const unsigned char*
1468 Dwo_file::remap_str_offsets(const unsigned char* contents,
1469                             section_size_type len)
1470 {
1471   if ((len & 3) != 0)
1472     gold_fatal(_("%s: .debug_str_offsets.dwo section size not a multiple of 4"),
1473                this->name_);
1474
1475   if (this->obj_->is_big_endian())
1476     return this->sized_remap_str_offsets<true>(contents, len);
1477   else
1478     return this->sized_remap_str_offsets<false>(contents, len);
1479 }
1480
1481 template <bool big_endian>
1482 const unsigned char*
1483 Dwo_file::sized_remap_str_offsets(const unsigned char* contents,
1484                                   section_size_type len)
1485 {
1486   unsigned char* remapped = new unsigned char[len];
1487   const unsigned char* p = contents;
1488   unsigned char* q = remapped;
1489   while (len > 0)
1490     {
1491       unsigned int val = elfcpp::Swap_unaligned<32, big_endian>::readval(p);
1492       val = this->remap_str_offset(val);
1493       elfcpp::Swap_unaligned<32, big_endian>::writeval(q, val);
1494       len -= 4;
1495       p += 4;
1496       q += 4;
1497     }
1498   return remapped;
1499 }
1500
1501 unsigned int
1502 Dwo_file::remap_str_offset(section_offset_type val)
1503 {
1504   Str_offset_map_entry entry;
1505   entry.first = val;
1506
1507   Str_offset_map::const_iterator p =
1508       std::lower_bound(this->str_offset_map_.begin(),
1509                        this->str_offset_map_.end(),
1510                        entry, Offset_compare());
1511
1512   if (p == this->str_offset_map_.end() || p->first > val)
1513     {
1514       if (p == this->str_offset_map_.begin())
1515         return 0;
1516       --p;
1517       gold_assert(p->first <= val);
1518     }
1519
1520   return p->second + (val - p->first);
1521 }
1522
1523 // Add a set of .debug_info.dwo or .debug_types.dwo and related sections
1524 // to OUTPUT_FILE.
1525
1526 void
1527 Dwo_file::add_unit_set(Dwp_output_file* output_file, unsigned int *debug_shndx,
1528                        bool is_debug_types)
1529 {
1530   unsigned int shndx = (is_debug_types
1531                         ? debug_shndx[elfcpp::DW_SECT_TYPES]
1532                         : debug_shndx[elfcpp::DW_SECT_INFO]);
1533
1534   gold_assert(shndx != 0);
1535
1536   if (debug_shndx[elfcpp::DW_SECT_ABBREV] == 0)
1537     gold_fatal(_("%s: no .debug_abbrev.dwo section found"), this->name_);
1538
1539   // Copy the related sections and track the section offsets and sizes.
1540   Section_bounds sections[elfcpp::DW_SECT_MAX + 1];
1541   for (int i = elfcpp::DW_SECT_ABBREV; i <= elfcpp::DW_SECT_MAX; ++i)
1542     {
1543       if (debug_shndx[i] > 0)
1544         sections[i] = this->copy_section(output_file, debug_shndx[i],
1545                                          static_cast<elfcpp::DW_SECT>(i));
1546     }
1547
1548   // Parse the .debug_info or .debug_types section and add each compilation
1549   // or type unit to the output file, along with the contributions to the
1550   // related sections.
1551   Unit_reader reader(is_debug_types, this->obj_, shndx);
1552   reader.add_units(output_file, debug_shndx[elfcpp::DW_SECT_ABBREV], sections);
1553 }
1554
1555 // Class Dwp_output_file.
1556
1557 // Record the target info from an input file.  On first call, we
1558 // set the ELF header values for the output file.  On subsequent
1559 // calls, we just verify that the values match.
1560
1561 void
1562 Dwp_output_file::record_target_info(const char*, int machine,
1563                                     int size, bool big_endian,
1564                                     int osabi, int abiversion)
1565 {
1566   // TODO: Check the values on subsequent calls.
1567   if (this->size_ > 0)
1568     return;
1569
1570   this->machine_ = machine;
1571   this->size_ = size;
1572   this->big_endian_ = big_endian;
1573   this->osabi_ = osabi;
1574   this->abiversion_ = abiversion;
1575
1576   if (size == 32)
1577     this->next_file_offset_ = elfcpp::Elf_sizes<32>::ehdr_size;
1578   else if (size == 64)
1579     this->next_file_offset_ = elfcpp::Elf_sizes<64>::ehdr_size;
1580   else
1581     gold_unreachable();
1582
1583   this->fd_ = ::fopen(this->name_, "wb");
1584   if (this->fd_ == NULL)
1585     gold_fatal(_("%s: %s"), this->name_, strerror(errno));
1586
1587   // Write zeroes for the ELF header initially.  We'll write
1588   // the actual header during finalize().
1589   static const char buf[elfcpp::Elf_sizes<64>::ehdr_size] = { 0 };
1590   if (::fwrite(buf, 1, this->next_file_offset_, this->fd_)
1591       < (size_t) this->next_file_offset_)
1592     gold_fatal(_("%s: %s"), this->name_, strerror(errno));
1593 }
1594
1595 // Add a string to the debug strings section.
1596
1597 section_offset_type
1598 Dwp_output_file::add_string(const char* str, size_t len)
1599 {
1600   Stringpool::Key key;
1601   this->stringpool_.add_with_length(str, len, true, &key);
1602   this->have_strings_ = true;
1603   // We aren't supposed to call get_offset() until after
1604   // calling set_string_offsets(), but the offsets will
1605   // not change unless optimizing the string pool.
1606   return this->stringpool_.get_offset_from_key(key);
1607 }
1608
1609 // Align the file offset to the given boundary.
1610
1611 static inline off_t
1612 align_offset(off_t off, int align)
1613 {
1614   return (off + align - 1) & ~(align - 1);
1615 }
1616
1617 // Add a new output section and return the section index.
1618
1619 unsigned int
1620 Dwp_output_file::add_output_section(const char* section_name, int align)
1621 {
1622   Section sect(section_name, align);
1623   this->sections_.push_back(sect);
1624   return this->shnum_++;
1625 }
1626
1627 // Add a contribution to a section in the output file, and return the offset
1628 // of the contribution within the output section.  The .debug_info.dwo section
1629 // is expected to be the largest one, so we will write the contents of this
1630 // section directly to the output file as we receive contributions, allowing
1631 // us to free that memory as soon as possible. We will save the remaining
1632 // contributions until we finalize the layout of the output file.
1633
1634 section_offset_type
1635 Dwp_output_file::add_contribution(elfcpp::DW_SECT section_id,
1636                                   const unsigned char* contents,
1637                                   section_size_type len,
1638                                   int align)
1639 {
1640   const char* section_name = get_dwarf_section_name(section_id);
1641   gold_assert(static_cast<size_t>(section_id) < this->section_id_map_.size());
1642   unsigned int shndx = this->section_id_map_[section_id];
1643
1644   // Create the section if necessary.
1645   if (shndx == 0)
1646     {
1647       section_name = this->shstrtab_.add_with_length(section_name,
1648                                                      strlen(section_name),
1649                                                      false, NULL);
1650       shndx = this->add_output_section(section_name, align);
1651       this->section_id_map_[section_id] = shndx;
1652     }
1653
1654   Section& section = this->sections_[shndx - 1];
1655
1656   section_offset_type section_offset;
1657
1658   if (section_id == elfcpp::DW_SECT_INFO)
1659     {
1660       // Write the .debug_info.dwo section directly.
1661       // We do not need to free the memory in this case.
1662       off_t file_offset = this->next_file_offset_;
1663       gold_assert(this->size_ > 0 && file_offset > 0);
1664
1665       file_offset = align_offset(file_offset, align);
1666       if (section.offset == 0)
1667         section.offset = file_offset;
1668
1669       if (align > section.align)
1670         {
1671           // Since we've already committed to the layout for this
1672           // section, an unexpected large alignment boundary may
1673           // be impossible to honor.
1674           if (align_offset(section.offset, align) != section.offset)
1675             gold_fatal(_("%s: alignment (%d) for section '%s' "
1676                          "cannot be honored"),
1677                        this->name_, align, section_name);
1678           section.align = align;
1679         }
1680
1681       section_offset = file_offset - section.offset;
1682       section.size = file_offset + len - section.offset;
1683
1684       ::fseek(this->fd_, file_offset, SEEK_SET);
1685       if (::fwrite(contents, 1, len, this->fd_) < len)
1686         gold_fatal(_("%s: error writing section '%s'"), this->name_,
1687                    section_name);
1688       this->next_file_offset_ = file_offset + len;
1689     }
1690   else
1691     {
1692       // Collect the contributions and keep track of the total size.
1693       if (align > section.align)
1694         section.align = align;
1695       section_offset = align_offset(section.size, align);
1696       section.size = section_offset + len;
1697       Contribution contrib = { section_offset, len, contents };
1698       section.contributions.push_back(contrib);
1699     }
1700
1701   return section_offset;
1702 }
1703
1704 // Add a set of .debug_info and related sections to the output file.
1705
1706 void
1707 Dwp_output_file::add_cu_set(Unit_set* cu_set)
1708 {
1709   uint64_t dwo_id = cu_set->signature;
1710   unsigned int slot;
1711   if (!this->cu_index_.find_or_add(dwo_id, &slot))
1712     this->cu_index_.enter_set(slot, cu_set);
1713   else
1714     gold_warning(_("%s: duplicate entry for CU (dwo_id 0x%llx)"),
1715                  this->name_, (unsigned long long)dwo_id);
1716 }
1717
1718 // Lookup a type signature and return TRUE if we have already seen it.
1719 bool
1720 Dwp_output_file::lookup_tu(uint64_t type_sig)
1721 {
1722   this->last_type_sig_ = type_sig;
1723   return this->tu_index_.find_or_add(type_sig, &this->last_tu_slot_);
1724 }
1725
1726 // Add a set of .debug_types and related sections to the output file.
1727
1728 void
1729 Dwp_output_file::add_tu_set(Unit_set* tu_set)
1730 {
1731   uint64_t type_sig = tu_set->signature;
1732   unsigned int slot;
1733   if (type_sig == this->last_type_sig_)
1734     slot = this->last_tu_slot_;
1735   else
1736     this->tu_index_.find_or_add(type_sig, &slot);
1737   this->tu_index_.enter_set(slot, tu_set);
1738 }
1739
1740 // Find a slot in the hash table for SIGNATURE.  Return TRUE
1741 // if the entry already exists.
1742
1743 bool
1744 Dwp_output_file::Dwp_index::find_or_add(uint64_t signature,
1745                                         unsigned int* slotp)
1746 {
1747   if (this->capacity_ == 0)
1748     this->initialize();
1749   unsigned int slot =
1750       static_cast<unsigned int>(signature) & (this->capacity_ - 1);
1751   unsigned int secondary_hash;
1752   uint64_t probe = this->hash_table_[slot];
1753   uint32_t row_index = this->index_table_[slot];
1754   if (row_index != 0 && probe != signature)
1755     {
1756       secondary_hash = (static_cast<unsigned int>(signature >> 32)
1757                         & (this->capacity_ - 1)) | 1;
1758       do
1759         {
1760           slot = (slot + secondary_hash) & (this->capacity_ - 1);
1761           probe = this->hash_table_[slot];
1762           row_index = this->index_table_[slot];
1763         } while (row_index != 0 && probe != signature);
1764     }
1765   *slotp = slot;
1766   return (row_index != 0);
1767 }
1768
1769 // Enter a CU or TU set at the given SLOT in the hash table.
1770
1771 void
1772 Dwp_output_file::Dwp_index::enter_set(unsigned int slot,
1773                                       const Unit_set* set)
1774 {
1775   gold_assert(slot < this->capacity_);
1776
1777   // Add a row to the offsets and sizes tables.
1778   this->section_table_.push_back(set);
1779   uint32_t row_index = this->section_table_rows();
1780
1781   // Mark the sections used in this set.
1782   for (unsigned int i = 1; i <= elfcpp::DW_SECT_MAX; i++)
1783     if (set->sections[i].size > 0)
1784       this->section_mask_ |= 1 << i;
1785
1786   // Enter the signature and pool index into the hash table.
1787   gold_assert(this->hash_table_[slot] == 0);
1788   this->hash_table_[slot] = set->signature;
1789   this->index_table_[slot] = row_index;
1790   ++this->used_;
1791
1792   // Grow the hash table when we exceed 2/3 capacity.
1793   if (this->used_ * 3 > this->capacity_ * 2)
1794     this->grow();
1795 }
1796
1797 // Initialize the hash table.
1798
1799 void
1800 Dwp_output_file::Dwp_index::initialize()
1801 {
1802   this->capacity_ = 16;
1803   this->hash_table_ = new uint64_t[this->capacity_];
1804   memset(this->hash_table_, 0, this->capacity_ * sizeof(uint64_t));
1805   this->index_table_ = new uint32_t[this->capacity_];
1806   memset(this->index_table_, 0, this->capacity_ * sizeof(uint32_t));
1807 }
1808
1809 // Grow the hash table when we reach 2/3 capacity.
1810
1811 void
1812 Dwp_output_file::Dwp_index::grow()
1813 {
1814   unsigned int old_capacity = this->capacity_;
1815   uint64_t* old_hash_table = this->hash_table_;
1816   uint32_t* old_index_table = this->index_table_;
1817   unsigned int old_used = this->used_;
1818
1819   this->capacity_ = old_capacity * 2;
1820   this->hash_table_ = new uint64_t[this->capacity_];
1821   memset(this->hash_table_, 0, this->capacity_ * sizeof(uint64_t));
1822   this->index_table_ = new uint32_t[this->capacity_];
1823   memset(this->index_table_, 0, this->capacity_ * sizeof(uint32_t));
1824   this->used_ = 0;
1825
1826   for (unsigned int i = 0; i < old_capacity; ++i)
1827     {
1828       uint64_t signature = old_hash_table[i];
1829       uint32_t row_index = old_index_table[i];
1830       if (row_index != 0)
1831         {
1832           unsigned int slot;
1833           bool found = this->find_or_add(signature, &slot);
1834           gold_assert(!found);
1835           this->hash_table_[slot] = signature;
1836           this->index_table_[slot] = row_index;
1837           ++this->used_;
1838         }
1839     }
1840   gold_assert(this->used_ == old_used);
1841
1842   delete[] old_hash_table;
1843   delete[] old_index_table;
1844 }
1845
1846 // Finalize the file, write the string tables and index sections,
1847 // and close the file.
1848
1849 void
1850 Dwp_output_file::finalize()
1851 {
1852   unsigned char* buf;
1853
1854   // Write the accumulated output sections.
1855   for (unsigned int i = 0; i < this->sections_.size(); i++)
1856     {
1857       Section& sect = this->sections_[i];
1858       // If the offset has already been assigned, the section has been written.
1859       if (sect.offset > 0 || sect.size == 0)
1860         continue;
1861       off_t file_offset = this->next_file_offset_;
1862       file_offset = align_offset(file_offset, sect.align);
1863       sect.offset = file_offset;
1864       this->write_contributions(sect);
1865       this->next_file_offset_ = file_offset + sect.size;
1866     }
1867
1868   // Write the debug string table.
1869   if (this->have_strings_)
1870     {
1871       this->stringpool_.set_string_offsets();
1872       section_size_type len = this->stringpool_.get_strtab_size();
1873       buf = new unsigned char[len];
1874       this->stringpool_.write_to_buffer(buf, len);
1875       this->write_new_section(".debug_str.dwo", buf, len, 1);
1876       delete[] buf;
1877     }
1878
1879   // Write the CU and TU indexes.
1880   if (this->big_endian_)
1881     {
1882       this->write_index<true>(".debug_cu_index", this->cu_index_);
1883       this->write_index<true>(".debug_tu_index", this->tu_index_);
1884     }
1885   else
1886     {
1887       this->write_index<false>(".debug_cu_index", this->cu_index_);
1888       this->write_index<false>(".debug_tu_index", this->tu_index_);
1889     }
1890
1891   off_t file_offset = this->next_file_offset_;
1892
1893   // Write the section string table.
1894   this->shstrndx_ = this->shnum_++;
1895   const char* shstrtab_name =
1896       this->shstrtab_.add_with_length(".shstrtab", sizeof(".shstrtab") - 1,
1897                                       false, NULL);
1898   this->shstrtab_.set_string_offsets();
1899   section_size_type shstrtab_len = this->shstrtab_.get_strtab_size();
1900   buf = new unsigned char[shstrtab_len];
1901   this->shstrtab_.write_to_buffer(buf, shstrtab_len);
1902   off_t shstrtab_off = file_offset;
1903   ::fseek(this->fd_, file_offset, 0);
1904   if (::fwrite(buf, 1, shstrtab_len, this->fd_) < shstrtab_len)
1905     gold_fatal(_("%s: error writing section '.shstrtab'"), this->name_);
1906   delete[] buf;
1907   file_offset += shstrtab_len;
1908
1909   // Write the section header table.  The first entry is a NULL entry.
1910   // This is followed by the debug sections, and finally we write the
1911   // .shstrtab section header.
1912   file_offset = align_offset(file_offset, this->size_ == 32 ? 4 : 8);
1913   this->shoff_ = file_offset;
1914   ::fseek(this->fd_, file_offset, 0);
1915   section_size_type sh0_size = 0;
1916   unsigned int sh0_link = 0;
1917   if (this->shnum_ >= elfcpp::SHN_LORESERVE)
1918     sh0_size = this->shnum_;
1919   if (this->shstrndx_ >= elfcpp::SHN_LORESERVE)
1920     sh0_link = this->shstrndx_;
1921   this->write_shdr(NULL, 0, 0, 0, 0, sh0_size, sh0_link, 0, 0, 0);
1922   for (unsigned int i = 0; i < this->sections_.size(); ++i)
1923     {
1924       Section& sect = this->sections_[i];
1925       this->write_shdr(sect.name, elfcpp::SHT_PROGBITS, 0, 0, sect.offset,
1926                        sect.size, 0, 0, sect.align, 0);
1927     }
1928   this->write_shdr(shstrtab_name, elfcpp::SHT_STRTAB, 0, 0,
1929                    shstrtab_off, shstrtab_len, 0, 0, 1, 0);
1930
1931   // Write the ELF header.
1932   this->write_ehdr();
1933
1934   // Close the file.
1935   if (this->fd_ != NULL)
1936     {
1937       if (::fclose(this->fd_) != 0)
1938         gold_fatal(_("%s: %s"), this->name_, strerror(errno));
1939     }
1940   this->fd_ = NULL;
1941 }
1942
1943 // Write the contributions to an output section.
1944
1945 void
1946 Dwp_output_file::write_contributions(const Section& sect)
1947 {
1948   for (unsigned int i = 0; i < sect.contributions.size(); ++i)
1949     {
1950       const Contribution& c = sect.contributions[i];
1951       ::fseek(this->fd_, sect.offset + c.output_offset, SEEK_SET);
1952       if (::fwrite(c.contents, 1, c.size, this->fd_) < c.size)
1953         gold_fatal(_("%s: error writing section '%s'"), this->name_, sect.name);
1954       delete[] c.contents;
1955     }
1956 }
1957
1958 // Write a new section to the output file.
1959
1960 void
1961 Dwp_output_file::write_new_section(const char* section_name,
1962                                    const unsigned char* contents,
1963                                    section_size_type len, int align)
1964 {
1965   section_name = this->shstrtab_.add_with_length(section_name,
1966                                                  strlen(section_name),
1967                                                  false, NULL);
1968   unsigned int shndx = this->add_output_section(section_name, align);
1969   Section& section = this->sections_[shndx - 1];
1970   off_t file_offset = this->next_file_offset_;
1971   file_offset = align_offset(file_offset, align);
1972   section.offset = file_offset;
1973   section.size = len;
1974   ::fseek(this->fd_, file_offset, SEEK_SET);
1975   if (::fwrite(contents, 1, len, this->fd_) < len)
1976     gold_fatal(_("%s: error writing section '%s'"), this->name_, section_name);
1977   this->next_file_offset_ = file_offset + len;
1978 }
1979
1980 // Write a CU or TU index section.
1981
1982 template<bool big_endian>
1983 void
1984 Dwp_output_file::write_index(const char* sect_name, const Dwp_index& index)
1985 {
1986   const unsigned int nslots = index.hash_table_total_slots();
1987   const unsigned int nused = index.hash_table_used_slots();
1988   const unsigned int nrows = index.section_table_rows();
1989
1990   int column_mask = index.section_table_cols();
1991   unsigned int ncols = 0;
1992   for (unsigned int c = 1; c <= elfcpp::DW_SECT_MAX; ++c)
1993     if (column_mask & (1 << c))
1994       ncols++;
1995   const unsigned int ntable = (nrows * 2 + 1) * ncols;
1996
1997   const section_size_type index_size = (4 * sizeof(uint32_t)
1998                                         + nslots * sizeof(uint64_t)
1999                                         + nslots * sizeof(uint32_t)
2000                                         + ntable * sizeof(uint32_t));
2001
2002   // Allocate a buffer for the section contents.
2003   unsigned char* buf = new unsigned char[index_size];
2004   unsigned char* p = buf;
2005
2006   // Write the section header: version number, padding,
2007   // number of used slots and total number of slots.
2008   elfcpp::Swap_unaligned<32, big_endian>::writeval(p, 2);
2009   p += sizeof(uint32_t);
2010   elfcpp::Swap_unaligned<32, big_endian>::writeval(p, ncols);
2011   p += sizeof(uint32_t);
2012   elfcpp::Swap_unaligned<32, big_endian>::writeval(p, nused);
2013   p += sizeof(uint32_t);
2014   elfcpp::Swap_unaligned<32, big_endian>::writeval(p, nslots);
2015   p += sizeof(uint32_t);
2016
2017   // Write the hash table.
2018   for (unsigned int i = 0; i < nslots; ++i)
2019     {
2020       elfcpp::Swap_unaligned<64, big_endian>::writeval(p, index.hash_table(i));
2021       p += sizeof(uint64_t);
2022     }
2023
2024   // Write the parallel index table.
2025   for (unsigned int i = 0; i < nslots; ++i)
2026     {
2027       elfcpp::Swap_unaligned<32, big_endian>::writeval(p, index.index_table(i));
2028       p += sizeof(uint32_t);
2029     }
2030
2031   // Write the first row of the table of section offsets.
2032   for (unsigned int c = 1; c <= elfcpp::DW_SECT_MAX; ++c)
2033     {
2034       if (column_mask & (1 << c))
2035         {
2036           elfcpp::Swap_unaligned<32, big_endian>::writeval(p, c);
2037           p += sizeof(uint32_t);
2038         }
2039     }
2040
2041   // Write the table of section offsets.
2042   Dwp_index::Section_table::const_iterator tbl = index.section_table();
2043   for (unsigned int r = 0; r < nrows; ++r)
2044     {
2045       gold_assert(tbl != index.section_table_end());
2046       const Section_bounds* sects = (*tbl)->sections;
2047       for (unsigned int c = 1; c <= elfcpp::DW_SECT_MAX; ++c)
2048         {
2049           if (column_mask & (1 << c))
2050             {
2051               section_offset_type offset = sects[c].offset;
2052               elfcpp::Swap_unaligned<32, big_endian>::writeval(p, offset);
2053               p += sizeof(uint32_t);
2054             }
2055           else
2056             gold_assert(sects[c].size == 0);
2057         }
2058       ++tbl;
2059     }
2060
2061   // Write the table of section sizes.
2062   tbl = index.section_table();
2063   for (unsigned int r = 0; r < nrows; ++r)
2064     {
2065       gold_assert(tbl != index.section_table_end());
2066       const Section_bounds* sects = (*tbl)->sections;
2067       for (unsigned int c = 1; c <= elfcpp::DW_SECT_MAX; ++c)
2068         {
2069           if (column_mask & (1 << c))
2070             {
2071               section_size_type size = sects[c].size;
2072               elfcpp::Swap_unaligned<32, big_endian>::writeval(p, size);
2073               p += sizeof(uint32_t);
2074             }
2075           else
2076             gold_assert(sects[c].size == 0);
2077         }
2078       ++tbl;
2079     }
2080
2081   gold_assert(p == buf + index_size);
2082
2083   this->write_new_section(sect_name, buf, index_size, sizeof(uint64_t));
2084
2085   delete[] buf;
2086 }
2087
2088 // Write the ELF header.
2089
2090 void
2091 Dwp_output_file::write_ehdr()
2092 {
2093   if (this->size_ == 32)
2094     {
2095       if (this->big_endian_)
2096         return this->sized_write_ehdr<32, true>();
2097       else
2098         return this->sized_write_ehdr<32, false>();
2099     }
2100   else if (this->size_ == 64)
2101     {
2102       if (this->big_endian_)
2103         return this->sized_write_ehdr<64, true>();
2104       else
2105         return this->sized_write_ehdr<64, false>();
2106     }
2107   else
2108     gold_unreachable();
2109 }
2110
2111 template<unsigned int size, bool big_endian>
2112 void
2113 Dwp_output_file::sized_write_ehdr()
2114 {
2115   const unsigned int ehdr_size = elfcpp::Elf_sizes<size>::ehdr_size;
2116   unsigned char buf[ehdr_size];
2117   elfcpp::Ehdr_write<size, big_endian> ehdr(buf);
2118
2119   unsigned char e_ident[elfcpp::EI_NIDENT];
2120   memset(e_ident, 0, elfcpp::EI_NIDENT);
2121   e_ident[elfcpp::EI_MAG0] = elfcpp::ELFMAG0;
2122   e_ident[elfcpp::EI_MAG1] = elfcpp::ELFMAG1;
2123   e_ident[elfcpp::EI_MAG2] = elfcpp::ELFMAG2;
2124   e_ident[elfcpp::EI_MAG3] = elfcpp::ELFMAG3;
2125   if (size == 32)
2126     e_ident[elfcpp::EI_CLASS] = elfcpp::ELFCLASS32;
2127   else if (size == 64)
2128     e_ident[elfcpp::EI_CLASS] = elfcpp::ELFCLASS64;
2129   else
2130     gold_unreachable();
2131   e_ident[elfcpp::EI_DATA] = (big_endian
2132                               ? elfcpp::ELFDATA2MSB
2133                               : elfcpp::ELFDATA2LSB);
2134   e_ident[elfcpp::EI_VERSION] = elfcpp::EV_CURRENT;
2135   ehdr.put_e_ident(e_ident);
2136
2137   ehdr.put_e_type(elfcpp::ET_REL);
2138   ehdr.put_e_machine(this->machine_);
2139   ehdr.put_e_version(elfcpp::EV_CURRENT);
2140   ehdr.put_e_entry(0);
2141   ehdr.put_e_phoff(0);
2142   ehdr.put_e_shoff(this->shoff_);
2143   ehdr.put_e_flags(0);
2144   ehdr.put_e_ehsize(elfcpp::Elf_sizes<size>::ehdr_size);
2145   ehdr.put_e_phentsize(0);
2146   ehdr.put_e_phnum(0);
2147   ehdr.put_e_shentsize(elfcpp::Elf_sizes<size>::shdr_size);
2148   ehdr.put_e_shnum(this->shnum_ < elfcpp::SHN_LORESERVE ? this->shnum_ : 0);
2149   ehdr.put_e_shstrndx(this->shstrndx_ < elfcpp::SHN_LORESERVE
2150                       ? this->shstrndx_
2151                       : static_cast<unsigned int>(elfcpp::SHN_XINDEX));
2152
2153   ::fseek(this->fd_, 0, 0);
2154   if (::fwrite(buf, 1, ehdr_size, this->fd_) < ehdr_size)
2155     gold_fatal(_("%s: error writing ELF header"), this->name_);
2156 }
2157
2158 // Write a section header.
2159
2160 void
2161 Dwp_output_file::write_shdr(const char* name, unsigned int type,
2162                             unsigned int flags, uint64_t addr, off_t offset,
2163                             section_size_type sect_size, unsigned int link,
2164                             unsigned int info, unsigned int align,
2165                             unsigned int ent_size)
2166 {
2167   if (this->size_ == 32)
2168     {
2169       if (this->big_endian_)
2170         return this->sized_write_shdr<32, true>(name, type, flags, addr,
2171                                                 offset, sect_size, link, info,
2172                                                 align, ent_size);
2173       else
2174         return this->sized_write_shdr<32, false>(name, type, flags, addr,
2175                                                  offset, sect_size, link, info,
2176                                                  align, ent_size);
2177     }
2178   else if (this->size_ == 64)
2179     {
2180       if (this->big_endian_)
2181         return this->sized_write_shdr<64, true>(name, type, flags, addr,
2182                                                 offset, sect_size, link, info,
2183                                                 align, ent_size);
2184       else
2185         return this->sized_write_shdr<64, false>(name, type, flags, addr,
2186                                                  offset, sect_size, link, info,
2187                                                  align, ent_size);
2188     }
2189   else
2190     gold_unreachable();
2191 }
2192
2193 template<unsigned int size, bool big_endian>
2194 void
2195 Dwp_output_file::sized_write_shdr(const char* name, unsigned int type,
2196                                   unsigned int flags, uint64_t addr,
2197                                   off_t offset, section_size_type sect_size,
2198                                   unsigned int link, unsigned int info,
2199                                   unsigned int align, unsigned int ent_size)
2200 {
2201   const unsigned int shdr_size = elfcpp::Elf_sizes<size>::shdr_size;
2202   unsigned char buf[shdr_size];
2203   elfcpp::Shdr_write<size, big_endian> shdr(buf);
2204
2205   shdr.put_sh_name(name == NULL ? 0 : this->shstrtab_.get_offset(name));
2206   shdr.put_sh_type(type);
2207   shdr.put_sh_flags(flags);
2208   shdr.put_sh_addr(addr);
2209   shdr.put_sh_offset(offset);
2210   shdr.put_sh_size(sect_size);
2211   shdr.put_sh_link(link);
2212   shdr.put_sh_info(info);
2213   shdr.put_sh_addralign(align);
2214   shdr.put_sh_entsize(ent_size);
2215   if (::fwrite(buf, 1, shdr_size, this->fd_) < shdr_size)
2216     gold_fatal(_("%s: error writing section header table"), this->name_);
2217 }
2218
2219 // Class Dwo_name_info_reader.
2220
2221 // Visit a compilation unit.
2222
2223 void
2224 Dwo_name_info_reader::visit_compilation_unit(off_t, off_t, Dwarf_die* die)
2225 {
2226   const char* dwo_name = die->string_attribute(elfcpp::DW_AT_GNU_dwo_name);
2227   if (dwo_name != NULL)
2228     {
2229       uint64_t dwo_id = die->uint_attribute(elfcpp::DW_AT_GNU_dwo_id);
2230       this->files_->push_back(Dwo_file_entry(dwo_id, dwo_name));
2231     }
2232 }
2233
2234 // Class Unit_reader.
2235
2236 // Read the CUs or TUs and add them to the output file.
2237
2238 void
2239 Unit_reader::add_units(Dwp_output_file* output_file,
2240                        unsigned int debug_abbrev,
2241                        Section_bounds* sections)
2242 {
2243   this->output_file_ = output_file;
2244   this->sections_ = sections;
2245   this->set_abbrev_shndx(debug_abbrev);
2246   this->parse();
2247 }
2248
2249 // Visit a compilation unit.
2250
2251 void
2252 Unit_reader::visit_compilation_unit(off_t, off_t cu_length, Dwarf_die* die)
2253 {
2254   if (cu_length == 0)
2255     return;
2256
2257   Unit_set* unit_set = new Unit_set();
2258   unit_set->signature = die->uint_attribute(elfcpp::DW_AT_GNU_dwo_id);
2259   for (unsigned int i = elfcpp::DW_SECT_ABBREV; i <= elfcpp::DW_SECT_MAX; ++i)
2260     unit_set->sections[i] = this->sections_[i];
2261
2262   // Dwp_output_file::add_contribution writes the .debug_info.dwo section
2263   // directly to the output file, so we do not need to duplicate the
2264   // section contents, and add_contribution does not need to free the memory.
2265   section_offset_type off =
2266       this->output_file_->add_contribution(elfcpp::DW_SECT_INFO,
2267                                            this->buffer_at_offset(0),
2268                                            cu_length, 1);
2269   Section_bounds bounds(off, cu_length);
2270   unit_set->sections[elfcpp::DW_SECT_INFO] = bounds;
2271   this->output_file_->add_cu_set(unit_set);
2272 }
2273
2274 // Visit a type unit.
2275
2276 void
2277 Unit_reader::visit_type_unit(off_t, off_t tu_length, off_t,
2278                              uint64_t signature, Dwarf_die*)
2279 {
2280   if (tu_length == 0)
2281     return;
2282   if (this->output_file_->lookup_tu(signature))
2283     return;
2284
2285   Unit_set* unit_set = new Unit_set();
2286   unit_set->signature = signature;
2287   for (unsigned int i = elfcpp::DW_SECT_ABBREV; i <= elfcpp::DW_SECT_MAX; ++i)
2288     unit_set->sections[i] = this->sections_[i];
2289
2290   unsigned char* contents = new unsigned char[tu_length];
2291   memcpy(contents, this->buffer_at_offset(0), tu_length);
2292   section_offset_type off =
2293       this->output_file_->add_contribution(elfcpp::DW_SECT_TYPES, contents,
2294                                            tu_length, 1);
2295   Section_bounds bounds(off, tu_length);
2296   unit_set->sections[elfcpp::DW_SECT_TYPES] = bounds;
2297   this->output_file_->add_tu_set(unit_set);
2298 }
2299
2300 }; // End namespace gold
2301
2302 using namespace gold;
2303
2304 // Options.
2305
2306 enum Dwp_options {
2307   VERIFY_ONLY = 0x101,
2308 };
2309
2310 struct option dwp_options[] =
2311   {
2312     { "exec", required_argument, NULL, 'e' },
2313     { "help", no_argument, NULL, 'h' },
2314     { "output", required_argument, NULL, 'o' },
2315     { "verbose", no_argument, NULL, 'v' },
2316     { "verify-only", no_argument, NULL, VERIFY_ONLY },
2317     { "version", no_argument, NULL, 'V' },
2318     { NULL, 0, NULL, 0 }
2319   };
2320
2321 // Print usage message and exit.
2322
2323 static void
2324 usage(FILE* fd, int exit_status)
2325 {
2326   fprintf(fd, _("Usage: %s [options] [file...]\n"), program_name);
2327   fprintf(fd, _("  -h, --help               Print this help message\n"));
2328   fprintf(fd, _("  -e EXE, --exec EXE       Get list of dwo files from EXE"
2329                                            " (defaults output to EXE.dwp)\n"));
2330   fprintf(fd, _("  -o FILE, --output FILE   Set output dwp file name\n"));
2331   fprintf(fd, _("  -v, --verbose            Verbose output\n"));
2332   fprintf(fd, _("  --verify-only            Verify output file against"
2333                                            " exec file\n"));
2334   fprintf(fd, _("  -V, --version            Print version number\n"));
2335
2336   // REPORT_BUGS_TO is defined in bfd/bfdver.h.
2337   const char* report = REPORT_BUGS_TO;
2338   if (*report != '\0')
2339     fprintf(fd, _("\nReport bugs to %s\n"), report);
2340   exit(exit_status);
2341 }
2342
2343 // Report version information.
2344
2345 static void
2346 print_version()
2347 {
2348   // This output is intended to follow the GNU standards.
2349   printf("GNU dwp %s\n", BFD_VERSION_STRING);
2350   printf(_("Copyright 2012 Free Software Foundation, Inc.\n"));
2351   printf(_("\
2352 This program is free software; you may redistribute it under the terms of\n\
2353 the GNU General Public License version 3 or (at your option) any later version.\n\
2354 This program has absolutely no warranty.\n"));
2355   exit(EXIT_SUCCESS);
2356 }
2357
2358 // Main program.
2359
2360 int
2361 main(int argc, char** argv)
2362 {
2363 #if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES)
2364   setlocale(LC_MESSAGES, "");
2365 #endif
2366 #if defined (HAVE_SETLOCALE)
2367   setlocale(LC_CTYPE, "");
2368 #endif
2369   bindtextdomain(PACKAGE, LOCALEDIR);
2370   textdomain(PACKAGE);
2371
2372   program_name = argv[0];
2373
2374   // Initialize the global parameters, to let random code get to the
2375   // errors object.
2376   Errors errors(program_name);
2377   set_parameters_errors(&errors);
2378
2379   // Initialize gold's global options.  We don't use these in
2380   // this program, but they need to be initialized so that
2381   // functions we call from libgold work properly.
2382   General_options options;
2383   set_parameters_options(&options);
2384
2385   // In libiberty; expands @filename to the args in "filename".
2386   expandargv(&argc, &argv);
2387
2388   // Collect file names and options.
2389   File_list files;
2390   std::string output_filename;
2391   const char* exe_filename = NULL;
2392   bool verbose = false;
2393   bool verify_only = false;
2394   int c;
2395   while ((c = getopt_long(argc, argv, "e:ho:vV", dwp_options, NULL)) != -1)
2396     {
2397       switch (c)
2398         {
2399           case 'h':
2400             usage(stdout, EXIT_SUCCESS);
2401           case 'e':
2402             exe_filename = optarg;
2403             break;
2404           case 'o':
2405             output_filename.assign(optarg);
2406             break;
2407           case 'v':
2408             verbose = true;
2409             break;
2410           case VERIFY_ONLY:
2411             verify_only = true;
2412             break;
2413           case 'V':
2414             print_version();
2415           case '?':
2416           default:
2417             usage(stderr, EXIT_FAILURE);
2418         }
2419     }
2420
2421   if (output_filename.empty())
2422     {
2423       if (exe_filename == NULL)
2424         gold_fatal(_("no output file specified"));
2425       output_filename.assign(exe_filename);
2426       output_filename.append(".dwp");
2427     }
2428
2429   // Get list of .dwo files from the executable.
2430   if (exe_filename != NULL)
2431     {
2432       Dwo_file exe_file(exe_filename);
2433       exe_file.read_executable(&files);
2434     }
2435
2436   // Add any additional files listed on command line.
2437   for (int i = optind; i < argc; ++i)
2438     files.push_back(Dwo_file_entry(0, argv[i]));
2439
2440   if (exe_filename == NULL && files.empty())
2441     gold_fatal(_("no input files and no executable specified"));
2442
2443   if (verify_only)
2444     {
2445       // Get list of DWO files in the DWP file and compare with
2446       // references found in the EXE file.
2447       Dwo_file dwp_file(output_filename.c_str());
2448       bool ok = dwp_file.verify(files);
2449       return ok ? EXIT_SUCCESS : EXIT_FAILURE;
2450     }
2451
2452   // Process each file, adding its contents to the output file.
2453   Dwp_output_file output_file(output_filename.c_str());
2454   for (File_list::const_iterator f = files.begin(); f != files.end(); ++f)
2455     {
2456       if (verbose)
2457         fprintf(stderr, "%s\n", f->dwo_name.c_str());
2458       Dwo_file dwo_file(f->dwo_name.c_str());
2459       dwo_file.read(&output_file);
2460     }
2461   output_file.finalize();
2462
2463   return EXIT_SUCCESS;
2464 }