summaryrefslogtreecommitdiffstats
path: root/src/readDwarf.h
blob: f9593f9729ddfb5e33dfb9a94b941d54ea85f2dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
#ifndef __READDWARF_H__

#define __READDWARF_H__


#include <Windows.h>

#include <cstring>

#include <string>

#include <vector>

#include <unordered_map>

#include "mspdb.h"


typedef unsigned char byte;
class PEImage;
class DIECursor;
struct SectionDescriptor;

enum DebugLevel : unsigned {
	DbgBasic = 0x1,
	DbgPdbTypes = 0x2,
	DbgPdbSyms = 0x4,
	DbgPdbLines = 0x8,
	DbgPdbContrib = 0x10,
	DbgDwarfCompilationUnit = 0x100,
	DbgDwarfTagRead = 0x200,
	DbgDwarfAttrRead = 0x400,
	DbgDwarfLocLists = 0x800,
	DbgDwarfRangeLists = 0x1000,
	DbgDwarfLines = 0x2000
};

DEFINE_ENUM_FLAG_OPERATORS(DebugLevel);

inline unsigned int LEB128(byte* &p)
{
	unsigned int x = 0;
	int shift = 0;
	while (*p & 0x80)
	{
		x |= (*p & 0x7f) << shift;
		shift += 7;
		p++;
	}
	x |= *p << shift;
	p++;
	return x;
}

inline int SLEB128(byte* &p)
{
	unsigned int x = 0;
	int shift = 0;
	while (*p & 0x80)
	{
		x |= (*p & 0x7f) << shift;
		shift += 7;
		p++;
	}
	x |= *p << shift;
	if (*p & 0x40)
		x |= -(1 << (shift + 7)); // sign extend

	p++;
	return x;
}

inline unsigned short RD2(byte* &p)
{
	unsigned int x = *p++;
	x |= *p++ << 8;
	return x;
}

inline unsigned int RD4(byte* &p)
{
	unsigned int x = *p++;
	x |= *p++ << 8;
	x |= *p++ << 16;
	x |= *p++ << 24;
	return x;
}

inline unsigned long long RD8(byte* &p)
{
	unsigned long long x = *p++;
	for (int shift = 8; shift < 64; shift += 8)
		x |= (unsigned long long) *p++ << shift;
	return x;
}

inline unsigned long long RDsize(byte* &p, int size)
{
	if (size > 8)
		size = 8;
	unsigned long long x = *p++;
	for (int shift = 8; shift < size * 8; shift += 8)
		x |= (unsigned long long) *p++ << shift;
	return x;
}

enum AttrClass
{
	Invalid,
	Addr,
	Block,
	Const,
	String,
	Flag,
	Ref,
	ExprLoc,
	SecOffset
};

struct DWARF_Attribute
{
	AttrClass type;
	union
	{
		unsigned long addr;
		struct { byte* ptr; unsigned len; } block;
		unsigned long cons;
		const char* string;
		bool flag;
		byte* ref;
		struct { byte* ptr; unsigned len; } expr;
		unsigned long sec_offset;
	};
};

///////////////////////////////////////////////////////////////////////////////


struct DWARF_CompilationUnitInfo
{
	uint32_t unit_length; // 12 byte in DWARF-64

	unsigned short version;
	byte address_size;
	byte unit_type;
	unsigned int debug_abbrev_offset; // 8 byte in DWARF-64


	// Value of the DW_AT_low_pc attribute for the current compilation unit.

	// Specify the default base address for use in location lists and range

	// lists.

	uint32_t base_address;

	// Indirect base address in .debug_addr for addrx forms

	byte* addr_base;

	// Indirect base address in .debug_str_offsets for strx forms

	byte* str_offset_base;

	// Indirect base address in .debug_loclists for loclistx forms

	byte* loclist_base;

	// Indirect base address in the .debug_rnglists for rnglistx forms

	byte* rnglist_base;

	// Offset within the debug_info section

