-
Notifications
You must be signed in to change notification settings - Fork 149
/
dwarfWalker.C
2548 lines (2123 loc) · 84.4 KB
/
dwarfWalker.C
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* See the dyninst/COPYRIGHT file for copyright information.
*
* We provide the Paradyn Tools (below described as "Paradyn")
* on an AS IS basis, and do not warrant its validity or performance.
* We reserve the right to update, modify, or discontinue this
* software at any time. We shall have no obligation to supply such
* updates or modifications or any other form of support to you.
*
* By your use of Paradyn, you understand and agree that we (or any
* other person or entity with proprietary rights in Paradyn) are
* under no obligation to provide either maintenance services,
* update services, notices of latent defects, or correction of
* defects for Paradyn.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "dwarfWalker.h"
#include "headers.h"
#include "Module.h"
#include "Symtab.h"
#include "Collections.h"
#include "dwarf.h"
#include "Object.h"
#include "Object-elf.h"
#include "Function.h"
#include "debug.h"
#include "dwarfExprParser.h"
#include "pathName.h"
#include "debug_common.h"
#include <boost/bind.hpp>
using namespace Dyninst;
using namespace SymtabAPI;
using namespace Dwarf;
using namespace std;
#define DWARF_FAIL_RET_VAL(x, v) { \
int status = (x); \
if (status != DW_DLV_OK) { \
types_printf("[%s:%d]: libdwarf returned %d, ret false\n", FILE__, __LINE__, status); \
return (v); \
} \
}
#define DWARF_FAIL_RET(x) DWARF_FAIL_RET_VAL(x, false)
#define DWARF_ERROR_RET_VAL(x, v) { \
int status = (x); \
if (status == DW_DLV_ERROR) { \
types_printf("[%s:%d]: parsing failure, ret false\n", FILE__, __LINE__); \
return (v); \
} \
}
#define DWARF_ERROR_RET(x) DWARF_ERROR_RET_VAL(x, false)
#define DWARF_CHECK_RET_VAL(x, v) { \
if (x) { \
types_printf("[%s:%d]: parsing failure, ret false\n", FILE__, __LINE__); \
return (v); \
} \
}
#define DWARF_CHECK_RET(x) DWARF_CHECK_RET_VAL(x, false)
DwarfWalker::DwarfWalker(Symtab *symtab, Dwarf_Debug dbg)
:
DwarfParseActions(symtab, dbg),
srcFileList_(NULL),
is_mangled_name_(false),
modLow(0),
modHigh(0),
cu_header_length(0),
version(0),
abbrev_offset(0),
addr_size(0),
offset_size(0),
extension_size(0),
signature(),
typeoffset(0),
next_cu_header(0),
compile_offset(0)
{
}
DwarfWalker::~DwarfWalker() {
}
bool DwarfWalker::parse() {
dwarf_printf("Parsing DWARF for %s\n",filename().c_str());
/* Start the dwarven debugging. */
Module *fixUnknownMod = NULL;
mod() = NULL;
/* Prepopulate type signatures for DW_FORM_ref_sig8 */
findAllSig8Types();
/* First .debug_types (0), then .debug_info (1) */
for (int i = 0; i < 2; ++i) {
Dwarf_Bool is_info = i;
/* NB: parseModule used to compute compile_offset as 11 bytes before the
* first die offset, to account for the header. This would need 23 bytes
* instead for 64-bit format DWARF, and even more for type units.
* (See DWARF4 sections 7.4 & 7.5.1.)
* But more directly, we know the first CU is just at 0x0, and each
* following CU is already reported in next_cu_header.
*/
compile_offset = next_cu_header = 0;
Dwarf_Error err;
/* Iterate over the compilation-unit headers. */
while (dwarf_next_cu_header_c(dbg(), is_info,
&cu_header_length,
&version,
&abbrev_offset,
&addr_size,
&offset_size,
&extension_size,
&signature,
&typeoffset,
&next_cu_header, &err) == DW_DLV_OK ) {
push();
bool ret = parseModule(is_info, fixUnknownMod);
pop();
if (!ret) return false;
compile_offset = next_cu_header;
}
}
if (!fixUnknownMod)
return true;
dwarf_printf("Fixing types for final module %s\n", fixUnknownMod->fileName().c_str());
/* Fix type list. */
typeCollection *moduleTypes = typeCollection::getModTypeCollection(fixUnknownMod);
assert(moduleTypes);
dyn_hash_map< int, Type * >::iterator typeIter = moduleTypes->typesByID.begin();
for (;typeIter!=moduleTypes->typesByID.end();typeIter++)
{
typeIter->second->fixupUnknowns(fixUnknownMod);
} /* end iteration over types. */
/* Fix the types of variables. */
std::string variableName;
dyn_hash_map< std::string, Type * >::iterator variableIter = moduleTypes->globalVarsByName.begin();
for (;variableIter!=moduleTypes->globalVarsByName.end();variableIter++)
{
if (variableIter->second->getDataClass() == dataUnknownType &&
moduleTypes->findType( variableIter->second->getID() ) != NULL )
{
moduleTypes->globalVarsByName[ variableIter->first ]
= moduleTypes->findType( variableIter->second->getID() );
} /* end if data class is unknown but the type exists. */
} /* end iteration over variables. */
moduleTypes->setDwarfParsed();
return true;
}
bool DwarfWalker::parseModule(Dwarf_Bool is_info, Module *&fixUnknownMod) {
/* Obtain the module DIE. */
Dwarf_Die moduleDIE;
DWARF_FAIL_RET(dwarf_siblingof_b( dbg(), NULL, is_info, &moduleDIE, NULL ));
/* Make sure we've got the right one. */
Dwarf_Half moduleTag;
DWARF_FAIL_RET(dwarf_tag( moduleDIE, & moduleTag, NULL ));
if (moduleTag != DW_TAG_compile_unit
&& moduleTag != DW_TAG_partial_unit
&& moduleTag != DW_TAG_type_unit)
return false;
/* Extract the name of this module. */
std::string moduleName;
if (!findDieName(dbg(), moduleDIE, moduleName)) return false;
if (moduleName.empty() && moduleTag == DW_TAG_type_unit) {
uint64_t sig8 = * reinterpret_cast<uint64_t*>(&signature);
char buf[20];
snprintf(buf, sizeof(buf), "{%016llx}", (long long) sig8);
moduleName = buf;
}
if (moduleName.empty()) {
moduleName = "{ANONYMOUS}";
}
dwarf_printf("Next DWARF module: %s with DIE %p and tag %d\n", moduleName.c_str(), moduleDIE, moduleTag);
/* Set the language, if any. */
Dwarf_Attribute languageAttribute;
DWARF_ERROR_RET(dwarf_attr( moduleDIE, DW_AT_language, & languageAttribute, NULL ));
// Set low and high ranges; this can fail, so don't check return addr.
setEntry(moduleDIE);
// These may not be set.
Address tempModLow, tempModHigh;
modLow = modHigh = 0;
if (findConstant(DW_AT_low_pc, tempModLow, entry(), dbg())) {
modLow = convertDebugOffset(tempModLow);
}
if (findConstant(DW_AT_high_pc, tempModHigh, entry(), dbg())) {
modHigh = convertDebugOffset(tempModHigh);
}
setModuleFromName(moduleName);
//dwarf_printf("Mapped to Symtab module %s\n", mod()->fileName().c_str());
if (!fixUnknownMod)
fixUnknownMod = mod();
if (!parse_int(moduleDIE, true)) return false;
return true;
}
void DwarfParseActions::setModuleFromName(std::string moduleName)
{
if (!symtab()->findModuleByName(mod(), moduleName))
{
std::string fName = extract_pathname_tail(moduleName);
if (!symtab()->findModuleByName(mod(), fName)) {
moduleName = symtab()->file();
if (!symtab()->findModuleByName(mod(), moduleName)) {
mod() = (symtab()->getDefaultModule());
}
}
}
}
bool DwarfWalker::buildSrcFiles(Dwarf_Debug dbg, Dwarf_Die entry, StringTablePtr srcFiles) {
Dwarf_Signed cnt = 0;
char** srcFileList;
DWARF_ERROR_RET(dwarf_srcfiles(entry, &srcFileList, &cnt, NULL));
if(!srcFiles->empty()) {
return true;
} // already parsed, the module had better be right.
srcFiles->push_back("Unknown file");
for (unsigned i = 0; i < cnt; ++i) {
srcFiles->push_back(srcFileList[i]);
dwarf_dealloc(dbg, srcFileList[i], DW_DLA_STRING);
}
dwarf_dealloc(dbg, srcFileList, DW_DLA_LIST);
return true;
}
// As mentioned in the header, this is separate from parse()
// so we can have a non-Context-creating parse method that reuses
// the Context from the parent. This allows us to pass in current
// function, etc. without the Context stack exploding
bool DwarfWalker::parse_int(Dwarf_Die e, bool p) {
dwarf_printf("PARSE_INT entry, context size %d\n", stack_size());
// We escape the loop by checking parseSibling() after
// parsing this DIE and its children, if any
while(1) {
ContextGuard cg(*this);
setEntry(e);
setParseSibling(p);
if (!findTag()) return false;
if (!findOffset()) return false;
curName() = std::string();
setMangledName(false);
dwarf_printf("(0x%lx) Parsing entry %p with context size %d, func %p, encl %p\n",
id(),
e,
stack_size(),
curFunc(),
// (curFunc() && !curFunc()->getAllMangledNames().empty()) ?
//curFunc()->getAllMangledNames()[0].c_str() : "<null>",
curEnclosure());
bool ret = false;
// BLUEGENE BUG HACK
#if defined(os_bg)
if (tag() == DW_TAG_base_type ||
tag() == DW_TAG_const_type ||
tag() == DW_TAG_pointer_type) {
// XLC compilers nest a bunch of stuff under an invented function; however,
// this is broken (they don't close the function properly). If we see a
// tag like this, close off the previous function immediately
clearFunc();
}
#endif
switch(tag()) {
case DW_TAG_subprogram:
case DW_TAG_entry_point:
ret = parseSubprogram(NormalFunc);
break;
case DW_TAG_inlined_subroutine:
ret = parseSubprogram(InlinedFunc);
break;
case DW_TAG_lexical_block:
ret = parseLexicalBlock();
break;
case DW_TAG_common_block:
ret = parseCommonBlock();
break;
case DW_TAG_constant:
ret = parseConstant();
break;
case DW_TAG_variable:
ret = parseVariable();
break;
case DW_TAG_formal_parameter:
ret = parseFormalParam();
break;
case DW_TAG_base_type:
ret = parseBaseType();
break;
case DW_TAG_typedef:
ret = parseTypedef();
break;
case DW_TAG_array_type:
ret = parseArray();
break;
case DW_TAG_subrange_type:
ret = parseSubrange();
break;
case DW_TAG_enumeration_type:
ret = parseEnum();
break;
case DW_TAG_inheritance:
ret = parseInheritance();
break;
case DW_TAG_structure_type:
case DW_TAG_union_type:
case DW_TAG_class_type:
ret = parseStructUnionClass();
break;
case DW_TAG_enumerator:
ret = parseEnumEntry();
break;
case DW_TAG_member:
ret = parseMember();
break;
case DW_TAG_const_type:
case DW_TAG_packed_type:
case DW_TAG_volatile_type:
ret = parseConstPackedVolatile();
break;
case DW_TAG_subroutine_type:
/* If the pointer specifies argument types, this DIE has
children of those types. */
case DW_TAG_ptr_to_member_type:
case DW_TAG_pointer_type:
case DW_TAG_reference_type:
ret = parseTypeReferences();
break;
case DW_TAG_compile_unit:
dwarf_printf("(0x%lx) Compilation unit, parsing children\n", id());
// Parse child
ret = parseChild();
break;
case DW_TAG_partial_unit:
dwarf_printf("(0x%lx) Partial unit, parsing children\n", id());
// Parse child
ret = parseChild();
break;
case DW_TAG_type_unit:
dwarf_printf("(0x%lx) Type unit, parsing children\n", id());
// Parse child
ret = parseChild();
break;
default:
dwarf_printf("(0x%lx) Warning: unparsed entry with tag %x\n",
id(), tag());
ret = true;
break;
}
dwarf_printf("Finished parsing 0x%lx, ret %d, parseChild %d, parseSibling %d\n",
id(), ret, parseChild(), parseSibling());
if (ret && parseChild() ) {
// Parse children
Dwarf_Die childDwarf;
int status = dwarf_child( entry(), & childDwarf, NULL );
DWARF_CHECK_RET(status == DW_DLV_ERROR);
if (status == DW_DLV_OK) {
if (!parse_int(childDwarf, true)) return false;
}
}
if (!parseSibling()) {
dwarf_printf("(0x%lx) Skipping sibling parse\n", id());
break;
}
dwarf_printf("(0x%lx) Asking for sibling\n", id());
Dwarf_Die siblingDwarf;
Dwarf_Bool is_info = dwarf_get_die_infotypes_flag(entry());
int status = dwarf_siblingof_b( dbg(), entry(), is_info, & siblingDwarf, NULL );
DWARF_CHECK_RET(status == DW_DLV_ERROR);
/* Deallocate the entry we just parsed. */
dwarf_dealloc( dbg(), entry(), DW_DLA_DIE );
if (status != DW_DLV_OK) {
break;
}
e = siblingDwarf;
}
dwarf_printf("PARSE_INT exit, context size %d\n", stack_size());
return true;
}
bool DwarfWalker::parseCallsite()
{
Dwarf_Bool has_line = false, has_file = false;
DWARF_FAIL_RET(dwarf_hasattr(entry(), DW_AT_call_file, &has_file, NULL));
if (!has_file)
return true;
DWARF_FAIL_RET(dwarf_hasattr(entry(), DW_AT_call_line, &has_line, NULL));
if (!has_line)
return true;
std::string inline_file;
bool result = findString(DW_AT_call_file, inline_file);
if (!result)
return false;
Dyninst::Offset inline_line;
result = findConstant(DW_AT_call_line, inline_line, entry(), dbg());
if (!result)
return false;
InlinedFunction *ifunc = static_cast<InlinedFunction *>(curFunc());
// cout << "Found inline call site in func (0x" << hex << id() << ") "
// << curFunc()->getName() << " at " << curFunc()->getOffset() << dec
// << ", file " << inline_file << ": " << inline_line << endl;
ifunc->setFile(inline_file);
ifunc->callsite_line = inline_line;
return true;
}
bool DwarfWalker::setFunctionFromRange(inline_t func_type)
{
//Use the lowest range as an entry for symbol matching
Address lowest = 0x0;
bool set_lowest = false;
if (!hasRanges()) {
dwarf_printf("(0x%lx) setFunctionFromRange has no ranges, returning false\n", id());
return false;
}
for (range_set_t::iterator i = ranges_begin(); i != ranges_end(); i++) {
if (!set_lowest) {
lowest = i->first;
set_lowest = true;
continue;
}
if (lowest > i->first)
lowest = i->first;
}
if (!set_lowest) {
//No ranges. Don't panic, this is probably an abstract origin or specification
// we'll get to it latter if it's really used.
dwarf_printf("(0x%lx) setFunctionFromRange has ranges, but no lowest, returning false\n", id());
return false;
}
if (func_type == InlinedFunc) {
return createInlineFunc();
}
//Try to associate the function with existing symbols
setFuncFromLowest(lowest);
return true;
}
void DwarfWalker::setFuncFromLowest(Address lowest) {
Function *f = NULL;
bool result = symtab()->findFuncByEntryOffset(f, lowest);
if (result) {
dwarf_printf("(0x%lx) Lookup by offset 0x%lx identifies %p\n",
id(), lowest, curFunc());
setFunc(f);
} else {
dwarf_printf("(0x%lx) Lookup by offset 0x%lx failed\n", id(), lowest);
}
}
bool DwarfWalker::createInlineFunc() {
FunctionBase *parent = curFunc();
if (parent) {
InlinedFunction *ifunc = new InlinedFunction(parent);
setFunc(ifunc);
// cout << "Created new inline, parent is " << parent->getName() << endl;
return true;
} else {
//InlinedSubroutine without containing subprogram. Weird.
dwarf_printf("(0x%lx) setFunctionFromRange found inline without parent, returning false\n", id());
return false;
}
}
void DwarfParseActions::addMangledFuncName(std::string name)
{
curFunc()->addMangledName(name, true, true);
}
void DwarfParseActions::addPrettyFuncName(std::string name)
{
curFunc()->addPrettyName(name, true, true);
}
void restore(int old) {
common_debug_dwarf = old;
}
bool DwarfWalker::parseSubprogram(DwarfWalker::inline_t func_type) {
bool name_result;
int old = common_debug_dwarf;
boost::shared_ptr<void> guard(static_cast<void*>(0), bind(restore, old));
// common_debug_dwarf = 1;
dwarf_printf("(0x%lx) parseSubprogram entry\n", id());
parseRangeTypes(dbg(), entry());
setFunctionFromRange(func_type);
// Name first
FunctionBase *func = curFunc();
name_result = findFuncName();
// if(func) cout << hex << "Begin parseSubprogram for (" << id() << ") " << func->getName() << " at " << func->getOffset() << dec << endl;
if (curEnclosure() && !func) {
// This is a member function; create the type entry
// Since curFunc is false, we're not going back to reparse this
// entry with a function object.
Type *ftype = NULL;
getReturnType(false, ftype);
addFuncToContainer(ftype);
dwarf_printf("(0x%lx) parseSubprogram not parsing member function's children\n", id());
setParseChild(false);
}
//curFunc will be set if we're parsing a defined object, or
// if we're recursively parsing a specification or abstract
// entry under a defined object. It'll be unset if we're
// parsing a specification or abstract entry at the top-level
//This keeps us from parsing abstracts or specifications until
// we need them.
if (!func) {
dwarf_printf("(0x%lx) parseSubprogram not parsing children b/c curFunc() NULL\n", id());
setParseChild(false);
return true;
}
if (parsedFuncs.find(func) != parsedFuncs.end()) {
dwarf_printf("(0x%lx) parseSubprogram not parsing children b/c curFunc() not in parsedFuncs\n", id());
if(name_result) {
dwarf_printf("\tname is %s\n", curName().c_str());
}
setParseChild(false);
return true;
}
if (name_result && !curName().empty()) {
dwarf_printf("(0x%lx) Identified function name as %s\n", id(), curName().c_str());
if (isMangledName()) {
func->addMangledName(curName(), true);
}
// Only keep pretty names around for inlines, which probably don't have mangled names
else {
// printf("(0x%lx) Adding %s as pretty name to inline at 0x%lx\n", id(), curName().c_str(), func->getOffset());
dwarf_printf("(0x%lx) Adding as pretty name to inline\n", id());
func->addPrettyName(curName(), true);
}
}
//Collect callsite information for inlined functions.
if (func_type == InlinedFunc) {
// cout << "Parsing callsite for (0x" << hex << id() << ") " << curName() << " at " << func->getOffset() << dec << endl;
parseCallsite();
}
// Get the return type
setFuncReturnType();
// Get range information
if (hasRanges()) {
setRanges(func);
}
// Dwarf outlines some function information. You have the base entry, which contains
// address ranges, frame base information, and optionally a "abstract origin"
// or "specification" entry that points to more information.
// We want to skip parsing specification or abstract entries until we have
// the base entry and can find/create the corresponding function object.
// Get the frame base if it exists
if (!getFrameBase()) return false;
// Parse parent nodes and their children but not their sibling
bool hasAbstractOrigin = false;
if (!handleAbstractOrigin(hasAbstractOrigin)) return false;
if (hasAbstractOrigin) {
dwarf_printf("(0x%lx) Parsing abstract parent\n", id());
if (!parse_int(abstractEntry(), false)) return false;
dwarf_dealloc(dbg(), abstractEntry(), DW_DLA_DIE);
}
// An abstract origin will point to a specification if it exists
// This can actually be three-layered, so backchain again
bool hasSpecification = false;
if (!handleSpecification(hasSpecification)) return false;
if ( hasSpecification ) {
dwarf_printf("(0x%lx) Parsing specification entry\n", id());
if (!parse_int(specEntry(), false)) return false;
}
parsedFuncs.insert(func);
if (func_type == InlinedFunc) {
// cout << "End parseSubprogram for inlined func " << curName() << " at " << func->getOffset() << endl;
}
return true;
}
void DwarfWalker::setRanges(FunctionBase *func) {
if(func->ranges.empty()) {
Address last_low = 0, last_high = 0;
func->ranges.reserve(rangesSize());
for (auto i = ranges_begin(); i != ranges_end(); i++) {
Address low = i->first;
Address high = i->second;
if (last_low == low && last_high == high)
continue;
last_low = low;
last_high = high;
func->ranges.push_back(FuncRange(low, high - low, curFunc()));
}
}
}
pair<AddressRange, bool> DwarfWalker::parseHighPCLowPC(Dwarf_Debug dbg, Dwarf_Die entry)
{
Dwarf_Attribute hasLow;
Dwarf_Attribute hasHigh;
std::pair<AddressRange, bool> result = make_pair(AddressRange(0,0), false);
if(dwarf_attr(entry, DW_AT_low_pc, &hasLow, NULL) != DW_DLV_OK) return result;
if(dwarf_attr(entry, DW_AT_high_pc, &hasHigh, NULL) != DW_DLV_OK) return result;
Address low, high;
if (!findConstant(DW_AT_low_pc, low, entry, dbg)) return result;
if (!findConstant(DW_AT_high_pc, high, entry, dbg)) return result;
Dwarf_Half form;
if(dwarf_whatform(hasHigh, &form, NULL) != DW_DLV_OK) return result;
if(form != DW_FORM_addr)
{
high += low;
}
// Don't add 0,0; it's not a real range but a sign something went wrong.
if(low || high)
{
dwarf_printf("Lexical block from 0x%lx to 0x%lx\n", low, high);
result = make_pair(AddressRange(low, high), true);
}
return result;
}
bool DwarfWalker::parseRangeTypes(Dwarf_Debug dbg, Dwarf_Die die) {
dwarf_printf("(0x%lx) Parsing ranges\n", id());
clearRanges();
std::vector<AddressRange> newRanges = getDieRanges(dbg, die, modLow);
for(auto r = newRanges.begin();
r != newRanges.end();
++r)
{
setRange(*r);
}
return !newRanges.empty();
}
vector<AddressRange> DwarfWalker::getDieRanges(Dwarf_Debug dbg, Dwarf_Die die, Offset range_base) {
std::vector<AddressRange> newRanges;
auto highlow = parseHighPCLowPC(dbg, die);
if(highlow.second) newRanges.push_back(highlow.first);
Address range_offset;
if (findConstant(DW_AT_ranges, range_offset, die, dbg))
{
Dwarf_Ranges *ranges = NULL;
Dwarf_Signed ranges_length = 0;
dwarf_printf("calling ranges_a, offset 0x%lx, die %p\n", range_offset, die);
int status = (dwarf_get_ranges_a(dbg, (Dwarf_Off) range_offset, die,
&ranges, &ranges_length, NULL, NULL));
bool done = (status != DW_DLV_OK);
for (unsigned i = 0; i < ranges_length && !done; i++) {
Dwarf_Ranges cur = ranges[i];
Address cur_base = range_base;
switch (cur.dwr_type) {
case DW_RANGES_ENTRY: {
Address low = cur.dwr_addr1 + cur_base;
Address high = cur.dwr_addr2 + cur_base;
dwarf_printf("Lexical block from 0x%lx to 0x%lx\n", low, high);
newRanges.push_back(AddressRange(low, high));
// mod()->addRange(low, high);
break;
}
case DW_RANGES_ADDRESS_SELECTION:
cur_base = cur.dwr_addr2;
break;
case DW_RANGES_END:
done = true;
break;
}
}
dwarf_ranges_dealloc(dbg, ranges, ranges_length);
}
return newRanges;
}
bool DwarfWalker::parseLexicalBlock() {
dwarf_printf("(0x%lx) Parsing lexical block\n", id());
return parseRangeTypes(dbg(), entry());
}
bool DwarfWalker::parseCommonBlock() {
dwarf_printf("(0x%lx) Parsing common block\n", id());
std::string commonBlockName;
if (!findDieName(dbg(), entry(), commonBlockName)) return false;
Symbol* commonBlockVar = findSymbolForCommonBlock(commonBlockName);
if(!commonBlockVar)
{
return false;
}
typeCommon *commonBlockType = getCommonBlockType(commonBlockName);
setCommon(commonBlockType);
return true;
}
Symbol *DwarfWalker::findSymbolForCommonBlock(const string &commonBlockName) {
return findSymbolByName(commonBlockName, Symbol::ST_OBJECT);
}
typeCommon *DwarfWalker::getCommonBlockType(string &commonBlockName) {
typeCommon *commonBlockType = NULL;
commonBlockType = dynamic_cast<typeCommon *>(tc()->findVariableType(commonBlockName));
if (commonBlockType == NULL) {
commonBlockType = new typeCommon( type_id(), commonBlockName );
tc()->addGlobalVariable(commonBlockName, commonBlockType );
}
return commonBlockType;
}
bool DwarfWalker::parseConstant() {
// Right now we don't handle these
dwarf_printf("(0x%lx) Skipping named constant/variable with constant value\n", id());
return true;
}
bool DwarfWalker::parseVariable() {
dwarf_printf("(0x%lx) ParseVariable entry\n", id());
/* Acquire the name, type, and line number. */
/* A variable may occur inside a function, as either static or local.
A variable may occur inside a container, as C++ static member.
A variable may not occur in either, as a global.
For the first two cases, we need the variable's name, its type,
its line number, and its offset or address in order to tell
Dyninst about it. Dyninst only needs to know the name and type
of a global. (Actually, it already knows the names of the globals;
we're really just telling it the types.)
Variables may have two entries, the second, with a _specification,
being the only one with the location. */
/* If this DIE has a _specification, use that for the rest of our inquiries. */
bool hasSpecification = false;
if (!handleSpecification(hasSpecification)) return false;
if (!findName(curName())) return false;
removeFortranUnderscore(curName());
/* We'll start with the location, since that's most likely to
require the _specification. */
std::vector<VariableLocation> locs;
if (!decodeLocationList(DW_AT_location, NULL, locs)) return false;
if (locs.empty()) return true;
for (unsigned i=0; i<locs.size(); i++) {
//if (locs[i].stClass != storageAddr)
//continue;
if (locs[i].lowPC) {
locs[i].lowPC = convertDebugOffset(locs[i].lowPC);
}
if (locs[i].hiPC) {
locs[i].hiPC = convertDebugOffset(locs[i].hiPC);
}
}
Type *type = NULL;
if (!findType(type, false)) return false;
assert(type);
Dwarf_Unsigned variableLineNo;
bool hasLineNumber = false;
std::string fileName;
if (!curFunc() && !curEnclosure()) {
createGlobalVariable(locs, type);
} /* end if this variable is a global */
else
{
if (!getLineInformation(variableLineNo, hasLineNumber, fileName)) return false;
if (!nameDefined()) return true;
if (curFunc()) {
/* We now have the variable name, type, offset, and line number.
Tell Dyninst about it. */
createLocalVariable(locs, type, variableLineNo, fileName);
} /* end if a local or static variable. */
else {
return addStaticClassVariable(locs, type);
}
} /* end if this variable is not global */
return true;
}
bool DwarfWalker::addStaticClassVariable(const vector<VariableLocation> &locs, Type *type) {
if( locs[0].stClass != storageRegOffset )
{
dwarf_printf("(0x%lx) Adding variable to an enclosure\n", id());
curEnclosure()->addField(curName(), type, locs[0].frameOffset);
return true;
}
return false;
}
void DwarfWalker::createGlobalVariable(const vector<VariableLocation> &locs, Type *type) {
/* The typeOffset forms a module-unique type identifier,
so the Type look-ups by it rather than name. */
dwarf_printf("(0x%lx) Adding global variable\n", id());
Offset addr = 0;
if (locs.size() && locs[0].stClass == storageAddr)
addr = locs[0].frameOffset;
Variable *var;
bool result = symtab()->findVariableByOffset(var, addr);
if (result) {
var->setType(type);
}
tc()->addGlobalVariable(curName(), type);
}
void DwarfWalker::createLocalVariable(const vector<VariableLocation> &locs, Type *type,
Dwarf_Unsigned variableLineNo,
const string &fileName) {
localVar * newVariable = new localVar(curName(),
type,
fileName,
(int) variableLineNo,
curFunc());
dwarf_printf("(0x%lx) localVariable '%s' (%p), currentFunction %p\n",
id(), curName().c_str(), newVariable, curFunc());
for (unsigned int i = 0; i < locs.size(); ++i) {
dwarf_printf("(0x%lx) (%s) Adding location %d of %d: (0x%lx - 0x%lx): %s, %s, %s, %ld\n",
id(), newVariable->getName().c_str(), i + 1, (int) locs.size(), locs[i].lowPC, locs[i].hiPC,
storageClass2Str(locs[i].stClass),
storageRefClass2Str(locs[i].refClass),
locs[i].mr_reg.name().c_str(),
locs[i].frameOffset);
newVariable->addLocation(locs[i]);
}
curFunc()->addLocalVar(newVariable);
}
bool DwarfWalker::parseFormalParam() {
dwarf_printf("(0x%lx) Parsing formal parameter\n", id());
/* A formal parameter must occur in the context of a function.
(That is, we can't do anything with a formal parameter to a
function we don't know about.) */
/* It's probably worth noting that a formal parameter may have a
default value. Since, AFAIK, Dyninst does nothing with this information,
neither will we. */
if (!curFunc()) {
dwarf_printf("(0x%lx) No function defined, returning\n", id());
return true;
}
/* We need the formal parameter's name, its type, its line number,
and its offset from the frame base in order to tell the
rest of Dyninst about it. A single _formal_parameter
DIE may not have all of this information; if it does not,
we will ignore it, hoping to catch it when it is later
referenced as an _abstract_origin from another _formal_parameter
DIE. If we never find such a DIE, than there is not enough
information to introduce it to Dyninst. */
/* We begin with the location, since this is the attribute
most likely to require using the _abstract_origin. */
std::vector<VariableLocation> locs;
if (!decodeLocationList(DW_AT_location, NULL, locs)) return false;
if (locs.empty()) {
dwarf_printf("(0x%lx) No locations associated with formal, returning\n", id());
return true;
}
/* If the DIE has an _abstract_origin, we'll use that for the
remainder of our inquiries. */
bool hasAbstractOrigin;
if (!handleAbstractOrigin(hasAbstractOrigin)) return false;
if (hasAbstractOrigin) {
// Clone to spec entry too
setSpecEntry(abstractEntry());
}
if (!findName(curName())) return false;
/* We can't do anything with anonymous parameters. */
if (!nameDefined()) {
dwarf_printf("(0x%lx) No name associated with formal, returning\n", id());
return true;
}
/* Acquire the parameter's type. */
Type *paramType = NULL;
if (!findType(paramType, false)) return false;
Dwarf_Unsigned lineNo = 0;
bool hasLineNumber = false;
std::string fileName;
if (!getLineInformation(lineNo, hasLineNumber, fileName)) return false;
createParameter(locs, paramType, lineNo, fileName);
return true;
}
void DwarfWalker::createParameter(const vector<VariableLocation> &locs, Type *paramType, Dwarf_Unsigned lineNo,
const string &fileName) {
localVar * newParameter = new localVar(curName(),
paramType,
fileName, (int) lineNo,
curFunc());
dwarf_printf("(0x%lx) Creating new formal parameter %s/%p (%s) (%p)\n",
id(),
curName().c_str(),
paramType, paramType->getName().c_str(),
// ((curFunc() && !curFunc()->getAllMangledNames().empty()) ?
//curFunc()->getAllMangledNames()[0].c_str() : ""),
curFunc());
for (unsigned int i = 0; i < locs.size(); ++i)
{
newParameter->addLocation(locs[i]);
}
/* This is just brutally ugly. Why don't we take care of this invariant automatically? */
curFunc()->addParam(newParameter);
}