-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathshadow.py
2441 lines (1931 loc) · 76.3 KB
/
shadow.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
# shadow - De Mysteriis Dom jemalloc
import os
import sys
import shutil
import time
import datetime
import copy
import tempfile
try:
import ConfigParser
except:
import configparser as ConfigParser
sys.path.append('.')
import jemalloc
import nursery
import symbol
VERSION = 'v2.0'
# globals
jeheap = None
arenas_addr = []
dbg_engine = None
# firefox globals
xul_version = ''
xul_symbols_pickle = ''
nursery_heap = nursery.nursery()
# android globals
android_version = ''
# detect debugger engine
try:
import gdb
import gdb_engine as dbg
dbg_engine = 'gdb'
storage_path = '/tmp/shadow'
android_version = '8'
except ImportError:
try:
import pykd
import pykd_engine as dbg
if pykd.isWindbgExt():
dbg_engine = 'pykd'
storage_path = '%s\\shadow' % tempfile.gettempdir()
xul_version = dbg.get_xul_version()
if dbg.get_arch() == 'x86':
xul_symbols_pickle = '%s\\pdb\\xul-%s.pdb.pkl' \
% (os.path.dirname(os.path.abspath(__file__)), xul_version)
else:
xul_symbols_pickle = '%s\\pdb\\xul-%s-x64.pdb.pkl' \
% (os.path.dirname(os.path.abspath(__file__)), xul_version)
except ImportError:
try:
import lldb
import lldb_engine as dbg
dbg_engine = 'lldb'
storage_path = '/tmp/shadow'
android_version = '8'
except ImportError:
pass
def store_jeheap(path):
try:
import pyrsistence
except ImportError:
raise Exception("pyrsistence is needed for heap snapshots")
global jeheap
if not os.path.isdir(path):
os.makedirs(path)
chunks_p = "%s/chunks" % path
runs_p = "%s/runs" % path
arenas_p = "%s/arenas" % path
tcaches_p = "%s/tcaches" % path
bin_info_p = "%s/bin_info" % path
modules_dict_p = "%s/modules_dict" % path
jeheap_txt_p = "%s/jeheap.txt" % path
# delete previous files
if os.path.isfile(chunks_p):
os.remove(chunks_p)
if os.path.isfile(runs_p):
os.remove(runs_p)
if os.path.isfile(arenas_p):
os.remove(arenas_p)
if os.path.isfile(tcaches_p):
os.remove(tcaches_p)
if os.path.isfile(bin_info_p):
os.remove(bin_info_p)
if os.path.isfile(modules_dict_p):
os.remove(modules_dict_p)
if os.path.isfile(jeheap_txt_p):
os.remove(jeheap_txt_p)
# store
chunks = pyrsistence.EMList(chunks_p)
for chunk in jeheap.chunks:
chunks.append(chunk)
chunks.close()
runs = pyrsistence.EMDict(runs_p)
for k,v in jeheap.runs.items():
runs[k] = v
runs.close()
arenas = pyrsistence.EMList(arenas_p)
for arena in jeheap.arenas:
arenas.append(arena)
arenas.close()
tcaches = pyrsistence.EMList(tcaches_p)
for tcache in jeheap.tcaches:
tcaches.append(tcache)
tcaches.close()
bin_info = pyrsistence.EMList(bin_info_p)
for info in jeheap.bin_info:
bin_info.append(info)
bin_info.close()
modules_dict = pyrsistence.EMDict(modules_dict_p)
for k,v in jeheap.modules_dict.items():
modules_dict[k] = v
modules_dict.close()
config = ConfigParser.RawConfigParser()
config.add_section("jeheap")
config.set("jeheap", "standalone", str(jeheap.standalone))
config.set("jeheap", "dword_size", hex(jeheap.dword_size))
config.set("jeheap", "narenas", hex(jeheap.narenas))
config.set("jeheap", "nbins", hex(jeheap.nbins))
config.set("jeheap", "chunk_size", hex(jeheap.chunk_size))
with open(jeheap_txt_p, "w") as f:
config.write(f)
def load_jeheap(path):
return jemalloc.jemalloc(path=path)
def int_from_sym(symbols_list):
for symbol in symbols_list:
try:
return dbg.to_int(dbg.get_value(symbol))
except:
continue
return None
def is_standalone_variant():
try:
_ = dbg.addressof('je_arena_bin_info')
return True
except:
return False
def has_symbols():
try:
_ = dbg.sizeof('arena_bin_info_t')
return True
except:
return False
debug_log_f = None
debug_log = lambda x: None
def _debug_log(s):
debug_log_f.write(s + "\n")
# parse functions
def parse(read_content_preview, config_path, do_debug_log=False):
global jeheap
global debug_log
global debug_log_f
global storage_path
global android_version
if do_debug_log:
debug_log_p = os.path.join(os.path.dirname(os.path.realpath(__file__)),
"debug.log")
debug_log_f = open(debug_log_p, "w")
debug_log = _debug_log
else:
debug_log = lambda x: None
if config_path:
print('[shadow] parsing configuration...')
if 'android8' in config_path:
android_version = '8'
elif 'android7' in config_path:
android_version = '7'
elif 'android6' in config_path:
android_version = '6'
update_dbg_cache_from_config(config_path)
else:
if is_standalone_variant() and not has_symbols():
print("[shadow] Detecting Android version...")
chunksize = int_from_sym(["je_chunksize", "chunksize"])
map_misc_offset = int_from_sym(["je_map_misc_offset"])
shadow_path = os.path.dirname(os.path.realpath(__file__))
cfg_path = os.path.join(shadow_path, "cfg")
# android 7/8 32bit
if chunksize == 0x80000:
# android 8 32 bit
if map_misc_offset == 0x230:
android_version = '8'
cfg_path = os.path.join(cfg_path, "android8_32.cfg")
print("[shadow] Using Android 8 32 bit configuration.")
print(" (%s)" % cfg_path)
# android 8 64 bit
elif map_misc_offset == 0x228:
android_version = '7'
cfg_path = os.path.join(cfg_path, "android7_32.cfg")
print("[shadow] Using Android 7 32 bit configuration.")
print(" (%s)" % cfg_path)
# android 7/8 64bit
elif chunksize == 0x200000:
# android 8 64bit
if map_misc_offset == 0x1010:
android_version = '8'
cfg_path = os.path.join(cfg_path, "android8_64.cfg")
print("[shadow] Using Android 8 64 bit configuration.")
print(" (%s)" % cfg_path)
# android 7 64bit
elif map_misc_offset == 0x1008:
android_version = '7'
cfg_path = os.path.join(cfg_path, "android7_64.cfg")
print("[shadow] Using Android 7 64 bit configuration.")
print(" (%s)" % cfg_path)
# android 6 32bit
elif chunksize == 0x40000 and dbg.get_dword_size() == 4:
android_version = '6'
cfg_path = os.path.join(cfg_path, "android6_32.cfg")
print("[shadow] Using Android 6 32 bit configuration.")
print(" (%s)" % cfg_path)
# android 6 64bit
elif chunksize == 0x40000 and dbg.get_dword_size() == 8:
android_version = '6'
cfg_path = os.path.join(cfg_path, "android6_64.cfg")
print("[shadow] Using Android 6 64 bit configuration.")
print(" (%s)" % cfg_path)
else:
print("[shadow] Could not detect Android version, try to use"
" a configuration file.")
return
update_dbg_cache_from_config(cfg_path)
print('[shadow] parsing structures from memory...')
print_timestamp()
jeheap = jemalloc.jemalloc()
parse_general(jeheap)
parse_chunks(jeheap)
parse_all_runs(jeheap, read_content_preview)
parse_arenas(jeheap)
if jeheap.standalone:
parse_tbin_info(jeheap)
parse_tcaches(jeheap)
if dbg_engine == "pykd":
path = os.path.join(storage_path, "jeheap")
shutil.rmtree(path, ignore_errors=True)
store_jeheap(path)
# write current config
p = os.path.join(storage_path, 'shadow.cfg')
if not os.path.isdir(storage_path):
os.makedirs(storage_path)
generate_config(p)
print('[shadow] structures parsed')
print_timestamp()
if debug_log_f:
debug_log_f.close()
def parse_general(jeheap):
global arenas_addr
debug_log("parse_general()")
jeheap.standalone = is_standalone_variant()
jeheap.dword_size = dbg.get_dword_size()
arenas_arr_addr = int_from_sym(['arenas', 'je_arenas'])
jeheap.narenas = int_from_sym(['narenas', 'narenas_total',
'je_narenas_total'])
arenas_addr = dbg.read_dwords(arenas_arr_addr, jeheap.narenas)
if jeheap.standalone:
jeheap.chunk_size = int_from_sym(['chunksize', 'je_chunksize'])
# firefox
else:
jeheap.chunk_size = 1 << 20
# number of bins
# first attempt
jeheap.nbins = int_from_sym(['nbins'])
# second attempt
if not jeheap.nbins:
jeheap.ntbins = int_from_sym(['ntbins'])
jeheap.nsbins = int_from_sym(['nsbins'])
jeheap.nqbins = int_from_sym(['nqbins'])
if jeheap.ntbins and jeheap.nsbins and jeheap.nqbins:
jeheap.nbins = jeheap.ntbins + jeheap.nsbins + jeheap.nqbins
# third attempt
# if dbg_engine == 'gdb':
# try:
# jeheap.nbins = int(dbg.execute('p __mallinfo_nbins()').split()[2])
# except:
# # print("[shadow] Using hardcoded number of bins.")
# pass
# fourth attempt - hardcoded values
if not jeheap.nbins:
# android
if jeheap.standalone:
# android 64 bit
if jeheap.dword_size == 8:
jeheap.nbins = 36
# android 32 bit
elif jeheap.dword_size == 4:
jeheap.nbins = 39
# firefox
else:
# linux
if dbg_engine == 'gdb':
# 32bit
if jeheap.dword_size == 4:
jeheap.nbins = 36
# 64 bit
else:
jeheap.nbins = 35
# windows
elif dbg_engine == 'pykd':
# 32bit
if jeheap.dword_size == 4:
jeheap.nbins = 35
# 64 bit
else:
jeheap.nbins = 34
elif dbg_engine == 'lldb':
# 32bit
if jeheap.dword_size == 4:
jeheap.nbins = 36
# 64 bit
else:
jeheap.nbins = 35
# standalone: parse the global je_arena_bin_info array
if jeheap.standalone:
info_addr = int(str(dbg.addressof('je_arena_bin_info')).split()[0], 16)
info_size = dbg.sizeof('arena_bin_info_t')
info_struct = "arena_bin_info_t"
# firefox: parse the bins of arena[0]
else:
info_addr = arenas_addr[0] + dbg.offsetof('arena_t', 'bins')
info_size = dbg.sizeof('arena_bin_t')
info_struct = "arena_bin_t"
int_size = dbg.int_size()
dword_size = dbg.get_dword_size()
bin_info_mem = dbg.read_bytes(info_addr, jeheap.nbins * info_size)
# split memory into buffers of info_struct
bin_info_mem = [bin_info_mem[i:i+info_size]
for i in range(0, jeheap.nbins * info_size, info_size)]
for buf in bin_info_mem:
reg_size = dbg.read_struct_member(buf, info_struct,
"reg_size", dword_size)
run_size = dbg.read_struct_member(buf, info_struct,
"run_size", dword_size)
reg0_off = dbg.read_struct_member(buf, info_struct,
"reg0_offset", int_size)
nregs = dbg.read_struct_member(buf, info_struct,
"nregs", int_size)
jeheap.bin_info.append(jemalloc.bin_info(reg_size,
run_size,
reg0_off,
nregs))
for name, range_list in dbg.modules_dict().items():
jeheap.modules_dict[name] = range_list
def parse_arenas(jeheap):
global arenas_addr
for i in range(0, jeheap.narenas):
new_arena_addr = arenas_addr[i]
if new_arena_addr == 0:
continue
new_arena = parse_arena(new_arena_addr, i, jeheap.nbins)
# Add arena to the list of arenas
jeheap.arenas.append(new_arena)
def parse_arena(addr, index, nbins):
new_arena = jemalloc.arena(addr, index, [], [], [])
# Read the array of bins
bin_size = dbg.sizeof('arena_bin_t')
bins_addr = addr + dbg.offsetof('arena_t', 'bins')
bins_mem = dbg.read_bytes(bins_addr, nbins * bin_size)
bins_mem = [bins_mem[z:z+bin_size]
for z in range(0, nbins * bin_size, bin_size)]
# Now parse each bin
for j in range(0, nbins):
bin_addr = bins_addr + bin_size * j
buf = bins_mem[j]
new_arena.bins.append(parse_arena_bin(bin_addr, j, buf))
return new_arena
def parse_arena_bin(addr, index, data):
dword_size = dbg.get_dword_size()
runcur = dbg.read_struct_member(data, "arena_bin_t", "runcur", dword_size)
# associate run address with run object
if runcur == 0:
run = None
else:
run = jeheap.runs[str(runcur)]
return jemalloc.arena_bin(addr, index, run)
def parse_run(jeheap, hdr_addr, addr, run_hdr, run_size, binind, read_content_preview):
if hdr_addr == 0 or run_size == 0:
return None
bin_invalid = 0xff
# case1: large run
if binind == bin_invalid:
return jemalloc.run(hdr_addr, addr, run_size, binind, 0, 0, [])
# case2: small run
bin_info = jeheap.bin_info
run_size = bin_info[binind].run_size
region_size = bin_info[binind].reg_size
reg0_offset = bin_info[binind].reg0_off
total_regions = bin_info[binind].nregs
free_regions = dbg.read_struct_member(run_hdr, "arena_run_t",
"nfree", dbg.int_size())
# run bitmap parsing
regs_mask_bits = (total_regions // 8) + 1
# "regs_mask" member changed to "bitmap" in the standalone version
if jeheap.standalone:
regs_mask_offset = dbg.offsetof('arena_run_t', 'bitmap')
else:
regs_mask_offset = dbg.offsetof('arena_run_t', 'regs_mask')
regs_mask_bytearr = run_hdr[regs_mask_offset:
regs_mask_offset + regs_mask_bits]
# parse the bitmap and store the bits to regs_mask
regs_mask = []
for byte in regs_mask_bytearr:
for bit_pos in range(0, 8):
if len(regs_mask) >= total_regions:
break
if byte & (1 << bit_pos) > 0:
regs_mask.append(1)
else:
regs_mask.append(0)
# regions parsing loop
regions = []
reg0_addr = addr + reg0_offset
if read_content_preview:
n_dwords = run_size // jeheap.dword_size
run_mem = dbg.read_dwords(addr, n_dwords)
for i in range(0, total_regions):
reg_addr = reg0_addr + (i * region_size)
data = None
data_map = None
if read_content_preview:
idx = (reg_addr - addr) // jeheap.dword_size
data = run_mem[idx]
regions.append(jemalloc.region(i, reg_addr, region_size,
regs_mask[i], data, data_map))
return jemalloc.run(hdr_addr, addr, run_size, binind, free_regions,
regs_mask, regions)
# parse the metadata of all runs and their regions
def parse_all_runs(jeheap, read_content_preview):
global dbg_engine
debug_log("parse_all_runs()")
# parse the bitmap of each chunk and find all the runs
# the arena_run_t header in the standalone version is stored at a
# map_misc array inside arena_chunk_t. The offset of this member can be
# found through the je_map_misc_offset symbol
if jeheap.standalone:
bits_offset = dbg.offsetof('arena_chunk_map_bits_t', 'bits') // jeheap.dword_size
chunk_map_dwords = dbg.sizeof('arena_chunk_map_bits_t') // jeheap.dword_size
bitmap_off = dbg.offsetof('arena_chunk_t', 'map_bits')
chunk_arena_off = dbg.offsetof('arena_chunk_t', 'node') \
+ dbg.offsetof('extent_node_t', 'en_arena')
map_misc_offset = dbg.to_int(dbg.get_value('je_map_misc_offset'))
arena_run_bin_off = None
map_bias = int_from_sym(['je_map_bias'])
# the arena_run_t header is stored at the hdr_addr of each run in
# the firefox version
else:
bits_offset = dbg.offsetof('arena_chunk_map_t', 'bits') // jeheap.dword_size
chunk_map_dwords = dbg.sizeof('arena_chunk_map_t') // jeheap.dword_size
bitmap_off = dbg.offsetof('arena_chunk_t', 'map')
chunk_arena_off = dbg.offsetof('arena_chunk_t', 'arena')
map_misc_offset = None
arena_run_bin_off = dbg.offsetof('arena_run_t', 'bin')
map_bias = 0
arena_bin_size = dbg.sizeof('arena_bin_t')
bins_offset = dbg.offsetof('arena_t', 'bins')
chunk_npages = jeheap.chunk_size >> 12
bitmap_len = (chunk_npages - map_bias) * chunk_map_dwords
# the 12 least significant bits of each bitmap entry hold
# various flags for the corresponding run
flags_mask = (1 << 12) - 1
dword_size = dbg.get_dword_size()
for chunk in jeheap.chunks:
debug_log(" parsing chunk @ 0x%x" % chunk.addr)
# does this skip huge regions?
if not chunk.arena_addr:
debug_log(" no arena_addr, skpping")
continue
if jeheap.standalone:
chunk_mem = dbg.read_bytes(chunk.addr, map_bias * dbg.get_page_size())
else:
chunk_mem = dbg.read_bytes(chunk.addr, jeheap.chunk_size)
if jeheap.standalone:
node_off = dbg.offsetof("arena_chunk_t", "node")
en_addr_off = dbg.offsetof("extent_node_t", "en_addr")
en_addr = dbg.dword_from_buf(chunk_mem, node_off + en_addr_off)
if en_addr != chunk.addr:
continue
# read the chunk bitmap
off = bitmap_off
bitmap_dwords = []
for i in range(bitmap_len):
bitmap_dwords.append(dbg.dword_from_buf(chunk_mem, off))
off += dword_size
bitmap = [bitmap_dwords[i] for i in range(int(bits_offset), \
int(len(bitmap_dwords)), int(bits_offset + 1))]
# parse chunk bitmap elements
i = -1
for mapelm in bitmap:
i += 1
unallocated = False
debug_log(" [%04d] mapelm = 0x%x" % (i, mapelm))
# standalone version
if jeheap.standalone:
# small run
if mapelm & 0xf == 1:
debug_log(" small run")
if android_version == '6':
offset = mapelm & ~flags_mask
binind = (mapelm & 0xFF0) >> 4
elif android_version == '7' or android_version == '8':
offset = (mapelm & ~0x1FFF) >> 1
binind = (mapelm & 0x1FE0) >> 5
debug_log(" offset = 0x%x" % offset)
# part of the previous run
if offset != 0:
continue
debug_log(" binind = 0x%x" % binind)
size = jeheap.bin_info[binind].run_size
debug_log(" size = 0x%x" % size)
# large run
elif mapelm & 0xf == 3:
debug_log(" large run")
if android_version == '6':
size = mapelm & ~flags_mask
elif android_version == '7' or android_version == '8':
size = (mapelm & ~0x1FFF) >> 1
binind = 0xff
debug_log(" size = 0x%x" % size)
# unallocated run
else:
debug_log(" unallocated run")
if android_version == '6':
size = mapelm & ~flags_mask
elif android_version == '7' or android_version == '8':
size = (mapelm & ~0x1FFF) >> 1
unallocated = True
binind = 0xff
debug_log(" size = 0x%x" % size)
map_misc_addr = chunk.addr + map_misc_offset
cur_arena_chunk_map_misc = map_misc_addr + \
i * dbg.sizeof('arena_chunk_map_misc_t')
hdr_addr = cur_arena_chunk_map_misc + \
dbg.offsetof('arena_chunk_map_misc_t', 'run')
debug_log(" run_hdr = 0x%x" % hdr_addr)
run_hdr_off = map_misc_offset \
+ i * dbg.sizeof('arena_chunk_map_misc_t') \
+ dbg.offsetof('arena_chunk_map_misc_t', 'run')
run_hdr = chunk_mem[run_hdr_off:
run_hdr_off + dbg.sizeof("arena_run_t")]
addr = chunk.addr + (i + map_bias) * dbg.get_page_size()
# Firefox
else:
# small run
if mapelm & 0xf == 1:
hdr_addr = mapelm & ~flags_mask
off = hdr_addr - chunk.addr
# part of the previous run
if str(hdr_addr) in jeheap.runs:
continue
run_hdr = chunk_mem[off:off+dbg.sizeof("arena_run_t")]
bin_addr = dbg.dword_from_buf(run_hdr, arena_run_bin_off)
# firefox stores the bin addr, we can find the binind as follows:
binind = (bin_addr - (chunk.arena_addr + bins_offset)) // arena_bin_size
size = jeheap.bin_info[binind].run_size
run_hdr_sz = dbg.sizeof("arena_run_t")
run_hdr_sz += (jeheap.bin_info[binind].nregs // 8) + 1
run_hdr = chunk_mem[off:
off + run_hdr_sz]
# large run
elif mapelm & 0xf == 3:
hdr_addr = chunk.addr + i * dbg.get_page_size()
off = hdr_addr - chunk.addr
run_hdr = chunk_mem[off:
off + dbg.sizeof("arena_run_t")]
size = mapelm & ~flags_mask
binind = 0xff
# unallocated run
else:
debug_log(" unallocated page")
continue
addr = hdr_addr
if hdr_addr == 0 or size == 0:
debug_log(" hdr_addr or size is 0, skipping")
continue
debug_log(" addr = 0x%x" % addr)
new_run = parse_run(jeheap, hdr_addr, addr, run_hdr, size, binind,
read_content_preview)
new_run.unallocated = unallocated
jeheap.runs[str(hdr_addr)] = new_run
chunk.runs.append(hdr_addr)
# parse all jemalloc chunks
def parse_chunks(jeheap):
debug_log("parse_chunks()")
dword_size = dbg.get_dword_size()
if jeheap.standalone:
chunks_rtree_addr = int(str(dbg.addressof('je_chunks_rtree')).split()[0], 16)
rtree_mem = dbg.read_bytes(chunks_rtree_addr, dbg.sizeof("rtree_t"))
max_height = dbg.read_struct_member(rtree_mem, "rtree_t",
"height", dbg.int_size())
# levels[] is of type rtree_level_t
levels_arr_addr = chunks_rtree_addr + \
dbg.offsetof('rtree_t', 'levels')
rtree_level_size = dbg.sizeof('rtree_level_t')
rtree_levels_mem = dbg.read_bytes(levels_arr_addr,
rtree_level_size * max_height)
root = None
for height in range(0, max_height):
off = height * rtree_level_size
level_mem = rtree_levels_mem[off:off+rtree_level_size]
addr = dbg.read_struct_member(level_mem, "rtree_level_t",
"subtree", dword_size)
if addr == 0:
continue
root = (addr, height)
break
# firefox
else:
chunks_rtree_addr = int_from_sym(['chunk_rtree'])
rtree_mem = dbg.read_bytes(chunks_rtree_addr, dbg.sizeof("malloc_rtree_t"))
max_height = dbg.read_struct_member(rtree_mem, "malloc_rtree_t",
"height", dbg.int_size())
root = dbg.read_struct_member(rtree_mem, "malloc_rtree_t",
"root", dbg.get_dword_size())
root = (root, 0)
levels_arr_addr = chunks_rtree_addr + \
dbg.offsetof('malloc_rtree_t', 'level2bits')
rtree_level_size = dbg.int_size()
rtree_levels_mem = dbg.read_bytes(levels_arr_addr,
rtree_level_size * max_height)
off = 0
level2bits = []
for i in range(0, max_height):
level2bits.append(dbg.int_from_buf(rtree_levels_mem, off))
off += dbg.int_size()
if not root:
raise Exception("[shadow] Could not find the root of chunks_rtree.")
stack = []
stack.append(root)
while len(stack):
(node, height) = stack.pop()
if jeheap.standalone:
cur_level_addr = levels_arr_addr + height * rtree_level_size
bits = dbg.read_memory(cur_level_addr +
dbg.offsetof('rtree_level_t', 'bits'),
dbg.int_size())
else:
bits = level2bits[height]
max_key = 1 << bits
subtree = dbg.read_dwords(node, max_key)
for addr in subtree:
if addr == 0:
continue
if height == max_height - 1:
if jeheap.standalone:
node_addr = addr + dbg.offsetof('arena_chunk_t', 'node')
en_arena = dbg.read_dword(node_addr +
dbg.offsetof('extent_node_t', 'en_arena'))
arena_addr = en_arena
else:
try:
arena_addr = dbg.read_dword(addr +
dbg.offsetof('arena_chunk_t', 'arena'))
except:
arena_addr = 0
global arenas_addr
exists = False
if arena_addr in arenas_addr:
exists = True
# this fixes the weird case where a non page aligned
# chunk address is found, for example:
# ...
# chunk @ 0xcc4ef4c0 <-- actually belongs to chunk 0xcc480000
# chunk @ 0xcc280000 |
# chunk @ 0xcc480000 <----------------------------------|
# ...
# XXX: investigate this
if addr & 0xfff:
debug_log(" skipping non-page aligned chunk address 0x%x" % addr)
continue
if exists:
debug_log(" chunk @ 0x%x" % addr)
jeheap.chunks.append(
jemalloc.chunk(addr, arena_addr, []))
else:
debug_log(" non-arena chunk @ 0x%x" % addr)
jeheap.chunks.append(
jemalloc.chunk(addr, None, []))
else:
stack.append((addr, height + 1))
# config functions
def update_dbg_cache_from_config(config_path):
config = ConfigParser.RawConfigParser()
config.read(config_path)
if config.has_section('offsets'):
for name,value in config.items('offsets'):
dbg.cache_offsets[name] = int(value, 16)
if config.has_section('values'):
for name,value in config.items('values'):
dbg.cache_values[name] = int(value, 16)
if config.has_section('sizes'):
for name,value in config.items('sizes'):
dbg.cache_sizes[name] = int(value, 16)
def generate_config(config_path):
config = ConfigParser.RawConfigParser()
config.add_section('values')
for name,value in dbg.cache_values.items():
if str(value).startswith('0x'):
config.set('values', name, str(value))
else:
config.set('values', name, hex(int(value)))
config.add_section('offsets')
for name,value in dbg.cache_offsets.items():
config.set('offsets', name, hex(value))
config.add_section('sizes')
for name,value in dbg.cache_sizes.items():
config.set('sizes', name, hex(value))
with open(config_path, 'w') as f:
config.write(f)
def parse_tbin_info(jeheap):
nhbins = int_from_sym(['je_nhbins', 'nhbins'])
int_size = dbg.int_size()
addr = dbg.get_value('je_tcache_bin_info')
size = nhbins * int_size
mem = dbg.read_bytes(addr, size)
off = 0
while off < len(mem):
ncached_max = dbg.int_from_buf(mem, off)
off += int_size
jeheap.tbin_info.append(jemalloc.tbin_info(ncached_max))
def parse_tcaches(jeheap):
nhbins = int_from_sym(['je_nhbins', 'nhbins'])
dword_size = dbg.get_dword_size()
max_cached = 0
for tbinfo in jeheap.tbin_info:
max_cached += tbinfo.ncached_max
tcache_size = dbg.offsetof("tcache_t", "tbins") + \
(dbg.sizeof("tcache_bin_t") * nhbins) + \
(max_cached * dword_size)
tcache_size = size2bin_size(jeheap, tcache_size)
# tcache_size = 0x1C00
BIONIC_PTHREAD_KEY_COUNT = 141
arenas_addr = [arena.addr for arena in jeheap.arenas]
data_off = dbg.offsetof("pthread_key_data_t" , "data")
pthread_internal_size = dbg.sizeof("pthread_internal_t")
key_data_off = dbg.offsetof('pthread_internal_t', 'key_data')
key_data_size = dbg.sizeof('pthread_key_data_t') * BIONIC_PTHREAD_KEY_COUNT
# g_thread_list points to the first pthread_internal_t struct
elm_addr = dbg.get_value("g_thread_list", True)
while elm_addr != 0:
elm_mem = dbg.read_bytes(elm_addr, pthread_internal_size)
elm_tid = dbg.read_struct_member(elm_mem, "pthread_internal_t",
"tid", dbg.int_size())
# key_data array
key_data = elm_mem[key_data_off:key_data_off + key_data_size]
# transform to a list containing only the key_data->data
off = data_off
key_data_data = []
while off < len(key_data):
data = dbg.dword_from_buf(key_data, off)
key_data_data.append(data)
off += data_off
# search for jemalloc TSD(Thread Specific Data)
tsd_addr = 0
for data in key_data_data:
if data == 0:
continue
# check if data is a ptr
addr = data
addr_info = find_address(addr, jeheap)
# jemalloc TSD is a 0x80 region that contains pointers to the
# tcache and the arena; unsure if we can rely on their offsets
# so we parse the region's data to make sure
if addr_info.region:
region_dwords = dbg.read_dwords(addr_info.region.addr,
addr_info.region.size)
for dword in region_dwords:
if dword in arenas_addr:
tsd_addr, tsd_dwords = addr, region_dwords
break
if tsd_addr:
break
if not tsd_addr:
k = str(elm_tid)
jeheap.tcaches[k] = None
elm_addr = dbg.read_struct_member(elm_mem, "pthread_internal_t",
"next", dbg.get_dword_size())
continue
arena_addr = 0
tcache_addr = 0
for dword in tsd_dwords:
if arena_addr and tcache_addr:
break
if dword in arenas_addr:
arena_addr = dword
continue
addr_info = find_address(dword, jeheap)
if addr_info.region:
if addr_info.region.size == tcache_size:
tcache_addr = dword
continue