	uint32_t cu_offset;
	byte* start_ptr;
	byte* end_ptr;

	bool is_dwarf64;

	byte* read(DebugLevel debug, const PEImage& img, unsigned long *off);

	bool isDWARF64() const { return is_dwarf64; }
};

struct DWARF_FileName
{
	const char* file_name;
	unsigned int  dir_index;
	unsigned long lastModification;
	unsigned long fileLength;

	void read(byte* &p)
	{
		file_name = (const char*)p;
		p += strlen((const char*)p) + 1;
		dir_index = LEB128(p);
		lastModification = LEB128(p);
		fileLength = LEB128(p);
	}
};

struct DWARF_InfoData
{
	byte* entryPtr;
	int code;
	byte* abbrev;
	int tag;
	int hasChild;

	const char* name;
	const char* linkage_name;
	const char* dir;
	unsigned long byte_size;
	byte* sibling;
	unsigned long encoding;
	unsigned long pclo;
	unsigned long pchi;
	unsigned long ranges; // -1u when attribute is not present

	unsigned long pcentry;
	byte* type;
	byte* containing_type;
	byte* specification;
	byte* abstract_origin;
	unsigned long inlined;
	bool external;
	DWARF_Attribute location;
	DWARF_Attribute member_location;
	DWARF_Attribute frame_base;
	long upper_bound;
	long lower_bound;
	bool has_lower_bound;
	unsigned language;
	unsigned long const_value;
	bool has_const_value;
	bool is_artificial;
	bool has_artificial;

	void clear()
	{
		entryPtr = 0;
		code = 0;
		abbrev = 0;
		tag = 0;
		hasChild = 0;

		name = 0;
		linkage_name = 0;
		dir = 0;
		byte_size = 0;
		sibling = 0;
		encoding = 0;
		pclo = 0;
		pchi = 0;
		ranges = ~0;
		pcentry = 0;
		type = 0;
		containing_type = 0;
		specification = 0;
		abstract_origin = 0;
		inlined = 0;
		external = 0;
		member_location.type = Invalid;
		location.type = Invalid;
		frame_base.type = Invalid;
		upper_bound = 0;
		lower_bound = 0;
		has_lower_bound = false;
		language = 0;
		const_value = 0;
		has_const_value = false;
		is_artificial = false;
		has_artificial = false;
	}

	void merge(const DWARF_InfoData& id)
	{
		if (!name) name = id.name;
		if (!linkage_name) linkage_name = id.linkage_name;
		if (!dir) dir = id.dir;
		if (!byte_size) byte_size = id.byte_size;
		if (!sibling) sibling = id.sibling;
		if (!encoding) encoding = id.encoding;
		if (!pclo) pclo = id.pclo;
		if (!pchi) pchi = id.pchi;
		if (ranges == ~0) ranges = id.ranges;
		if (!pcentry) pcentry = id.pcentry;
		if (!type) type = id.type;
		if (!containing_type) containing_type = id.containing_type;
		if (!specification) specification = id.specification;
		if (!abstract_origin) abstract_origin = id.abstract_origin;
		if (!inlined) inlined = id.inlined;
		if (!external) external = id.external;
		if (member_location.type == Invalid) member_location = id.member_location;
		if (location.type == Invalid) location = id.location;
		if (frame_base.type == Invalid) frame_base = id.frame_base;
		if (!upper_bound) upper_bound = id.upper_bound;
		if (!has_lower_bound) { lower_bound = id.lower_bound; has_lower_bound = id.has_lower_bound; }
		if (!has_const_value) { const_value = id.const_value; has_const_value = id.has_const_value; }
		if (!has_artificial) { is_artificial = id.is_artificial; has_artificial = id.has_artificial; }
	}
};

static const int maximum_operations_per_instruction = 1;

struct DWARF_TypeForm
{
	unsigned int type, form;
};

#include "pshpack1.h"


struct DWARF_LineNumberProgramHeader
{
	unsigned int unit_length; // 12 byte in DWARF-64

