-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathCTypeGen.cpp
1350 lines (1206 loc) · 42.6 KB
/
CTypeGen.cpp
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
/*
Copyright 2017 Arista Networks.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifdef __clang__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wregister"
#endif
#define PY_SSIZE_T_CLEAN 1
#include <Python.h>
#ifdef __clang__
#pragma GCC diagnostic pop
#endif
#include <structmember.h>
#include <iostream>
#include <deque>
#include <memory>
#include <set>
#include <sstream>
#include <vector>
#include <libpstack/elf.h>
#include <libpstack/dwarf.h>
#include <libpstack/stringify.h>
#include <libpstack/global.h>
namespace {
/*
* descriptors for the types implemented here.
*/
static PyTypeObject elfObjectType = { PyObject_HEAD_INIT( 0 ) 0 };
static PyTypeObject unitsType = { PyObject_HEAD_INIT( 0 ) 0 };
static PyTypeObject unitsIteratorType = { PyObject_HEAD_INIT( 0 ) 0 };
static PyTypeObject dwarfEntryType = { PyObject_HEAD_INIT( 0 ) 0 };
static PyTypeObject dwarfEntryIteratorType = { PyObject_HEAD_INIT( 0 ) 0 };
static PyTypeObject dwarfTagsType = { PyObject_HEAD_INIT( 0 ) 0 };
static PyTypeObject dwarfBaseTypeEncodingsType = { PyObject_HEAD_INIT( 0 ) 0 };
static PyTypeObject dwarfAttrsType = { PyObject_HEAD_INIT( 0 ) 0 };
static PyTypeObject unitType = { PyObject_HEAD_INIT( 0 ) 0 };
static PyObject * attrnames; // attribute name -> value mapping
static PyObject * attrvalues; // attribute value -> name mapping
static PyObject * tagnames;
using namespace pstack;
// These are the DWARF tags for DIEs that introduce a new namespace in C/C++
static std::set< Dwarf::Tag > namespacetags = {
Dwarf::DW_TAG_structure_type,
Dwarf::DW_TAG_namespace,
Dwarf::DW_TAG_class_type,
Dwarf::DW_TAG_union_type,
};
} // namespace
extern "C" {
// clang-format off
// The formatter does not like the PyObject_HEAD macros in the start of python
// objects - they look like types preceding a field name. Disable while
// we define our structure types.
/*
* Python representaiton of a loaded ELF object and it's DWARF debug data.
*/
typedef struct {
PyObject_HEAD
Elf::Object::sptr obj;
Dwarf::Info::sptr dwarf;
PyObject *dynaddrs; // dict mapping address to list-of-dynamic name
int fileId;
} PyElfObject;
// Give each file loaded a unique ID to ensure anonymous names are unique
static std::map< const Dwarf::Info *, PyElfObject * > openFiles;
static int nextFileId = 1;
/*
* Python representaiton of the "Units" collection from an object.
* This provides a forward iterator over the units of the object.
*/
typedef struct {
PyObject_HEAD
Dwarf::Info::Units units;
} PyUnits;
/*
* Python representation of an iterator over the child DIEs of a parent DIE
*/
typedef struct {
PyObject_HEAD
Dwarf::DIE::Children::const_iterator begin;
Dwarf::DIE::Children::const_iterator end;
} PyDwarfEntryIterator;
/*
* Python representation of an iterator over the Units in an object.
*/
typedef struct {
PyObject_HEAD
Dwarf::Info::Units::iterator begin;
Dwarf::Info::Units::iterator end;
} PyDwarfUnitIterator;
/*
* Python representaiton of a DWARF Unit
*/
typedef struct {
PyObject_HEAD
Dwarf::Unit::sptr unit;
} PyDwarfUnit;
/*
* Python representaiton of a DWARF information entry. (a DIE)
*/
typedef struct {
PyObject_HEAD
Dwarf::DIE die;
PyObject * fullName;
} PyDwarfEntry;
/*
* Tabulate objects, members, and init functions for "attrs" and "types" objects
* inside the libCTypeGen namespace that can be used to access the DWARF attribute
* and tags values symbolically.
*/
typedef struct {
PyObject_HEAD
#define DWARF_ATTR( name, value ) int name;
#include <libpstack/dwarf/attr.h>
#undef DWARF_ATTR
} PyDwarfAttrsObject;
typedef struct {
PyObject_HEAD
#define DWARF_TAG( name, value ) int name;
#include <libpstack/dwarf/tags.h>
#undef DWARF_TAG
} PyDwarfTagsObject;
typedef struct {
PyObject_HEAD
#define DWARF_ATE( name, value ) int name;
#include <libpstack/dwarf/encodings.h>
#undef DWARF_ATE
} PyDwarfBaseTypeEncodingsObject;
// clang-format on
struct PyMemberDef attr_members[] = {
#define DWARF_ATTR( name, value ) \
{ ( char * )#name, \
T_INT, \
offsetof( PyDwarfAttrsObject, name ), \
0, \
( char * )#name },
#include <libpstack/dwarf/attr.h>
#undef DWARF_ATTR
{ NULL }
};
struct PyMemberDef tag_members[] = {
#define DWARF_TAG( name, value ) \
{ ( char * )#name, \
T_INT, \
offsetof( PyDwarfTagsObject, name ), \
0, \
( char * )#name },
#include <libpstack/dwarf/tags.h>
#undef DWARF_TAG
{ NULL }
};
struct PyMemberDef ate_members[] = {
#define DWARF_ATE( name, value ) \
{ ( char * )#name, \
T_INT, \
offsetof( PyDwarfBaseTypeEncodingsObject, name ), \
0, \
( char * )#name },
#include <libpstack/dwarf/encodings.h>
#undef DWARF_ATE
{ NULL }
};
}
namespace {
/*
* Return the name of a DIE.
* If the DIE has a name attribute, that's returned.
* If not, we fabricate an anonymous name based on the DIEs offset.
*/
static std::string
dieName( const Dwarf::DIE & die ) {
const Dwarf::DIE::Attribute & name = die.attribute( Dwarf::DW_AT_name );
if ( name.valid() )
return std::string( name );
std::ostringstream os;
auto it = openFiles.find(die.getUnit()->dwarf);
// We may not have an open file if we have a separate DWZ splitdwarf object.
// For such a split image, we'll only have one for all units, so just use a
// large fixed ID.
int id = it != openFiles.end() ? it->second->fileId : 1000000;
os << "anon_" << id << "_" << die.getOffset();
switch ( die.tag() ) {
case Dwarf::DW_TAG_structure_type:
os << "_struct";
break;
case Dwarf::DW_TAG_class_type:
os << "_class";
break;
case Dwarf::DW_TAG_union_type:
os << "_union";
break;
case Dwarf::DW_TAG_enumeration_type:
os << "_enum";
break;
default:
break;
}
return os.str();
}
/*
* For DIE nested in namespaces, construct a sequence in a std container for
* it's name and containing namespaces, from outer to inner.
*/
template< typename container >
static void
getFullName( const Dwarf::DIE & die, container & fullname, bool leaf = true ) {
auto spec = die.attribute( Dwarf::DW_AT_specification );
if ( spec.valid() ) {
return getFullName( Dwarf::DIE( spec ), fullname, leaf );
}
if ( die.getParentOffset() != 0 ) {
const Dwarf::DIE & parent =
die.getUnit()->offsetToDIE( Dwarf::DIE(), die.getParentOffset() );
getFullName( parent, fullname, false );
}
if ( leaf || namespacetags.find( die.tag() ) != namespacetags.end() ) {
fullname.push_back( dieName( die ) );
}
}
/*
* DIEs with the DW_AT_declaration attribute set are indicative of an incomplete
* type (eg, "struct foo;". Typedefs can refer to such DIEs, in which case
* we need to find the actual definition to fulfill the output of the typedef.
* "findDefinition" finds a defining DIE (one with no DW_AT_declaration attribute)
* for a declaration DIE with the same name/scope.
*
* arguments:
* die: the node of the tree we wish to search.
* tag: the tag of the original DIE
* first/end: the remaining scopes in the DIEs name (when die is the root node, these
* are the name of the DIE we want split into its component namespaces)
*/
template< typename T >
static Dwarf::DIE
findDefinition( const Dwarf::DIE & die,
Dwarf::Tag tag,
typename T::iterator first,
typename T::iterator end ) {
const auto & nameA = die.attribute( Dwarf::DW_AT_name );
const bool sameName = nameA.valid() && std::string( nameA ) == *first;
if ( end - first == 1 ) {
/*
* We've decended all the namespaces - this is the leaf of the name. We
* have a match if its the right name, if the DIE we're looking at is not
* a declaration, and it's also got the same type as what we're looking
* for.
*/
const auto & declA = die.attribute( Dwarf::DW_AT_declaration );
if ( sameName && !bool( declA ) && tag == die.tag() )
return die;
}
/*
* If the current DIE is a namespace, and the name matches the next namesspace
* we are intereted in, then descend down it.
*/
switch ( die.tag() ) {
case Dwarf::DW_TAG_namespace:
case Dwarf::DW_TAG_structure_type:
case Dwarf::DW_TAG_class_type:
if ( !sameName )
return Dwarf::DIE();
first++;
if ( end == first )
return Dwarf::DIE();
// FALLTHROUGH
case Dwarf::DW_TAG_compile_unit:
// Compile units are a bit special - we just fall into them, but they don't
// consume a namespace.
for ( const auto &c : die.children() ) {
const auto ischild = findDefinition< T >( c, tag, first, end );
if ( ischild )
return ischild;
}
break;
default:
break;
}
return Dwarf::DIE();
}
/*
* Convert C++ string to python string.
*/
static PyObject *
makeString( const std::string & s ) {
return PyUnicode_FromString( s.c_str() );
}
/* Get a reference to python's true or false values. */
static PyObject *
pythonBool( bool cbool ) {
PyObject * pybool = cbool ? Py_True : Py_False;
Py_INCREF( pybool );
return pybool;
};
/* Implement a basic "rich compare" given a long difference between two values */
static PyObject *
richCompare( long diff, int op ) {
switch ( op ) {
case Py_EQ:
return pythonBool( diff == 0 );
case Py_NE:
return pythonBool( diff != 0 );
case Py_GT:
return pythonBool( diff > 0 );
case Py_GE:
return pythonBool( diff >= 0 );
case Py_LT:
return pythonBool( diff < 0 );
case Py_LE:
return pythonBool( diff <= 0 );
default:
Py_INCREF( Py_NotImplemented );
return Py_NotImplemented;
}
}
} // namespace
extern "C" {
static int
attr_init( PyObject * object, PyObject * args, PyObject * kwds ) {
auto attrs = ( PyDwarfAttrsObject * )object;
#define DWARF_ATTR( name, value ) attrs->name = value;
#include <libpstack/dwarf/attr.h>
#undef DWARF_ATTR
return 0;
};
static PyObject *
make_attrnames() {
auto namedict = PyDict_New();
#define DWARF_ATTR( name, value ) \
{ \
auto v = makeString( #name ); \
auto k = PyLong_FromLong( value ); \
PyDict_SetItem( namedict, k, v ); \
Py_DECREF( k ); \
Py_DECREF( v ); \
}
#include <libpstack/dwarf/attr.h>
#undef DWARF_ATTR
return namedict;
};
static PyObject *
make_attrvalues() {
auto valuedict = PyDict_New();
#define DWARF_ATTR( name, value ) \
{ \
auto val = PyLong_FromLong( value ); \
PyDict_SetItemString( valuedict, #name, val ); \
Py_DECREF( val ); \
}
#include <libpstack/dwarf/attr.h>
#undef DWARF_ATTR
return valuedict;
};
static PyObject *
make_tagnames() {
auto namedict = PyDict_New();
#define DWARF_TAG( name, value ) \
{ \
auto k = PyLong_FromLong( value ); \
auto v = makeString( #name ); \
PyDict_SetItem( namedict, k, v ); \
Py_DECREF( k ); \
Py_DECREF( v ); \
}
#include <libpstack/dwarf/tags.h>
#undef DWARF_TAG
return namedict;
};
static int
tags_init( PyObject * object, PyObject * args, PyObject * kwds ) {
auto tags = ( PyDwarfTagsObject * )object;
#define DWARF_TAG( name, value ) tags->name = value;
#include <libpstack/dwarf/tags.h>
#undef DWARF_TAG
return 0;
};
static int
ates_init( PyObject * object, PyObject * args, PyObject * kwds ) {
auto ates = ( PyDwarfBaseTypeEncodingsObject * )object;
#define DWARF_ATE( name, value ) ates->name = value;
#include <libpstack/dwarf/encodings.h>
#undef DWARF_ATE
return 0;
};
static PyObject *
makeUnit( const Dwarf::Unit::sptr & unit ) {
PyDwarfUnit * value = PyObject_New( PyDwarfUnit, &unitType );
new ( &value->unit ) Dwarf::Unit::sptr( unit );
return ( PyObject * )value;
}
static PyObject *
unit_compare( PyObject * lhso, PyObject * rhso, int op ) {
if ( Py_TYPE( rhso ) != &unitType ) {
Py_INCREF( Py_NotImplemented );
return Py_NotImplemented;
}
auto * lhs = ( PyDwarfUnit * )lhso;
auto * rhs = ( PyDwarfUnit * )rhso;
auto diff = lhs->unit->dwarf->elf.get() - rhs->unit->dwarf->elf.get();
if ( !diff )
diff = lhs->unit->offset - rhs->unit->offset;
return richCompare( diff, op );
}
static void
unit_free( PyObject * o ) {
PyDwarfUnit * value = ( PyDwarfUnit * )o;
value->unit.std::shared_ptr< Dwarf::Unit >::~shared_ptr();
unitType.tp_free( o );
}
static PyObject *
makeFullnameR( const Dwarf::DIE & die, int depth ) {
auto spec = die.attribute( Dwarf::DW_AT_specification );
if ( spec.valid() ) {
return makeFullnameR( Dwarf::DIE( spec ), depth );
}
auto poff = die.getParentOffset();
PyObject *tuple;
bool thisCounts = depth == 0 || namespacetags.find( die.tag() ) != namespacetags.end();
int nextDepth = thisCounts ? depth + 1 : depth;
if (poff != 0) {
tuple = makeFullnameR( die.getUnit()->offsetToDIE( Dwarf::DIE(), poff ), nextDepth );
} else {
tuple = PyTuple_New( nextDepth );
}
if ( thisCounts ) {
int idx = PyTuple_Size( tuple ) - depth - 1;
assert(idx >= 0 && idx < PyTuple_Size( tuple ));
PyTuple_SET_ITEM( tuple, idx, makeString( dieName( die ) ) );
}
return tuple;
}
static PyObject *
makeFullname( const Dwarf::DIE & die ) {
return makeFullnameR( die, 0);
}
static PyObject *
makeEntry( const Dwarf::DIE & die ) {
PyDwarfEntry * value = PyObject_New( PyDwarfEntry, &dwarfEntryType );
new ( &value->die ) Dwarf::DIE( die );
value->fullName = nullptr;
return ( PyObject * )value;
}
static PyObject *
unit_root( PyObject * self, PyObject * args ) {
PyDwarfUnit * unit = ( PyDwarfUnit * )self;
return makeEntry( unit->unit->root() );
}
struct PythonMacros : public Dwarf::MacroVisitor {
Dwarf::Unit::csptr unit;
PyObject *callback;
PythonMacros(const Dwarf::Unit::csptr &unit_, PyObject *callback_) :
unit { unit_ }, callback { callback_ } {}
bool define( int line, const std::string &definition ) override {
PyObject *o = PyObject_CallMethod( callback, (char *)"define", (char *)"is",
line, definition.c_str() );
if ( !o )
return false;
Py_DECREF( o );
return true;
}
bool undef( int line, const std::string &definition ) override {
PyObject *o = PyObject_CallMethod( callback, (char *)"undef",
(char *)"is", line, definition.c_str() );
if ( !o )
return false;
Py_DECREF( o );
return true;
}
bool startFile( int line, const std::string &dir, const Dwarf::FileEntry &ent )
override {
PyObject *o = PyObject_CallMethod( callback, (char *)"startFile",
(char *)"iss", line, dir.c_str(),
ent.name.c_str() );
if ( !o )
return false;
Py_DECREF( o );
return true;
}
bool endFile() override {
PyObject *o = PyObject_CallMethod( callback, (char *)"endFile", NULL );
if ( !o )
return false;
Py_DECREF( o );
return true;
}
};
static PyObject *
unit_macros( PyObject * self, PyObject * args ) {
auto unit = ( ( PyDwarfUnit * )self )->unit;
PyObject *callback;
if ( !PyArg_ParseTuple( args, "O", &callback ) )
return nullptr;
const Dwarf::Macros *macros = unit->getMacros();
if ( macros != nullptr ) {
PythonMacros visitor( unit, callback );
if ( !macros->visit( *unit, &visitor ) )
return nullptr;
}
Py_RETURN_NONE;
}
static PyObject *
unit_purge( PyObject * self, PyObject * args ) {
PyDwarfUnit * unit = ( PyDwarfUnit * )self;
unit->unit->purge();
Py_RETURN_NONE;
}
static Dwarf::ImageCache imageCache;
static PyObject *
elf_open( PyObject * self, PyObject * args ) {
try {
const char * image;
Py_ssize_t imagelen;
if ( !PyArg_ParseTuple( args, "s#", &image, &imagelen ) )
return nullptr;
auto dwarf = imageCache.getDwarf( image );
auto &it = openFiles[ dwarf.get()];
if ( it != nullptr ) {
// We already have a handle on this file - return the existing object.
Py_INCREF( it );
return (PyObject *)it;
}
auto obj = dwarf->elf;
PyElfObject * val = PyObject_New( PyElfObject, &elfObjectType );
new ( &val->obj ) std::shared_ptr< Elf::Object >( obj );
new ( &val->dwarf ) std::shared_ptr< Dwarf::Info >( dwarf );
val->dynaddrs = nullptr;
// DW_AT_linker_name attributes refer to the name of the symbol in .symtabv
// We are more interested in the name for dynamic linking - so we can decorate
// its types, and refer to it for mocking. These maps allow us to convert from
// a DW_AT_linker_name to an address, and from there to a list of candidate
// dynamic symbols at that address. They don't always match up, because of
// aliases, weak bindings, etc.
it = val;
val->fileId = nextFileId++;
return ( PyObject * )val;
} catch ( const std::exception & ex ) {
PyErr_SetString( PyExc_RuntimeError, ex.what() );
return nullptr;
}
}
static PyObject *
elf_verbose( PyObject * self, PyObject * args ) {
int verbosity;
if ( !PyArg_ParseTuple( args, "I", &verbosity ) )
return nullptr;
verbose = verbosity;
Py_RETURN_NONE;
}
static PyObject *
elf_units( PyObject * self, PyObject * args ) {
try {
PyElfObject * elf = ( PyElfObject * )self;
PyUnits * units = PyObject_New( PyUnits, &unitsType );
new ( &units->units ) Dwarf::Info::Units( elf->dwarf->getUnits() );
return ( PyObject * )units;
} catch ( const std::exception & ex ) {
PyErr_SetString( PyExc_RuntimeError, ex.what() );
return nullptr;
}
}
static PyObject *
elf_soname( PyObject * self, PyObject * args ) {
try {
PyElfObject * pyelf = ( PyElfObject * )self;
auto &elf = pyelf->dwarf->elf;
// Grab the PT_DYNAMIC header.
for ( auto &segment : elf->getSegments( PT_DYNAMIC ) ) {
OffsetReader dynReader("dynamic segment", elf->io, segment.p_offset,
segment.p_filesz);
constexpr Elf::Off NOT_FOUND = std::numeric_limits<Elf::Off>::max();
Elf::Off soname = NOT_FOUND;
Elf::Off strtab = NOT_FOUND;
for (const auto &i : ReaderArray<Elf::Dyn>(dynReader)) {
switch (i.d_tag) {
case DT_STRTAB:
strtab = i.d_un.d_ptr;
break;
case DT_SONAME:
soname = i.d_un.d_ptr;
break;
}
}
if (soname == NOT_FOUND || strtab == NOT_FOUND)
continue;
auto strings = elf->getSegmentForAddress(strtab);
if (strings == nullptr)
continue;
return makeString( elf->io->readString(
strings->p_offset + strtab + soname - strings->p_vaddr ) );
}
Py_RETURN_NONE;
} catch ( const std::exception & ex ) {
PyErr_SetString( PyExc_RuntimeError, ex.what() );
return nullptr;
}
}
/*
* Returns a dict mapping names from .symtab (debug symbols) to a list of names
* in .dynsym (used for linking). The Dwarf tree matches what's in the debug
* table, but the dynamic section can name things a little differently
*/
static PyObject *
elf_dynaddrs( PyObject * self, PyObject * args ) {
PyElfObject * pyelf = ( PyElfObject * )self;
if ( pyelf->dynaddrs == nullptr ) {
pyelf->dynaddrs = PyDict_New();
std::map< Elf::Addr, PyObject * > addr2dynname;
auto obj = pyelf->dwarf->elf;
auto dynsyms = obj->dynamicSymbols();
// First, create mapping from addr to list-of-dynamic-name
if (dynsyms) {
for ( const auto & sym : *dynsyms ) {
if ( sym.st_shndx == SHN_UNDEF )
continue;
if ( sym.isHidden() )
continue;
auto name = dynsyms->name( sym );
if (name == "")
continue;
auto & list = addr2dynname[ sym.st_value ];
if ( list == nullptr ) {
list = PyList_New( 0 );
}
auto str = makeString( dynsyms->name( sym ) );
PyList_Append( list, str );
Py_DECREF( str ); // PyList_Append doesn't steal a ref, so release ours.
}
}
for ( auto &&[addr, list] : addr2dynname ) {
auto key = PyLong_FromLong( addr );
PyDict_SetItem( pyelf->dynaddrs, key, list );
// PyDict_SetItem doesn't steal references.
Py_DECREF( key );
Py_DECREF( list );
}
}
Py_INCREF( pyelf->dynaddrs );
return pyelf->dynaddrs;
}
static PyObject *
elf_symbol( PyObject * self, PyObject * args ) {
PyElfObject * pyelf = ( PyElfObject * )self;
const char *name = nullptr;
if ( !PyArg_ParseTuple( args, "s", &name ) ) {
return nullptr;
}
auto sym = pyelf->dwarf->elf->findDynamicSymbol(name);
if ( sym.st_shndx == SHN_UNDEF )
Py_RETURN_NONE;
return PyLong_FromLong ( sym.st_value );
}
static PyObject *
elf_findDefinition( PyObject * self, PyObject * args ) {
PyDwarfEntry * die;
PyElfObject * elf = ( PyElfObject * )self;
if ( !PyArg_ParseTuple( args, "O", &die ) )
return nullptr;
std::vector< std::string > namelist;
getFullName( die->die, namelist );
for ( const auto & u : elf->dwarf->getUnits() ) {
const auto & top = u->root();
const auto & defn = findDefinition< std::vector< std::string > >(
top, die->die.tag(), namelist.begin(), namelist.end() );
if ( defn )
return makeEntry( defn );
}
Py_INCREF( Py_None );
return Py_None;
}
static PyObject *
elf_flush( PyObject * self, PyObject * args ) {
try {
PyElfObject * elf = ( PyElfObject * )self;
imageCache.flush( elf->obj );
} catch ( std::exception & ex ) {
PyErr_SetString( PyExc_RuntimeError, ex.what() );
return nullptr;
}
Py_RETURN_NONE;
}
static void
elf_free( PyObject * o ) {
PyElfObject * pye = ( PyElfObject * )o;
openFiles.erase( pye->dwarf.get() );
pye->obj.std::shared_ptr< Elf::Object >::~shared_ptr< Elf::Object >();
pye->dwarf.std::shared_ptr< Dwarf::Info >::~shared_ptr< Dwarf::Info >();
if ( pye->dynaddrs != nullptr )
Py_DECREF( pye->dynaddrs );
elfObjectType.tp_free( o );
}
static int
units_asnumber_bool( PyObject * o ) {
PyUnits * pye = ( PyUnits * )o;
return pye->units.begin() == pye->units.end() ? 0 : 1;
};
static void
units_free( PyObject * o ) {
PyUnits * pye = ( PyUnits * )o;
pye->units.Units::~Units();
unitsType.tp_free( o );
}
static PyObject *
entry_type( PyObject * self, PyObject * args ) {
PyDwarfEntry * ent = ( PyDwarfEntry * )self;
return PyLong_FromLong( ent->die.tag() );
}
static PyObject *
entry_object( PyObject * self, PyObject * args ) {
PyDwarfEntry * ent = ( PyDwarfEntry * )self;
PyElfObject * pyelf = openFiles[ ent->die.getUnit()->dwarf ];
Py_INCREF( pyelf );
return ( PyObject * )pyelf;
}
static PyObject *
entry_unit( PyObject * self, PyObject * args ) {
PyDwarfEntry * ent = ( PyDwarfEntry * )self;
return makeUnit( ent->die.getUnit() );
}
static PyObject *
entry_parent( PyObject * self, PyObject * args ) {
PyDwarfEntry * ent = ( PyDwarfEntry * )self;
if ( ent->die.getParentOffset() != 0 ) {
auto parent = ent->die.getUnit()->offsetToDIE( Dwarf::DIE(),
ent->die.getParentOffset() );
return makeEntry( parent );
}
Py_RETURN_NONE;
}
/*
* DIEs have offsets within their unit, and the units have offsets within the
* DWARF section they are defined in.
* We compare two dies by comparing the offsets of their units first, and then
* the offsets of the DIEs themselves.
*/
static PyObject *
entry_compare( PyObject * lhso, PyObject * rhso, int op ) {
if ( Py_TYPE( rhso ) != &dwarfEntryType || Py_TYPE( lhso ) != &dwarfEntryType ) {
Py_INCREF( Py_NotImplemented );
return Py_NotImplemented;
}
PyDwarfEntry * lhs = ( PyDwarfEntry * )lhso;
PyDwarfEntry * rhs = ( PyDwarfEntry * )rhso;
size_t diff = lhs->die.getUnit()->offset - rhs->die.getUnit()->offset;
if ( diff == 0 )
diff = lhs->die.getOffset() - rhs->die.getOffset();
return richCompare( op, diff );
}
Py_hash_t
entry_hash( PyObject * self ) {
PyDwarfEntry * ent = ( PyDwarfEntry * )self;
return Py_hash_t( ent->die.getOffset() ^ ent->die.getUnit()->offset );
}
/*
* Provide an iterator over the children of a DIE.
*/
static PyObject *
entry_iterator( PyObject * self ) {
try {
PyDwarfEntry * ent = ( PyDwarfEntry * )self;
PyDwarfEntryIterator * it =
PyObject_New( PyDwarfEntryIterator, &dwarfEntryIteratorType );
Dwarf::DIE::Children list = ent->die.children();
new ( &it->begin ) Dwarf::DIE::Children::const_iterator( list.begin() );
new ( &it->end ) Dwarf::DIE::Children::const_iterator( list.end() );
return ( PyObject * )it;
} catch ( const std::exception & ex ) {
PyErr_SetString( PyExc_RuntimeError, ex.what() );
return nullptr;
}
}
/*
* Provide an iterator over the children of a DIE.
*/
static PyObject *
units_iterator( PyObject * self ) {
try {
PyUnits * units = ( PyUnits * )self;
PyDwarfUnitIterator * it =
PyObject_New( PyDwarfUnitIterator, &unitsIteratorType );
new ( &it->begin ) Dwarf::Info::Units::iterator( units->units.begin() );
new ( &it->end ) Dwarf::Info::Units::iterator( units->units.end() );
return ( PyObject * )it;
} catch ( const std::exception & ex ) {
PyErr_SetString( PyExc_RuntimeError, ex.what() );
return nullptr;
}
}
/*
* Return the local name of the entry
*/
static PyObject *
entry_name( PyObject * self, PyObject * args ) {
PyDwarfEntry * ent = ( PyDwarfEntry * )self;
return makeString( dieName( ent->die ) );
}
/*
* Return the offset of the entry
*/
static PyObject *
entry_offset( PyObject * self, PyObject * args ) {
PyDwarfEntry * ent = ( PyDwarfEntry * )self;
return PyLong_FromLong( ent->die.getOffset() );
}
/*
* Return the name of the file containing the DIE.
*/
static PyObject *
entry_file( PyObject * self, PyObject * args ) {
PyDwarfEntry * ent = ( PyDwarfEntry * )self;
std::string txt = stringify( *ent->die.getUnit()->dwarf->elf->io );
return makeString( txt );
}
static PyObject *
pyAttr( PyDwarfEntry *entry, Dwarf::AttrName name, const Dwarf::DIE::Attribute & attr ) {
try {
if ( !attr.valid() )
Py_RETURN_NONE;
switch (name) {
case Dwarf::DW_AT_decl_file: {
auto idx = intmax_t( attr );
auto lines = entry->die.getUnit()->getLines();
return makeString( lines->files[ idx ].name );
}
default:
break;
}
switch ( attr.form() ) {
case Dwarf::DW_FORM_addr:
return PyLong_FromUnsignedLongLong( uintmax_t( attr ) );
// Assume "data" types are unsigned, unless we know better (eg,
// DW_AT_upper_bound is set to 2^31-1/-1 by gcc)
case Dwarf::DW_FORM_data1:
case Dwarf::DW_FORM_data2:
case Dwarf::DW_FORM_data4:
case Dwarf::DW_FORM_sec_offset:
if ( name == Dwarf::DW_AT_upper_bound )
return PyLong_FromLong( intmax_t( attr ) );
return PyLong_FromUnsignedLong( uintmax_t( attr ) );
case Dwarf::DW_FORM_sdata:
case Dwarf::DW_FORM_implicit_const:
return PyLong_FromLongLong( intmax_t( attr ) );
case Dwarf::DW_FORM_udata:
case Dwarf::DW_FORM_data8:
if ( name == Dwarf::DW_AT_upper_bound )
return PyLong_FromLongLong( intmax_t( attr ) );
return PyLong_FromUnsignedLongLong( uintmax_t( attr ) );
case Dwarf::DW_FORM_strx1:
case Dwarf::DW_FORM_strx2:
case Dwarf::DW_FORM_strx3:
case Dwarf::DW_FORM_strx4:
case Dwarf::DW_FORM_strx:
case Dwarf::DW_FORM_GNU_strp_alt:
case Dwarf::DW_FORM_string:
case Dwarf::DW_FORM_strp:
case Dwarf::DW_FORM_line_strp:
return makeString( std::string( attr ) );
case Dwarf::DW_FORM_ref1:
case Dwarf::DW_FORM_ref2:
case Dwarf::DW_FORM_ref4:
case Dwarf::DW_FORM_ref8:
case Dwarf::DW_FORM_ref_udata:
case Dwarf::DW_FORM_GNU_ref_alt:
case Dwarf::DW_FORM_ref_addr:
return makeEntry( Dwarf::DIE( attr ) );
case Dwarf::DW_FORM_flag_present:
Py_RETURN_TRUE;
case Dwarf::DW_FORM_flag:
if ( bool( attr ) ) {
Py_RETURN_TRUE;
} else {
Py_RETURN_FALSE;
}
default:
std::clog << "no handler for form " << attr.form() << "\n";
break;
}
Py_RETURN_NONE;
} catch ( const std::exception & ex ) {
PyErr_SetString( PyExc_RuntimeError, ex.what() );
return nullptr;
}
}