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