-
Notifications
You must be signed in to change notification settings - Fork 5
/
core_utils.py
2107 lines (1813 loc) · 67.7 KB
/
core_utils.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) 2002-2011 IronPort Systems and Cisco Systems
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""Python core file analysis tool.
core_utils is a module for interacting with a python core file. The same
efficiencies gained by working with python instead of C are realized by using
core_utils instead of gdb. Obviously this statement only applies to python core
files, core_utils doesn't help much if you're exploring a core file that wasn't
created from a python binary.
core_utils works by providing object wrappers around PyObject structures. The
wrappers provide access to meta data about the object, like its address and
reference count and can also usually provide access to the actual value stored
within. For PyStringObject (regular python strings) core_utils can show the
actual string value inside of it. The same holds for ints, longs and floats.
core_utils can inspect the members of a list, tuple and even a dictionary.
The example below takes the python frame pointer (a pointer to a python frame
object) and from that gets the listing of local variables for that frame. Given
those local variables we begin digging around inside of classes to find member
variables and inspect their values.
Once you've mastered the techniques shown here you can debug almost anything :-)
Getting a Python Traceback
==========================
An example might be the best way to see this in action. First we start with
gdb and the first few lines of bt output::
(gdb) bt
#0 0x28389e27 in getipnodebyname () from /lib/libc.so.6
#1 0x28411f98 in sock_recv (s=0x8634ca0, args=0x86ec3cc)
at /data/home/bvanzant/work/sam-v6-2/third_party/python2.6_6_i386_thr/Modules/socketmodule.c:2313
#2 0x080d2311 in PyEval_EvalFrameEx (f=0x86b100c, throwflag=0)
at Python/ceval.c:3679
#3 0x080d3388 in PyEval_EvalCodeEx (co=0x83fff08, globals=0x4,
locals=0x8634ca0, args=0x81e002c, argcount=2, kws=0xe8ddf78, kwcount=0,
defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2942
#4 0x080d1510 in PyEval_EvalFrameEx (f=0xe8dde0c, throwflag=0)
at Python/ceval.c:3774
From there the topmost python frame is the C frame #2 (Being in
PyEval_EvalFrameEx tells us this). From this call we can see that the actual
Python frame object is at 0x86b100c. Let's take that address over to core_utils
and make an object (MO) of it::
>>> f = MO(0x86b100c)
>>> print f
<frame [1] at 0x86b100c>
>>> help(f.__repr__)
__repr__(self) method of __main__.frame_object instance
<type_name [reference count] address>
The repr of f tells us a few things that are fairly common for the objects that
MO returns. The number in [] is the reference count for this object. Reference
counts that are way out of whack (way higher than expected) may be a clue that
something is wrong. The "at" is obviously an address and is the same one we just
passed into MO.
One of the most immediately useful things to get from a frame object is the
python traceback. While gdb can show us where we were in C-land it doesn't tell
us anything about where we were in python. core_utils can tell us though::
>>> print_traceback(f)
('/usr/local/lib/python2.6_6_i386_thr/site-packages/fast_rpc_blocking_threadsafe.py',
'_read', 84)
('/usr/local/lib/python2.6_6_i386_thr/site-packages/fast_rpc_blocking_threadsafe.py',
'run', 96)
('/usr/local/lib/python2.6_6_i386_thr/threading.py', '__bootstrap_inner',
522)
('/usr/local/lib/python2.6_6_i386_thr/threading.py', '__bootstrap', 497)
Inspecting Python Variables
===========================
The frame object from the prior section isn't an actual python frame object. But
we can get most of what we need from this object::
>>> dir(f)
['__doc__', '__getattr__', '__getitem__', '__init__', '__module__',
'__repr__', 'address', 'locals', 'object_at_offset', 'offsetof',
'read_slot', 'slots']
>>> f.print_locals()
0: ss: <_socketobject [4] at 0x875bbc4>
1: nbytes: <int 14464 [2] at 0x8475a2c>
2: res: <str '(J\xd1\x9f\xb1\x00...' (1938 bytes) [1] at 0x9769000>
3: res2: <str '(J\xd1\x9f\xb1\x00...' (1938 bytes) [1] at 0xc678000>
From that output we can see that there are a few variables in this frame.
There's a socket object, an integer and two strings. Each of these objects,
being of different types, are inspected in different ways. To get access to any
of these objects we take the index from print_locals() and call local()
Let's look at one of the string objects::
>>> res = f.local(2)
>>> res.value()
'(J\xd1\xe7\x01\x00N ... <truncated>
Unfortunatey socket is a new style python class that uses __slots__ to save
memory. As of this writing I don't know how to find the member _sock that is the
actual C structure containing the socket information (file descriptor, address
family, etc). With this particular core file and this particular C backtrace it
is easy to get the C socket structure, however, this is not necessarily common.
Here's a slightly more advanced example. In this case we start with a tuple::
>>> t = MO(0x865acac)
>>> t
<tuple [[<int 1 [1981] at 0x8231340>, <request_thread [12] at 0x863936c>]]
(2 items) [1] at 0x865acac>
>>> t.objects
[<int 1 [1981] at 0x8231340>, <request_thread [12] at 0x863936c>]
>>> rt = t.objects[1]
rt now contains the request_thread instance. To get access to the members of
this request_thread instance we call class_members(). class_members() locates
the dictionary (__dict__) for this class instance. New-style python classes that
define __slots__ are not supported by class_members just yet.
>>> rt.class_members()
<dict (18 items) [1] at 0x8637824>
>>> rt.class_members().entries
[(<str 'job_queue' (9 bytes) [108] (interned) at 0x83934f8>, 141894412),
<truncated>
And now we're rinsing and repeating. We have a python list of tuples in entries.
Each tuple has two items, both python objects. The first is the key, the second
the value at that key. It just so happens that 'job_queue' is an old style
class, let's see how to open it up::
>>> jq = MO(141894412)
>>> jq.in_dict
<dict (5 items) [1] at 0x875c0b4>
And again, rinse and repeat. Given the dictionary in jq.in_dict we can look at
all of the properites of class job_queue.
::
>>> jq.in_dict['queue']
139496812
>>> q = MO(_)
>>> q
<list [<tuple [[<client [570] at 0x863bb8c>, <int 922106 [1] at 0x8474804>
<truncated>
>>> len(q)
358
That job_queue has 358 items in it. We could dig through that big old list there
and inspect each of those items. Or not :-)
Dealing with Threads
====================
These examples should work without threads too. The underlying python structures
don't change with or without threads, its just that the linked list of threads
has length 1 :-).
If you're debugging a threaded python app core_utils can help.
::
>>> info_threads()
0 <frame [1] at 0x86b100c>
1 <frame [1] at 0x975160c>
2 <frame [1] at 0x9745c0c>
Or to show the traceback for each of those threads::
>>> ptb_threads(0, 1)
0 <frame [1] at 0x86b100c>
('/usr/local/lib/python2.6_6_i386_thr/site-packages/fast_rpc_blocking_threadsafe.py', '_read', 84)
('/usr/local/lib/python2.6_6_i386_thr/site-packages/fast_rpc_blocking_threadsafe.py', 'run', 96)
('/usr/local/lib/python2.6_6_i386_thr/threading.py', '__bootstrap_inner', 522)
('/usr/local/lib/python2.6_6_i386_thr/threading.py', '__bootstrap', 497)
1 <frame [1] at 0x975160c>
('/usr/local/lib/python2.6_6_i386_thr/site-packages/third_party_utils.py', 'recv_exact', 364)
('/usr/local/lib/python2.6_6_i386_thr/site-packages/third_party_utils.py', '_run', 416)
('/usr/local/lib/python2.6_6_i386_thr/site-packages/third_party_utils.py', 'run', 401)
('/usr/local/lib/python2.6_6_i386_thr/threading.py', '__bootstrap_inner', 522)
('/usr/local/lib/python2.6_6_i386_thr/threading.py', '__bootstrap', 497)
To dig in further on a given frame use MO() with the frame address.
Extending core_utils
====================
Put a module named core_utils_local somewhere in your PYTHONPATH and core_utils
will import it for you on startup, loading everything for you to use. This is
similar to a .gdbinit file.
"""
import os
import parse_elf
import struct
import sys
from pprint import pprint as pp
W = sys.stderr.write
elf_data = {}
# this should be set by the elf data
psize = None
def read_map (filename, base=0):
global elf_data
info = parse_elf.go (filename)
elf_data[filename] = (base, info)
ehdr, phdrs, shdrs, syms, core_info = info
result = []
for phdr in phdrs:
if phdr['type'] == 'load':
result.append ((phdr['memsz'], base + phdr['vaddr'], phdr['offset'], phdr['filesz']))
result.sort()
return result
# rules for poking around in memory.
# 1) how to find and verify objects in memory.
# Py_OBJECT_HEAD = {refcount, &type}
# Type Objects also have a head, and they point at the 'type' type,
# which we can get the address of as well.
class searchable_file:
block_size = 1<<16
def __init__ (self, fd, size):
self.fd = fd
self.size = size
def find (self, needle, position, size=None):
if size is None:
size = self.size - position
while position < self.size:
os.lseek (self.fd, position, 0)
block = os.read (self.fd, self.block_size)
maybe = block.find (needle)
if maybe != -1:
return position + maybe
else:
# fuzz the block size in case needle straddles the boundary
position += (self.block_size - (len(needle) - 1))
return None # Not found
def seek (self, position):
os.lseek (self.fd, position, 0)
def read (self, size):
return os.read (self.fd, size)
def valid_address (addr):
for mmap, mfd, msize, mfile, base in maps:
for memsz, vaddr, offset, filesz in mmap:
if vaddr <= addr < (vaddr + memsz):
return (addr - vaddr) + offset, mfile
return None
def to_disk (addr):
probe = valid_address (addr)
if probe is None:
raise ValueError ("address out of range")
else:
return probe
def from_disk (pos, addr_map):
for mmap, mfd, msize, mfile, base in maps:
for memsz, vaddr, offset, filesz in mmap:
if offset <= pos < (offset + filesz):
return (pos - offset) + vaddr
raise ValueError, "address out of range"
def read (address, nbytes=4):
# verify all addresses before trying to read them.
probe = valid_address (address)
if probe is not None:
pos, mm = probe
mm.seek (pos)
#print 'addr: %x, pos: %d, mm=%s' % (address, pos, mm)
return mm.read (nbytes)
else:
raise ValueError, "address out of range"
def read_long (address):
return struct.unpack (long_struct, read (address, psize))[0]
def read_struct (address, format):
return struct.unpack (format, read (address, struct.calcsize (format)))
def read_string (address):
if not address:
return '<null>'
else:
r = []
while 1:
ch = read (address, 1)
if ch == '\000':
break
else:
r.append (ch)
address += 1
return ''.join (r)
# ================================================================================
# walking the python pymalloc heap
# these might get tweaked in future
ARENA_SIZE = 256 * 1024
POOL_SIZE = 4 * 1024
POOL_SIZE_MASK = POOL_SIZE - 1
ALIGNMENT_SHIFT = 3
ALIGNMENT = 8
ALIGNMENT_MASK = ALIGNMENT - 1
SMALL_REQUEST_THRESHOLD = 256
# /* Pool for small blocks. */
# struct pool_header {
# union { block *_padding;
# uint count; } ref; /* number of allocated blocks */
# block *freeblock; /* pool's free list head */
# struct pool_header *nextpool; /* next pool of this size class */
# struct pool_header *prevpool; /* previous pool "" */
# uint arenaindex; /* index into arenas of base adr */
# uint szidx; /* block size class index */
# uint nextoffset; /* bytes to virgin block */
# uint maxnextoffset; /* largest valid nextoffset */
# };
poolp_struct = 'IPPPIIII'
poolp_size = struct.calcsize (poolp_struct)
def ROUNDUP (x):
return (x + ALIGNMENT_SHIFT) & ~ALIGNMENT_MASK
POOL_OVERHEAD = ROUNDUP(poolp_size)
def INDEX2SIZE (i):
return (i + 1) << ALIGNMENT_SHIFT
def NUMBLOCKS (i):
return (POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE (i)
def POOL_ADDR (p):
"""Round down an address to the beginning of the pool."""
return (p & ~POOL_SIZE_MASK)
class pymalloc_pool:
def __init__(self, addr):
self.addr = POOL_ADDR(addr)
self._unpack()
def _unpack(self):
bytes = read(self.addr, poolp_size)
(self.count, self.freeblock, self.next, self.prev,
self.arenaindex, self.szidx,
self.nextoffset, self.maxnextoffset
) = struct.unpack (poolp_struct, bytes)
def __repr__(self):
return '<pymalloc_pool count=%r freeblock=%r arenaindex=%r szidx=%r>' % (
self.count,
self.freeblock,
self.arenaindex,
self.szidx,
)
class pymalloc_arena:
def __init__(self, addr):
self.object_addr = addr
self._unpack()
def _unpack(self):
arena_struct = 'PPIIPPP'
arena_object_size = struct.calcsize(arena_struct)
bytes = read(self.object_addr, arena_object_size)
(self.address, self.pool_address, self.nfreepools, self.ntotalpools,
self.freepools, self.nextarena, self.prevarena
) = struct.unpack(arena_struct, bytes)
def __repr__(self):
return '<pymalloc_arena addr=0x%x pool_addr=0x%x nfreepools=%r ntotalpools=%r' % (
self.address, self.pool_address, self.nfreepools, self.ntotalpools
)
def describe_pymalloc():
num_classes = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT
numpools = [0] * num_classes
numblocks = [0] * num_classes
numfreeblocks = [0] * num_classes
num_free_pools = 0
maxarenas = get_sym ('maxarenas')
arenas = get_sym ('arenas')
print 'maxarenas', maxarenas
# Visit every arena gathering information.
for arena_idx in xrange(maxarenas):
# 28 = sizeof(arena_object) on 32-bit
addr = arenas + 28*arena_idx
arena = pymalloc_arena(addr)
# Address == NULL means it has not been allocated, yet.
if arena.address:
base = arena.address
if base & POOL_SIZE_MASK:
# Due to alignment, space is lost. This doesn't seem to happen
# on our platform.
base &= ~POOL_SIZE_MASK
base += POOL_SIZE
pool_idx = 0
while base < arena.pool_address:
pool = pymalloc_pool(base)
# Check if it is empty.
if pool.count == 0:
num_free_pools += 1
else:
numpools[pool.szidx] += 1
numblocks[pool.szidx] += pool.count
numfreeblocks[pool.szidx] += (NUMBLOCKS(pool.szidx) - pool.count)
pool_idx += 1
base += POOL_SIZE
print
headers = ('class', 'size', '#pools', 'used blocks', 'used bytes', 'avail blocks')
print ('%15s' * len(headers)) % headers
allocated_bytes = 0
available_bytes = 0
pool_header_bytes = 0
quantization = 0
for i in range (num_classes):
size = INDEX2SIZE (i)
print ('%15s' * len(headers)) % (
i, size, numpools[i], numblocks[i], numblocks[i] * size, numfreeblocks[i]
)
allocated_bytes += numblocks[i] * size
available_bytes += numfreeblocks[i] * size
pool_header_bytes += numpools[i] * POOL_OVERHEAD
quantization += numpools[i] * ((POOL_SIZE - POOL_OVERHEAD) % size)
print '%12d bytes in allocated blocks' % allocated_bytes
print '%12d bytes in available blocks' % available_bytes
print '%12d bytes lost to pool headers' % pool_header_bytes
print '%12d bytes in %d unused pools' % (num_free_pools * POOL_SIZE, num_free_pools)
def _block_is_free(pool, bp):
p = pool.freeblock
while p:
if p == bp:
return 1
p = read_long(p)
return 0
def pymalloc_walk_heap (idx, callback, limit=100, pool_offset=0):
"""Walk the Python malloc heap and call `callback` for every allocated
piece of membery.
`callback` should be a function that takes two arguments. The first is the
address of the allocation. The second is the size of the allocation.
Beware that pointers for garbage-collected objects point to the gc header,
not the object header.
"""
maxarenas = get_sym ('maxarenas')
arenas = get_sym ('arenas')
every = maxarenas/10
for arena_idx in xrange(maxarenas):
addr = arenas + 4*arena_idx
arena = pymalloc_arena(addr)
if arena.address:
base = arena.address
if base & POOL_SIZE_MASK:
# Due to alignment, space is lost. This doesn't seem to happen
# on our platform.
base &= ~POOL_SIZE_MASK
base += POOL_SIZE
pool_idx = 0
while base < arena.pool_address:
pool = pymalloc_pool(base)
# Check if it is empty.
if pool.count != 0 and pool.szidx == idx:
size = INDEX2SIZE(pool.szidx)
bp = pool.addr + POOL_OVERHEAD
for block_idx in xrange(NUMBLOCKS(pool.szidx)):
if limit:
if not _block_is_free(pool, bp):
callback (bp, size)
limit -= 1
else:
return
bp += size
pool_idx += 1
base += POOL_SIZE
# progress dot
if every and not ((i+1) % every):
sys.stderr.write ('.')
# ================================================================================
# walking the freebsd malloc heap
#/*
# * This structure describes a page worth of chunks.
# */
#struct pginfo {
# struct pginfo *next; /* next on the free list */
# void *page; /* Pointer to the page */
# u_short size; /* size of this page's chunks */
# u_short shift; /* How far to shift for this size chunks */
# u_short free; /* How many free chunks */
# u_short total; /* How many chunk */
# u_int bits[1]; /* Which chunks are free */
#};
#/* Pointer to page directory. Allocated "as if with" malloc */
#static struct pginfo **page_dir;
#/*
# * This structure describes a number of free pages.
# */
#struct pgfree {
# struct pgfree *next; /* next run of free pages */
# struct pgfree *prev; /* prev run of free pages */
# void *page; /* pointer to free pages */
# void *end; /* pointer to end of free pages */
# size_t size; /* number of bytes free */
#};
#/* Free pages line up here */
#static struct pgfree free_list;
page_table_origin = None
malloc_pageshift = 15
malloc_minsize = 16
malloc_pagesize = 1L << malloc_pageshift
malloc_pagemask = malloc_pagesize - 1
sizeof_pginfo = struct.calcsize ('=llHHHH')
# struct pginfo *next; /* next on the free list */
# void *page; /* Pointer to the page */
# u_short size; /* size of this page's chunks */
# u_short shift; /* How far to shift for this size chunks */
# u_short free; /* How many free chunks */
# u_short total; /* How many chunk */
# u_int bits[1]; /* Which chunks are free */
MALLOC_NOT_MINE = 0
MALLOC_FREE = 1
MALLOC_FIRST = 2
MALLOC_FOLLOW = 3
MALLOC_MAGIC = 4
MALLOC_MAGICS = ['not_mine', 'free', 'first', 'follow']
W = sys.stderr.write
# two kinds of allocation - 'page' and 'chunk'
# if page_dir[index] == MALLOC_FIRST => 'page allocation'
# >= MALLOC_MAGIC => 'chunk allocation'
def collect_alloc_stats():
page_dir = get_sym ('page_dir')
ninfo = get_sym ('malloc_ninfo')
run_start = 0
run_n = 0
# Counts of each page type (4 types)
chunk_pages = 0
not_mine_pages = 0
block_pages = 0
free_pages = 0
runs = []
hist = {}
i = 0
while i < ninfo:
maybe_magic = read_long (page_dir)
if maybe_magic < MALLOC_MAGIC:
if maybe_magic == MALLOC_FREE:
# this page is free
free_pages += 1
elif maybe_magic == MALLOC_FIRST:
# first of a multi-page run
run_start = i
run_n = 1
while i < ninfo:
i += 1
page_dir += 4
maybe_magic = read_long (page_dir)
if maybe_magic==MALLOC_FOLLOW:
run_n += 1
else:
runs.append ((run_start, run_n))
break
block_pages += run_n
continue
elif maybe_magic == MALLOC_FOLLOW:
raise 'Floating follow?'
elif maybe_magic == MALLOC_NOT_MINE:
not_mine_pages += 1
else:
raise "Huh?"
else:
next, page, size, shift, free, total = read_struct (maybe_magic, '=llHHHH')
chunk_total, chunk_free = hist.get (size, (0, 0))
hist[size] = (chunk_total + total, chunk_free + free)
chunk_pages += 1
page_dir += 4
i += 1
if i % (ninfo/10) == 0:
sys.stderr.write ('.')
print
print 'Found %i chunk_pages' % chunk_pages
print 'Found %i free_pages' % free_pages
print 'Found %i block_pages' % block_pages
print 'Found %i not_mine_pages' % not_mine_pages
return hist, runs, ninfo, free_pages
def num_allocated_arenas():
total = 0
maxarenas = get_sym ('maxarenas')
arenas = get_sym ('arenas')
for arena_idx in xrange(maxarenas):
addr = arenas + 4*arena_idx
arena = pymalloc_arena(addr)
if arena.address:
total += 1
return total
def describe_heap():
"""Print information about the malloc heap.
This will print a summary of the malloc heap. You'll need to read and
study the malloc implementation to understand how it uses buckets and
pages to understand this output.
"""
hist, runs, ninfo, nfree = collect_alloc_stats()
narenas = num_allocated_arenas()
hi = hist.items()
hi.sort()
sum_btotal = 0
sum_bfree = 0
for size, (total, free) in hi:
print 'size: %5d total:%8d free:%8d bused:%9d btotal:%9d bfree:%9d' % (
size, total, free, (total-free) * size, total * size, free * size
)
sum_btotal += total * size
sum_bfree += free * size
run_d = {}
for (run_start, run_n) in runs:
n = run_d.get (run_n, 0)
run_d[run_n] = n + 1
probably_pymalloc = run_d[8]
run_d = run_d.items()
run_d.sort()
print 'page allocations:'
print 'npages KB count'
sum_ptotal = 0
sum_pages = 0
for (size, count) in run_d:
print '%3d %10d %5d' % (
size,
(size * malloc_pagesize) / 1024,
count
)
sum_ptotal += (size * malloc_pagesize) * count
sum_pages += (count * size)
print '--- chunked data ---'
print 'bytes_total: %10d' % sum_btotal
print 'bytes_free : %10d' % sum_bfree
print '--- page allocations ---'
print 'bytes_total: %10d' % sum_ptotal
print 'pages_total: %10d' % sum_pages
print '--- page allocations (excluding pymalloc) ---'
print 'bytes_total: %10d' % (sum_ptotal - (narenas * 256 * 1024))
print 'pages_total: %10d' % (sum_pages - (narenas * 8))
print '--- all pages ---'
print 'total pages:%d free:%d' % (ninfo, nfree)
print 'bytes_total: %10d' % (ninfo * malloc_pagesize)
print 'bytes_free : %10d' % (nfree * malloc_pagesize)
# here we should walk the free list and see if the numbers match.
def ptr2index (address):
return (address >> malloc_pageshift) - page_table_origin
def index2ptr (index):
return (index + page_table_origin) << malloc_pageshift
def pageround (address):
return address - (address & malloc_pagemask)
def print_bits (ints):
l = [None] * (len(ints) * 32)
i = 0
for n in ints:
for x in range (32):
l[i] = n & 1
n >>= 1
i += 1
return ''.join (map (str, l))
def describe_pointer (address=None):
if address is None:
address = _
if is_pymalloc_pointer(address):
print 'malloc:'
describe_malloc_pointer(address)
print 'pymalloc:'
describe_pymalloc_pointer(address)
else:
describe_malloc_pointer(address)
def describe_malloc_pointer (address):
index = ptr2index (address)
page_dir = get_sym ('page_dir')
page_entry = page_dir + (4 * index)
maybe_magic = read_long (page_entry)
if maybe_magic > MALLOC_MAGIC:
next, page, size, shift, free, total = read_struct (maybe_magic, '=llHHHH')
# how many ints in the bitmap? (no I don't understand this calculation)
n_ints = ((malloc_pagesize >> shift)+31) / 32
ints = read_struct (maybe_magic + sizeof_pginfo, '=' + ('l' * n_ints))
bits = print_bits (ints)[:total]
which = (address & malloc_pagemask) / size
front = page + (which * size)
print 'size:%d shift:%d page:0x%x address:0x%x total:%d free:%d' % (
size,
shift,
page,
address,
total,
free
)
print 'bitmap %r' % (bits)
print 'front:0x%x index:%d free?:%s internal?:%d' % (
front,
which,
bits[which],
front != address
)
else:
print 'page-alloc: page=0x%x status=%s' % (
address >> malloc_pageshift,
MALLOC_MAGICS[maybe_magic]
)
def _pymalloc_address_in_range(p, pool):
arenas = get_sym ('arenas')
maxarenas = get_sym ('maxarenas')
try:
arena = pymalloc_arena(arenas + 4*pool.arenaindex)
except ValueError:
return False
return pool.arenaindex < maxarenas and (p - arena.address) < ARENA_SIZE and arena.address != 0
def is_pymalloc_pointer(p):
try:
pool = pymalloc_pool(p)
except ValueError:
return False
return _pymalloc_address_in_range(p, pool)
def describe_pymalloc_pointer (p=None):
if p is None:
p = _
pool = pymalloc_pool(p)
if not _pymalloc_address_in_range(p, pool):
raise AssertionError('Address was not allocated by pymalloc.')
size = INDEX2SIZE (pool.szidx)
n, offset = divmod ((p - (pool.addr + poolp_size)), size)
front = (n * size) + pool.addr + poolp_size
print 'addr:0x%x front:0x%x pool:0x%x count=%d/%d arenaindex=%d szidx=%d [%d bytes]' % (
p, front, pool.addr, pool.count, NUMBLOCKS (pool.szidx), pool.arenaindex, pool.szidx, size
)
DPP = describe_pymalloc_pointer
def front(p):
if is_pymalloc_pointer(p):
pool = pymalloc_pool(p)
size = INDEX2SIZE (pool.szidx)
n, offset = divmod ((p - (pool.addr + poolp_size)), size)
return (n * size) + pool.addr + poolp_size
else:
index = ptr2index (p)
page_dir = get_sym ('page_dir')
page_entry = page_dir + (4 * index)
maybe_magic = read_long (page_entry)
if maybe_magic > MALLOC_MAGIC:
next, page, size, shift, free, total = read_struct (maybe_magic, '=llHHHH')
# how many ints in the bitmap? (no I don't understand this calculation)
n_ints = ((malloc_pagesize >> shift)+31) / 32
ints = read_struct (maybe_magic + sizeof_pginfo, '=' + ('l' * n_ints))
bits = print_bits (ints)[:total]
which = (p & malloc_pagemask) / size
return page + (which * size)
elif maybe_magic == MALLOC_FOLLOW:
return front(p-malloc_pagesize)
elif maybe_magic == MALLOC_FIRST:
return (p >> malloc_pageshift) << malloc_pageshift
elif maybe_magic == MALLOC_NOT_MINE:
raise ValueError('Address not allocated by malloc.')
elif maybe_magic == MALLOC_FREE:
raise ValueError('Page freed.')
else:
raise ValueError('Unknown magic %r.' % (maybe_magic,))
def find_recent_page_chunks (search_size, n=5, offset=10):
# search the most recently-allocated pages for chunk size <size>
# and return their addresses
first_page_dir = get_sym ('page_dir')
ninfo = get_sym ('malloc_ninfo')
result = []
for i in range (ninfo-(1+offset), 1, -1):
page_dir = first_page_dir + (4 * i)
maybe_magic = read_long (page_dir)
if maybe_magic > MALLOC_MAGIC:
next, page, size, shift, free, total = read_struct (maybe_magic, '=llHHHH')
if size == search_size:
result.append ((maybe_magic, next, page, size, shift, free, total))
n -= 1
if not n:
return result
def explore_page (address, size):
for i in range (malloc_pagesize / size):
try:
print make_object (address + (size * i))
except:
print repr(read (address + (size * i), size))
def dump_free_list():
free_list = get_sym ('free_list')
sum = 0L
while free_list:
free_list, prev, page, end, size = read_struct (free_list, '=lllll')
#sys.stderr.write ('[%x %d]' % (page, size))
s = str(size/(4096 * 8))
if len(s) == 1:
sys.stderr.write (s)
else:
sys.stderr.write ('[%s]' % s)
sum += size
sys.stderr.write ('\ntotal free: %r\n' % sum)
def walk_pages (file=sys.stderr):
page_dir = get_sym ('page_dir')
ninfo = get_sym ('malloc_ninfo')
nfree = 0
run_start = 0
run_n = 0
ninfo_i = 0
import array
page_dir = array.array ('l', read (page_dir, 4 * ninfo))
# space in chunks up to ninfo
chunks = [None] * ninfo
chunk_i = 0
# first pass, read page data
while ninfo_i < ninfo:
maybe_magic = page_dir[ninfo_i]
if maybe_magic < MALLOC_MAGIC:
if maybe_magic == MALLOC_FREE:
file.write ('0')
# this page is free
elif maybe_magic == MALLOC_FIRST:
file.write ('[')
# first of a multi-page run
run_start = ninfo_i
run_n = 1
while ninfo_i < ninfo:
ninfo_i += 1
maybe_magic = page_dir[ninfo_i]
if maybe_magic==MALLOC_FOLLOW:
#file.write ('1')
run_n += 1
else:
file.write ('%d]' % run_n)
break
continue
elif maybe_magic == MALLOC_FOLLOW:
# follow-on in a multi-page run
raise 'Floating follow?'
elif maybe_magic == MALLOC_NOT_MINE:
file.write ('?')
else:
raise "Huh?"
else:
file.write ('-')
ninfo_i += 1
BITS = [ 1L << i for i in range (32) ]
def walk_heap (callback):
"""Walk the FreeBSD malloc heap, and call `callback` for every allocated
piece of memory.
`callback` should be a function that takes 3 arguments. The first argument
is the type of allocation ('page' or 'chunk'). The second is the size of
the allocation (not the size the user requested, the aligned size in
malloc). The third is the address of the allocation.
"""
page_dir = get_sym ('page_dir')
ninfo = get_sym ('malloc_ninfo')
origo = get_sym ('malloc_origo')
nfree = 0
run_start = 0
run_n = 0
ninfo_i = 0
import array
page_dir = array.array ('L', read (page_dir, 4 * ninfo))
# space in chunks up to ninfo
chunks = [None] * ninfo
chunk_i = 0
# first pass, read page data
while ninfo_i < ninfo:
maybe_magic = page_dir[ninfo_i]
if maybe_magic < MALLOC_MAGIC:
if maybe_magic == MALLOC_FREE:
# this page is free
nfree += 1
elif maybe_magic == MALLOC_FIRST:
# first of a multi-page run
run_start = ninfo_i
run_n = 1
while ninfo_i < ninfo:
ninfo_i += 1
maybe_magic = page_dir[ninfo_i]
if maybe_magic==MALLOC_FOLLOW:
run_n += 1
else:
size = run_n << malloc_pageshift
address = (run_start+origo) << malloc_pageshift
callback ('page', size, address)
break
continue
elif maybe_magic == MALLOC_FOLLOW:
# follow-on in a multi-page run
raise 'Floating follow?'
elif maybe_magic == MALLOC_NOT_MINE:
pass
else:
raise "Huh?"
else:
chunks[chunk_i] = maybe_magic
chunk_i += 1
if ninfo_i % (ninfo/10) == 0:
sys.stderr.write ('.')
ninfo_i += 1
# second pass, sort and read chunks
chunks = chunks[:chunk_i]
chunks.sort()
n_chunks = len(chunks)
sys.stderr.write ('\n')
for j in xrange (n_chunks):
chunk = chunks[j]
next, page, size, shift, free, total = read_struct (chunk, '=LLHHHH')
n_ints = ((malloc_pagesize >> shift)+31) / 32
ints = read_struct (chunk + sizeof_pginfo, '=' + ('l' * n_ints))
#callback ('chunk-page', (page, size, shift, total, print_bits (ints)[:total]))
i = 0
for n in ints:
for bit in BITS:
# n & 1 == 'free'
if not (n & bit):
callback ('chunk', size, page + (size * i))
i += 1
if i >= total:
break
if j % (n_chunks/10) == 0:
sys.stderr.write ('*')
sys.stderr.write ('\n')
# sample callback that prints the address of all page allocations
def big_cb (kind, size, addr):