android中分析内存的工具有DDMS 的 Heap Dump,showmap,procrank等。下面介绍一下showmap。
用法:
showmap [-t] [-v] [-c]
-t = terse (show only items with private pages)
-v = verbose (don’t coalesce maps with the same name)
-a = addresses (show virtual memory map)
-s = swap (show swap pages)
比如systemui的进程:
system 3905 2650 2410116 167656 SyS_epoll_ 0000000000 S com.android.systemui
pid为3905
则 showmap 3905
结果如下面形式:
virtual shared shared private private
size RSS PSS clean dirty clean dirty # object
源代码:
system/extras/showmap/showmap.c
161 static mapinfo *load_maps(int pid, int sort_by_address, int coalesce_by_name)
162 {
163 char fn[128];
164 FILE *fp;
165 char line[1024];
166 mapinfo *head = NULL;
167 mapinfo *current = NULL;
168 int len;
169
170 snprintf(fn, sizeof(fn), "**/proc/%d/smaps**", pid);
171 fp = fopen(fn, "r");
172 if (fp == 0) {
173 fprintf(stderr, "cannot open /proc/%d/smaps: %s\n", pid, strerror(errno));
174 return NULL;
175 }
176
177 while (fgets(line, sizeof(line), fp) != 0) {
178 len = strlen(line);
179 if (line[len - 1] == '\n') {
180 line[--len] = 0;
181 }
182
183 if (current != NULL && !parse_field(current, line)) {
184 continue;
185 }
186
187 mapinfo *next;
188 if (!parse_header(line, current, &next)) {
189 enqueue_map(&head, current, sort_by_address, coalesce_by_name);
190 current = next;
191 continue;
192 }
193
194 fprintf(stderr, "warning: could not parse map info line: %s\n", line);
195 }
196
197 enqueue_map(&head, current, sort_by_address, coalesce_by_name);
198
199 fclose(fp);
200
201 if (!head) {
202 fprintf(stderr, "could not read /proc/%d/smaps\n", pid);
203 return NULL;
204 }
205
206 return head;
207 }
实际上是读取/proc/pid/smap 文件。