	unsigned short version;
	byte address_size; // new in DWARF5

	byte segment_selector_size; // new in DWARF5

	unsigned int header_length; // 8 byte in DWARF-64

	byte minimum_instruction_length;
	byte maximum_operations_per_instruction; // not in DWARF 2/3

	byte default_is_stmt;
	signed char line_base;
	byte line_range;
	byte opcode_base;
	//LEB128 standard_opcode_lengths[opcode_base];

	// string include_directories[] // zero byte terminated

	// DWARF_FileNames file_names[] // zero byte terminated

};

struct DWARF4_LineNumberProgramHeader
{
	unsigned int unit_length; // 12 byte in DWARF-64

	unsigned short version;
	unsigned int header_length; // 8 byte in DWARF-64

	byte minimum_instruction_length;
	byte maximum_operations_per_instruction; // not in DWARF 2/3

	byte default_is_stmt;
	signed char line_base;
	byte line_range;
	byte opcode_base;
	//LEB128 standard_opcode_lengths[opcode_base];

	// string include_directories[] // zero byte terminated

	// DWARF_FileNames file_names[] // zero byte terminated

};

struct DWARF2_LineNumberProgramHeader
{
	unsigned int unit_length; // 12 byte in DWARF-64

	unsigned short version;
	unsigned int header_length; // 8 byte in DWARF-64

	byte minimum_instruction_length;
	//byte maximum_operations_per_instruction; (// not in DWARF 2

	byte default_is_stmt;
	signed char line_base;
	byte line_range;
	byte opcode_base;
	//LEB128 standard_opcode_lengths[opcode_base];

	// string include_directories[] // zero byte terminated

	// DWARF_FileNames file_names[] // zero byte terminated

};

#include "poppack.h"


struct DWARF_LineState
{
	// hdr info

	std::vector<const char*> include_dirs;
	std::vector<DWARF_FileName> files;

	unsigned long address;
	unsigned int  op_index;
	unsigned int  file;
	unsigned int  line;
	unsigned int  column;
	bool          is_stmt;
	bool          basic_block;
	bool          end_sequence;
	bool          prologue_end;
	bool          epilogue_end;
	unsigned int  isa;
	unsigned int  discriminator;

	// not part of the "documented" state

	DWARF_FileName* file_ptr;
	unsigned long seg_offset;
	unsigned long section;
	unsigned long last_addr;
	std::vector<mspdb::LineInfoEntry> lineInfo;
	unsigned int lineInfo_file;

	DWARF_LineState()
	{
		file_ptr = nullptr;
		seg_offset = 0x400000;
		last_addr = 0;
		lineInfo_file = 0;

		init(0);
	}

	void init(DWARF_LineNumberProgramHeader* hdr)
	{
        section = -1;
		address = 0;
		op_index = 0;
		file = 1;
		line = 1;
		column = 0;
		is_stmt = hdr && hdr->default_is_stmt != 0;
		basic_block = false;
		end_sequence = false;
		prologue_end = false;
		epilogue_end = false;
		isa = 0;
		discriminator = 0;
	}

	void advance_addr(DWARF_LineNumberProgramHeader* hdr, int operation_advance)
	{
		int address_advance = hdr->minimum_instruction_length * ((op_index + operation_advance) / maximum_operations_per_instruction);
		address += address_advance;
		op_index = (op_index + operation_advance) % maximum_operations_per_instruction;
	}
};


///////////////////////////////////////////////////////////////////////////////


#define DW_REG_CFA 257


struct Location
{
	enum Type
	{
		Invalid, // Failed to evaluate the location expression

		InReg,   // In register (reg)

		Abs,     // Absolute address (off)

		RegRel   // Register-relative address ($reg + off)

	};

	Type type;
	int reg;
	int off;

	bool is_invalid() const { return type == Invalid; }
	bool is_inreg() const { return type == InReg; }
	bool is_abs() const { return type == Abs; }
	bool is_regrel() const { return type == RegRel; }
};

// Location list entry

