-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmap_analyzer.py
More file actions
executable file
·249 lines (207 loc) · 7.3 KB
/
smap_analyzer.py
File metadata and controls
executable file
·249 lines (207 loc) · 7.3 KB
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
#!/bin/env python3
# Based on linux_smap_analyzer.py by https://gist.github.com/LanderlYoung
# https://gist.github.com/LanderlYoung/aedd0e1fe09214545a7f20c40c01776c
from argparse import ArgumentParser
import re
import sys
head_regex = re.compile(r"^[\da-f]{8,}-[\da-f]{8,}")
# This ignores VmFlags: and Name: lines but we don't want those
item_regex = re.compile(r"^(\w+):\s*(\d+) kB")
parser = ArgumentParser(
description='A utility to analyze smaps on Linux. It requires either an '
'smaps file or a pid to analyze. Per default only objects which have a '
'value will be shown. You can list zero objects by specifying the '
'--full argument.'
)
arggroup = parser.add_mutually_exclusive_group()
arggroup.add_argument(
"-f", "--file",
help="input smaps file to parse",
required=False,
type=str,
)
arggroup.add_argument(
"-p", "--pid",
help="pid to analyze (requires root). This is equivalent to --file="
"/proc/<pid>/smaps",
required=False,
type=str,
)
parser.add_argument(
"-t", "--type",
help="column to sort output based on, valid arguments are: pss, rss, size, anon",
required=False,
type=str,
default="pss",
)
parser.add_argument(
"-F", "--full-map",
help="list full smap list, even for objects that have a zero count",
required=False,
default=False,
action="store_true"
)
parser.add_argument(
"-S", "--stack",
help="list all stack maps",
required=False,
default=False,
action="store_true"
)
parser.add_argument(
"-T", "--thread-stack",
help="list all thread stack maps",
required=False,
default=False,
action="store_true"
)
parser.add_argument(
"-s", "--shared-object",
help="list all shared object maps (.so maps)",
required=False,
default=False,
action="store_true"
)
parser.add_argument(
"-d", "--dex",
help="list all DEX maps",
required=False,
default=False,
action="store_true"
)
parser.add_argument(
"-P", "--process-name",
help="process name to specify in the output",
required=False,
default="",
type=str
)
def is_head_line(line):
return head_regex.search(line) != None
def get_object_name(line):
m = re.search(' {3,}', line)
if m != None:
return line[m.end():].rstrip()
return "unknown"
stack_regex = re.compile('\[.*stack.*\]')
so_regex = re.compile('\.so$')
dex_regex = re.compile('\.(dex)|(odex)|(art)$')
thread_stack_regex = re.compile('(\[anon:stack_and_tls:\d+)|(anon:thread signal stack)|(anon:dalvik-thread local mark stack)')
def parse_smap(lines):
smaps = {}
i = 0
while i < len(lines):
name = get_object_name(lines[i])
if not name in smaps:
values = {}
smaps[name] = values
else:
values = smaps[name]
i += 1
while i < len(lines) and not is_head_line(lines[i]):
seg_line = lines[i]
i += 1
if seg_line.startswith('Name:') or seg_line.startswith('VmFlags:'):
continue;
m = item_regex.search(seg_line)
if m != None:
type = m.group(1).lower()
size = int(m.group(2))
if not type in values:
values[type] = size
else:
values[type] = values[type] + size
return smaps
def sort_smaps(smaps, args):
return sorted(smaps.items(), key = lambda x: x[1][args.type.lower()], reverse=True)
NAME = "name"
PSS = "pss"
RSS = "rss"
SIZE = "size"
ANON = "anonymous"
OTHER = "other"
def print_cond(smaps, args, if_cond=lambda name, map: True):
fmt = "{:<11}{:<11}{:<11}{:<11}{:<11}"
print(fmt.format("PSS", "RSS", "Size", "Anon", "Name"))
for (name, map) in smaps:
if if_cond(name, map) and (map[args.type.lower()] > 0 or args.full_map):
print(fmt.format(str(map[PSS]) + " kB", str(map[RSS]) + " kB", str(map[SIZE]) + " kB", str(map[ANON]) + " kB", name))
def count_cond(smaps, type, if_cond=lambda name, map: True):
count = 0
for (name, map) in smaps:
if if_cond(name, map):
count += map[type]
return count
def count_thread_stack(smaps):
count = 0
for (name, map) in smaps:
if thread_stack_regex.search(name):
count += map[ANON]
return count
def print_data(smaps, args):
# order by pss
smaps = sort_smaps(smaps, args)
is_stack = lambda name, map: stack_regex.search(name) != None
all_so_maps_if = lambda name, map: so_regex.search(name) != None
all_dex_maps_if = lambda name, map: dex_regex.search(name) != None
print("Per object data: " + args.process_name)
print("===============================================================================")
print_cond(smaps, args)
if args.stack:
print("\nStack maps:")
print("===============================================================================")
print_cond(smaps, args, is_stack)
if args.shared_object:
print("\nAll SO maps:")
print("===============================================================================")
print_cond(smaps, args, all_so_maps_if)
if args.dex:
print("\nAll DEX maps:")
print("===============================================================================")
print_cond(smaps, args, all_dex_maps_if)
print("")
print("Summary: " + args.process_name)
print("===============================================================================")
fmt = "{:<20} = {:>8} kB"
print(fmt.format("PSS", count_cond(smaps, 'pss')))
print(fmt.format("RSS", count_cond(smaps, 'rss')))
print(fmt.format("Size (VSS)", count_cond(smaps, 'size')))
print(fmt.format("Shared_Clean", count_cond(smaps, 'shared_clean')))
print(fmt.format("Shared_Dirty", count_cond(smaps, 'shared_dirty')))
print(fmt.format("Private_Clean", count_cond(smaps, 'private_clean')))
print(fmt.format("Private_Dirty", count_cond(smaps, 'private_dirty')))
print(fmt.format("Anonymous", count_cond(smaps, 'anonymous')))
print(fmt.format("Swap", count_cond(smaps, 'swap')))
print(fmt.format("Swap PSS", count_cond(smaps, 'swappss')))
print(fmt.format("Stacks PSS", count_cond(smaps, 'pss', is_stack)))
print(fmt.format("Stacks VSS", count_cond(smaps, 'size', is_stack)))
print(fmt.format("Thread Stacks (anon)", count_thread_stack(smaps)))
if args.shared_object:
print(fmt.format("All SO map PSS", count_cond(smaps, 'pss', all_so_maps_if)))
print(fmt.format("All SO map VSS", count_cond(smaps, 'size', all_so_maps_if)))
if args.dex:
print(fmt.format("All DEX map PSS", count_cond(smaps, 'pss', all_dex_maps_if)))
print(fmt.format("All DEX map VSS", count_cond(smaps, 'size', all_dex_maps_if)))
if __name__ == '__main__':
args = parser.parse_args()
if args.type == 'anon':
args.type = 'anonymous'
fd = -1
if args.file:
file = args.file
if args.file == '-':
fd = sys.stdin
elif args.pid:
file = "/proc/"+args.pid+"/smaps"
else:
parser.print_help()
exit(0)
if fd == -1:
try:
fd = open(file)
except OSError as err:
print("{0}".format(err))
exit(0)
lines = [l.strip('\n') for l in fd.readlines()]
smaps = parse_smap(lines)
print_data(smaps, args)