Debian Codegraph @

src/bin/dwarfgen/dwarfgen.cc

raw
1 /*
2 Copyright (C) 2010-2019 David Anderson. All rights reserved.
3
4 Redistribution and use in source and binary forms, with
5 or without modification, are permitted provided that the
6 following conditions are met:
7
8 * Redistributions of source code must retain the above
9 copyright notice, this list of conditions and the following
10 disclaimer.
11
12 * Redistributions in binary form must reproduce the above
13 copyright notice, this list of conditions and the following
14 disclaimer in the documentation and/or other materials
15 provided with the distribution.
16
17 * Neither the name of the example nor the names of its
18 contributors may be used to endorse or promote products
19 derived from this software without specific prior written
20 permission.
21
22 THIS SOFTWARE IS PROVIDED BY David Anderson ''AS IS'' AND ANY
23 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
24 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
25 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL David
26 Anderson BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
32 OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34
35 */
36 // dwarfgen.cc
37 //
38 // Using some information source, create a tree of dwarf
39 // information (speaking of a DIE tree).
40 // Turn the die tree into dwarfdata using libdwarf producer
41 // and write the resulting data in an object file.
42 // It is a bit inconsistent in error handling just to
43 // demonstrate the various possibilities using the producer
44 // library.
45 //
46 // dwarfgen [-t def|obj|txt] [-o outpath] [-c cunum] path
47
48 // where -t means what sort of input to read
49 // def means predefined (no input is read, the output
50 // is based on some canned setups built into dwarfgen).
51 // 'path' is ignored in this case. This is the default.
52 //
53 // obj means 'path' is required, it is the object file to
54 // read (the dwarf sections are duplicated
55 // in the output file)
56 //
57 // txt means 'path' is required, path must contain plain text
58 // (in a form rather like output by dwarfdump)
59 // that defines the dwarf that is to be output.
60 //
61 // where -o means specify the pathname of the output object. If not
62 // supplied testout.o is used as the default output path.
63 // where -c supplies a CU number of the obj input to output
64 // because the dwarf producer wants just one CU.
65 // Default is -1 which won't match anything.
66
67 #include "config.h"
68
69 /* Windows specific header files */
70 #if defined(_WIN32) && defined(HAVE_STDAFX_H)
71 #include "stdafx.h"
72 #endif /* HAVE_STDAFX_H */
73 #if HAVE_UNISTD_H
74 #include <unistd.h>
75 #endif
76 #include <stdlib.h> /* for exit() */
77 #include <iostream>
78 #include <sstream>
79 #include <iomanip>
80 #include <string>
81 #include <cstring> // For memcpy
82 #include <list>
83 #include <map>
84 #include <vector>
85 #include <string.h> /* for strchr etc */
86 #ifdef HAVE_SYS_TYPES_H
87 #include <sys/types.h> /* For open() S_IRUSR etc */
88 #endif /* HAVE_SYS_TYPES_H */
89 #ifdef HAVE_SYS_STAT_H
90 #include <sys/stat.h> /* For open() S_IRUSR etc */
91 #endif /* HAVE_SYS_STAT_H */
92 #include <fcntl.h> //open
93 #include "general.h"
94 #include "dg_getopt.h"
95 #include "strtabdata.h"
96 #include "dwarf.h"
97 #include "libdwarf.h"
98 #include "libdwarfp.h"
99 #include "libdwarf_private.h"
100 #include "dwarf_elfstructs.h"
101 #include "dwarf_elf_defines.h"
102 #include "irepresentation.h"
103 #include "ireptodbg.h"
104 #include "createirepfrombinary.h"
105 #ifdef _WIN32
106 #ifdef HAVE_STDINT_H
107 #include <stdint.h>
108 #endif /* HAVE_STDINT_H */
109 #include <io.h>
110 #endif /* _WIN32 */
111
112 #ifdef _WIN32
113 #ifndef O_RDONLY
114 /* This is for a Windows environment */
115 # define O_RDONLY _O_RDONLY
116 #endif
117 #ifdef _O_BINARY
118 /* This is for a Windows environment */
119 #define O_BINARY _O_BINARY
120 #endif
121 #else /* !_WIN32 */
122 # ifndef O_BINARY
123 # define O_BINARY 0 /* So it does nothing in Linux/Unix */
124 # endif
125 #endif /* !_WIN32 */
126
127 /* These are for a Windows environment */
128 #ifdef _WIN32
129 #ifdef _O_WRONLY
130 #define O_WRONLY _O_WRONLY
131 #endif
132 #ifdef _O_CREAT
133 #define O_CREAT _O_CREAT
134 #endif
135 #ifdef _O_TRUNC
136 #define O_TRUNC _O_TRUNC
137 #endif
138 #ifdef _S_IREAD
139 #define S_IREAD _S_IREAD
140 #endif
141 #ifdef _S_IWRITE
142 #define S_IWRITE _S_IWRITE
143 #endif
144 /* open modes S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH */
145 #ifndef S_IRUSR
146 #define S_IRUSR _S_IREAD
147 #endif // S_IRUSR
148 #ifndef S_IWUSR
149 #define S_IWUSR _S_IWRITE
150 #endif
151 #ifndef S_IRGRP
152 #define S_IRGRP 0
153 #endif
154 #ifndef S_IROTH
155 #define S_IROTH 0
156 #endif
157 #endif /* _WIN32 */
158
159 using std::string;
160 using std::cout;
161 using std::endl;
162 using std::vector;
163 extern "C" {
164 static int CallbackFunc(
165 const char* name,
166 int size,
167 Dwarf_Unsigned type,
168 Dwarf_Unsigned flags,
169 Dwarf_Unsigned link,
170 Dwarf_Unsigned info,
171 Dwarf_Unsigned* sect_name_symbol_index,
172 void * user_data,
173 int* error);
174 }
175 // End extern "C"
176
177 static void create_debug_sup_content(Dwarf_P_Debug dbg);
178 // FIXME. This is incomplete. See FIXME just below here.
179 #ifdef WORDS_BIGENDIAN
180 static void
181 _dwarf_memcpy_swap_bytes(void *s1, const void *s2, unsigned long len)
182 {
183 unsigned char *targ = (unsigned char *) s1;
184 const unsigned char *src = (const unsigned char *) s2;
185
186 if (len == 4) {
187 targ[3] = src[0];
188 targ[2] = src[1];
189 targ[1] = src[2];
190 targ[0] = src[3];
191 } else if (len == 8) {
192 targ[7] = src[0];
193 targ[6] = src[1];
194 targ[5] = src[2];
195 targ[4] = src[3];
196 targ[3] = src[4];
197 targ[2] = src[5];
198 targ[1] = src[6];
199 targ[0] = src[7];
200 } else if (len == 2) {
201 targ[1] = src[0];
202 targ[0] = src[1];
203 }
204 /* should NOT get below here: is not the intended use */
205 else if (len == 1) {
206 targ[0] = src[0];
207 } else {
208 memcpy(s1, s2, (size_t)len);
209 }
210 return;
211 }
212 #endif /* WORDS_BIGENDIAN */
213
214 // There are issues 32/64 here, and endianness.
215 // We are asserting here in dwarfgen that the target
216 // object created is to be DW_DLC_TARGET_LITTLEENDIAN.
217 // FIXME. not general.
218 // op and ol aread MUST NOT overlap.
219 // ip and il should be 2,4,or 8. Nothing else.
220 // These could perfectly well be functions.
221 #ifdef WORDS_BIGENDIAN
222 #define ASNX(op,ol,ip,il) \
223 do { \
224 if (ol > il) { \
225 Dwarf_Unsigned sbyte = 0;\
226 memset(op,0,ol); \
227 sbyte = ol - il; \
228 const void * ipi = \
229 (const void *)ip; \
230 _dwarf_memcpy_swap_bytes(((char *)(op))+sbyte,\
231 ipi,il);\
232 } else { \
233 Dwarf_Unsigned sbyte = 0;\
234 sbyte = il - ol; \
235 const void * ipi = \
236 ((Dwarf_Small*)ip) +sbyte; \
237 _dwarf_memcpy_swap_bytes((char *)(op), \
238 (const void *)ipi, \
239 ol); \
240 } \
241 } while (0)
242 #else // LITTLEENDIAN
243 #define ASNX(op,ol,ip,il) \
244 do { \
245 if (ol > il) { \
246 const void *ipi = \
247 (const void *)ip; \
248 memset(op,0,ol); \
249 memcpy(((char *)(op)), \
250 ipi,il); \
251 } else { \
252 const void *ipi = \
253 (const void *)ip; \
254 memcpy((char *)(op), \
255 ipi,ol); \
256 } \
257 } while (0)
258 #endif // ENDIANNESS
259
260 static void write_object_file(Dwarf_P_Debug dbg,
261 IRepresentation &irep,
262 unsigned machine,
263 unsigned endian,
264 unsigned long dwbitflags,
265 void * user_data);
266
267 static void create_initial_section(void);
268 static void create_text_section(void);
269 static Dwarf_Unsigned create_namestr_section(void);
270 static void write_generated_dbg(Dwarf_P_Debug dbg,
271 IRepresentation &irep);
272
273 static string outfile("testout.o");
274 static string infile;
275 static enum WhichInputSource { OptNone, OptReadText,
276 OptReadBin,OptPredefined}
277 whichinput(OptPredefined);
278
279 // Use a generic call to open the file
280 // (issues with Windows)
281 int open_a_file(const char * name);
282 void close_a_file(int f);
283 Dwarf_Unsigned write_to_object(void);
284
285 // This is a global so thet CallbackFunc can get to it
286 // If we used the dwarf_producer_init_c() user_data pointer
287 // creatively we would not need a global.
288 static IRepresentation Irep;
289
290 static strtabdata secstrtab;
291
292 CmdOptions cmdoptions = {
293 false, //transformHighpcToConst
294 DW_FORM_string, // defaultInfoStringForm
295 false, //showrelocdetails
296 false, //adddata16
297 false, //addimplicitconst
298 false, //addframeadvanceloc
299 false, //addSUNfuncoffsets
300 false, //add_debug_sup
301 false //addskipbranch
302 };
303
304 // loff_t is signed for some reason (strange)
305 // but we make offsets unsigned.
306 #define LOFFTODWUNS(x) ( (Dwarf_Unsigned)(x))
307
308 class Writer {
309 public:
310 int fd_;
311 string name_;
312 Dwarf_Unsigned curoffset_;
313 Writer() {
314 fd_ = -1;
315 curoffset_ =0;
316 };
317
318 void wwrite(Dwarf_Unsigned offset,
319 Dwarf_Unsigned length,
320 const void *bytes) {
321 if (fd_ == -1) {
322 cout << "dwarfgen: write with fd_ -1" << endl;
323 exit(1);
324 }
325 if (curoffset_ != offset) {
326 off_t v = lseek(fd_,offset,SEEK_SET);
327 if (v == (off_t)-1) {
328 cout << "dwarfgen: fseek to " << offset<<
329 " fails " << endl;
330 exit(1);
331 }
332 curoffset_ = v;
333 }
334 ssize_t wrote = write(fd_,bytes,(size_t)length);
335 if (wrote == -1) {
336 cout << "dwarfgen: write length " << length<<
337 "fails " << endl;
338 exit(1);
339 }
340 curoffset_ += length;
341 }
342 void closeFile() {
343 if (fd_ != -1) {
344 close(fd_);
345 fd_ = -1;
346 }
347 curoffset_ = 0;
348 }
349 ~Writer() {
350 closeFile();
351 };
352 void openFile(string & name) {
353 name_ = name;
354 fd_ = open(name_.c_str(), O_CREAT|O_WRONLY | O_BINARY,
355 00666);
356 if (fd_ ==-1) {
357 cout << "dwarfgen: open " << name_ << " fails" << endl;
358 exit(1);
359 }
360 curoffset_ =0;
361 }
362 };
363
364 class ByteBlob {
365 public:
366 ByteBlob() {bytes_ = 0; len_=0;};
367 ByteBlob(unsigned char *bytes,size_t len) {
368 bytes_ = bytes;
369 len_ = len;
370 };
371 void setBlob(unsigned char *bytes,size_t len) {
372 if (len_) {
373 cout << "dwarfgen: Duplicate ByteBlob setting " <<
374 "for length "<< len_ << " to length"
375 << len << endl;
376 exit(1);
377 }
378 bytes_ = bytes;
379 len_ = len;
380 };
381 unsigned char *bytes_;
382 Dwarf_Unsigned len_;
383 ~ByteBlob() { bytes_ = 0; len_= 0; };
384 };
385
386 /* See the Elf ABI for further definitions of these fields. */
387 // By definition, this outputs data to file offset zero.
388 class ElfHeaderForDwarf {
389 public:
390 unsigned char e_ident_[EI_NIDENT];
391 Dwarf_Unsigned e_type_;
392 Dwarf_Unsigned e_machine_;
393 Dwarf_Unsigned e_version_;
394 Dwarf_Unsigned e_entry_;
395 Dwarf_Unsigned e_phoff_;
396 Dwarf_Unsigned e_shoff_;
397 Dwarf_Unsigned e_flags_;
398 Dwarf_Unsigned e_ehsize_;
399 Dwarf_Unsigned e_phentsize_;
400 Dwarf_Unsigned e_phnum_;
401 Dwarf_Unsigned e_shentsize_;
402 Dwarf_Unsigned e_shnum_;
403 Dwarf_Unsigned e_shstrndx_;
404 bool e_dwarf_32bit_;
405 dw_elf32_ehdr e_32_;
406 dw_elf64_ehdr e_64_;
407 unsigned char e_ptrbytesize_;
408 Dwarf_Unsigned e_hdrlen_;
409 bool elf_is_64bit() { return e_ptrbytesize_ == 8;};
410 bool elf_is_32bit() { return e_ptrbytesize_ == 4;};
411 bool dwarf_is_64bit() {return !e_dwarf_32bit_;};
412 bool dwarf_is_32bit() {return e_dwarf_32bit_;};
413 ElfHeaderForDwarf() {
414 memset(&e_32_,0,sizeof(e_32_));
415 memset(&e_64_,0,sizeof(e_64_));
416 memset(e_ident_,0,sizeof(e_ident_));
417 e_type_= 0; e_machine_= 0;; e_version_= 0;; e_entry_= 0;
418 e_phoff_= 0; e_shoff_= 0; e_flags_= 0; e_ehsize_= 0;
419 e_phentsize_= 0; e_phnum_= 0; e_shentsize_= 0; e_shnum_= 0;
420 e_shstrndx_ = 0;
421 e_dwarf_32bit_ = true;
422 e_ptrbytesize_=0; e_hdrlen_ = 0;
423 };
424 };
425
426 class SectionForDwarf {
427 public:
428 SectionForDwarf():sh_name_(0),
429 section_name_symidx_(0),
430 sh_type_(0),
431 sh_addr_(0),
432 sh_offset_(0),
433 sh_flags_(0),
434 sh_size_(0),
435 sh_link_(0), sh_info_(0),
436 sh_addralign_(1),
437 sh_entsize_(0),
438 elf_sect_index_(0)
439 {
440 memset(&shdr64_,0,sizeof(shdr64_));
441 memset(&shdr32_,0,sizeof(shdr32_));
442 };
443 SectionForDwarf(const string name,
444 Dwarf_Unsigned type,
445 Dwarf_Unsigned flags, Dwarf_Unsigned link,
446 Dwarf_Unsigned info):
447 name_(name),
448 sh_type_(type),
449 sh_addr_(0),
450 sh_offset_(0),
451 sh_flags_(flags),
452 sh_size_(0),
453 sh_link_(link),
454 sh_info_(info),
455 sh_addralign_(1),
456 sh_entsize_(0),
457 elf_sect_index_(0)
458 {
459 memset(&shdr64_,0,sizeof(shdr64_));
460 memset(&shdr32_,0,sizeof(shdr32_));
461 // Now create section name string section .
462 sh_name_ = secstrtab.addString(name.c_str());
463 ElfSymbols& es = Irep.getElfSymbols();
464 // Now creat a symbol for the section name.
465 // (which has its own string table)
466 section_name_symidx_ = es.addElfSymbol(0,name);
467 };
468 ~SectionForDwarf() { };
469 string name_;
470 Dwarf_Unsigned sh_name_; /* section_name_itself */
471 ElfSymIndex section_name_symidx_;
472 Dwarf_Unsigned sh_type_;
473 Dwarf_Unsigned sh_addr_;
474 Dwarf_Unsigned sh_offset_;
475 Dwarf_Unsigned sh_flags_;
476 Dwarf_Unsigned sh_size_;
477 Dwarf_Unsigned sh_link_;
478 Dwarf_Unsigned sh_info_;
479 Dwarf_Unsigned sh_addralign_;
480 Dwarf_Unsigned sh_entsize_;
481
482 /* type: SHT_REL, RELA: Section header index of the section
483 relocation applies to.
484 SHT_SYMTAB: Section header index of the
485 associated string table. */
486 unsigned int elf_sect_index_;
487 dw_elf64_shdr shdr64_;
488 dw_elf32_shdr shdr32_;
489 // Blobs are not tiny, libdwarfp aggregates many blocks
490 vector<ByteBlob> sectioncontent_; // All (but not header)
491 // content size is sh_size_ (over all blobs)
492
493 void add_section_content(unsigned char *data,
494 Dwarf_Unsigned datalen) {
495 ByteBlob x(data,datalen);
496 sectioncontent_.push_back(x);
497 sh_size_ += datalen;
498 };
499 Dwarf_Unsigned getSectionNameSymidx() {
500 return section_name_symidx_.getSymIndex(); };
501 void setSectIndex(unsigned v) { elf_sect_index_ = v; };
502 Dwarf_Unsigned getSectIndex() const { return elf_sect_index_;};
503 }; // SectionForDwarf
504
505 // The elf header, with native integers
506 ElfHeaderForDwarf dwelfheader;
507
508 // Data for section header headers is kept in native integers
509 // Eventually contains the section headers
510 // and section content, including Elf Section zero.
511 // The vector is indexable by ElfSectIndex.getSectIndex()
512 vector<SectionForDwarf> dwsectab;
513
514 Writer dwwriter;
515
516 #if 0
517 static SectionForDwarf & FindMySection(
518 const ElfSectIndex & elf_section_index)
519 {
520 for (unsigned i =0; i < dwsectab.size(); ++i) {
521 if (elf_section_index.getSectIndex() !=
522 dwsectab[i].getSectIndex().getSectIndex()) {
523 continue;
524 }
525 return dwsectab[i];
526 }
527 cout << "dwarfgen: Unable to find my dw sec data "
528 "for elf section " <<
529 elf_section_index.getSectIndex() << endl;
530 exit(1);
531 }
532 #endif
533
534 static int
535 FindMySectionNum(const ElfSectIndex & elf_section_index)
536 {
537 for (unsigned i =0; i < dwsectab.size(); ++i) {
538 if (elf_section_index.getSectIndex() !=
539 dwsectab[i].getSectIndex()) {
540 continue;
541 }
542 return i;
543 }
544 cout << "dwarfgen: Unable to find my dw sec index "
545 "for elf section " <<
546 elf_section_index.getSectIndex() << endl;
547 exit(1);
548 }
549
550 void
551 create_initial_section(void)
552 {
553 unsigned sectindex = dwsectab.size();
554 dwsectab.push_back(SectionForDwarf());
555 cout << "New Elf section: " << "" <<
556 " Type=" << 0 << " Flags=" << 0 <<
557 " Elf secnum=" << sectindex <<
558 " link section=" << 0 <<
559 " info="<< 0 << endl;
560 }
561
562 static Dwarf_Unsigned
563 create_namestr_section(void)
564 {
565 unsigned long sectindex = dwsectab.size();
566 string s(".shstrtab");
567 SectionForDwarf ds = SectionForDwarf(
568 s,
569 DWARF_T_BYTE,
570 SHT_STRTAB,
571 0,0);
572 ds.setSectIndex(sectindex);
573 ds.add_section_content(
574 static_cast<unsigned char *>(secstrtab.exposedata()),
575 secstrtab.exposelen());
576 dwelfheader.e_shstrndx_ = sectindex;
577 dwsectab.push_back(ds);
578 cout << "New Elf section: " << s <<
579 " Type=" << DWARF_T_BYTE << " Flags=" << SHT_STRTAB <<
580 " Elf secnum=" << sectindex <<
581 " link section=" << 0 <<
582 " info="<< 0 << endl;
583 return sectindex;
584 }
585
586 // This functional interface is defined by libdwarf.
587 // Please see the comments in libdwarf2p.1.pdf
588 // (libdwarf2p.1.mm) on this callback interface.
589 // Returns (to libdwarf) an Elf section number, so
590 // since 0 is always empty and dwarfgen sets 1 to be a fake
591 // text section on the first call this returns 2, second 3, etc.
592 static int CallbackFunc(
593 const char* name,
594 int size,
595 Dwarf_Unsigned type,
596 Dwarf_Unsigned flags,
597 Dwarf_Unsigned link,
598 Dwarf_Unsigned info,
599 Dwarf_Unsigned* sect_name_symbol_index,
600 void * user_data,
601 int* error)
602 {
603 // Create an elf section.
604 // If the data is relocations, we suppress the generation
605 // of a section when we intend to do the relocations
606 // ourself (fine for dwarfgen but would
607 // be really surprising for a normal compiler
608 // back end using the producer code).
609 (void)error;
610 (void)size;
611 (void)user_data;
612
613 if (0 == strncmp(name,".rel",4)) {
614 // It is relocation, create no section!
615 return 0;
616 }
617 unsigned new_sect_index = dwsectab.size();
618 SectionForDwarf ds(name,type,flags,link,info) ;
619 ds.setSectIndex(new_sect_index);
620 cout << "New Elf section: " << name <<
621 " Type=" <<type << " Flags=" << flags <<
622 " Elf secnum=" << new_sect_index <<
623 " link section=" << link <<
624 " info="<< info << endl;
625
626 // In Elf, each section gets an elf symbol table entry.
627 // So that relocations have an address to refer to.
628 // You will create the Elf symbol table, so you have to tell
629 // libdwarf the index to put into relocation records for the
630 // section newly defined here.
631 *sect_name_symbol_index = ds.getSectionNameSymidx();
632
633 // Do all the data creation before pushing
634 // (copying) ds onto dwsectab!
635 dwsectab.push_back(ds);
636 // The number returned is elf section which
637 // is the same as dwsectab vector index;
638 return ds.getSectIndex();
639 }
640
641 static void
642 setinput(enum WhichInputSource *src,
643 const string &type,
644 bool *pathreq)
645 {
646 if (type == "txt") {
647 *src = OptReadText;
648 *pathreq = true;
649 return;
650 } else if (type == "obj") {
651 *src = OptReadBin;
652 *pathreq = true;
653 return;
654 } else if (type == "def") {
655 *src = OptPredefined;
656 *pathreq = false;
657 return;
658 }
659 cout << "dwarfgen: Giving up, only txt obj or def "
660 "accepted after -t" << endl;
661 exit(1);
662 }
663
664 int
665 main(int argc, char **argv)
666 {
667 try {
668 int opt;
669 bool pathrequired(false);
670 long cu_of_input_we_output = -1;
671 bool force_empty_dnames = false;
672
673 // Overriding macro constants from pro_line.h
674 // so we can choose at runtime
675 // and avoid modifying header files.
676 // This is the original set of constants
677 // used for testing.
678 // see also output_v4_test (--output-v4-test
679 // longopt).
680 const char *dwarf_extras ="opcode_base=13,"
681 "minimum_instruction_length=1,"
682 "line_base=-1,"
683 "line_range=4";
684 int endian = DW_DLC_TARGET_LITTLEENDIAN;
685 const char *dwarf_version = "V2";
686 const char * isa_name = "x86";
687 unsigned long ptrsizeflagbit = DW_DLC_POINTER32;
688 unsigned long dwarfoffsetsizeflagbit = DW_DLC_OFFSET32;
689 /* DW_DLC_ELF_OFFSET_SIZE 32/64 winds up determining
690 the ELFCLASS 32/64 in write_object_file() */
691 unsigned long elfoffsetsizeflagbit =
692 DW_DLC_ELF_OFFSET_SIZE_32;
693 unsigned machine = EM_386; /* from elf.h */
694 int output_v4_test = 0;
695
696 unsigned global_elfclass = 0;
697
698 int longindex;
699 static struct dwoption longopts[] = {
700 {"adddata16",dwno_argument,0,1000},
701 {"force-empty-dnames",dwno_argument,0,1001},
702 {"add-implicit-const",dwno_argument,0,1002},
703 {"add-frame-advance-loc",dwno_argument,0,1003},
704 {"add-sun-func-offsets",dwno_argument,0,1004},
705 {"add-debug-sup",dwno_argument,0,1006},
706 {"output-pointer-size",dwrequired_argument,0,'p'},
707 {"output-offset-size",dwrequired_argument,0,'f'},
708 {"output-dwarf-version",dwrequired_argument,0,'v'},
709 {"output-v4-test",dwno_argument,0,1005},
710 {"default-form-strp",dwno_argument,0,'s'},
711 {"show-reloc-details",dwno_argument,0,'r'},
712 {"high-pc-as-const",dwno_argument,0,'h'},
713 {"add-skip-branch-ops",dwno_argument,0,1007},
714 {0,0,0,0},
715 };
716 // -p is pointer size
717 // -f is offset size, overriding the above
718 // -v is version number for dwarf output
719
720 while((opt=dwgetopt_long(argc,argv,
721 "o:t:c:hsrv:p:f:",
722 longopts,&longindex)) != -1) {
723 switch(opt) {
724 case 1000:
725 if (longindex == 0) {
726 // To test adding the DWARF5
727 // DW_FORM_data16
728 // libdwarf reading is thus testable.
729 cmdoptions.adddata16 = true;
730 } else {
731 cout << "dwarfgen: Invalid lnogoption input " <<
732 longindex << endl;
733 exit(1);
734 }
735 break;
736 case 1001:
737 // To test having an empty .debug_dnames
738 // section.
739 // libdwarf reading is thus testable.
740 force_empty_dnames = true;
741 break;
742 case 1002:
743 // To test creating DWARF5
744 // DW_FORM_implicit_const.
745 // libdwarf reading is thus testable.
746 cmdoptions.addimplicitconst = true;
747 break;
748 case 1003:
749 // To test dwarf_add_fde_inst_a().
750 // libdwarf reading is thus testable.
751 cmdoptions.addframeadvanceloc = true;
752 break;
753 case 1004:
754 //{"add-sun-func-offsets",dwno_argument,0,1004},
755 // To test creating DWARF5
756 // DW_AT_SUN_func_offsets.
757 // libdwarf reading is thus testable.
758 cmdoptions.addSUNfuncoffsets = true;
759 break;
760 case 1005:
761 //{"output-v4-test",dwno_argument,0,1005}
762 output_v4_test = 1;
763 break;
764 case 1006:
765 //{"add-debug-sup",dwno_argument,0,1006}
766 cmdoptions.adddebugsup = true;
767 break;
768 case 1007:
769 //{"add-skip-branch-ops",dwno_argument,0,1007},
770 cmdoptions.addskipbranch = true;
771 break;
772 case 'c':
773 // At present we can only create a single
774 // cu in the output of the libdwarf producer.
775 cu_of_input_we_output = atoi(dwoptarg);
776 break;
777 case 'r':
778 cmdoptions.showrelocdetails=true;
779 break;
780 case 's': // --default-form-strp
781 cmdoptions.defaultInfoStringForm = DW_FORM_strp;
782 break;
783 case 'p': /* pointer size: value 4 or 8. */
784 if (!strcmp("4",dwoptarg)) {
785 ptrsizeflagbit = DW_DLC_POINTER32;
786 elfoffsetsizeflagbit = DW_DLC_ELF_OFFSET_SIZE_32;
787 } else if (!strcmp("8",dwoptarg)) {
788 ptrsizeflagbit = DW_DLC_POINTER64;
789 elfoffsetsizeflagbit = DW_DLC_ELF_OFFSET_SIZE_64;
790 } else {
791 cout << "dwarfgen: Invalid p option input " <<
792 dwoptarg << endl;
793 exit(1);
794 }
795 break;
796 case 'f': /* offset size for DWARF: value 4 or 8. */
797 if (!strcmp("4",dwoptarg)) {
798 dwarfoffsetsizeflagbit = DW_DLC_OFFSET32;
799 } else if (!strcmp("8",dwoptarg)) {
800 dwarfoffsetsizeflagbit = DW_DLC_OFFSET64;
801 } else {
802 cout << "dwarfgen: Invalid f option input " <<
803 dwoptarg << endl;
804 exit(1);
805 }
806 break;
807 case 'v': /* Version 2 3 4 or 5 */
808 if (!strcmp("5",dwoptarg)) {
809 dwarf_version = "V5";
810 } else if (!strcmp("4",dwoptarg)) {
811 dwarf_version = "V4";
812 } else if (!strcmp("3",dwoptarg)) {
813 dwarf_version = "V3";
814 } else if (!strcmp("2",dwoptarg)) {
815 dwarf_version = "V2";
816 } else {
817 cout << "dwarfgen: Invalid v option input " <<
818 dwoptarg << endl;
819 exit(1);
820 }
821 break;
822 case 't':
823 setinput(&whichinput,dwoptarg,&pathrequired);
824 break;
825 case 'h':
826 cmdoptions.transformHighpcToConst = true;
827 break;
828 case 'o':
829 outfile = dwoptarg;
830 break;
831 case '?':
832 cout << "dwarfgen: Invalid quest? option input "
833 << endl;
834 exit(1);
835 default:
836 cout << "dwarfgen: Invalid option input " << endl;
837 exit(1);
838 }
839 }
840 if ( (dwoptind >= argc) && pathrequired) {
841 cout << "dwarfgen: Expected argument after options!"
842 " Giving up."
843 << endl;
844 exit(EXIT_FAILURE);
845 }
846 if (pathrequired) {
847 infile = argv[dwoptind];
848 }
849 if (output_v4_test) {
850 dwarf_extras ="opcode_base=13,"
851 "minimum_instruction_length=1,"
852 "line_base=-1,"
853 "line_range=4";
854 endian = DW_DLC_TARGET_LITTLEENDIAN;
855 dwarf_version = "V4";
856 isa_name = "x86_64";
857 ptrsizeflagbit = DW_DLC_POINTER64;
858 dwarfoffsetsizeflagbit = DW_DLC_OFFSET32;
859 elfoffsetsizeflagbit = DW_DLC_ELF_OFFSET_SIZE_64;
860 machine = EM_X86_64; /* from elf.h */
861 }
862
863 if (whichinput == OptReadBin) {
864 createIrepFromBinary(infile,Irep);
865 } else if (whichinput == OptReadText) {
866 cout << "dwarfgen: dwarfgen: text read not supported yet"
867 << endl;
868 exit(EXIT_FAILURE);
869 } else if (whichinput == OptPredefined) {
870 cout << "dwarfgen: predefined not supported yet" << endl;
871 exit(EXIT_FAILURE);
872 } else {
873 cout << "dwarfgen: Impossible: unknown input style."
874 << endl;
875 exit(EXIT_FAILURE);
876 }
877
878 // We use the latest calls returning
879 // DW_DLV_OK, DW_DLV_NO_ENTRY, or DW_DLV_ERROR
880 // as an int.
881 Dwarf_Ptr errarg = 0;
882 Dwarf_Error err = 0;
883
884 // The point of user_data is, as here, to
885 // have crucial data available to the callback
886 // function implementation.
887 void *user_data = &global_elfclass;
888
889 Dwarf_P_Debug dbg = 0;
890 unsigned long dwbitflags =
891 endian |
892 ptrsizeflagbit|
893 elfoffsetsizeflagbit|
894 dwarfoffsetsizeflagbit|
895 DW_DLC_SYMBOLIC_RELOCATIONS;
896
897 // We use DW_DLC_SYMBOLIC_RELOCATIONS so we can
898 // read the relocations and do our own relocating.
899 // See calls of dwarf_get_relocation_info().
900 int res = dwarf_producer_init(
901 dwbitflags,
902 CallbackFunc,
903 0, // errhand
904 errarg,
905 user_data,
906 isa_name,
907 dwarf_version,
908 dwarf_extras,
909 &dbg,
910 &err);
911 if (res == DW_DLV_NO_ENTRY) {
912 cout << "dwarfgen: Failed dwarf_producer_init() NO_ENTRY"
913 << endl;
914 exit(EXIT_FAILURE);
915 }
916 if (res == DW_DLV_ERROR) {
917 cout << "dwarfgen: Failed dwarf_producer_init() ERROR"
918 << endl;
919 cout << "dwarfgen errmsg " << dwarf_errmsg(err)<<endl;
920 exit(EXIT_FAILURE);
921 }
922 res = dwarf_pro_set_default_string_form(dbg,
923 cmdoptions.defaultInfoStringForm,&err);
924 if (res != DW_DLV_OK) {
925 cout << "dwarfgen: Failed " <<
926 "dwarf_pro_set_default_string_form" << endl;
927 exit(EXIT_FAILURE);
928 }
929 if (force_empty_dnames) {
930 /* Fills out a default dnames for testing. */
931 res = dwarf_force_dnames(dbg,0,&err);
932 if (res != DW_DLV_OK) {
933 cout << "dwarfgen: "
934 "Failed dwarf_force_debug_names"
935 << endl;
936 exit(EXIT_FAILURE);
937 }
938 }
939 if (cmdoptions.adddebugsup) {
940 create_debug_sup_content(dbg);
941 }
942 transform_irep_to_dbg(dbg,Irep,cu_of_input_we_output);
943 write_object_file(dbg,Irep,machine,endian, dwbitflags,
944 user_data);
945
946 Dwarf_Unsigned str_count = 0;
947 Dwarf_Unsigned str_len = 0;
948 Dwarf_Unsigned debug_str_count = 0;
949 Dwarf_Unsigned debug_str_len = 0;
950 Dwarf_Unsigned reused_count = 0;
951 Dwarf_Unsigned reused_len = 0;
952 res = dwarf_pro_get_string_stats(dbg,
953 &str_count,&str_len,
954 &debug_str_count,
955 &debug_str_len,
956 &reused_count,
957 &reused_len,&err);
958 if (res != DW_DLV_OK) {
959 cout << "Unable to get string statistics. ERROR."
960 << endl;
961 } else {
962 cout << "Debug_Str: debug_info str count " <<str_count <<
963 ", byte total len " <<str_len << endl;
964 cout << "Debug_Str: count " <<debug_str_count <<
965 ", byte total len " <<debug_str_len << endl;
966 cout << "Debug_Str: Reused count " <<reused_count <<
967 ", byte total len not emitted " <<reused_len << endl;
968 }
969 dwarf_producer_finish_a( dbg, 0);
970 return 0;
971 } // End try
972 catch (std::bad_alloc &ba) {
973 cout << "dwarfgen FAIL:bad alloc caught " <<
974 ba.what() << endl;
975 exit(EXIT_FAILURE);
976 }
977 catch (std::exception &e) {
978 cout << "dwarfgen FAIL:std lib exception " <<
979 e.what() << endl;
980 exit(EXIT_FAILURE);
981 }
982 catch (...) {
983 cout << "dwarfgen FAIL:other failure " << endl;
984 exit(EXIT_FAILURE);
985 }
986 exit(1);
987 }
988
989 static void
990 create_debug_sup_content(Dwarf_P_Debug dbg)
991 {
992 int res = 0;
993 Dwarf_Error err = 0;
994 char x_content[] = "fake checksum_content";
995 Dwarf_Small * content = (Dwarf_Small *)x_content;
996
997 res = dwarf_add_debug_sup(dbg,
998 2,0,
999 (char *)"fake-file/fake-file-name",
1000 sizeof(x_content),
1001 content,&err);
1002 if (res != DW_DLV_OK) {
1003 printf("FAIL creating .debug_sup data in dbg "
1004 " due to error %s\n",
1005 dwarf_errmsg(err));
1006 exit(1);
1007 }
1008 return;
1009 }
1010
1011 // Layout is Elf Hdr, Section content, section headers
1012 static void
1013 calculate_all_offsets(void)
1014 {
1015 Dwarf_Unsigned total_length = 0;
1016 Dwarf_Unsigned ehdr_length = 0;
1017 Dwarf_Unsigned section_headers_length = 0;
1018 Dwarf_Unsigned sechdr_length = 0;
1019 Dwarf_Unsigned section_content_len = 0;
1020
1021 if (dwelfheader.elf_is_32bit()) {
1022 ehdr_length = sizeof(dw_elf32_ehdr);
1023 sechdr_length = sizeof(dw_elf32_shdr);
1024 total_length += ehdr_length;
1025 } else {
1026 ehdr_length += sizeof(dw_elf64_ehdr);
1027 sechdr_length = sizeof(dw_elf64_shdr);
1028 total_length += ehdr_length;
1029 }
1030 dwelfheader.e_shentsize_ = sechdr_length;
1031 dwelfheader.e_hdrlen_ = ehdr_length;
1032 dwelfheader.e_shnum_ = dwsectab.size();
1033 dwelfheader.e_ehsize_ = ehdr_length;
1034
1035 for (vector<SectionForDwarf>::iterator it = dwsectab.begin();
1036 it != dwsectab.end();
1037 it++) {
1038 SectionForDwarf &sec = *it;
1039 sec.sh_offset_ = total_length;
1040 section_content_len += sec.sh_size_;
1041 total_length += sec.sh_size_;
1042 }
1043 section_headers_length = sechdr_length*dwsectab.size();
1044 total_length += section_headers_length;
1045
1046 Dwarf_Unsigned curoff = ehdr_length;
1047 for (vector<SectionForDwarf>::iterator it = dwsectab.begin();
1048 it != dwsectab.end();
1049 it++) {
1050 SectionForDwarf &sec = *it;
1051 sec.sh_offset_= curoff;
1052 curoff += sec.sh_size_;
1053 }
1054 dwelfheader.e_shoff_ = ehdr_length + section_content_len;
1055 dwelfheader.e_shnum_ = dwsectab.size();
1056 }
1057
1058 // Gets all the data from libdwarfp and writes
1059 // an Elf object to outfile.c_str()
1060 static void
1061 write_object_file(Dwarf_P_Debug dbg,
1062 IRepresentation &irep,
1063 unsigned machine,
1064 unsigned endian,
1065 unsigned long dwbitflags,
1066 void *user_data)
1067 {
1068 unsigned elfclass = (dwbitflags & DW_DLC_ELF_OFFSET_SIZE_64)?
1069 ELFCLASS64:
1070 ELFCLASS32;
1071 unsigned elfendian = (endian & DW_DLC_TARGET_LITTLEENDIAN)?
1072 ELFDATA2LSB:
1073 ELFDATA2MSB;
1074 bool dwarfoffset32 = (dwbitflags&DW_DLC_OFFSET64)?true:false;
1075 bool elfpointer64 = (dwbitflags&DW_DLC_POINTER64)?true:false;
1076 *(unsigned *)user_data = elfclass;
1077 dwwriter.openFile(outfile);
1078 dwelfheader = ElfHeaderForDwarf();
1079 dwelfheader.e_ident_[EI_MAG0] = ELFMAG0;
1080 dwelfheader.e_ident_[EI_MAG1] = ELFMAG1;
1081 dwelfheader.e_ident_[EI_MAG2] = ELFMAG2;
1082 dwelfheader.e_ident_[EI_MAG3] = ELFMAG3;
1083 dwelfheader.e_ident_[EI_CLASS] = elfclass;
1084 dwelfheader.e_ident_[EI_DATA] = elfendian;
1085 dwelfheader.e_ident_[EI_VERSION] = EV_CURRENT;
1086 dwelfheader.e_machine_ = machine;
1087 dwelfheader.e_type_ = ET_REL;
1088 dwelfheader.e_version_ = EV_CURRENT;
1089 dwelfheader.e_dwarf_32bit_ = dwarfoffset32;
1090 dwelfheader.e_ptrbytesize_ = elfpointer64?8:4;
1091
1092 create_initial_section();
1093 create_text_section();
1094
1095 // Write the DWARF to our section data in memory.
1096 write_generated_dbg(dbg,irep);
1097 // Create the section name string section,
1098 // set e_shstrndx.
1099 create_namestr_section();
1100 calculate_all_offsets();
1101 Dwarf_Unsigned finalsize = write_to_object();
1102 cout << " output image size in bytes " << finalsize << endl;
1103 dwwriter.closeFile();
1104 }
1105
1106 static unsigned char text[4] = {0,0,0,0};
1107
1108 // an object section with fake .text data (just as an example).
1109 static void
1110 create_text_section(void)
1111 {
1112 string s(".text");
1113 unsigned sectindex = dwsectab.size();
1114
1115 SectionForDwarf ds(s,
1116 (Dwarf_Unsigned)SHT_PROGBITS,
1117 (Dwarf_Unsigned)0,(Dwarf_Unsigned)0,
1118 (Dwarf_Unsigned) 0);
1119 cout << "New Elf section: " << s <<
1120 " Type=" <<SHT_PROGBITS << " Flags=" << 0 <<
1121 " Elf secnum=" << sectindex <<
1122 " link section=" << 0 <<
1123 " info="<< 0 << endl;
1124 ds.sh_addralign_ = dwelfheader.elf_is_64bit()?8:4;
1125 ds.add_section_content(text,sizeof(text));
1126 ds.setSectIndex(sectindex);
1127 dwsectab.push_back(ds);
1128 }
1129
1130 // Take the lists of data blocks and build a single
1131 // malloc block to contain it all pointing
1132 // to it with the public struct DW_Elf_Data that
1133 // _dwarf_elf_newdata() creates.
1134 // d is dwarfgen section index
1135 static void
1136 InsertDataIntoElf(Dwarf_Unsigned d,Dwarf_P_Debug dbg)
1137 {
1138 Dwarf_Unsigned dw_section_index = 0;
1139 Dwarf_Unsigned length = 0;
1140 int res = 0;
1141 Dwarf_Ptr bytes = 0;
1142
1143 res = dwarf_get_section_bytes_a(dbg,d,
1144 &dw_section_index,&length,&bytes,0);
1145 if (res != DW_DLV_OK) {
1146 cout << "dwarfgen: get_section_bytes_a problem " << d
1147 << endl;
1148 exit(1);
1149 }
1150 SectionForDwarf &ds = dwsectab[dw_section_index];
1151 ds.add_section_content((unsigned char *)bytes,length);
1152 cout << "Inserted " << length <<
1153 " bytes into elf section index "
1154 << dw_section_index << endl;
1155 return;
1156 }
1157
1158 #if 0
1159 {
1160 if (!scn) {
1161 cout <<
1162 "dwarfgen: Unable to _dwarf_elf_getscn "
1163 "on disk transform # "
1164 << d << endl;
1165 exit(1);
1166 }
1167
1168 ElfSectIndex si(elf_section_index);
1169 SectionForDwarf & sfd = FindMySection(si);
1170
1171 DW_Elf_Data* ed = _dwarf_elf_newdata(scn);
1172 if (!ed) {
1173 cout <<
1174 "dwarfgen: _dwarf_elf_newdata died on transformed index "
1175 << d << endl;
1176 exit(1);
1177 }
1178 ed->d_buf = bytes;
1179 ed->d_type = DWARF_T_BYTE;
1180 ed->d_size = length;
1181 ed->d_off = sfd.getNextOffset();
1182 sfd.setNextOffset(ed->d_off + length);
1183 ed->d_align = 1;
1184 ed->d_version = EV_CURRENT;
1185 cout << "Inserted " << length << " bytes into elf section index "
1186 << elf_section_index << endl;
1187 }
1188 #endif
1189
1190 #if 0
1191 static string
1192 printable_rel_type(unsigned char reltype)
1193 {
1194 enum Dwarf_Rel_Type t = (enum Dwarf_Rel_Type)reltype;
1195 switch(t) {
1196 case dwarf_drt_none:
1197 return "dwarf_drt_none";
1198 case dwarf_drt_data_reloc:
1199 return "dwarf_drt_data_reloc";
1200 case dwarf_drt_segment_rel:
1201 return "dwarf_drt_segment_rel";
1202 case dwarf_drt_first_of_length_pair:
1203 return "dwarf_drt_first_of_length_pair";
1204 case dwarf_drt_second_of_length_pair:
1205 return "dwarf_drt_second_of_length_pair";
1206 default:
1207 break;
1208 }
1209 return "drt-unknown (impossible case)";
1210 }
1211 #endif
1212
1213 static Dwarf_Unsigned
1214 FindSymbolValue(ElfSymIndex symi,IRepresentation &irep)
1215 {
1216 ElfSymbols & syms = irep.getElfSymbols();
1217 ElfSymbol & es = syms.getElfSymbol(symi);
1218 Dwarf_Unsigned symv = es.getSymbolValue();
1219 return symv;
1220 }
1221
1222 #if 0
1223 static int
1224 dump_bytes(const char *msg,void *val,int len)
1225 {
1226 char *p = (char *)val;
1227 int i = 0;
1228 cout << msg << " ";
1229 for (; i < len; ++i) {
1230 char x = *(p+i);
1231 cout << IToHex(x,2) <<" ";
1232 }
1233 cout << endl;
1234 }
1235 #endif
1236
1237 /* Lets not assume that the quantities are aligned. */
1238 static void
1239 bitreplace(char *buf, unsigned int targlen, Dwarf_Unsigned newval,
1240 size_t newvalsize)
1241 {
1242 (void)newvalsize;
1243 if (targlen == 4) {
1244 Dwarf_Unsigned my4 = newval;
1245 Dwarf_Unsigned oldval = 0;
1246 ASNX(&oldval,sizeof(oldval),buf,(unsigned)targlen);
1247 oldval += my4;
1248 ASNX(buf,(unsigned)targlen,&oldval,sizeof(oldval));
1249 } else if (targlen == 8) {
1250 Dwarf_Unsigned my8 = newval;
1251 Dwarf_Unsigned oldval = 0;
1252 memcpy(&oldval,buf,targlen);
1253 oldval += my8;
1254 memcpy(buf,&oldval,targlen);
1255 } else {
1256 cout << "dwarfgen: Relocation is length " << targlen <<
1257 " which we do not yet handle." << endl;
1258 exit(1);
1259 }
1260 }
1261
1262 // This remembers nothing, so is slow.
1263 // Used solely with relocations
1264 static char *
1265 findelfbuf(SectionForDwarf &scn,
1266 Dwarf_Unsigned offset,
1267 Dwarf_Unsigned length)
1268 {
1269 Dwarf_Unsigned bloboff = 0;
1270
1271 for (vector<ByteBlob>::iterator it =
1272 scn.sectioncontent_.begin();
1273 it != scn.sectioncontent_.end();
1274 it++) {
1275 ByteBlob &bb = *it;
1276 if (offset >= (bb.len_ + bloboff)) {
1277 bloboff += bb.len_;
1278 continue;
1279 }
1280 Dwarf_Unsigned localoff = offset - bloboff;
1281 if ((localoff + length) > bb.len_) {
1282 cout << "dwarfgen: Relocation at offset " <<
1283 offset << " cannot be accomplished, no buffer. "
1284 << endl;
1285 exit(1);
1286 }
1287 char *lclptr = reinterpret_cast<char *>(bb.bytes_) +
1288 localoff;
1289 return lclptr;
1290 }
1291 cout << " Relocation at offset " << offset <<
1292 " cannot be accomplished, past end of buffers" << endl;
1293 return 0;
1294 }
1295
1296 static void
1297 write_generated_dbg(Dwarf_P_Debug dbg,
1298 IRepresentation &irep)
1299 {
1300 Dwarf_Error err = 0;
1301
1302 // Sectioncount here is dwarfgen blob count, not Elf
1303 // or even section count
1304 Dwarf_Unsigned sectioncount = 0;
1305
1306 // This call does callbacks to inform of all the sections
1307 // we need to create.
1308 int res = dwarf_transform_to_disk_form_a(dbg,&sectioncount,&err);
1309 if (res != DW_DLV_OK) {
1310 if (res == DW_DLV_ERROR) {
1311 string msg(dwarf_errmsg(err));
1312 cout << "Dwarfgen fails: " << msg << endl;
1313 exit(1);
1314 }
1315 /* ASSERT: rex == DW_DLV_NO_ENTRY */
1316 cout << "Dwarfgen fails, some internal error " << endl;
1317 exit(1);
1318 }
1319 Dwarf_Unsigned d = 0;
1320 for (d = 0; d < sectioncount ; ++d) {
1321 InsertDataIntoElf(d,dbg);
1322 }
1323
1324 // Since we are emitting in final form sometimes, we may
1325 // do relocation processing here or we could (but do not)
1326 // emit relocation records into the object file.
1327 // The following is for DW_DLC_SYMBOLIC_RELOCATIONS.
1328
1329 Dwarf_Unsigned reloc_sections_count = 0;
1330 int drd_version = 0;
1331 res = dwarf_get_relocation_info_count(dbg,&reloc_sections_count,
1332 &drd_version,&err);
1333 if (res != DW_DLV_OK) {
1334 cout << "dwarfgen: Error getting relocation info count."
1335 << endl;
1336 exit(1);
1337
1338 }
1339 cout << "Relocations sections count= " << reloc_sections_count <<
1340 " relversion=" << drd_version << endl;
1341 for (Dwarf_Unsigned ct = 0; ct < reloc_sections_count ; ++ct) {
1342 // elf_section_index is the elf index of the
1343 // section to be relocated, and the section number
1344 // in the object file which we are creating.
1345 // In dwarfgen we do not use this as we do not create
1346 // relocation sections. Here it is always zero.
1347 Dwarf_Unsigned elf_section_index = 0;
1348
1349 // elf_section_index_link is the elf index of the
1350 // section the relocations apply to, such as .debug_info.
1351 // An elf index, not dwsectab[] index.
1352 Dwarf_Unsigned elf_section_index_link = 0;
1353
1354 // relocation_buffer_count is the number of relocations
1355 // of this section.
1356 Dwarf_Unsigned relocation_buffer_count = 0;
1357 Dwarf_Relocation_Data reld;
1358 res = dwarf_get_relocation_info(dbg,&elf_section_index,
1359 &elf_section_index_link,
1360 &relocation_buffer_count,
1361 &reld,&err);
1362 // elf_section_index_link
1363 // refers to the output section numbers, not to dwsectab.
1364 if (res != DW_DLV_OK) {
1365 cout << "dwarfgen: Error getting relocation record " <<
1366 ct << "." << endl;
1367 exit(1);
1368 }
1369
1370 int dwseclink = FindMySectionNum(elf_section_index_link);
1371 Dwarf_Unsigned sitarg = dwsectab[dwseclink].getSectIndex();
1372 string linktarg= dwsectab[dwseclink].name_;
1373 Dwarf_Unsigned targsec = sitarg;
1374
1375 cout << "Relocs for sec=" << ct <<
1376 " ourlinkto=" << elf_section_index_link <<
1377 " linktoobjsecnum=" << targsec <<
1378 " name=" << linktarg <<
1379 " reloc-count=" << relocation_buffer_count << endl;
1380 SectionForDwarf &scn = dwsectab[elf_section_index_link];
1381
1382 for (Dwarf_Unsigned r = 0;
1383 r < relocation_buffer_count; ++r) {
1384 Dwarf_Relocation_Data rec = reld+r;
1385 ElfSymIndex symi(rec->drd_symbol_index);
1386 Dwarf_Unsigned newval = FindSymbolValue(symi,irep);
1387 char *buf_to_update = findelfbuf(scn,
1388 rec->drd_offset,rec->drd_length);
1389 if (buf_to_update) {
1390 if (cmdoptions.showrelocdetails) {
1391 cout << "Reloc "<< r <<
1392 " symindex=" << rec->drd_symbol_index <<
1393 " targoffset= " << IToHex(rec->drd_offset) <<
1394 " newval = " << IToHex(newval) << endl;
1395 }
1396 bitreplace(buf_to_update,rec->drd_length,
1397 newval,sizeof(newval));
1398 } else {
1399 if (cmdoptions.showrelocdetails) {
1400 cout << "Reloc "<< r << "does nothing"<<endl;
1401 }
1402 }
1403 }
1404 }
1405 }
1406
1407 static void
1408 write_elf_header(void)
1409 {
1410 unsigned char *datap = 0;
1411
1412 if (dwelfheader.elf_is_32bit()) {
1413 dw_elf32_ehdr &ehp = dwelfheader.e_32_;
1414 memset(&ehp,0,sizeof(ehp));
1415 ehp.e_ident[EI_MAG0] = dwelfheader.e_ident_[EI_MAG0];
1416 ehp.e_ident[EI_MAG1] = dwelfheader.e_ident_[EI_MAG1];
1417 ehp.e_ident[EI_MAG2] = dwelfheader.e_ident_[EI_MAG2];
1418 ehp.e_ident[EI_MAG3] = dwelfheader.e_ident_[EI_MAG3];
1419 ehp.e_ident[EI_CLASS] = dwelfheader.e_ident_[EI_CLASS];
1420 ehp.e_ident[EI_DATA] = dwelfheader.e_ident_[EI_DATA];
1421 ehp.e_ident[EI_VERSION] = dwelfheader.e_ident_[EI_VERSION];
1422 ASNX(ehp.e_machine,sizeof(ehp.e_machine),
1423 &dwelfheader.e_machine_,
1424 sizeof(dwelfheader.e_machine_));
1425 ASNX(ehp.e_type,sizeof(ehp.e_type),
1426 &dwelfheader.e_type_,sizeof(dwelfheader.e_type_));
1427 ASNX(ehp.e_version,sizeof(ehp.e_version),
1428 &dwelfheader.e_version_,
1429 sizeof(dwelfheader.e_version_));
1430 ASNX(ehp.e_shnum,sizeof(ehp.e_shnum),
1431 &dwelfheader.e_shnum_,
1432 sizeof(dwelfheader.e_shnum_));
1433 ASNX(ehp.e_shentsize,sizeof(ehp.e_shentsize),
1434 &dwelfheader.e_shentsize_,
1435 sizeof(dwelfheader.e_shentsize_));
1436 ASNX(ehp.e_shstrndx,sizeof(ehp.e_shstrndx),
1437 &dwelfheader.e_shstrndx_,
1438 sizeof(dwelfheader.e_shstrndx_));
1439 ASNX(ehp.e_shoff,sizeof(ehp.e_shoff),
1440 &dwelfheader.e_shoff_,
1441 sizeof(dwelfheader.e_shoff_));
1442 ASNX(ehp.e_ehsize,sizeof(ehp.e_ehsize),
1443 &dwelfheader.e_ehsize_,
1444 sizeof(dwelfheader.e_ehsize_));
1445 datap = (unsigned char *)&dwelfheader.e_32_;
1446 } else {
1447 dw_elf64_ehdr &ehp = dwelfheader.e_64_;
1448 ehp.e_ident[EI_MAG0] = dwelfheader.e_ident_[EI_MAG0];
1449 ehp.e_ident[EI_MAG1] = dwelfheader.e_ident_[EI_MAG1];
1450 ehp.e_ident[EI_MAG2] = dwelfheader.e_ident_[EI_MAG2];
1451 ehp.e_ident[EI_MAG3] = dwelfheader.e_ident_[EI_MAG3];
1452 ehp.e_ident[EI_CLASS] = dwelfheader.e_ident_[EI_CLASS];
1453 ehp.e_ident[EI_DATA] = dwelfheader.e_ident_[EI_DATA];
1454 ehp.e_ident[EI_VERSION] = dwelfheader.e_ident_[EI_VERSION];
1455 ASNX(ehp.e_machine,sizeof(ehp.e_machine),
1456 &dwelfheader.e_machine_,
1457 sizeof(dwelfheader.e_machine_));
1458 ASNX(ehp.e_type,sizeof(ehp.e_type),
1459 &dwelfheader.e_type_,sizeof(dwelfheader.e_type_));
1460 ASNX(ehp.e_version,sizeof(ehp.e_version),
1461 &dwelfheader.e_version_,
1462 sizeof(dwelfheader.e_version_));
1463 ASNX(ehp.e_shnum,sizeof(ehp.e_shnum),
1464 &dwelfheader.e_shnum_,
1465 sizeof(dwelfheader.e_shnum_));
1466 ASNX(ehp.e_shentsize,sizeof(ehp.e_shentsize),
1467 &dwelfheader.e_shentsize_,
1468 sizeof(dwelfheader.e_shentsize_));
1469 ASNX(ehp.e_shstrndx,sizeof(ehp.e_shstrndx),
1470 &dwelfheader.e_shstrndx_,
1471 sizeof(dwelfheader.e_shstrndx_));
1472 ASNX(ehp.e_shoff,sizeof(ehp.e_shoff),
1473 &dwelfheader.e_shoff_,
1474 sizeof(dwelfheader.e_shoff_));
1475 ASNX(ehp.e_ehsize,sizeof(ehp.e_ehsize),
1476 &dwelfheader.e_ehsize_,
1477 sizeof(dwelfheader.e_ehsize_));
1478 datap = (unsigned char *)&dwelfheader.e_64_;
1479 }
1480 dwwriter.wwrite(0,dwelfheader.e_hdrlen_,datap);
1481 }
1482
1483 // Returns pointer to the content, len of each is
1484 // dwelfheader.e_shentsize_
1485 static unsigned char *
1486 copy_section_hdr_data (SectionForDwarf&sec)
1487 {
1488 if (dwelfheader.elf_is_32bit())
1489 {
1490 dw_elf32_shdr * shdr = &sec.shdr32_;
1491 ASNX(shdr->sh_name,sizeof(shdr->sh_name),
1492 &sec.sh_name_,
1493 sizeof(sec.sh_name_));
1494 ASNX(shdr->sh_type,sizeof(shdr->sh_type),
1495 &sec.sh_type_, sizeof(sec.sh_type_));
1496 ASNX(shdr->sh_flags,sizeof(shdr->sh_flags),
1497 &sec.sh_flags_, sizeof(sec.sh_flags_));
1498 ASNX(shdr->sh_addr,sizeof(shdr->sh_addr),
1499 &sec.sh_addr_, sizeof(sec.sh_addr_));
1500 ASNX(shdr->sh_offset,sizeof(shdr->sh_offset),
1501 &sec.sh_offset_,sizeof(sec.sh_offset_));
1502 ASNX(shdr->sh_size,sizeof(shdr->sh_size),
1503 &sec.sh_size_,sizeof(sec.sh_size_));
1504 ASNX(shdr->sh_link,sizeof(shdr->sh_link),
1505 &sec.sh_link_,sizeof(sec.sh_link_));
1506 ASNX(shdr->sh_info,sizeof(shdr->sh_info),
1507 &sec.sh_info_,sizeof(sec.sh_info_));
1508 ASNX(shdr->sh_addralign,sizeof(shdr->sh_addralign),
1509 &sec.sh_addralign_,sizeof(sec.sh_addralign_));
1510 ASNX(shdr->sh_entsize,sizeof(shdr->sh_entsize),
1511 &sec.sh_entsize_,sizeof(sec.sh_entsize_));
1512 return (unsigned char *)shdr;
1513 } else {
1514 dw_elf64_shdr * shdr = &sec.shdr64_;
1515 ASNX(shdr->sh_name,sizeof(shdr->sh_name),
1516 &sec.sh_name_,
1517 sizeof(sec.sh_name_));
1518 ASNX(shdr->sh_type,sizeof(shdr->sh_type),
1519 &sec.sh_type_, sizeof(sec.sh_type_));
1520 ASNX(shdr->sh_flags,sizeof(shdr->sh_flags),
1521 &sec.sh_flags_, sizeof(sec.sh_flags_));
1522 ASNX(shdr->sh_addr,sizeof(shdr->sh_addr),
1523 &sec.sh_addr_, sizeof(sec.sh_addr_));
1524 ASNX(shdr->sh_offset,sizeof(shdr->sh_offset),
1525 &sec.sh_offset_,sizeof(sec.sh_offset_));
1526 ASNX(shdr->sh_size,sizeof(shdr->sh_size),
1527 &sec.sh_size_,sizeof(sec.sh_size_));
1528 ASNX(shdr->sh_link,sizeof(shdr->sh_link),
1529 &sec.sh_link_,sizeof(sec.sh_link_));
1530 ASNX(shdr->sh_info,sizeof(shdr->sh_info),
1531 &sec.sh_link_,sizeof(sec.sh_link_));
1532 ASNX(shdr->sh_addralign,sizeof(shdr->sh_addralign),
1533 &sec.sh_addralign_,sizeof(sec.sh_addralign_));
1534 ASNX(shdr->sh_entsize,sizeof(shdr->sh_entsize),
1535 &sec.sh_entsize_,sizeof(sec.sh_entsize_));
1536 return (unsigned char *)shdr;
1537 }
1538 /* not reached */
1539 }
1540
1541 static void
1542 write_section_contents(void)
1543 {
1544 for (vector<SectionForDwarf>::iterator it = dwsectab.begin();
1545 it != dwsectab.end();
1546 it++) {
1547 SectionForDwarf &sec = *it;
1548 Dwarf_Unsigned curoff = sec.sh_offset_;
1549
1550 for (vector<ByteBlob>::iterator itb =
1551 sec.sectioncontent_.begin();
1552 itb != sec.sectioncontent_.end();
1553 itb++) {
1554 ByteBlob &bb = *itb;
1555
1556 //cout << "Writing section content " <<i <<
1557 // " at offset " << curoff << endl;
1558 dwwriter.wwrite(curoff,bb.len_,bb.bytes_);
1559 curoff += bb.len_;
1560 }
1561 }
1562 }
1563
1564 static void
1565 write_section_headers()
1566 {
1567 Dwarf_Unsigned headeroff = dwelfheader.e_shoff_;
1568 for (vector<SectionForDwarf>::iterator it = dwsectab.begin();
1569 it != dwsectab.end();
1570 it++) {
1571 //cout << "Writing section header " <<i <<
1572 // " at offset " << headeroff << endl;
1573 SectionForDwarf &sec = *it;
1574 Dwarf_Unsigned hdrlen = dwelfheader.e_shentsize_;
1575
1576 unsigned char *data = copy_section_hdr_data(sec);
1577 dwwriter.wwrite(headeroff,hdrlen,data);
1578 headeroff += dwelfheader.e_shentsize_;
1579 }
1580 }
1581
1582 // We write elf header, sections, section headers.
1583 Dwarf_Unsigned
1584 write_to_object(void)
1585 {
1586 write_elf_header();
1587 write_section_contents();
1588 write_section_headers();
1589
1590 Dwarf_Unsigned len = dwelfheader.e_shoff_+
1591 dwelfheader.e_shnum_* dwelfheader.e_shentsize_;
1592 return len;
1593 }
1594
1595 int
1596 open_a_file(const char * name)
1597 {
1598 /* Set to a file number that cannot be legal. */
1599 int f = -1;
1600
1601 f = open(name, O_RDONLY | O_BINARY);
1602 return f;
1603 }
1604
1605 void
1606 close_a_file(int f)
1607 {
1608 close(f);
1609 }