class LOCEntry
{
public:
	unsigned long beg_offset;
	unsigned long end_offset;
	bool isDefault;
	Location loc;

	void addBase(uint32_t base)
	{
		beg_offset += base;
		end_offset += base;
	}
};

// Location list cursor

class LOCCursor
{
public:
	LOCCursor(const DIECursor& parent, unsigned long off);

	const DIECursor& parent;
	uint32_t base;
	byte* end;
	byte* ptr;
	bool isLocLists;

	bool readNext(LOCEntry& entry);
};

// Range list entry

class RangeEntry
{
public:
	uint64_t pclo;
	uint64_t pchi;

	void addBase(uint64_t base)
	{
		pclo += base;
		pchi += base;
	}
};

// Range list cursor

class RangeCursor
{
public:
	RangeCursor(const DIECursor& parent, unsigned long off);

	const DIECursor& parent;
	uint32_t base;
	byte *end;
	byte *ptr;
	bool isRngLists;

	bool readNext(RangeEntry& entry);
};

typedef std::unordered_map<std::pair<unsigned, unsigned>, byte*> abbrevMap_t;

// Attempts to partially evaluate DWARF location expressions.

// The only supported expressions are those, whose result may be represented

// as either an absolute value, a register, or a register-relative address.

Location decodeLocation(const DWARF_Attribute& attr, const Location* frameBase = 0, int at = 0);

void mergeAbstractOrigin(DWARF_InfoData& id, const DIECursor& parent);
void mergeSpecification(DWARF_InfoData& id, const DIECursor& parent);

// Debug Information Entry Cursor

class DIECursor
{
public:
	DWARF_CompilationUnitInfo* cu;
	byte* ptr;
	unsigned int entryOff;
	int level;
	bool hasChild; // indicates whether the last read DIE has children

	byte* sibling;

	static PEImage *img;
	static abbrevMap_t abbrevMap;
	static DebugLevel debug;

	byte* getDWARFAbbrev(unsigned off, unsigned findcode);

public:

	static void setContext(PEImage* img_, DebugLevel debug_);

	// Create a new DIECursor

	DIECursor(DWARF_CompilationUnitInfo* cu_, byte* ptr);

	// Create a child DIECursor

	DIECursor(const DIECursor& parent, byte* ptr_);

	// Goto next sibling DIE.  If the last read DIE had any children, they will be skipped over.

	void gotoSibling();

	// Reads next sibling DIE.  If the last read DIE had any children, they will be skipped over.

	// Returns 'false' upon reaching the last sibling on the current level.

	bool readSibling(DWARF_InfoData& id);

	// Returns cursor that will enumerate children of the last read DIE.

	DIECursor getSubtreeCursor();

	// Reads the next DIE in physical order, returns 'true' if succeeds.

	// If stopAtNull is true, readNext() will stop upon reaching a null DIE (end of the current tree level).

	// Otherwise, it will skip null DIEs and stop only at the end of the subtree for which this DIECursor was created.

	bool readNext(DWARF_InfoData& id, bool stopAtNull = false);

	// Read an address from p according to the ambient pointer size.

	uint64_t RDAddr(byte* &p) const
	{
		if (cu->address_size == 4)
			return RD4(p);

		return RD8(p);
	}

	unsigned long long RDref(byte* &ptr) const { return cu->isDWARF64() ? RD8(ptr) : RD4(ptr); }
	int refSize() const { return cu->isDWARF64() ? 8 : 4; }

	// Obtain the address of a string for a strx form.

	const char *resolveIndirectString(uint32_t index) const ;
	uint32_t readIndirectAddr(uint32_t index) const ;
	uint32_t resolveIndirectSecPtr(uint32_t index, const SectionDescriptor &secDesc, byte *baseAddress) const;

};

// iterate over DWARF debug_line information

// if mod is null, print them out, otherwise add to module

bool interpretDWARFLines(const PEImage& img, mspdb::Mod* mod, DebugLevel debug = DebugLevel{});

#endif