-
Notifications
You must be signed in to change notification settings - Fork 7
/
libdlmalloc_26x.py
1826 lines (1623 loc) · 67.7 KB
/
libdlmalloc_26x.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
# libdlmalloc_26x.py
#
# This file is part of libdlmalloc.
# Copyright (c) 2017, Aaron Adams <aaron.adams(at)nccgroup(dot)trust>
# Copyright (c) 2017, Cedric Halbronn <cedric.halbronn(at)nccgroup(dot)trust>
#
# Some parts of this code were taken from libheap, a ptmalloc2 GDB
# plugin: https://github.com/cloudburst/libheap
#
# Some gdb argument handling functions were taken and/or inspired from
# https://github.com/0vercl0k/stuffz/blob/master/dps_like_for_gdb.py
#
# The show_last_exception() code was derived from https://github.com/hugsy/gef
#
# Note libdmalloc_26x was primarily tested on 2.6.3i?, which is not the latest
# version.
#
# Note this has been heavily ported from libdlmalloc_28x.py so it may not actually
# be close enough to malloc-2.6.3i.c. It still contains lots of 2.8.x
# references that need to be cleaned up.
#
# See http://gee.cs.oswego.edu/pub/misc/malloc-2.6.7.c
#
# TODO
# - support IS_MMAPPED
from __future__ import print_function
import traceback
import importlib
try:
import gdb
is_gdb = True
except ImportError:
is_gdb = False
print("[libdlmalloc_26x] Not running inside of GDB, limited functionality")
from os.path import basename
import re
import sys, os, json
import struct
from functools import wraps
################################################################################
# HELPERS
################################################################################
# XXX - move to _gdb.py
# Taken from gef. Let's us see proper backtraces from python exceptions
def show_last_exception():
PYTHON_MAJOR = sys.version_info[0]
horizontal_line = "-"
right_arrow = "->"
down_arrow = "\\->"
print("")
exc_type, exc_value, exc_traceback = sys.exc_info()
print(" Exception raised ".center(80, horizontal_line))
print("{}: {}".format(exc_type.__name__, exc_value))
print(" Detailed stacktrace ".center(80, horizontal_line))
for fs in traceback.extract_tb(exc_traceback)[::-1]:
if PYTHON_MAJOR==2:
filename, lineno, method, code = fs
else:
try:
filename, lineno, method, code = fs.filename, fs.lineno, fs.name, fs.line
except:
filename, lineno, method, code = fs
print("""{} File "{}", line {:d}, in {}()""".format(down_arrow, filename,
lineno, method))
print(" {} {}".format(right_arrow, code))
# XXX - move to _gdb.py
def get_info():
res = gdb.execute("maintenance info sections ?", to_string=True)
bin_name = basename(build_bin_name(res))
if not bin_name:
raise("get_info: failed to find bin name")
if bin_name[0] == '_':
return bin_name[1:]
return bin_name
# XXX - Not sure if these should go into dlmalloc()
# XXX - move to _gdb.py
def get_inferior():
if not is_gdb:
return
try:
if len(gdb.inferiors()) == 0:
logmsg("No gdb inferior could be found.")
return -1
else:
inferior = gdb.inferiors()[0]
return inferior
except AttributeError:
logmsg("This gdb's python support is too old.")
exit()
# XXX - move to _gdb.py
def has_inferior(f):
"decorator to make sure we have an inferior to operate on"
@wraps(f)
def with_inferior(*args, **kwargs):
inferior = get_inferior()
if inferior != -1:
if (inferior.pid != 0) and (inferior.pid is not None):
return f(*args, **kwargs)
else:
logmsg("No debugee could be found. Attach or start a program.")
exit()
else:
exit()
return with_inferior
# General class for most dlmalloc-related methods to avoid namespace overlap
# with other heap libraries we might load at the same time. Most helper methods
# try to match the macros from malloc-2.8.x.c files
class dl_helper:
DLMALLOC_VERSION = "2.6"
MALLOC_ALIGNMENT = 8
SIZE_T_ZERO = 0
SIZE_T_ONE = 1
SIZE_T_TWO = 2
CHUNK_ALIGN_MASK = MALLOC_ALIGNMENT - SIZE_T_ONE
NSMALLBINS = 32
NTREEBINS = 32
SMALLBIN_SHIFT = 3
SMALLBIN_WIDTH = SIZE_T_ONE << SMALLBIN_SHIFT
TREEBIN_SHIFT = 8
MIN_LARGE_SIZE = SIZE_T_ONE << TREEBIN_SHIFT
MAX_SMALL_SIZE = MIN_LARGE_SIZE - SIZE_T_ONE
#MAX_SMALL_REQUEST = (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD)
PINUSE_BIT = 1
IS_MMAPPED = 2
SIZE_BITS = (PINUSE_BIT|IS_MMAPPED)
# XXX - If we find the malloc_params struct in mem, we should update these
DEFAULT_TRIM_THRESHOLD = 2 * 1024 * 1024
treebin_sz = [ 0x180, 0x200, 0x300, 0x400, 0x600, 0x800, 0xc00, 0x1000,
0x1800, 0x2000, 0x3000, 0x4000, 0x6000, 0x8000, 0xc000, 0x10000,
0x18000, 0x20000, 0x30000, 0x40000, 0x60000, 0x80000, 0xc0000, 0x100000,
0x180000, 0x200000, 0x300000, 0x400000, 0x600000, 0x800000, 0xc00000,
0xffffffff]
def __init__(self, size_sz=0):
self.terse = True # XXX - This should be configurable
# Non-gdb users will have to specify the size themselves
if size_sz == 0:
self.retrieve_sizesz()
else:
self.SIZE_SZ = size_sz
self.INUSE_HDR_SZ = 2 * self.SIZE_SZ
self.FREE_HDR_SZ = 4 * self.SIZE_SZ
self.MAX_HDR_SZ = self.FREE_HDR_SZ
self.MIN_CHUNK_SZ = 4 * self.SIZE_SZ
self.MALLOC_ALIGNMENT = 2 * self.SIZE_SZ
self.MALLOC_ALIGN_MASK = self.MALLOC_ALIGNMENT - 1
self.MINSIZE = (self.MIN_CHUNK_SZ+self.MALLOC_ALIGN_MASK) & \
~self.MALLOC_ALIGN_MASK
self.MSEGMENT_SZ = 4 * self.SIZE_SZ
# The MSTATE_SZ constants used here are a best guess. It will be
# dynamically adjusted if found to be incorrect. We want this size to
# be the largest possible though, so we always have enough memory to
# figure it out.
if self.SIZE_SZ == 4:
self.MSTATE_SZ = 0x1dc
elif self.SIZE_SZ == 8:
self.MSTATE_SZ = 0x3b0
self.MALLOC_PARAM_SZ = (self.SIZE_SZ * 5) + 4
self.dlchunk_callback = None
self.dlchunk_callback_cached = None
self.cached_mstate = None
self.colors = True
def logmsg(self, s, end=None):
if type(s) == str:
if end != None:
print("[libdlmalloc] " + s, end=end)
else:
print("[libdlmalloc] " + s)
else:
print(s)
# XXX - move to _gdb.py
def retrieve_sizesz(self):
"Retrieve the SIZE_SZ after binary loading finished"
_machine = self.get_arch()
if "elf64" in _machine:
self.SIZE_SZ = 8
elif "elf32" in _machine:
self.SIZE_SZ = 4
else:
raise Exception("Retrieving the SIZE_SZ failed.")
def register_callback(self, func):
self.dlchunk_callback = func
self.logmsg("Registered new dlchunk callback")
# XXX - move to _gdb.py
def get_arch(self):
res = gdb.execute("maintenance info sections ?", to_string=True)
if "elf32-i386" in res and "elf64-x86-64" in res:
raise("get_arch: could not determine arch (1)")
if "elf32-i386" not in res and "elf64-x86-64" not in res:
raise("get_arch: could not determine arch (2)")
if "elf32-i386" in res:
return "elf32-i386"
elif "elf64-x86-64" in res:
return "elf64-x86-64"
else:
raise("get_arch: failed to find arch")
# This is the 64-bit version of the macro since the 32-bit uses inline asm
def compute_tree_index(self, sz):
x = sz >> self.TREEBIN_SHIFT
if x == 0:
return 0
elif x > 0xffff:
return self.NTREEBINS-1
else:
y = x
n = ((y - 0x100) >> 16) & 8
k = (((y << n) - 0x1000) >> 16) & 4
n += k
y <<= k
k = ((y - 0x4000) >> 16) & 2
n += k
y <<= k
k = 14 - n + (y >> 15)
return (k << 1) + ((sz >> (k + (self.TREEBIN_SHIFT-1)) & 1))
def chunk2mem(self, p):
"conversion from malloc header to user pointer"
return (p.address + (2 * self.SIZE_SZ))
def mem2chunk(self, mem):
"conversion from user pointer to malloc header"
return (mem - (2 * self.SIZE_SZ))
def request2size(self, req):
"pad request bytes into a usable size"
if (req + self.SIZE_SZ + self.MALLOC_ALIGN_MASK < self.MINSIZE):
return self.MINSIZE
else:
return (int(req + self.SIZE_SZ + self.MALLOC_ALIGN_MASK) & \
~self.MALLOC_ALIGN_MASK)
def pinuse(self, p):
"extract inuse bit of previous chunk"
return (p.size & self.PINUSE_BIT)
def chunksize(self, p):
"Get size, ignoring use bits"
return (p.size & ~self.SIZE_BITS)
def ptr_from_chunk(self, p):
return (p.address + p.hdr_size)
def next_chunk(self, p):
"Ptr to next physical malloc_chunk."
return (p.address + (p.size & ~self.SIZE_BITS))
def prev_chunk(self, p):
"Ptr to previous physical malloc_chunk"
return (p.address - p.prev_size)
def next_pinuse(self, p):
"extract next chunk's pinuse bit"
chunk = dl_chunk(self, self.next_chunk(p), inuse=False)
return self.pinuse(chunk)
def chunk_plus_offset(self, p, s):
"Treat space at ptr + offset as a chunk"
return dl_chunk(self, p.address + s, inuse=False)
def chunk_minus_offset(self, p, s):
"Treat space at ptr - offset as a chunk"
return dl_chunk(self, p.address - s, inuse=False)
def set_cinuse(self, p):
"set chunk as being inuse without otherwise disturbing"
chunk = dl_chunk(self, (p.address + (p.size & ~self.SIZE_BITS)),
inuse=False)
next_chunk = self.next_chunk(p)
next_chunk.size |= self, self.PINUSE_BIT
next_chunk.write()
def clear_cinuse(self, p):
"clear chunk as being inuse without otherwise disturbing"
chunk = dl_chunk(self, (p.address + (p.size & ~self.SIZE_BITS)),
inuse=False)
next_chunk = self.next_chunk(p)
next_chunk.size &= ~self.PINUSE_BIT
next_chunk.write()
def pinuse(self, p):
"extract p's inuse bit"
return (p.size & self.PINUSE_BIT)
def set_pinuse(self, p):
"set chunk as having prev_inuse without otherwise disturbing"
chunk = dl_chunk(self, (p.address + (p.size & ~self.SIZE_BITS)),
inuse=False)
chunk.size |= self.PINUSE_BIT
chunk.write()
def clear_pinuse(self, p):
"clear chunk as not having pre_inuse without otherwise disturbing"
chunk = dl_chunk(self, (p.address + (p.size & ~self.SIZE_BITS)),
inuse=False)
chunk.size &= ~self.PINUSE_BIT
chunk.write()
def is_small(self, sz):
"check if size is in smallbin range"
return (sz < self.MIN_LARGE_SIZE)
def small_index(self, sz):
"return the smallbin index"
if self.SMALLBIN_WIDTH == 16:
return (sz >> 4)
else:
return (sz >> 3)
# The very last chunk in a segment is free but does not have the PINUSE
# flag set. This should never normally happen, because coalescing should
# always force a free chunk to be adjacent to an inuse chunk. So we can
# detect it. Size might always be 0x30 on 32-bit too? Not sure
def is_end_chunk(self, p):
if not self.next_pinuse(p) and not self.pinuse(p):
return True
return False
def top(self, mstate):
return mstate.top
# XXX - This should decode the footer if it exists
def mstate_for_ptr(self, ptr):
"find the heap and corresponding mstate for a given ptr"
return (ptr & ~(self.HEAP_MAX_SIZE-1))
# XXX - move to _gdb.py
def hexdump(self, p, maxlen=0, off=0):
data = self.ptr_from_chunk(p) + off
size = self.chunksize(p) - p.hdr_size - off
if size < 0:
self.logmsg("[!] Chunk corrupt? Bad size")
return
elif size == 0:
self.logmsg("[!] Empty chunk?")
return
if maxlen != 0:
if size > maxlen:
size = maxlen
print("0x%x bytes of chunk data:" % size)
cmd = "x/%dwx 0x%x\n" % (size/4, data)
gdb.execute(cmd, True)
return
def chunk_info(self, p):
info = []
info.append("0x%lx " % p.address)
if self.next_pinuse(p):
info.append("M ")
else:
info.append("F ")
sz = self.chunksize(p)
if sz == 0:
self.logmsg("[!] Chunk at address 0x%.x invalid or corrupt?" % p.address)
if self.terse:
info.append("sz:0x%.05x " % sz)
else:
info.append("sz:0x%.08x " % sz)
flag_str = ""
if self.terse:
info.append("fl:")
if self.pinuse(p):
flag_str += "P"
else:
flag_str += "-"
info.append("%1s" % flag_str)
else:
info.append("flags: ")
if self.pinuse(p):
flag_str += "PINUSE"
else:
flag_str += "------"
info.append("%6s" % flag_str)
if self.dlchunk_callback != None:
size = self.chunksize(p) - p.hdr_size
cbinfo = {}
cbinfo["caller"] = "dlchunk" # This is a lie but shouldn't matter
cbinfo["allocator"] = "dlmalloc"
cbinfo["version"] = self.DLMALLOC_VERSION
cbinfo["addr"] = p.data_address
cbinfo["hdr_sz"] = p.hdr_size
cbinfo["chunksz"] = self.chunksize(p)
cbinfo["min_hdr_sz"] = self.INUSE_HDR_SZ
cbinfo["data_size"] = size
cbinfo["inuse"] = p.inuse
cbinfo["chunk_info"] = True
cbinfo["size_sz"] = self.SIZE_SZ
if p.from_mem:
cbinfo["mem"] = p.mem[p.hdr_size:]
extra = self.dlchunk_callback(cbinfo)
info.append(" " + extra)
return ''.join(info)
def print_segment_chunks(self, seg=None, show_free=True, show_inuse=True,
sz=0, min_sz=0, max_sz=0):
addr = seg.base
while addr < (seg.base + seg.size):
chunk = dl_chunk(self.dl, addr)
chunksz = self.dl.chunksize(chunk)
if min_sz != 0:
if chunksz > min_sz:
continue
if max_sz != 0:
if chunksz > max_sz:
continue
if sz != 0:
if chunksz != sz:
continue
if show_free != True and not self.dl.next_pinuse(chunk):
continue
if show_inuse != True and self.dl.next_pinuse(chunk):
continue
print(self.dl.chunk_info(chunk))
addr += self.dl.chunksize(chunk)
# Walk from the start showing each chunk, but only printing an
# abbreviated version.
def print_mstate_chunks(self, addr=None, mstate=None, seg=None):
cur_seg = mstate.seg
while True:
self.print_segment_chunks(cur_seg)
if cur_seg.next == 0:
break
cur_seg = dl_msegment(self.dl, cur_seg.next)
# XXX - anything that walks segments is redundant so should be done with
# callbacks maybe?
def print_mstate_segments(self, addr=None, mstate=None, seg=None):
cur_seg = mstate.seg
while True:
print(cur_seg)
if cur_seg.next == 0:
break
cur_seg = dl_msegment(self.dl, cur_seg.next)
# XXX - This is broken atm.
def search_heap(self, seg, search_for, min_size, max_size):
"walk chunks searching for value starting from the seg address"
results = []
# XXX - Use global constants for 0x440 and 0x868
if self.SIZE_SZ == 4:
p = dl_chunk(seg) # need to fix
elif self.SIZE_SZ == 8:
# empiric offset: chunks start after the dl_mstate + offset
p = dl_chunk(seg)
# heap_size = heap_info(mstate_for_ptr(ar_ptr))
while True:
if self.chunksize(p) == 0x0:
self.logmsg("sz=0x0 detected at 0x%x, assuming end of heap"
% p.address)
break
if max_size == 0 or self.chunksize(p) <= max_size:
if self.chunksize(p) >= min_size:
print(self.chunk_info(p)) # debug
if self.search_chunk(p, search_for):
results.append(p.address)
p = dl_chunk(self.dl, addr=(p.address + self.chunksize(p)))
return results
def search_chunk(self, p, search_for, depth=0):
"searches a chunk. includes the chunk header in the search"
if depth == 0 or depth > self.chunksize(p):
depth = self.chunksize(p)
try:
out_str = gdb.execute('find /1w 0x%x, 0x%x, %s' % \
(p.address, p.address + depth, search_for), \
to_string = True)
except Exception:
#print(sys.exc_info()[0])
#print("[libdlmalloc] failed to execute 'find'")
return False
str_results = out_str.split('\n')
for str_result in str_results:
if str_result.startswith('0x'):
return True
return False
# Assumes caller checked for cached mstate...
def is_smallbin_empty(self, bidx):
mstate = self.cached_mstate
if mstate.smallmap & (1 << bidx):
return False
return True
# Assumes caller checked for cached mstate...
def is_treebin_empty(self, bidx):
mstate = self.cached_mstate
if mstate.treemap & (1 << bidx):
return False
return True
# Count the number of entries in a smallbin
# XXX - We could speed this up significantly by just reading the fd instead
# of creating new chunks each time. Quite slow over serial
def smallbin_count(self, bidx, depth=0, get_sz_set=False):
sz_set = []
if self.cached_mstate == None:
print("Can't currently count bins without cached mstate")
return None
mstate = self.cached_mstate
if bidx > len(mstate.smallbins):
print("idx %d is outside of smallbin range")
return None
if not self.is_smallbin_empty(bidx):
bins_addr = mstate.address + mstate.small_bins_off
# Each index holds an fd and bck pointer
bin_addr = bins_addr + (2*self.SIZE_SZ) * bidx
# Due to trickery, the chunk address points to the "prev_size"
# of the chunk which doesn't, actually exist. But we need to use
# that address
bin_addr -= 2*self.SIZE_SZ
count = 1
cur = dl_chunk(dl=self, addr=bin_addr)
while cur.fd != bin_addr:
count += 1
if depth != 0 and count > depth:
return count
cur = dl_chunk(dl=self, addr=cur.fd)
if get_sz_set:
sz_set.append(self.chunksize(cur))
if get_sz_set:
print(sz_set)
return count
return 0
def treebin_count_children(self, p, depth=0, sz_set=None):
count = 0
if sz_set != None:
sz_set.append(self.chunksize(p))
if p.left != 0:
count += 1
if depth != 0 and count > depth:
return count
chunk = dl_chunk(dl=self, addr=p.left)
count += self.treebin_count_children(chunk, depth, sz_set)
if p.right != 0:
count += 1
if depth != 0 and count > depth:
return count
chunk = dl_chunk(dl=self, addr=p.right)
count += self.treebin_count_children(chunk, depth, sz_set)
return count
# Count the number of entries in a treebin
def treebin_count(self, bidx, depth=0, get_sz_set=False):
if get_sz_set:
sz_set = []
else:
sz_set = None
if self.cached_mstate == None:
print("Can't currently count bins without cached mstate")
return None
mstate = self.cached_mstate
if bidx > len(mstate.treebins):
print("idx %d is outside of treebin range")
return None
if not self.is_treebin_empty(bidx):
count = 1
cur = dl_chunk(dl=self, addr=mstate.treebins[bidx])
count += self.treebin_count_children(cur, depth, sz_set)
if get_sz_set:
print("bin sizes: " + ", ".join(("0x{:02x}".format(s) \
for s in sz_set)))
return count
return 0
# XXX - fixme
def print_smallbins(self, inferior, mstate=None):
"walk and print the small bins"
print("Smallbins")
pad_width = 33
if mstate == None and self.cached_mstate == None:
self.logmsg("Don't know where mstate is and no address specified")
return
if mstate == None:
mstate = self.cached_mstate
else:
mstate = dl_mstate(mstate)
if mstate == None:
self.logmsg("Can't print bins from bad mstate")
return
else:
cached_mstate = mstate
# XXX - This doesn't properly print everything
for i in range(2, (self.NSMALLBINS+1), 2):
print("")
print("[ sb {:02} ] ".format(int(i/2)))
# print("{:#x}{:>{width}}".format(int(), "-> ", width=5), end="")
print("[ {:#x} | {:#x} ] ".format(int(mstate.smallbins[i]), int(mstate.smallbins[i+1])))
print("")
nextc = dl_chunk(mstate.smallbins[i])
while (1):
if nextc.fd == mstate.smallbins[i]:
break
print(self.chunk_info(nextc))
nextc = dl_chunk(nextc.fd)
# print("")
# print("{:>{width}}{:#x} | {:#x} ] ".format("[ ", int(chunk.fd), int(chunk.bk), width=pad_width))
# print("({})".format(int(chunksize(chunk))), end="")
# fd = chunk.fd
#
# if sb_num != None: #only print one smallbin
# return
# XXX - this currently assumes p is a chunk vs mstate
def dispatch_callback(self, p, debug=False, caller="dlchunk"):
if self.dlchunk_callback != None:
size = self.chunksize(p) - p.hdr_size
if p.data_address != None:
# We can provide an excess of information and the callback can
# choose what to use
cbinfo = {}
cbinfo["caller"] = caller
cbinfo["allocator"] = "dlmalloc"
cbinfo["version"] = self.DLMALLOC_VERSION
cbinfo["addr"] = p.data_address
if p.from_mem:
cbinfo["mem"] = p.mem[p.hdr_size:]
cbinfo["hdr_sz"] = p.hdr_size
cbinfo["chunksz"] = self.chunksize(p)
cbinfo["min_hdr_sz"] = self.INUSE_HDR_SZ
cbinfo["data_size"] = size
cbinfo["inuse"] = p.inuse
cbinfo["size_sz"] = self.SIZE_SZ
if debug:
cbinfo["debug"] = True
# We expect callback to tell us how much data it
# 'consumed' in printing out info
return self.dlchunk_callback(cbinfo)
return 0
################################################################################
# STRUCTURES
################################################################################
class dl_structure(object):
def __init__(self, dl, inferior=None):
self.dl = dl
self.is_x86 = dl.SIZE_SZ == 4
self.address = None
self.initOK = True
if inferior == None:
self.inferior = get_inferior()
if self.inferior == -1:
self.dl.logmsg("Error obtaining gdb inferior")
self.initOK = False
return
else:
self.inferior = inferior
# XXX - move this to _gdb.py
def _get_cpu_register(self, reg):
"""
Get the value holded by a CPU register
"""
expr = ''
if reg[0] == '$':
expr = reg
else:
expr = '$' + reg
try:
val = self._normalize_long(long(gdb.parse_and_eval(expr)))
except Exception:
self.dl.logmsg("[!] Did you run a process? Can't retrieve registers")
return None
return val
def _normalize_long(self, l):
return (0xffffffff if self.is_x86 else 0xffffffffffffffff) & l
def _is_register(self, s):
"""
Is it a valid register ?
"""
x86_reg = ['eax', 'ebx', 'ecx', 'edx', 'esi',
'edi', 'esp', 'ebp', 'eip']
x64_reg = ['rax', 'rbx', 'rcx', 'rdx', 'rsi',
'rdi', 'rsp', 'rbp', 'rip'] + \
['r%d' % i for i in range(8, 16)]
if s[0] == '$':
s = s[1:]
if s in (x86_reg if self.is_x86 else x64_reg):
return True
return False
def _parse_base_offset(self, r):
base = r
offset = 0
if "+" in r:
# we assume it is a register or address + a hex value
tmp = r.split("+")
base = tmp[0]
offset = int(tmp[1], 16)
if "-" in r:
# we assume it is a register or address - a hex value
tmp = r.split("-")
base = tmp[0]
offset = int(tmp[1], 16)*-1
if self._is_register(base):
base = self._get_cpu_register(base)
if not base:
return None
else:
try:
# we assume it's an address
base = int(base, 16)
except Exception:
print('Error: not an address')
return None
return base, offset
def validate_addr(self, addr):
if addr == None or addr == 0:
self.initOK = False
self.address = None
return False
elif type(addr) == str:
res = self._parse_base_offset(addr)
if res == None:
self.dl.logmsg('[!] first arg MUST be an addr or a register (+ optional offset)"')
self.initOK = False
return False
self.address = res[0] + res[1]
else:
self.address = addr
return True
################################################################################
class dl_chunk(dl_structure):
"python representation of a struct malloc_chunk {} (malloc-2.8.3.c)"
def __init__(self, dl, addr=None, mem=None, size=None, inferior=None,
inuse=None):
# sets self.dl, self.inferior, and self.initOK
dl_structure.__init__(self, dl, inferior)
if not self.initOK:
return
self.prev_size = 0
self.size = 0
self.data = None
self.fd = None
self.bk = None
# Tree chunk specific
self.left = None
self.right = None
self.parent = None
self.bindex = None
# Actual chunk flags
self.cinuse_bit = 0
self.pinuse_bit = 0
self.mmapped_bit = 0
# General indicator if we are inuse
self.inuse = inuse
self.istree = False
self.data_address = None
self.hdr_size = 0
self.mem = mem
self.from_mem = False
# setup self.address
if not self.validate_addr(addr):
return
if mem == None:
# a string of raw memory was not provided
try:
# MAX_HDR_SZ is based on SIZE_SZ already
mem = self.inferior.read_memory(self.address, self.dl.MAX_HDR_SZ)
# XXX - Technically if the last chunk is only 0x10 bytes, and
# we read it as a MAX_HDR_SZ it will fail. Better way to do the
# above
except TypeError:
self.dl.logmsg("Invalid address specified.")
self.initOK = False
return
except RuntimeError:
self.dl.logmsg("Could not read address {0:#x}".format(self.address))
self.initOK = False
return
else:
self.from_mem = True
# a string of raw memory was provided
if self.inuse:
if (len(mem) != self.dl.MIN_HDR_SZ) and \
(len(mem) < self.dl.FREE_HDR_SZ):
self.dl.logmsg("Insufficient memory provided for a dl_chunk.")
self.initOK = False
return
else:
if (len(mem) != self.dl.FREE_HDR_SZ) and \
(len(mem) < self.dl.FREE_HDR_SZ):
self.dl.logmsg("Insufficient memory provided for a free chunk.")
self.initOK = False
return
# First we just read the header
if self.dl.SIZE_SZ == 4:
(self.prev_size,
self.size) = struct.unpack_from("<II", mem, 0x0)
elif self.dl.SIZE_SZ == 8:
(self.prev_size,
self.size) = struct.unpack_from("<QQ", mem, 0x0)
# read next chunk size field to determine if current chunk is inuse
if size == None:
nextchunk_addr = self.address + (self.size & ~self.dl.SIZE_BITS)
self.pinuse_bit = self.size & self.dl.PINUSE_BIT
real_size = (self.size & ~self.dl.SIZE_BITS)
else:
nextchunk_addr = self.address + (size & ~self.dl.SIZE_BITS)
self.pinuse_bit = size & self.dl.PINUSE_BIT
real_size = size & ~self.dl.SIZE_BITS
try:
mem2 = self.inferior.read_memory(nextchunk_addr + self.dl.SIZE_SZ,
self.dl.SIZE_SZ)
except gdb.MemoryError:
self.dl.logmsg("Could not read nextchunk's size. Invalid chunk address?")
self.initOK = False
return
if self.dl.SIZE_SZ == 4:
nextchunk_size = struct.unpack_from("<I", mem2, 0x0)[0]
elif self.dl.SIZE_SZ == 8:
nextchunk_size = struct.unpack_from("<Q", mem2, 0x0)[0]
self.cinuse_bit = nextchunk_size & self.dl.PINUSE_BIT
if inuse == None:
if self.cinuse_bit:
self.inuse = True
self.hdr_size = self.dl.INUSE_HDR_SZ
else:
self.inuse = False
else:
# Trust the caller is right
self.inuse = inuse
self.hdr_size = self.dl.INUSE_HDR_SZ
if self.inuse:
# if read_data:
# if self.address != None:
# # a string of raw memory was not provided
# try:
# mem = self.inferior.read_memory(self.address, real_size + self.dl.SIZE_SZ)
# except TypeError:
# self.dl.logmsg("Invalid address specified.")
# return None
# except RuntimeError:
# self.dl.logmsg("Could not read address {0:#x}".format(self.address))
# return None
#
real_size = (real_size - self.dl.SIZE_SZ) / self.dl.SIZE_SZ
# self.data = struct.unpack_from("<%dI" % real_size, mem, self.dl.INUSE_HDR_SZ)
if not self.inuse:
# We sometimes provide an address to use for reference, even when
# we pass in mem. So can't just check for self.address != None
if self.address != None and mem == None:
# a string of raw memory was not provided
if self.inferior != None:
if self.dl.SIZE_SZ == 4:
mem = self.inferior.read_memory(self.address, self.dl.MAX_HDR_SZ)
elif self.dl.SIZE_SZ == 8:
mem = self.inferior.read_memory(self.address, self.dl.MAX_HDR_SZ)
# Both small and large chunks use a regular free chunk structure
# There is no concept of tree chunk in dlmalloc 2.6.x
if self.dl.SIZE_SZ == 4:
(self.fd, \
self.bk ) = struct.unpack_from("<II", mem, self.dl.INUSE_HDR_SZ)
elif self.dl.SIZE_SZ == 8:
(self.fd, \
self.bk ) = struct.unpack_from("<QQ", mem, self.dl.INUSE_HDR_SZ)
self.hdr_size = self.dl.FREE_HDR_SZ
if self.address != None:
self.data_address = self.address + self.hdr_size
def __str__(self):
if self.prev_size == 0 and self.size == 0:
return ""
# inuse chunk
elif self.inuse:
mc = "struct malloc_chunk @ "
mc += "{:#x} ".format(self.address)
mc += "{"
mc += "\n{:11} = ".format("prev_size")
mc += "{:#x}".format(self.prev_size)
mc += "\n{:11} = ".format("size")
mc += "{:#x}".format(self.size & ~self.dl.SIZE_BITS)
if self.pinuse_bit == 1:
mc += " (PINUSE)"
return mc
else:
if self.istree:
mc = "struct malloc_tree_chunk @ "
else:
mc = "struct malloc_chunk @ "
mc += "{:#x} ".format(self.address)
mc += "{"
mc += "\n{:11} = ".format("prev_size")
mc += "{:#x}".format(self.prev_size)
mc += "\n{:11} = ".format("head")
mc += "{:#x}".format(self.dl.chunksize(self))
if self.pinuse_bit == 1:
mc += " (PINUSE)"
mc += "\n{:11} = ".format("fd")
mc += "{:#x}".format(self.fd)
mc += "\n{:11} = ".format("bk")
mc += "{:#x}".format(self.bk)
if self.istree:
mc += "\n{:11} = ".format("left")
mc += "{:#x}".format(self.left)
mc += "\n{:11} = ".format("right")
mc += "{:#x}".format(self.right)
mc += "\n{:11} = ".format("parent")
mc += "{:#x}".format(self.parent)
mc += "\n{:11} = ".format("bindex")
mc += "{:#x}".format(self.bindex)
return mc
################################################################################
class dl_msegment(dl_structure):
"python representation of a struct malloc_segment"
def __init__(self, dl, addr=None, mem=None, inferior=None):
dl_structure.__init__(self, dl)
#super(dl_msegment, self).__init__()
self.dl = dl
self.base = 0
self.size = 0