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