forked from volatilityfoundation/community
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathheap_analysis.py
4214 lines (3178 loc) · 163 KB
/
heap_analysis.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
# Copyright (c) 2017, Frank Block, ERNW GmbH <[email protected]>
"""
This module implements several classes, allowing the glibc heap analysis for a
given process.
"""
import re
import pdb
import struct
import traceback
import json
import os
from numbers import Number
from volatility.plugins.linux.linux_yarascan import VmaYaraScanner
import volatility.plugins.linux.common as linux_common
import volatility.plugins.linux.pslist as linux_pslist
import volatility.plugins.linux.cpuinfo as cpuinfo
import volatility.obj as obj
import volatility.debug as debug
import volatility.scan as scan
#############
_PREV_INUSE = 0x1
_IS_MMAPPED = 0x2
_NON_MAIN_ARENA = 0x4
_SIZE_BITS = (_PREV_INUSE | _IS_MMAPPED | _NON_MAIN_ARENA)
# is set on HeapAnalysis instantiation
_MIN_LARGE_SIZE = None
# Probably more versions would work, especially when the corresponding vtype
# information are provided, but those are the versions we tested against
_SUPPORTED_GLIBC_VERSIONS = ['2.25', '2.24', '2.23', '2.22', '2.21', '2.20']
_LIBC_REGEX = '(?:^|/)libc[^a-zA-Z][^/]*\\.so'
def get_vma_for_offset(vmas, offset):
"""Returns a list with identifier and vm_area that given offset belongs to.
Expects the output from _get_vmas_for_task as argument.
"""
for vma in vmas:
if vma['vma'].vm_start <= offset < vma['vma'].vm_end:
return vma
return None
def dereference_pointer(pointer):
"""Ensures that we don't deal with pointers."""
if isinstance(pointer, obj.Pointer):
return pointer.dereference()
return pointer
def iterate_through_linked_list(node, iterate_func):
"""Iterates over a linked list starting with current Node.
Stops if the first node or the last node is hit again, or if the next node is NULL.
"""
node = dereference_pointer(node)
first_node = node
last_node = node
next_node = node
while True:
if not next_node:
break
yield next_node
last_node = next_node
next_node = dereference_pointer(iterate_func(next_node))
if next_node == first_node or next_node == last_node:
break
def get_libc_filename(vmas):
"""Returns the libc file name from the vma, where the _LIBC_REGEX matches.
"""
if vmas:
for vma in vmas:
if re.search(_LIBC_REGEX, vma['name'], re.IGNORECASE):
return vma['name']
def get_libc_range(vmas):
"""Returns the lowest and highest address for the libc vma. See also
get_mem_range_for_regex."""
return get_mem_range_for_regex(vmas, _LIBC_REGEX)
def get_mem_range_for_regex(vmas, regex):
"""Returns the lowest and highest address of memory areas belonging to the
vm_areas, the given regex matches on. The result is given as a list, where
the lowest address is the first element. Expects the output from
_get_vmas_for_task as argument."""
offsets = None
if vmas:
for vma in vmas:
if re.search(regex, vma['name'], re.IGNORECASE):
if not offsets:
offsets = [vma['vma'].vm_start]
offsets.append(vma['vma'].vm_end)
else:
offsets[1] = vma['vma'].vm_end
return offsets
class HeapAnalysis(linux_pslist.linux_pslist):
"""Basic abstract class for linux heap analysis.
Mostly serves the main_arena.
"""
__abstract = True
_main_heap_identifier = "[heap]"
# used to mark vm_areas residing between the [heap] and the first file or
# stack object and all other vm_areas that have no file object for
# (mmapped regions can also reside somewhere beyond the typical heap/stack
# area) note that vmas with this identifier might be empty, old thread
# stacks or vm_areas belonging to e.g. mapped files.
# A pretty reliable source for heap vm_areas is the self.heap_vmas list as
# it contains vm_areas which are identified to most probably belong to a
# heap or mmapped region.
_heap_vma_identifier = "[heap-vma]"
_pot_mmapped_vma_identifier = "[pot-mmapped-vma]"
# is normally only automatically set when using a dummy arena or the chunk
# dumper, as in those cases all chunks are walked at least two times
def activate_chunk_preservation(self):
"""Sets _preserve_chunks to True. This forces all allocated chunk
functions to store chunks in lists, which highly increases the speed
of a second walk over those chunks. This feature can only be activated
if performance is set to 'fast'."""
if not self._preserve_chunks:
debug.debug(
"Chunk preservation has been activated."
"This might consume large amounts of memory"
" depending on the chunk count. If you are low on free memory "
"space (RAM), you might want to deactivate this feature by "
"not using the 'fast' option. The only downside is in some "
"cases a longer plugin runtime.")
self._preserve_chunks = True
def _get_saved_stack_frame_pointers(self, task):
"""Returns a list of dicts, containing the ebp,esp and pid values
for each thread."""
if not task.mm:
return None
# To gather thread stacks, we examine the pt_regs struct for each
# thread and extract the saved stack frame pointers
thread_stack_offsets = []
thread_group_offset = self.profile.get_obj_offset("task_struct",
"thread_group")
for thread_group in iterate_through_linked_list(task.thread_group,
lambda x: x.next):
thread_task = obj.Object(
"task_struct",
offset=thread_group.obj_offset - thread_group_offset,
vm=self.process_as)
pt_regs = obj.Object("pt_regs",
offset=(thread_task.thread.sp0 -
self.profile.get_obj_size("pt_regs")),
vm=self.process_as)
thread_stack_offsets.append(dict(ebp=pt_regs.bp.v(),
esp=pt_regs.sp.v(),
pid=thread_task.pid.v()))
return thread_stack_offsets
# Basically the code from the proc_maps plugin but with thread specific
# enhancements
def _get_vmas_for_task(self, task):
"""Returns a list of lists, containing ["name", vm_area] pairs. """
if not task.mm:
return None
result = []
thread_stack_offsets = self._get_saved_stack_frame_pointers(task)
# The first pair contains the "main" thread and the mm start_stack
# value is more reliable for identifying the relevant memory region
# than the saved frame pointers
thread_stack_offsets[0]['start_stack'] = task.mm.start_stack
heap_area = False
for vma in iterate_through_linked_list(task.mm.mmap,
lambda x: x.vm_next):
temp_vma = dict()
if vma.vm_file:
fname = vma.info(task)[0]
if heap_area:
heap_area = False
else:
fname = ""
if heap_area:
fname = self._heap_vma_identifier
else:
fname = self._pot_mmapped_vma_identifier
# main heap can have 3 or more vm_area_struct structs
if vma.vm_start <= task.mm.start_brk <= vma.vm_end or \
(task.mm.start_brk <= vma.vm_start
< vma.vm_end <= task.mm.brk) or \
vma.vm_start <= task.mm.brk <= vma.vm_end:
fname = self._main_heap_identifier
heap_area = True
else:
for offsets in thread_stack_offsets:
if (('start_stack' in offsets.keys() and
vma.vm_start <= offsets['start_stack']
<= vma.vm_end) or
vma.vm_start <= offsets['ebp'] <= vma.vm_end or
vma.vm_start <= offsets['esp'] <= vma.vm_end):
fname = "[stack"
pid = offsets['pid']
fname += "]" if task.pid == pid else \
":{:d}]".format(pid)
temp_vma['ebp'] = offsets['ebp']
temp_vma['esp'] = offsets['esp']
heap_area = False
temp_vma['name'] = fname
temp_vma['vma'] = vma
result.append(temp_vma)
return sorted(result, key=lambda vma: vma['vma'].vm_start)
def _load_libc_profile(self):
"""Loads the Libc profile for the current libc version."""
# we try to gather version information from the mapped libc lib
libc_version_string = None
major_version = None
minor_version = None
match = None
libc_profile = None
if self._config.glibc_profile:
try:
if self._config.glibc_profile:
libc_profile_file = open(self._config.glibc_profile, 'r').read()
libc_profile = json.loads(libc_profile_file)
debug.debug("Loading libc profile: " + self._config.glibc_profile)
except IOError as ex:
debug.error("Libc profile read error: {}".format(ex))
except Exception as ex:
debug.error("Fatal Error: {}".format(ex))
else:
libc_filename = get_libc_filename(self.vmas)
if libc_filename:
match = re.search(r'(\d+)\.(\d+)', libc_filename)
libc_version_string = '224'
if match and len(match.groups()) == 2:
major_version = int(match.group(1))
minor_version = int(match.group(2))
libc_version_string = str(major_version) + str(minor_version)
debug.debug("Trying to load profile for version {:s}."
.format(libc_version_string))
if major_version and minor_version:
if major_version == 2:
if minor_version >= 24:
libc_version_string = '224'
elif minor_version == 23:
libc_version_string = '223'
else:
libc_version_string = '220'
debug.debug(
"Loading internal profile for version {:s}."
.format(libc_version_string))
if self.profile.metadata.get('memory_model') == '64bit':
libc_profile = GlibcProfile64(version=libc_version_string).libcprofile
else:
libc_profile = GlibcProfile32(version=libc_version_string).libcprofile
if not libc_profile:
debug.error('Unable to load a libc profile.')
else:
self.profile.vtypes.update(libc_profile)
if all(x in self.profile.vtypes.keys() for x in
['malloc_chunk', 'malloc_state',
'malloc_par', '_heap_info']):
self._libc_profile_success = True
self.profile.object_classes.update({
"malloc_chunk": malloc_chunk,
"malloc_state" : malloc_state,
"_heap_info" : _heap_info
})
else:
debug.error('Error while loading libc profile.')
self.profile.compile()
def _check_and_report_chunksize(self, chunk, current_border):
"""Checks whether or not the current chunk
- is bigger than the given border
- smaller than the minimum size a chunk is allowed to be
- 's address is aligned.
"""
if chunk.v() + chunk.chunksize() > current_border:
debug.warning(
"Chunk at offset 0x{:x} has a size larger than the current "
"memory region. This shouldn't be the case."
.format(chunk.v()))
return False
elif chunk.chunksize() < self._minsize:
if not self._check_and_report_chunk_for_being_swapped(chunk):
debug.warning(
"Chunk at offset 0x{:x} has a size smaller than MINSIZE, "
"which shouldn't be the case and indicates a problem."
.format(chunk.v()))
return False
elif not self._aligned_ok(chunk.chunksize()):
debug.warning(
"The size of chunk at offset 0x{:x} is not a multiple of "
"MALLOC_ALIGNMENT, which shouldn't be the case and indicates "
"a problem.".format(chunk.v()))
return False
return True
def _check_and_report_chunk_for_being_swapped(self, chunk):
"""Tests the size field of a given chunk for being 0. If this field
is null, it is a good indication that the corresponding memory region
has been swapped. The reason might however also be a calculation error
for the chunk's offset."""
if not chunk or chunk.get_size() == 0:
debug.warning(
"It seems like the memory page(s) belonging to the "
"chunk at offset 0x{:x} have been swapped. This will lead "
"to incorrect/incomplete results and more warnings/errors."
.format(chunk.v()))
return True
return False
def _check_and_report_allocated_chunk(
self, arena, chunk, next_chunk, current_border):
"""Checks if the given chunk should be in use (depending on the
PREV_INUSE bit of the next chunk), has a size > MINSIZE, is aligned,
whether or not it is part of any bin or fastbin in conjunction with
next_chunks PREV_INUSE bit and if next_chunks prev_size field has
same value as current chunk's size. This function is not intended to
be used for the "bottom chunks". It returns True if no error occurs
and if the given chunk is not part of bins or fastbins.
"""
error_base_string = (
"Found a presumably {0} chunk at offset 0x{1:x} which is however "
"{2}part of the bins. This is unexpected and might either "
"indicate an error or possibly in seldom cases be the result "
"from a race condition.")
if not self._check_and_report_chunksize(chunk, current_border):
return False
if not self._aligned_ok(chunk.v()):
debug.warning(
"Chunk at offset 0x{:x} is not aligned. As chunks are normally"
" always aligned, this indicates a mistakenly chosen chunk and"
" probably results in wrong results.".format(chunk.v()))
return False
# current chunk is tested in _check_and_report_chunksize for
# being swapped
self._check_and_report_chunk_for_being_swapped(next_chunk)
if next_chunk.prev_inuse():
# for chunks in fastbins, the prev_inuse bit is not unset,
# so we don't check that here
if chunk in arena.freed_chunks:
# freed chunks shouldn't be marked as in use
debug.warning(
error_base_string.format("allocated", chunk.v(), "")
)
elif chunk not in arena.freed_fast_chunks:
return True
else:
# current chunk seems to be freed, hence its size should equal
# next chunk's prev_size
if chunk.chunksize() != next_chunk.get_prev_size():
debug.warning(
"Chunk at offset 0x{:x} seems to be freed but its size "
"doesn't match the next chunk's prev_size value."
.format(chunk.v()))
elif chunk in arena.freed_fast_chunks:
# fastbins normally have the prev_inuse bit set
debug.warning(
"Unexpected: Found fastbin-chunk at offset 0x{0:x} which "
"prev_inuse bit is unset. This shouldn't normally be the "
"case.".format(chunk.v()))
elif chunk not in arena.freed_chunks:
# chunk is not marked as in use, but neither part of any bin
# or fastbin
debug.warning(
error_base_string.format("freed", chunk.v(), "not ")
)
return False
def _allocated_chunks_for_mmapped_chunk(self, mmap_first_chunk):
"""Returns all allocated chunks for the mmap region the given chunk
belongs to."""
if not mmap_first_chunk:
debug.warning(
"_allocated_chunks_for_mmapped_chunk has been called with "
"invalid pointer.")
return
mmap_vma = get_vma_for_offset(self.vmas, mmap_first_chunk.v())['vma']
current_border = mmap_vma.vm_end
# we can't check here for hitting the bottom, as mmapped regions can
# contain slack space but this test is in essence done in
# check_and_report_mmap_chunk
for curr_chunk in self.iterate_through_chunks(mmap_first_chunk,
current_border):
if self._check_and_report_mmapped_chunk(curr_chunk, mmap_vma) \
and self._check_and_report_chunksize(curr_chunk,
current_border):
yield curr_chunk
else:
# As the checks for the last MMAPPED chunk reported an error,
# we are stopping walking the MMAPPED chunks for that vm_area.
break
def get_all_mmapped_chunks(self):
"""Returns all allocated MMAPPED chunks."""
main_arena = self.get_main_arena()
if main_arena:
if main_arena.allocated_mmapped_chunks:
for chunk in main_arena.allocated_mmapped_chunks:
yield chunk
return
main_arena.allocated_mmapped_chunks = list()
for mmap_first_chunk in main_arena.mmapped_first_chunks:
for chunk in self._allocated_chunks_for_mmapped_chunk(
mmap_first_chunk):
main_arena.allocated_mmapped_chunks.append(chunk)
yield chunk
######### code taken from malloc/malloc.c (glibc-2.23)
# origins from the MINSIZE definition
def get_aligned_address(self, address, different_align_mask=None):
"""Returns an aligned address or MINSIZE, if given MIN_CHUNK_SIZE as
argument."""
if different_align_mask:
return (address + different_align_mask) & ~ different_align_mask
return (address + self._malloc_align_mask) & ~ self._malloc_align_mask
def _aligned_ok(self, value):
"""Returns True if the given address/size is aligned."""
return (value & self._malloc_align_mask) == 0
# essentially the request2size macro code
def get_aligned_size(self, size):
"""Returns an aligned size. Originally used to align a user request
size."""
if size + self._size_sz + self._malloc_align_mask < self._minsize:
return self._minsize & ~ self._malloc_align_mask
return ((size + self._size_sz + self._malloc_align_mask)
& ~ self._malloc_align_mask)
###########
def _check_mmap_alignment(self, address):
"""Returns True if the given address is aligned according to the
minimum pagesize."""
return (address & (self._min_pagesize - 1)) == 0
def _get_page_aligned_address(self, address):
"""Returns an address aligned to the internal pagesize.
The given address should be a number, not a chunk.
This function is primarily used in the context of MMAPPED chunks.
"""
return (address + self._min_pagesize - 1) & ~ (self._min_pagesize - 1)
def _check_for_bottom_chunks(self, chunk, heap_end):
"""Checks the current chunk for conditions normally only found on the
second last chunk of a heap, when there are more heaps following.
"""
if chunk.chunksize() <= self._minsize and \
(chunk.v() + chunk.chunksize() + (self._size_sz * 2)) == \
heap_end:
return True
return False
def _allocated_chunks_for_thread_arena(self, arena):
"""Returns all allocated chunks contained in all heaps for the given
arena, assuming the arena is not the main_arena."""
if arena.is_main_arena:
debug.warning(
"Unexpected: This method has been called with the main_arena.")
# since main_arena doesn't contain heap_infos, we return here
return
if arena.allocated_chunks:
for chunk in arena.allocated_chunks:
yield chunk
return
elif self._preserve_chunks:
arena.allocated_chunks = list()
heap_count = len(arena.heaps)
for i in range(heap_count):
heap = arena.heaps[i]
current_border = heap.v() + heap.get_size()
hit_heap_bottom = False
last_chunk = None
curr_chunk = None
for next_chunk in heap.first_chunk.next_chunk_generator():
if not curr_chunk:
curr_chunk = next_chunk
continue
last_chunk = curr_chunk
if (curr_chunk.v() + curr_chunk.chunksize()) == current_border:
# we hit the top chunk
break
else:
is_in_use = next_chunk.prev_inuse()
# on multiple heaps, for all but the last heap, the old
# top chunk is divided in at least two chunks at the
# bottom, where the second last has a size of
# minimum 2 * SIZE_SZ and maximum MINSIZE the last chunk
# has a size of 2* SIZE_SZ while the size field is set
# to 0x1 (the PREV_INUSE bit is set) and the prev_size
# contains the second last chunks size
# (min: 2 * SIZE_SZ , max: MINSIZE)
#
# see the part for creating a new heap within the
# sysmalloc function in malloc/malloc.c
# For glibc-2.23 beginning with line 2417
#
# as this behavior is included since version 2.0.1 from
# 1997, it should be safe to rely on it for most glibc
# versions
if curr_chunk.chunksize() <= self._minsize \
and (curr_chunk.v() + curr_chunk.chunksize()
+ (self._size_sz * 2)) == current_border:
# The last condition also tests if there are further
# heaps following.
# - if not, the current chunk which is only
# size_sz * 2 bytes away from
#
# - heap border shouldn't normally exist
if next_chunk.chunksize() == 0 and is_in_use and \
(next_chunk.get_prev_size()
== curr_chunk.chunksize()) and \
i < (heap_count - 1):
# we probably hit the bottom of the current heap
# which should'nt be the last one
debug.debug(
"We hit the expected two chunks at the bottom "
"of a heap. This is a good sign.")
hit_heap_bottom = True
curr_chunk.is_bottom_chunk = True
if self._preserve_chunks:
arena.allocated_chunks.append(curr_chunk)
yield curr_chunk
break
elif curr_chunk.chunksize() < self._minsize:
debug.warning(
"Unexpected: We hit a chunk at offset 0x{0:x} "
"with a size smaller than the default minimum "
"size for a chunk but which appears to be "
"not part of the typical end of a heap. This "
"might either indicate a fatal error, or "
"maybe a custom libc implementation/custom "
"compile time flags.".format(curr_chunk.v()))
else:
debug.warning(
"Unexpected: We hit a chunk at offset 0x{0:x} "
"which presumably should have been the second "
"last chunk of that heap, but some conditions "
"don't meet.".format(curr_chunk.v()))
if curr_chunk not in arena.freed_fast_chunks:
self._check_and_report_non_main_arena(curr_chunk,
is_in_use)
if self._preserve_chunks:
arena.allocated_chunks.append(curr_chunk)
yield curr_chunk
# normal chunk, not located at the bottom of the heap
else:
if self._check_and_report_allocated_chunk(
arena, curr_chunk, next_chunk, current_border):
self._check_and_report_non_main_arena(curr_chunk,
is_in_use)
if self._preserve_chunks:
arena.allocated_chunks.append(curr_chunk)
yield curr_chunk
curr_chunk = next_chunk
if not hit_heap_bottom and \
(last_chunk.v() + last_chunk.chunksize()) < current_border:
debug.warning(
"Seems like we didn't hit the top chunk or the bottom of "
"the current heap at offset: 0x{0:x}".format(heap.v()))
def _allocated_chunks_for_main_arena(self):
"""Returns all allocated chunks for the main_arena's heap.
mmap'ed regions are not included.
"""
arena = self.get_main_arena()
if arena.allocated_chunks:
for chunk in arena.allocated_chunks:
yield chunk
else:
current_border = 0
if self._preserve_chunks:
arena.allocated_chunks = list()
if arena.first_chunk and arena.first_chunk.chunksize() > 0:
# as the main heap can spread among multiple vm_areas, we take
# the system_mem value as the upper boundary
if arena.get_system_mem() > 0:
current_border = arena.first_chunk.v() + \
arena.get_system_mem()
# there have been rare scenarios, in which the system_mem
# value was 0
else:
debug.warning(
"Unexpected: system_mem value of main arena is <= 0. "
"We will calculate it with the top chunk. This will "
"lead to follow up warnings regarding size "
"inconsistencies.")
current_border = arena.top.v() + arena.top.chunksize()
last_chunk = None
curr_chunk = None
for next_chunk in arena.first_chunk.next_chunk_generator():
last_chunk = curr_chunk
if not curr_chunk:
curr_chunk = next_chunk
continue
if (curr_chunk.v() + curr_chunk.chunksize()) \
== current_border:
# reached top chunk
break
else:
if self._check_and_report_allocated_chunk(
arena, curr_chunk, next_chunk, current_border):
if self._preserve_chunks:
arena.allocated_chunks.append(curr_chunk)
yield curr_chunk
curr_chunk = next_chunk
if (last_chunk.v() + last_chunk.chunksize()) < current_border:
debug.warning("Seems like we didn't hit the "
"top chunk for main_arena.")
elif arena.first_chunk and arena.first_chunk.chunksize() == 0:
if not self._libc_offset:
debug.warning(
"The first main arena chunk seems to have a zero "
"size. As we didn't find a mapped libc module, the "
"reason might be a statically linked executable. "
"Please provide offset for the malloc_par struct "
"(symbol name is 'mp_'). Another reason might be "
"swapped memory pages.")
else:
debug.warning(
"Unexpected error: The first main arena chunk "
"seems to have a zero size. The reason might be "
"swapped memory pages. Walking the chunks is aborted.")
def get_all_allocated_chunks_for_arena(self, arena):
"""Returns all allocated chunks for a given arena.
This function is basically a wrapper around
_allocated_chunks_for_main_arena and allocated_chunks_for_thread_arena.
"""
if not arena:
debug.error(
"Error: allocated_chunks_for_arena called with an empty arena")
return
if arena.freed_fast_chunks is None or arena.freed_chunks is None:
debug.error(
"Unexpected error: freed chunks seem to not be initialized.")
return
if arena.is_main_arena:
for i in self._allocated_chunks_for_main_arena():
yield i
else:
# not main_arena
for chunk in self._allocated_chunks_for_thread_arena(arena):
yield chunk
# at least the function depends on getting allocated chunks first and then
# freed chunks, so this order shouldn't be changed
def get_all_chunks(self):
"""Returns all chunks (allocated, freed and MMAPPED chunks)."""
for chunk in self.get_all_allocated_chunks():
yield chunk
for freed_chunk in self.get_all_freed_chunks():
yield freed_chunk
def get_all_allocated_main_chunks(self):
"""Returns all allocated chunks belonging to the main arena (excludes
thread and MMAPPED chunks)."""
for chunk in self.get_all_allocated_chunks_for_arena(
self.get_main_arena()):
yield chunk
def get_all_allocated_thread_chunks(self):
"""Returns all allocated chunks which belong to a thread arena."""
if self.get_main_arena():
for arena in self.arenas:
if not arena.is_main_arena:
for chunk in self.get_all_allocated_chunks_for_arena(
arena):
yield chunk
def get_all_allocated_chunks(self):
"""Returns all allocated chunks, no matter to what arena they belong
or if they are MMAPPED or not."""
if self.get_main_arena():
for arena in self.arenas:
for chunk in self.get_all_allocated_chunks_for_arena(arena):
yield chunk
for chunk in self.get_all_mmapped_chunks():
yield chunk
def get_all_freed_fastbin_chunks(self):
"""Returns all freed fastbin chunks, no matter to what arena they
belong."""
if self.get_main_arena():
for arena in self.arenas:
for free_chunk in arena.freed_fast_chunks:
yield free_chunk
def get_all_freed_bin_chunks(self):
"""Returns all freed chunks, no matter to what arena they belong."""
if self.get_main_arena():
for arena in self.arenas:
for free_chunk in arena.freed_chunks:
yield free_chunk
def get_all_freed_chunks(self):
"""Returns all top chunks, freed chunks and freed fastbin chunks,
no matter to what arena they belong."""
if self.get_main_arena():
for freed_chunk in self.get_all_freed_fastbin_chunks():
yield freed_chunk
for freed_chunk in self.get_all_freed_bin_chunks():
yield freed_chunk
for arena in self.arenas:
if arena.top_chunk:
yield arena.top_chunk
def _last_heap_for_vma(self, vma):
"""Returns the last heap_info within the given vma."""
heap_hit = None
if self.get_main_arena:
for arena in self.arenas:
for heap in arena.heaps:
if vma.vm_start <= heap.v() < vma.vm_end:
if not heap_hit or heap.v() > heap_hit.v():
heap_hit = heap
return heap_hit
def heap_for_ptr(self, ptr):
"""Returns the heap from the internal heap lists, the given pointer
belongs to."""
if self.get_main_arena:
ptr_offset = None
if isinstance(ptr, Number):
ptr_offset = ptr
else:
ptr_offset = ptr.v()
for arena in self.arenas:
for heap in arena.heaps:
if heap.v() <= ptr_offset < (heap.v() + heap.get_size()):
return heap
return None
# We don't use the code from glibc for this function, as it depends on the
# HEAP_MAX_SIZE value and we might not have the correct value
def _heap_for_ptr(self, ptr, vma=None, suppress_warning=False):
"""Returns a new heap_info struct object within the memory region, the
given pointer belongs to. If the vm_area contains multiple heaps it
walks all heap_info structs until it finds the corresponding one.
"""
if self._libc_profile_success:
ptr_offset = None
if isinstance(ptr, Number):
ptr_offset = ptr
else:
ptr_offset = ptr.v()
if not vma:
temp = get_vma_for_offset(self.vmas, ptr_offset)
if temp:
vma = temp['vma']
if vma:
heap_info = obj.Object('_heap_info',
offset=vma.vm_start,
vm=self.process_as)
# there might be at least two heaps in one vm_area
while heap_info.get_size() > 0 and \
(heap_info.v() + heap_info.get_size() < ptr_offset):
heap_info = obj.Object(
'_heap_info',
offset=heap_info.v() + heap_info.get_size(),
vm=self.process_as)
if heap_info.ar_ptr not in self.arenas and not \
suppress_warning:
debug.warning(
"The arena pointer of the heap_info struct gathered "
"from the given offset {0:x} does not seem to point "
"to any known arena. This either indicates a fatal "
"error which probably leads to unreliable results "
"or might be the result from using a pointer to a "
"MMAPPED region.".format(ptr_offset)
)
return heap_info
else:
debug.warning(
"No vm_area found for the given pointer 0x{:x}."
.format(ptr_offset))
else:
debug.error(
"Libc profile is not loaded, hence no struct or constant "