-
Notifications
You must be signed in to change notification settings - Fork 0
/
kvardump.py
executable file
·1848 lines (1494 loc) · 56.7 KB
/
kvardump.py
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
#!/usr/bin/env python
from __future__ import print_function
from datetime import datetime
import os
import re
import sys
import time
import json
import copy
import codecs
import hashlib
import argparse
import platform
import struct
import functools
import traceback
DEFAULT_ARRAY_MAX = 5
DEFAULT_STRING_MAX = 64
DEFAULT_BTF_PATH = '/sys/kernel/btf/vmlinux'
DEFAULT_CACHE_DIR = '/tmp/kvardump'
verbose = False
quiet = False
log_nest_level = 0
try:
from six import reraise
except ImportError:
if sys.version_info[0] >= 3:
def reraise(exc_type, exc_value, exc_traceback):
raise exc_value.with_traceback(exc_traceback)
else:
exec("def reraise(exc_type, exc_value, exc_traceback):\n"
" raise exc_type, exc_value, exc_traceback\n")
def err_txt(err):
return getattr(err, "show_txt", str(err))
def append_err(err, txt_before='', txt_after=''):
err.show_txt = "%s%s%s" % (txt_before, err_txt(err), txt_after)
def log_info(txt):
if not quiet:
print(txt, file=sys.stderr)
def log_debug(txt):
if verbose:
print(txt, file=sys.stderr)
def log_error(txt):
print("Error: %s" % txt, file=sys.stderr)
def log_exception():
if not verbose:
return
exc_type, exc_value, exc_traceback = sys.exc_info()
log_error(err_txt(exc_value))
traceback.print_exception(exc_type, exc_value, exc_traceback,
file=sys.stderr)
def log_call(func):
@functools.wraps(func)
def _func(*args, **kwargs):
global log_nest_level
ret = 'Error'
log_nest_level += 1
try:
ret = func(*args, **kwargs)
finally:
log_nest_level -= 1
if verbose:
args = args[1:]
arg_str1 = ', '.join([repr(i) for i in args])
arg_str2 = ', '.join([repr(k) + '=' + repr(v)
for k, v in kwargs.items()])
if arg_str1 and arg_str2:
arg_str = arg_str1 + ', ' + arg_str2
else:
arg_str = arg_str1 + arg_str2
print("call[%d]: %s(%s) = %s" %
(log_nest_level, func.__name__, arg_str, repr(ret)),
file=sys.stderr)
return ret
return _func
class FormatOpt(object):
def __init__(self,
array_max=DEFAULT_ARRAY_MAX,
string_max=DEFAULT_STRING_MAX,
array_max_force=False,
string_max_force=False,
hex_string=False,
blank=' '):
self.array_max = array_max
self.string_max = string_max
self.array_max_force = array_max_force
self.string_max_force = string_max_force
self.hex_string = hex_string
self.blank = blank
class BTF(object):
KIND_VOID = 0
KIND_INT = 1
KIND_PTR = 2
KIND_ARRAY = 3
KIND_STRUCT = 4
KIND_UNION = 5
KIND_ENUM = 6
KIND_FWD = 7
KIND_TYPEDEF = 8
KIND_VOLATILE = 9
KIND_CONST = 10
KIND_RESTRICT = 11
KIND_FUNC = 12
KIND_FUNC_PROTO = 13
KIND_VAR = 14
KIND_DATASEC = 15
TYPE_MAP = {}
def __init__(self,
btf_path=DEFAULT_BTF_PATH,
cache_dir=DEFAULT_CACHE_DIR,
mem_reader=None,
fmt=FormatOpt(),
value_init_hook=None):
self.arch_size = 8
if platform.architecture()[0] == '32bit':
self.arch_size = 4
self.btf_path = btf_path
self.mem_reader = mem_reader
self.value_init_hook = value_init_hook
self.fmt = fmt
self.id2type = {}
self.open_btf()
cache_path = (os.path.join(cache_dir, os.path.basename(btf_path)) +
'.btfcache') if cache_dir else None
if cache_path:
try:
if os.path.exists(cache_path):
self.load_cache(cache_path)
return
except Exception as e:
log_error("load cache from %s failed: %s" % (cache_path, e))
log_exception()
self.parse()
if cache_path:
try:
self.save_cache(cache_path)
except Exception as e:
log_error("save cache to %s failed: %s" % (cache_path, e))
log_exception()
def __getitem__(self, kind_name):
return self.get(kind_name)
def __len__(self):
return len(self.offsets)
@classmethod
def register_kind(cls, kind):
def _decorator(target):
target.KIND = kind
cls.TYPE_MAP[kind] = target
return target
return _decorator
def load_cache(self, path):
log_info("loading cache from '%s'" % path)
with open(path, 'r') as f:
cache = json.load(f)
if cache['md5'] != self.md5:
raise Exception("checksum of '%s' changed" % self.btf_path)
self.name2id = cache['name2id']
self.offsets = cache['offsets']
def save_cache(self, path):
log_info("writing cache to '%s'" % path)
dir = os.path.dirname(path)
if not os.path.exists(dir):
os.mkdir(dir)
with open(path, 'w') as f:
cache = {
'name2id': self.name2id,
'offsets': self.offsets,
'md5': self.md5,
}
json.dump(cache, f)
def open_btf(self):
with open(self.btf_path, 'rb') as f:
self.data = f.read()
header = struct.unpack('HBBIIIII', self.data[0:24])
self.magic = header[0]
self.version = header[1]
self.flags = header[2]
self.hdr_len = header[3]
self.type_off = header[4]
self.type_len = header[5]
self.str_off = header[6]
self.str_len = header[7]
self.data = self.data[self.hdr_len:]
self.md5 = hashlib.md5(self.data).hexdigest()
self.pos = 0
if (self.type_off + self.type_len > len(self.data)):
raise Exception("invalid BTF, may be truncated")
if (self.str_off + self.str_len > len(self.data)):
raise Exception("invalid BTF, may be truncated")
if self.magic != 0xeb9f:
raise Exception("invalid BTF file, wrong magic: 0x%x" % self.magic)
self.str_data = self.data[self.str_off : self.str_off + self.str_len]
self.type_data = self.data[self.type_off : self.type_off + self.type_len]
def eat(self, size):
if self.pos + size > len(self.type_data):
raise Exception(
"invalid BTF, 0x%x reaches the end of data" % (self.pos + size))
data = self.type_data[self.pos : self.pos + size]
self.pos += size
return data
def parse_one(self):
data = self.eat(12)
btf_type = struct.unpack("III", data)
name_off = btf_type[0]
info = btf_type[1]
size = type = btf_type[2]
vlen = info & 0xffff
kind = (info >> 24) & 0xf
kind_flag = info >> 31
name = self.offset2name(name_off)
cls = self.TYPE_MAP[kind]
ext_size = cls.btf_ext_size(vlen)
bpf_type = cls.from_btf(
self, name, size, type, vlen, kind_flag, self.eat(ext_size))
return bpf_type
def parse(self):
log_info("parsing types in '%s'" % self.btf_path)
self.name2id = {}
# type ID start from 1
self.offsets = [None]
while self.pos < len(self.type_data):
id = len(self.offsets)
self.offsets.append(self.pos)
data = self.eat(8)
name_off, info = struct.unpack("II", data)
vlen = info & 0xffff
kind = (info >> 24) & 0xf
name = self.offset2name(name_off)
cls = self.TYPE_MAP[kind]
ext_size = cls.btf_ext_size(vlen)
self.pos += (4 + ext_size)
self.name2id["%s.%s" % (cls.KIND, name)] = id
def offset2name(self, offset):
if offset >= len(self.str_data):
raise Exception("invalid BTF file, invalid name offset: 0x%x" % offset)
end = self.str_data[offset:].find(b'\x00')
if end < 0:
raise Exception("invalid BTF file, invalid string at 0x%x" % offset)
return self.str_data[offset : offset + end].decode('ascii')
def get(self, item, *args):
if isinstance(item, int):
id = item
if id >= len(self) or id <= 0:
if args:
return args[0]
raise IndexError("invalid type id %s" % id)
else:
key = '%s.%s' % item
if key not in self.name2id:
if args:
return args[0]
raise KeyError("no type name '%s' with kind %s" %
(item[1], item[0]))
id = self.name2id[key]
if id in self.id2type:
return self.id2type[id]
self.pos = self.offsets[id]
self.id2type[id] = self.parse_one()
return self.id2type[id]
class BaseValue(object):
def __init__(self, type, data=None, addr=None):
if not data and not addr:
raise Exception("both data and addr are not specified")
self.type = type
self.btf = type.btf
self.fmt = type.btf.fmt
self._data = data
self.addr = addr
if self.btf.value_init_hook:
self.btf.value_init_hook(self)
def __str__(self):
return self.to_str()
def __repr__(self):
if self.addr is None:
addr_str = 'None'
else:
addr_str = "0x%x" % self.addr
if self._data is None:
data_str = 'None'
else:
data_str = codecs.encode(self._data[:8], 'hex').decode()
if len(self._data) > 8:
data_str += '...'
return "%s(type='%s', addr=%s, data=%s)" % (
self.type.__class__.__name__,
str(self.type), addr_str, data_str)
@property
def data(self):
if self._data:
return self._data
try:
self._data = self.btf.mem_reader.read(self.addr, self.type.size)
except AttributeError:
msg = "read data 0x%x~0x%x failed: %s" % (
self.addr, self.addr + self.type.size, str(sys.exc_info()[1]))
reraise(Exception, msg, sys.exc_info()[2])
return self._data
@property
def pointer(self):
if self.addr is None:
raise Exception("unknown address of %s" % repr(self))
type = Ptr(self.btf, '', self.type)
return type(data=struct.pack('P', self.addr))
def to_str(self, indent=0):
raise NotImplementedError()
def to_int(self):
return int(self)
def _cast(self, type):
if self.addr:
return type(addr=self.addr)
elif type.size <= len(self.data):
return type(data=self.data[:type.size])
raise Exception("unknown address of '%s'" % repr(self))
class BTFType(object):
@classmethod
def from_btf(cls, btf, name, size, type, vlen, kind_flag, ext_data):
raise NotImplementedError()
@staticmethod
def btf_ext_size(vlen):
return 0
def __str__(self):
if not self.name:
return 'NO_NAME'
return self.name
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, str(self))
def __call__(self, data=None, addr=None):
if isinstance(data, BaseValue):
return self.Value(self, addr=data.addr)
return self.Value(self, data, addr)
@property
def ref(self):
if not hasattr(self, 'type'):
raise NotImplementedError()
if isinstance(self.type, int):
self.type = self.btf[self.type]
return self.type
def is_kind(self, kind):
return self.KIND == kind
@BTF.register_kind(BTF.KIND_VOID)
class Void(BTFType):
def __init__(self, btf, name):
self.btf = btf
self.name = name
self.size = 0
@classmethod
def from_btf(cls, btf, name, size, type, vlen, kind_flag, ext_data):
return cls(btf, name)
def __str__(self):
return self.name or "void"
class Value(BaseValue):
pass
@BTF.register_kind(BTF.KIND_INT)
class Int(BTFType):
def __init__(self, btf, name, size, signed=False, char=False,
bool=False, offset=0, bits=0):
self.btf = btf
self.name = name
self.size = size
self.signed = signed
self.char = char
self.bool = bool
self.offset = offset
self.bits = bits
@staticmethod
def btf_ext_size(vlen):
return 4
@classmethod
def from_btf(cls, btf, name, size, type, vlen, kind_flag, ext_data):
info = struct.unpack("I", ext_data)[0]
return cls(btf, name, size,
signed=(info & 0x01000000) != 0,
char=(info & 0x02000000) != 0,
bool=(info & 0x04000000) != 0,
offset=(info >> 16) & 0xff,
bits=(info & 0xff))
class Value(BaseValue):
def __int__(self):
if self.type.size == 1:
if self.type.signed:
val = struct.unpack('b', self.data)[0]
else:
val = struct.unpack('B', self.data)[0]
elif self.type.size == 2:
if self.type.signed:
val = struct.unpack('h', self.data)[0]
else:
val = struct.unpack('H', self.data)[0]
elif self.type.size == 4:
if self.type.signed:
val = struct.unpack('i', self.data)[0]
else:
val = struct.unpack('I', self.data)[0]
elif self.type.size == 8:
if self.type.signed:
val = struct.unpack('q', self.data)[0]
else:
val = struct.unpack('Q', self.data)[0]
else:
raise Exception("invalid int size: %s", self.type.size)
# TODO bitfield
return val
def to_str(self, indent=0):
if self.type.bool:
return str(bool(int(self)))
return str(int(self))
class Ref(BTFType):
def __init__(self, btf, name, type):
self.btf = btf
self.name = name
self.type = type
@classmethod
def from_btf(cls, btf, name, size, type, vlen, kind_flag, ext_data):
return cls(btf, name, type)
@BTF.register_kind(BTF.KIND_PTR)
class Ptr(Ref):
def __str__(self):
return "%s *" % str(self.ref)
@property
def size(self):
return self.btf.arch_size
class Value(BaseValue):
def __int__(self):
return struct.unpack('P', self.data)[0]
def to_str(self, indent=0):
return '0x%x' % int(self)
def __getitem__(self, idx):
addr = int(self) + idx * self.type.ref.size
return self.type.ref(addr=addr)
def __getattr__(self, name):
return getattr(self.value, name)
def __add__(self, num):
addr = int(self)
addr += (int(num) * self.type.ref.size)
return self.type(data=struct.pack('P', addr))
def __sub__(self, num):
addr = int(self)
addr -= (int(num) * self.type.ref.size)
return self.type(data=struct.pack('P', addr))
@property
def value(self):
try:
return self.type.ref(addr=int(self))
except AttributeError:
msg = "dereference value failed: %s" % (
str(sys.exc_info()[1]))
reraise(Exception, msg, sys.exc_info()[2])
class Bedeck(Ref):
def __getattr__(self, name):
return getattr(self.ref, name)
def __getitem__(self, idx):
return self.ref[idx]
def __len__(self):
return len(self.ref)
def is_kind(self, kind):
if self.KIND == kind:
return True
return self.ref.is_kind(kind)
class Value(BaseValue):
@property
def ref(self):
try:
return self.type.ref(data=self.data, addr=self.addr)
except AttributeError:
msg = "ref failed: %s" % (str(sys.exc_info()[1]))
reraise(Exception, msg, sys.exc_info()[2])
def __getattr__(self, name):
return getattr(self.ref, name)
def __int__(self):
return int(self.ref)
def __str__(self):
return str(self.ref)
def __getitem__(self, idx):
return self.ref[idx]
def __len__(self):
return len(self.ref)
def to_str(self, indent=0):
return self.ref.to_str(indent)
@BTF.register_kind(BTF.KIND_TYPEDEF)
class TypeDef(Bedeck):
pass
@BTF.register_kind(BTF.KIND_VOLATILE)
class Volatile(Bedeck):
def __str__(self):
return "volatile %s" % str(self.ref)
@BTF.register_kind(BTF.KIND_CONST)
class Const(Bedeck):
def __str__(self):
return "const %s" % str(self.ref)
@BTF.register_kind(BTF.KIND_RESTRICT)
class Restrict(Bedeck):
def __str__(self):
return "restrict %s" % str(self.ref)
@BTF.register_kind(BTF.KIND_ARRAY)
class Array(BTFType):
def __init__(self, btf, name, type, nelems):
self.btf = btf
self.name = name
self.type = type
self.nelems = nelems
def __str__(self):
return "%s[%d]" % (str(self.ref), self.nelems)
@staticmethod
def btf_ext_size(vlen):
return 12
@classmethod
def from_btf(cls, btf, name, size, type, vlen, kind_flag, ext_data):
info = struct.unpack("III", ext_data)
return cls(btf, name, info[0], info[2])
@property
def size(self):
try:
return self.nelems * self.ref.size
except AttributeError:
msg = "get size failed: %s" % (str(sys.exc_info()[1]))
reraise(Exception, msg, sys.exc_info()[2])
class Value(BaseValue):
def __len__(self):
return self.type.nelems
def __getitem__(self, idx):
elem_size = self.type.ref.size
addr = self.addr + idx * elem_size if self.addr else None
data = self.data[idx * elem_size : (idx + 1) * elem_size]
return self.type.ref(data=data, addr=addr)
def dump_byte_array(self, indent):
omit_tip = ''
data = self.data
if (indent > 0 or self.fmt.string_max_force) and \
self.type.nelems > self.fmt.string_max:
data = self.data[:self.fmt.string_max]
omit_tip = '...'
if not self.fmt.hex_string:
try:
# dump as string if there is no unprintable character
str_val = self.data.decode('ascii')
end = str_val.find('\x00')
if end >= 0:
str_val = str_val[:end]
if not re.search(r'[^\t-\r\x20-\x7e]', str_val):
return ('"%s"' if indent > 0 else '%s') % (
str_val + (omit_tip if end < 0 else ''))
except Exception:
pass
# dump as hex
return '"<binary>" /* hex: %s */' % \
(codecs.encode(data, 'hex').decode() + omit_tip)
def to_str(self, indent=0):
elem_type = self.type.ref
elem_size = elem_type.size
array_len = self.type.nelems
omit_count = 0
if elem_type.is_kind(BTF.KIND_INT) and elem_size == 1:
return self.dump_byte_array(indent)
# dump array in each line
if (indent > 0 or self.fmt.array_max_force) and \
array_len > self.fmt.array_max:
omit_count = array_len - self.fmt.array_max
array_len = self.fmt.array_max
indent += 1
if elem_type.is_kind(BTF.KIND_INT):
txt = '{'
sep = ' '
before = ''
else:
txt = '{\n'
sep = '\n'
before = indent * self.fmt.blank
for i in range(array_len):
txt += before + self[i].to_str(indent) + ',' + sep
if omit_count:
txt += before + '/* other %s elements are omitted */%s' % (
omit_count, sep)
indent -= 1
if sep == '\n':
txt += indent * self.fmt.blank + '}'
else:
txt += '}'
return txt
class StructUnion(BTFType):
class Member(BTFType):
def __init__(self, parent, btf, name, type, offset, size):
self.parent = parent
self.btf = btf
self.name = name
self.type = type
self.offset_bits = offset
self.offset = offset // 8
self.size = size
def __repr__(self):
try:
return '%s:%s' % (self.name, repr(self.ref))
except Exception:
return '%s:%s' % (self.name, repr(self.type))
def __call__(self, *args, **kwargs):
return NotImplementedError()
def __init__(self, btf, name, vlen, size):
self.btf = btf
self.name = name
self.vlen = vlen
self.size = size
self.members = []
self.member_map = {}
self.anonymous_members = []
def __len__(self):
return len(self.members)
def __getitem__(self, idx):
return self.members[idx]
def __getattr__(self, name):
return self.get(name)
def get(self, member):
member = str(member)
ret = self.member_map.get(member, None)
if ret:
return ret
for m in self.anonymous_members:
if isinstance(m.ref, StructUnion):
try:
dup = copy.copy(m.ref.get(member))
dup.offset += m.offset
dup.offset_bits += m.offset_bits
return dup
except KeyError:
pass
raise KeyError("'%s' has no member '%s'" % (str(self), member))
def add_member(self, name, type, offset, size):
self.members.append(
self.Member(self, self.btf, name, type, offset, size))
if not name:
self.anonymous_members.append(self.members[-1])
else:
self.member_map[name] = self.members[-1]
@staticmethod
def btf_ext_size(vlen):
return 12 * vlen
@classmethod
def from_btf(cls, btf, name, size, type, vlen, kind_flag, ext_data):
obj = cls(btf, name, vlen, size)
for i in range(vlen):
info = struct.unpack("III", ext_data[12 * i : 12 * (i + 1)])
obj.add_member(
btf.offset2name(info[0]), info[1], info[2] & 0xffffff, info[2] >> 24)
return obj
class Value(BaseValue):
def __len__(self):
return len(self.type.members)
def __getitem__(self, idx):
# TODO offset_bits
member = self.type.members[idx]
return self._get(member)
def __getattr__(self, name):
return self.get(name)
def _get(self, member):
addr = self.addr + member.offset if self.addr else None
data = self.data[member.offset : member.offset + member.ref.size]
return member.ref(data=data, addr=addr)
def get(self, name):
member = self.type.get(name)
return self._get(member)
def to_str(self, indent=0):
txt = '{\n'
indent += 1
for m in self.type.members:
if m.name:
txt += indent * self.fmt.blank + '.' + m.name + ' = '
elif m.ref.is_kind(BTF.KIND_STRUCT):
txt += indent * self.fmt.blank + '/* nested anonymous struct */ '
else:
txt += indent * self.fmt.blank + '/* nested anonymous union */ '
txt += self._get(m).to_str(indent)
txt += ',\n'
indent -= 1
txt += indent * self.fmt.blank + '}'
return txt
@BTF.register_kind(BTF.KIND_STRUCT)
class Struct(StructUnion):
def __str__(self):
return "struct %s" % str(self.name)
@BTF.register_kind(BTF.KIND_UNION)
class Union(StructUnion):
def __str__(self):
return "union %s" % str(self.name)
@BTF.register_kind(BTF.KIND_ENUM)
class Enum(Int):
class Member(BTFType):
def __init__(self, parent, btf, name, val):
self.parent = parent
self.btf = btf
self.name = name
self.val = val
def __call__(self, *args, **kwargs):
return NotImplementedError()
def __init__(self, btf, name, vlen, size):
self.vlen = vlen
self.members = []
self.member_map = {}
self.value_map = {}
super(self.__class__, self).__init__(btf, name, size)
def __str__(self):
return "enum %s" % str(self.name)
def add_member(self, name, val):
self.members.append(self.Member(self, self.btf, name, val))
self.member_map[name] = self.members[-1]
self.value_map[val] = self.members[-1]
@staticmethod
def btf_ext_size(vlen):
return 8 * vlen
@classmethod
def from_btf(cls, btf, name, size, type, vlen, kind_flag, ext_data):
obj = cls(btf, name, vlen, size)
for i in range(vlen):
info = struct.unpack("Ii", ext_data[8 * i : 8 * (i + 1)])
obj.add_member(btf.offset2name(info[0]), info[1])
return obj
class Value(Int.Value):
def __int__(self):
if isinstance(self.data, Int):
return self.data
return super(self.__class__, self).__int__()
def to_str(self, indent=0):
val = int(self)
if val in self.type.value_map:
return self.type.value_map[val].name
return super(self.__class__, self).to_str(indent)
@BTF.register_kind(BTF.KIND_FWD)
class Fwd(BTFType):
def __init__(self, btf, name, kind_flag):
self.btf = btf
self.name = name
self.kind_flag = kind_flag
def __str__(self):
if self.kind_flag:
return "union %s" % self.name
else:
return "struct %s" % self.name
@classmethod
def from_btf(cls, btf, name, size, type, vlen, kind_flag, ext_data):
return cls(btf, name, kind_flag)
@BTF.register_kind(BTF.KIND_FUNC_PROTO)
class FuncProto(BTFType):
def __init__(self, btf, name, vlen, type):
self.btf = btf
self.name = name
self.vlen = vlen
self.type = type
def __str__(self):
return "%s (*%s)(...)" % (str(self.ref), self.name)
@staticmethod
def btf_ext_size(vlen):
return 8 * vlen
@classmethod
def from_btf(cls, btf, name, size, type, vlen, kind_flag, ext_data):
return cls(btf, name, vlen, type)
@property
def size(self):
return self.btf.arch_size
class Value(BaseValue):
def __int__(self):
return struct.unpack('P', self.data)[0]
def to_str(self, indent=0):
return '0x%x' % int(self)
@BTF.register_kind(BTF.KIND_FUNC)
class Func(Ref):
pass
@BTF.register_kind(BTF.KIND_VAR)
class Var(BTFType):
def __init__(self, btf, name, type):
self.btf = btf
self.name = name
self.type = type
@staticmethod
def btf_ext_size(vlen):
return 4
@classmethod
def from_btf(cls, btf, name, size, type, vlen, kind_flag, ext_data):
return cls(btf, name, type)
@BTF.register_kind(BTF.KIND_DATASEC)
class DataSec(BTFType):
def __init__(self, btf, name, vlen, size):
self.btf = btf
self.name = name
self.vlen = vlen
self.size = size
@staticmethod
def btf_ext_size(vlen):
return 12 * vlen
@classmethod
def from_btf(cls, btf, name, size, type, vlen, kind_flag, ext_data):
return cls(btf, name, vlen, size)
class Token(object):
def __repr__(self):
return str(self)
class AST(object):
def __repr__(self):
return str(self)
class Symbol(Token, AST):
def __init__(self, value):
self.value = value