-
Notifications
You must be signed in to change notification settings - Fork 5
/
libtalloc.py
1701 lines (1496 loc) · 55.2 KB
/
libtalloc.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
### libtalloc.py - GDB talloc analysis plugin
# Written by Aaron Adams
# NCC 2015
###
# USAGE:
# Run tchelp to see commands
# Always run tcprobe once before other commands
# See README.md for extensive usage
#
# TODO:
# - Add color-coded corrupted chunks when validating the whole heap, instead of
# printing
# - Add more functions that use the heap walk: find all pools, find all pool
# members, find all with size greater than X, etc
# - Add support for the samba-specific stackframe memory contexts
# - Add memlimit support
# - Add pretty printer for talloc_pool_chunk
# - Add an item that shows the amount of data left in a talloc pool, even though
# there isn't an explicit field that holds it.
# - A lot of the chunk reading logic can be put into a superclass that all the
# different chunk objects inherit from
# - If you have pagination on in gdb and prematurely kill the tcreport command
# output, you'll have chunks remaining looped which isn't ideal. Could catch the
# exception and walk the whole heap unsetting the loop flags...
# - Maybe make it auto execute tcprobe on initialization?
###
try:
import gdb
except ImportError:
print("Not running inside of GDB, exiting...")
exit()
import re
import sys
import struct
from os import uname
# bash color support
color_support = True
if color_support:
c_red = "\033[31m"
c_red_b = "\033[01;31m"
c_green = "\033[32m"
c_green_b = "\033[01;32m"
c_yellow = "\033[33m"
c_yellow_b = "\033[01;33m"
c_blue = "\033[34m"
c_blue_b = "\033[01;34m"
c_purple = "\033[35m"
c_purple_b = "\033[01;35m"
c_teal = "\033[36m"
c_teal_b = "\033[01;36m"
c_none = "\033[0m"
else:
c_red = ""
c_red_b = ""
c_green = ""
c_green_b = ""
c_yellow = ""
c_yellow_b = ""
c_blue = ""
c_blue_b = ""
c_purple = ""
c_purple_b = ""
c_teal = ""
c_teal_b = ""
c_none = ""
c_error = c_red
c_title = c_green_b
c_header = c_yellow_b
c_value = c_blue_b
_machine = uname()[4]
if _machine == "x86_64":
SIZE_SZ = 8
elif _machine in ("i386", "i686"):
SIZE_SZ = 4
# We use this as the root of operations on the whole heap.
null_context = None
TALLOC_ALIGNMENT = 16
TALLOC_ALIGN_MASK = TALLOC_ALIGNMENT - 1
if SIZE_SZ == 4:
TC_SIZE = SIZE_SZ * 10
elif SIZE_SZ == 8:
TC_SIZE = SIZE_SZ * 12
TC_HDR_SIZE = (TC_SIZE+TALLOC_ALIGN_MASK) & ~TALLOC_ALIGN_MASK
if SIZE_SZ == 4:
TP_SIZE = SIZE_SZ * 3
elif SIZE_SZ == 8:
TP_SIZE = SIZE_SZ * 4
TP_HDR_SIZE = (TP_SIZE+TALLOC_ALIGN_MASK) & ~TALLOC_ALIGN_MASK
def talloc_chunk_from_ptr(p):
"Ptr to talloc_chunk header"
return (p - TC_HDR_SIZE)
def ptr_from_talloc_chunk(tc):
"Ptr to chunk data"
return (tc.address + tc.header_size)
TALLOC_MAGIC_BASE = 0xe814ec70
TALLOC_VERSION_MAJOR = 2
TALLOC_VERSION_MINOR = 0
TALLOC_MAGIC = TALLOC_MAGIC_BASE + (TALLOC_VERSION_MAJOR << 12) \
+ (TALLOC_VERSION_MINOR << 4)
TALLOC_MAGIC_REFERENCE = 1
MAX_TALLOC_SIZE = 0x10000000
TALLOC_FLAG_FREE = 1
TALLOC_FLAG_LOOP = 2
TALLOC_FLAG_POOL = 4
TALLOC_FLAG_POOLMEM = 8
TALLOC_FLAG_MASK = ~0xF
# version found dynamically by tcprobe and friends. heavily relied on for proper
# structure versions
talloc_version = None
# File location of library
talloc_path = None
# Checked against to determine if the script is likely to fail or not.
tested_versions = []
# Used by a variety of callbacks that can't relay their data back to callers
# easily
chunklist = []
def find_talloc_version():
"tries to find the talloc version so we can make sure the structures are setup sanely"
global talloc_version
global talloc_path
output = gdb.execute("info proc mappings", False, True)
start = output.find("0x")
output = output[start-2:]
found = 0
# [1:] is to skip a blank entry that is at the start
for entry in output.split("\n")[1:]:
if entry.find("talloc") != -1:
found = 1
break
if found == 0:
print(c_error + "Couldn't find talloc shared library" + c_none)
return
talloc_lib = entry.split()
talloc_path = talloc_lib[4]
results = gdb.execute("find %s, %s, 'T', 'A', 'L', 'L', 'O', 'C', '_'" % (talloc_lib[0], talloc_lib[1]), False, True)
for version in results.split("\n"):
if version.find("0x") != -1:
ver = read_string(int(version, 16))
# Weed out anything that's not TALLOC_x.y.z
if ver.find('.') != -1:
idx = ver.find("_")
if idx == -1:
print(c_error + "Version string found seems wrong: %s" % (ver) + c_none)
ver = ver[idx+1:]
ver = ver.split('.')
talloc_version = int(ver[0]), int(ver[1]), int(ver[2])
def version_eq_or_newer(wanted_version=(0,0,0)):
return version_cmp(wanted_version) >= 0
def version_eq_or_older(wanted_version=(0,0,0)):
return version_cmp(wanted_version) <= 0
def version_cmp(w):
global talloc_version
if talloc_version == None:
find_talloc_version()
if talloc_version == None:
return False
t = talloc_version
for i in xrange(len(t)):
if (t[i] != w[i]):
return t[i] - w[i];
return 0
def tc_chunk(p, warn=True, fixup=True):
'''Creates a talloc_chunk() object from a given address. Tries to help by
testing for a legitimate header and if not found, tries again a header's
length backwards'''
tc = talloc_chunk(p)
if not fixup:
return tc
old = tc
if bad_magic(tc):
if warn:
print(c_error + "WARNING: 0x%lx not a talloc_chunk. Assuming ptr to chunk data" % p + c_none)
tc = talloc_chunk(talloc_chunk_from_ptr(p))
if bad_magic(tc):
# Assume they wanted to pass in the first wrong one if both are wrong...
tc = old
if warn:
print(c_error + "WARNING: 0x%lx also not a talloc_chunk. Corrupt chunk?" % talloc_chunk_from_ptr(p) + c_none)
return tc
def tc_version(flags):
version = (flags & TALLOC_FLAG_MASK) - TALLOC_MAGIC_BASE
major = version >> 12
minor = (version - (major << 12)) >> 4
return (major, minor)
def annotate_entry(p):
tc = tc_chunk(p)
print(" - name: %s" % talloc_get_name(tc))
print(" - size: %d (0x%x) bytes" % (tc.size, tc.size))
print(" - valid: %s" % is_valid_chunk(tc))
# TODO
# - Would be nice to resolve destructor symbols
# - Also more info about tc->refs
def annotate_chunk(p):
"verbosely describe a chunk with all flags"
print(c_title + "===========================")
print("Chunk @ 0x%lx" % p.address)
print(" valid: %s" % is_valid_chunk(p))
print("===========================" + c_none)
print("next = 0x%lx" % p.next_tc)
if p.next_tc:
tc = annotate_entry(p.next_tc)
print("prev = 0x%lx" % p.prev_tc)
if p.prev_tc:
tc = annotate_entry(p.prev_tc)
print("parent = 0x%lx" % p.parent)
if p.parent:
tc = annotate_entry(p.parent)
print("child = 0x%lx" % p.child)
if p.child:
tc = annotate_entry(p.child)
print("refs = 0x%lx" % p.refs)
print("destructor = 0x%lx" % p.destructor)
print("name = 0x%lx" % p.name)
if p.name:
print(" - %s" % talloc_get_name(p))
print("size = %d (0x%lx) bytes" % (p.size, p.size))
print("flags = 0x%lx" % p.flags)
if is_free(p):
print(" - TALLOC_FLAG_FREE")
if is_loop(p):
print(" - TALLOC_FLAG_LOOP")
if is_pool(p):
print(" - TALLOC_FLAG_POOL")
if is_pool_member(p):
print(" - TALLOC_FLAG_POOLMEM")
print("pool = 0x%lx" % p.pool)
if p.pool:
tc = annotate_entry(p.pool)
print("===========================")
if is_valid_chunk(p) == False:
print(" Validation output:")
print("===========================")
validate_chunk(p)
def get_mappings():
output = gdb.execute("info proc mappings", False, True)
start = output.find("0x")
output = output[start-2:]
address_map = []
# [1:] is to skip a blank entry that is at the start
for entry in output.split("\n"):
data = re.sub("\s+", " ", entry.lstrip()).split(" ")
if len(data) < 2:
continue
start_addr = data[0]
end_addr = data[1]
address_map.append((start_addr, end_addr))
return address_map
def is_valid_addr(p):
asmap = get_mappings()
for entry in asmap:
if (p >= int(entry[0], 16)) and (p < int(entry[1], 16)):
return True
return False
def is_valid_chunk(p):
return validate_chunk(p, False)
def validate_chunk(p, talk=True):
valid = True
if bad_magic(p):
valid = False
if talk:
print("0x%lx: Chunk has bad magic 0x%lx" % (p.address, (p.flags & TALLOC_FLAG_MASK)))
if p.next_tc:
if not is_valid_addr(p.next_tc):
valid = False
if talk:
print("0x%lx: Chunk has bad next pointer 0x%lx" % (p.address, p.next_tc))
if p.prev_tc:
if not is_valid_addr(p.prev_tc):
valid = False
if talk:
print("0x%lx: Chunk has bad prev pointer 0x%lx" % (p.address, p.prev_tc))
if p.child:
if not is_valid_addr(p.child):
valid = False
if talk:
print("0x%lx: Chunk has bad child pointer 0x%lx" % (p.address, p.child))
if p.parent:
if not is_valid_addr(p.parent):
valid = False
if talk:
print("0x%lx: Chunk has bad parent pointer 0x%lx" % (p.address, p.parent))
if p.refs and (p.refs != TALLOC_MAGIC_REFERENCE):
if not is_valid_addr(p.refs):
valid = False
if talk:
print("0x%lx: Chunk has bad refs pointer 0x%lx" % (p.address, p.refs))
if p.destructor:
if not is_valid_addr(p.destructor):
valid = False
if talk:
print("0x%lx: Chunk has bad destructor pointer 0x%lx" % (p.address, p.destructor))
if p.pool:
if not is_valid_addr(p.pool):
valid = False
if talk:
print("0x%lx: Chunk has bad pool pointer 0x%lx" % (p.address, p.pool))
if p.size >= MAX_TALLOC_SIZE:
valid = False
if talk:
print("0x%lx: Chunk has bad size 0x%lx" % (p.address, p.size))
return valid
def search_chunk(p, search_for):
"searches a chunk. includes the chunk header in the search"
results = []
try:
out_str = gdb.execute('find 0x%x, 0x%x, %s' % \
(p.address, p.address + p.header_size + p.size, search_for), \
to_string = True)
except:
#print(sys.exc_info()[0])
return results
str_results = out_str.split('\n')
for str_result in str_results:
if str_result.startswith('0x'):
results.append(p.address)
return results
def tc_search_heap(p, search_for, depth=0, find_top=True):
"walk chunks searching for specified value"
results = []
if (depth == 0) and (find_top == True):
top = talloc_top_chunk(p)
p = top
results = search_chunk(p, search_for)
if p.child:
p = tc_chunk(p.child)
while True:
results.extend(tc_search_heap(p, search_for, (depth+1)))
if not p.next_tc:
break;
p = tc_chunk(p.next_tc)
return results
def tc_find_addr(p, search_addr, depth=0, find_top=True):
"walk chunks searching if address falls within chunk"
results = []
if (depth == 0) and (find_top == True):
top = talloc_top_chunk(p)
p = top
if (p.address <= search_addr) and ((p.address + TC_HDR_SIZE + p.size) >= search_addr):
results.append(p)
if p.child:
p = tc_chunk(p.child)
while True:
results.extend(tc_find_addr(p, search_addr, (depth+1)))
if not p.next_tc:
break;
p = tc_chunk(p.next_tc)
return results
# This is our workhorse for analyzing the entire heap. Supply a callback and it
# will be passed every encountered chunk and depth. It recurses through every memory
# context from the top (typically null_context)
def tc_walk_heap(p, cb=None, depth=0, find_top=True):
if cb == None:
print(c_error + "WARNING: tc_walk_heap requires a callback..." + c_none)
return
if (depth == 0) and (find_top == True):
top = talloc_top_chunk(p)
p = top
cb(p)
if p.child:
p = tc_chunk(p.child)
while True:
tc_walk_heap(p, cb, (depth+1))
if not p.next_tc:
break;
p = tc_chunk(p.next_tc)
def tc_heap_validate_all(p, depth=0):
tc_walk_heap(p, validate_chunk)
def tc_print_heap(p, sort=False, find_top=True):
global chunklist
if sort == True:
chunklist[:] = []
tc_walk_heap(p, collect_chunk, find_top)
chunklist.sort()
for chunk in chunklist:
print(chunk)
else:
tc_walk_heap(p, print_chunk, find_top)
def collect_chunk(p):
chunklist.append(chunk_info(p))
def print_chunk(p):
print(chunk_info(p))
def chunk_info(p):
info = []
info.append(("0x%lx " % p.address))
info.append(("sz:0x%.08x, " % p.size))
info.append(("flags:"))
if (is_free(p)):
info.append("F")
else:
info.append(".")
if (is_pool(p)):
info.append("P")
else:
info.append(".")
if (is_pool_member(p)):
info.append("p")
else:
info.append(".")
if (is_loop(p)):
info.append("L")
else:
info.append(".")
info.append((", name:%s" % talloc_get_name(p)))
return ''.join(info)
def bad_magic(p):
return (p.flags & TALLOC_FLAG_MASK != TALLOC_MAGIC)
def is_free(p):
"Extract p's TALLOC_FLAG_FREE bit"
return (p.flags & TALLOC_FLAG_FREE)
def set_free(p):
"set chunk as being free without otherwise disturbing"
p.flags |= TALLOC_FLAG_FREE
p.write()
return
def clear_free(p):
"set chunk as being inuse without otherwise disturbing"
p.flags &= ~TALLOC_FLAG_FREE
p.write()
return
def is_loop(p):
"Extract p's TALLOC_FLAG_LOOP bit"
return (p.flags & TALLOC_FLAG_LOOP)
def set_loop(p):
"set chunk as looped without otherwise disturbing"
p.flags |= TALLOC_FLAG_LOOP
p.write()
return
def clear_loop(p):
"set chunk as non-looped without otherwise disturbing"
p.flags &= ~TALLOC_FLAG_LOOP
p.write()
return
def set_destructor(p, fptr):
p.destructor = fptr
p.write()
return
def set_size(p, sz):
"set chunks size without otherwise disturbing"
p.size = sz
p.write()
return
def talloc_total_blocks(tc):
total = 0
if is_loop(tc):
return total
set_loop(tc)
total += 1
if tc.child:
p = talloc_chunk(tc.child)
while True:
total += talloc_total_blocks(p)
if not p.next_tc:
break
p = talloc_chunk(p.next_tc)
clear_loop(tc)
return total
def talloc_total_size(tc):
total = 0
if is_loop(tc):
return total
set_loop(tc)
if tc.name != TALLOC_MAGIC_REFERENCE:
total = tc.size
if tc.child:
p = talloc_chunk(tc.child)
while True:
total += talloc_total_size(p)
if not p.next_tc:
break
p = talloc_chunk(p.next_tc)
clear_loop(tc)
return total
def talloc_parent_chunk(tc):
"ptr to parent talloc_chunk"
while tc.prev_tc:
tc = talloc_chunk(tc.prev_tc)
if tc.parent:
return talloc_chunk(tc.parent)
return None
def talloc_top_chunk(tc):
global null_context
while True:
last = tc
tc = talloc_parent_chunk(tc)
if (null_context == None) and (tc != None) and (talloc_get_name(tc) == "null_context"):
null_context = tc
if tc == None:
return last
def talloc_reference_count(tc):
"number of external references to a pointer"
ret = 0
while tc.next_tc:
ret += 1
tc = talloc_chunk(tc.next_tc)
return ret
def tc_hexdump(p):
data = ptr_from_talloc_chunk(p)
print(c_title + "Chunk data (%d bytes):" % p.size + c_none)
cmd = "x/%dwx 0x%x\n" % (p.size/4, data)
gdb.execute(cmd, True)
return
def is_pool(p):
return (p.flags & TALLOC_FLAG_POOL)
def is_pool_member(p):
return (p.flags & TALLOC_FLAG_POOLMEM)
def get_chunk_pool(p):
if p.flags & TALLOC_FLAG_POOLMEM == 0:
print(c_error + "WARNING: 0x%lx not part of a pool." \
% p + c_none)
return None
return p.pool
def read_string(p, inferior=None):
if inferior == None:
inferior = get_inferior()
if inferior == -1:
return None
string = []
curp = p
while True:
byte = inferior.read_memory(curp, 1)
if byte[0] == b'\x00':
break;
string.append(byte[0])
curp += 1
return b''.join(string).decode('utf-8')
def talloc_print_parents(tc):
parents = []
parents.append(tc)
while True:
tc = talloc_parent_chunk(tc)
if tc == None:
break;
parents.append(tc)
depth = 0
parents.reverse()
for tc in parents:
print("%*s0x%lx: %s" % (depth*2, "", tc.address, talloc_get_name(tc)))
depth += 1
return
def talloc_print_children(tc, depth=0):
p = tc
if p.child:
p = tc_chunk(p.child)
while True:
poolstr = ""
if is_pool(p):
poolstr = " (POOL)"
print("%*s0x%lx: %s%s" % (depth*2, "", p.address, talloc_get_name(p), poolstr))
talloc_print_children(p, depth+1)
if not p.next_tc:
break;
p = tc_chunk(p.next_tc)
def talloc_get_name(tc):
if tc.name == TALLOC_MAGIC_REFERENCE:
return ".reference"
elif tc.name:
try:
return read_string(tc.name);
except RuntimeError:
print(c_error + "Could not read name" + c_none)
return None
else:
return "UNNAMED"
def talloc_report_callback(tc, depth, is_ref=False):
name = talloc_get_name(tc)
if is_ref:
print("%*sreference to: %s" % (depth*4, "", name))
elif depth == 0:
print("Full talloc report on '%s' (total %6lu bytes in %3lu blocks)" % \
(name, talloc_total_size(tc), talloc_total_blocks(tc)))
return
else:
print("%*s%-30s contains %6lu bytes in %3lu blocks (ref %d) 0x%lx" % \
(depth*4, "", name, talloc_total_size(tc), \
talloc_total_blocks(tc), talloc_reference_count(tc), tc.address))
def talloc_report_full(tc, full=False):
if full == True:
tc = talloc_top_chunk(tc)
talloc_report_depth(tc, 0)
def talloc_report_depth(tc, depth):
if is_loop(tc):
return
talloc_report_callback(tc, depth)
set_loop(tc)
p = tc
if p.child:
p = talloc_chunk(p.child)
while True:
if p.name == TALLOC_MAGIC_REFERENCE:
h = talloc_reference_handle(ptr_from_talloc_chunk(p))
talloc_report_callback(talloc_chunk(h.ptr), depth+1, True)
else:
talloc_report_depth(p, depth+1)
if not p.next_tc:
break
p = talloc_chunk(p.next_tc)
clear_loop(tc)
def get_inferior():
try:
if len(gdb.inferiors()) == 0:
print(c_error + "No gdb inferior could be found." + c_none)
return -1
else:
inferior = gdb.inferiors()[0]
return inferior
except AttributeError:
print(c_error + "This gdb's python support is too old." + c_none)
exit()
################################################################################
class talloc_chunk:
"python representation of a struct talloc_chunk"
def __init__(self,addr=None,mem=None,min_size=TC_HDR_SIZE,inferior=None,read_data=True,show_pad=False, pool=None):
global talloc_version
self.vspecific = None
self.str_name = "talloc_chunk"
# Struct members
self.next_tc = None
self.prev_tc = None
self.parent = None
self.child = None
self.refs = None
self.destructor = None
self.name = None
self.size = None
self.flags = None
self.pool = None
self.limit = None
self.pad1 = None
self.pad2 = None
self.pad3 = None
# Used by child objects to know read offsets
self.struct_size = 0
self.header_size = TC_HDR_SIZE
# >= TALLOC 2.1.0 we might have a prefixed talloc_pool_hdr
self.pool_hdr = None
# Init these now to adjust header_size
if version_eq_or_newer((2, 0, 8)):
self.vspecific = talloc_chunk_v208(self)
elif version_eq_or_older((2, 0, 7)):
self.vspecific = talloc_chunk_v207(self)
else:
print("No version detected")
if addr == None or addr == 0:
if mem == None:
sys.stdout.write(c_error)
sys.stdout.write("Please specify a valid struct talloc_chunk address.")
sys.stdout.write(c_none)
return None
self.address = None
else:
self.address = addr
if inferior == None and mem == None:
inferior = get_inferior()
if inferior == -1:
return None
if mem == None:
# a string of raw memory was not provided
try:
if SIZE_SZ == 4:
# XXX - Size is arbitrary. copied from libheap
self.mem = inferior.read_memory(addr, 0x44c)
elif SIZE_SZ == 8:
# XXX - Size is arbitrary. copied from libheap
self.mem = inferior.read_memory(addr, 0x880)
except TypeError:
print(c_error + "Invalid address specified." + c_none)
return None
except RuntimeError:
print(c_error + "Could not read address 0x%x" % addr + c_none)
return None
else:
# a string of raw memory was provided
if len(self.mem) < self.header_size:
sys.stdout.write(c_error)
sys.stdout.write("Insufficient memory provided for a talloc_chunk.")
sys.stdout.write(c_none)
return None
if len(self.mem) == header_size:
#header only provided
read_data = False
if SIZE_SZ == 4:
(self.next_tc, \
self.prev_tc, \
self.parent, \
self.child, \
self.refs, \
self.destructor, \
self.name, \
self.size, \
self.flags, \
) = struct.unpack_from("<9I", self.mem, 0x0)
self.struct_size = 9*4
elif SIZE_SZ == 8:
(self.next_tc, \
self.prev_tc, \
self.parent, \
self.child, \
self.refs, \
self.destructor, \
self.name, \
self.size, \
self.flags, \
) = struct.unpack_from("<8QI", self.mem, 0x0)
self.struct_size = ((8*8) + 4)
# Depending on the version we have to read in additional data...
if version_eq_or_newer((2, 0, 8)):
self.vspecific.getdata(self)
if version_eq_or_older((2, 0, 7)):
self.vspecific.getdata(self)
# Create a copy of the pool header
if is_pool(self) and version_eq_or_newer((2, 1, 0)):
if pool != None:
self.pool_hdr = talloc_pool_hdr(self.address-TP_HDR_SIZE, parent=self)
else:
self.pool_hdr
# always try to find null_context asap
global null_context
if null_context == None and is_valid_chunk(self):
talloc_top_chunk(self)
def write(self, inferior=None, do_write=True):
if inferior == None:
self.inferior = get_inferior()
if self.inferior == -1:
return None
if SIZE_SZ == 4:
self.mem = struct.pack("<9I", self.next_tc, self.prev_tc, \
self.parent, self.child, self.refs, self.destructor, self.name,\
self.size, self.flags)
elif SIZE_SZ == 8:
self.mem = struct.pack("<8QI", self.next_tc, self.prev_tc, \
self.parent, self.child, self.refs, self.destructor, self.name,\
self.size, self.flags)
# Add the version-specific bits
self.vspecific.write(self)
if do_write:
self.inferior.write_memory(self.address, self.mem)
def get_flags(self):
"return a string indicating what flags are set"
string = []
flags = [(is_free, "FREE"),
(is_pool, "POOL"),
(is_pool_member, "POOLMEM"),
(is_loop, "LOOP")
]
seen_flag = 0
for item in flags:
if (item[0](self)):
if seen_flag:
string.append(", ")
string.append(item[1])
seen_flag = 1
return ''.join(string)
def __str__(self):
string = []
string.append("%s%lx%s%s%lx%s%lx%s%lx%s%lx%s%lx%s%lx%s%lx%s%s%lx%s%lx%s%s" % \
(c_title + "struct " + self.str_name + " @ 0x", \
self.address, \
" {", \
c_none + "\nnext = " + c_value + "0x",
self.next_tc, \
c_none + "\nprev = " + c_value + "0x", \
self.prev_tc, \
c_none + "\nparent = " + c_value + "0x", \
self.parent, \
c_none + "\nchild = " + c_value + "0x", \
self.child, \
c_none + "\nrefs = " + c_value + "0x", \
self.refs, \
c_none + "\ndestructor = " + c_value + "0x", \
self.destructor,
c_none + "\nname = " + c_value + "0x", \
self.name, \
c_none + (" (%s)" % talloc_get_name(self)), \
c_none + "\nsize = " + c_value + "0x", \
self.size, \
c_none + "\nflags = " + c_value + "0x", \
self.flags, \
c_none + (" (%s)" % self.get_flags()),
c_none))
string.append("%s" % self.vspecific)
return ''.join(string)
class talloc_chunk_v208():
"python representation of a struct talloc_chunk with a limit member"
def __init__(self, parent):
self.parent = parent
# TODO: talloc_chunk already assumes TC_HDR_SIZE so we don't need to
# adjust, but if that changes, we'll need to adjust here
#if SIZE_SZ == 4:
# parent.header_size += (3*4)
#elif SIZE_SZ == 8:
# parent.header_size += ((2*8) + (3*4))
def getdata(self, parent):
if SIZE_SZ == 4:
(parent.limit, \
parent.pool, \
parent.pad1) = struct.unpack_from("<3I", parent.mem, parent.struct_size)
elif SIZE_SZ == 8:
(parent.pad1, \
parent.limit, \
parent.pool) = struct.unpack_from("<IQQ", parent.mem, parent.struct_size)
def write(self, parent):
if SIZE_SZ == 4:
parent.mem += struct.pack("<3I", parent.limit, parent.pool, parent.pad1)
elif SIZE_SZ == 8:
parent.mem += struct.pack("<QQI", parent.limit, parent.pool, parent.pad1)
def __str__(self):
return "%s0x%lx%s0x%lx%s" % (\
c_none + "\nlimit = " + c_value, \
self.parent.limit, \
c_none + "\npool = " + c_value, \
self.parent.pool,\
c_none)
class talloc_chunk_v207():
"python representation of a struct talloc_chunk without a limit member"
def __init__(self, parent):
self.parent = parent
#if SIZE_SZ == 4:
#parent.header_size += (3*4)
#else:
#parent.header_size += (8 + (2*4))
def getdata(self, parent):
if SIZE_SZ == 4:
(parent.pool, \
parent.pad1, \
parent.pad2) = struct.unpack_from("<3I", parent.mem, parent.struct_size)
elif SIZE_SZ == 8:
(parent.pad1, \
parent.pool, \
parent.pad2) = struct.unpack_from("<IQI", parent.mem, parent.struct_size)
def write(self, parent, do_write=True):
if SIZE_SZ == 4:
parent.mem += struct.pack("<3I", parent.pool, parent.pad1, parent.pad2)
elif SIZE_SZ == 8:
parent.mem += struct.pack("<QII", parent.pool, parent.pad1, parent.pad2)
def __str__(self):
return "%s0x%lx%s" % (\
c_none + "\npool = " + c_value, \
self.parent.pool,\
c_none)
# Note that pool chunks changed in Talloc 2.1.0, they know have their own header
# prefixing the talloc chunk. So the below is only for <2.1.0
class talloc_pool_chunk(talloc_chunk, object):
"python representation of a struct talloc_pool_chunk"
def __init__(self,addr=None,mem=None,min_size=TC_HDR_SIZE,inferior=None,read_data=True,show_pad=False):
super(talloc_pool_chunk, self).__init__(addr, mem, min_size, inferior, read_data, show_pad)
global talloc_version
self.str_name = "talloc_pool_chunk"
# Padding is ordered differently on 32-bit vs 64-bit
if SIZE_SZ == 4:
if version_eq_or_newer((2, 0, 8)):
self.object_count = self.pad1
# On 2.0.7 there is actually a separate 16 byte header after the chunk lol... ugh
elif version_eq_or_older((2, 0, 7)):
self.object_count = struct.unpack_from("<I", self.mem, self.header_size)[0]
self.header_size += 16
elif SIZE_SZ == 8:
# XXX - This is untested. Likely broken
self.object_count = self.pad2
def dump(self):
pool_start = self.address + self.header_size
pool_end = self.pool
p = talloc_chunk(pool_start)
while p.address < pool_end:
print_chunk(p)
p = p.address + (((p.header_size + p.size) + TALLOC_ALIGN_MASK) & ~TALLOC_ALIGN_MASK)
p = talloc_chunk(p)
def __str__(self):
string = []
string.append("%s\n" % super(talloc_pool_chunk, self).__str__())
string.append("%s%lx%s" % (\
"object_count = " + c_value + "0x", \
self.object_count, \
c_none))
return ''.join(string)
class talloc_pool_hdr:
"python representation of a struct talloc_pool_hdr"
def __init__(self,addr=None,mem=None,min_size=TP_HDR_SIZE,inferior=None, parent=None):
self.chunk = None
self.end = None
self.object_count = None