OSDN Git Service

aslr_test: Fix typo.
[android-x86/system-extras.git] / procrank / procrank.c
1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <dirent.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <inttypes.h>
21 #include <stdbool.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/types.h>
25 #include <unistd.h>
26
27 #include <pagemap/pagemap.h>
28
29 struct proc_info {
30     pid_t pid;
31     pm_memusage_t usage;
32     uint64_t wss;
33 };
34
35 static void usage(char *myname);
36 static int getprocname(pid_t pid, char *buf, int len);
37 static int numcmp(uint64_t a, uint64_t b);
38
39 #define declare_sort(field) \
40     static int sort_by_ ## field (const void *a, const void *b)
41
42 declare_sort(vss);
43 declare_sort(rss);
44 declare_sort(pss);
45 declare_sort(uss);
46 declare_sort(swap);
47
48 int (*compfn)(const void *a, const void *b);
49 static int order;
50
51 enum {
52     MEMINFO_TOTAL,
53     MEMINFO_FREE,
54     MEMINFO_BUFFERS,
55     MEMINFO_CACHED,
56     MEMINFO_SHMEM,
57     MEMINFO_SLAB,
58     MEMINFO_SWAP_TOTAL,
59     MEMINFO_SWAP_FREE,
60     MEMINFO_ZRAM_TOTAL,
61     MEMINFO_MAPPED,
62     MEMINFO_VMALLOC_USED,
63     MEMINFO_PAGE_TABLES,
64     MEMINFO_KERNEL_STACK,
65     MEMINFO_COUNT
66 };
67
68 void get_mem_info(uint64_t mem[]) {
69     char buffer[1024];
70     unsigned int numFound = 0;
71
72     int fd = open("/proc/meminfo", O_RDONLY);
73
74     if (fd < 0) {
75         printf("Unable to open /proc/meminfo: %s\n", strerror(errno));
76         return;
77     }
78
79     const int len = read(fd, buffer, sizeof(buffer)-1);
80     close(fd);
81
82     if (len < 0) {
83         printf("Empty /proc/meminfo");
84         return;
85     }
86     buffer[len] = 0;
87
88     static const char* const tags[] = {
89             "MemTotal:",
90             "MemFree:",
91             "Buffers:",
92             "Cached:",
93             "Shmem:",
94             "Slab:",
95             "SwapTotal:",
96             "SwapFree:",
97             "ZRam:",            /* not read from meminfo but from /sys/block/zram0 */
98             "Mapped:",
99             "VmallocUsed:",
100             "PageTables:",
101             "KernelStack:",
102             NULL
103     };
104     static const int tagsLen[] = {
105             9,
106             8,
107             8,
108             7,
109             6,
110             5,
111             10,
112             9,
113             5,
114             7,
115             12,
116             11,
117             12,
118             0
119     };
120
121     char* p = buffer;
122     while (*p && (numFound < (sizeof(tagsLen) / sizeof(tagsLen[0])))) {
123         int i = 0;
124         while (tags[i]) {
125             if (strncmp(p, tags[i], tagsLen[i]) == 0) {
126                 p += tagsLen[i];
127                 while (*p == ' ') p++;
128                 char* num = p;
129                 while (*p >= '0' && *p <= '9') p++;
130                 if (*p != 0) {
131                     *p = 0;
132                     p++;
133                 }
134                 mem[i] = atoll(num);
135                 numFound++;
136                 break;
137             }
138             i++;
139         }
140         while (*p && *p != '\n') {
141             p++;
142         }
143         if (*p) p++;
144     }
145 }
146
147 static uint64_t get_zram_mem_used() {
148 #define ZRAM_SYSFS "/sys/block/zram0/"
149     FILE *f = fopen(ZRAM_SYSFS "mm_stat", "r");
150     if (f) {
151         uint64_t mem_used_total = 0;
152
153         int matched = fscanf(f, "%*d %*d %" SCNu64 " %*d %*d %*d %*d", &mem_used_total);
154         if (matched != 1)
155             fprintf(stderr, "warning: failed to parse " ZRAM_SYSFS "mm_stat\n");
156
157         fclose(f);
158         return mem_used_total;
159     }
160
161     f = fopen(ZRAM_SYSFS "mem_used_total", "r");
162     if (f) {
163         uint64_t mem_used_total = 0;
164
165         int matched = fscanf(f, "%" SCNu64, &mem_used_total);
166         if (matched != 1)
167             fprintf(stderr, "warning: failed to parse " ZRAM_SYSFS "mem_used_total\n");
168
169         fclose(f);
170         return mem_used_total;
171     }
172
173     return 0;
174 }
175
176 int main(int argc, char *argv[]) {
177     pm_kernel_t *ker;
178     pm_process_t *proc;
179     pid_t *pids;
180     struct proc_info **procs;
181     size_t num_procs;
182     uint64_t total_pss;
183     uint64_t total_uss;
184     uint64_t total_swap;
185     uint64_t total_pswap;
186     uint64_t total_uswap;
187     uint64_t total_zswap;
188     char cmdline[256]; // this must be within the range of int
189     int error;
190     bool has_swap = false, has_zram = false;
191     uint64_t required_flags = 0;
192     uint64_t flags_mask = 0;
193
194     #define WS_OFF   0
195     #define WS_ONLY  1
196     #define WS_RESET 2
197     int ws;
198
199     int arg;
200     size_t i, j;
201
202     uint64_t mem[MEMINFO_COUNT] = { };
203     pm_proportional_swap_t *p_swap;
204     float zram_cr = 0.0;
205
206     signal(SIGPIPE, SIG_IGN);
207     compfn = &sort_by_pss;
208     order = -1;
209     ws = WS_OFF;
210
211     for (arg = 1; arg < argc; arg++) {
212         if (!strcmp(argv[arg], "-v")) { compfn = &sort_by_vss; continue; }
213         if (!strcmp(argv[arg], "-r")) { compfn = &sort_by_rss; continue; }
214         if (!strcmp(argv[arg], "-p")) { compfn = &sort_by_pss; continue; }
215         if (!strcmp(argv[arg], "-u")) { compfn = &sort_by_uss; continue; }
216         if (!strcmp(argv[arg], "-s")) { compfn = &sort_by_swap; continue; }
217         if (!strcmp(argv[arg], "-c")) { required_flags = 0; flags_mask = PM_PAGE_SWAPBACKED; continue; }
218         if (!strcmp(argv[arg], "-C")) { required_flags = flags_mask = PM_PAGE_SWAPBACKED; continue; }
219         if (!strcmp(argv[arg], "-k")) { required_flags = flags_mask = PM_PAGE_KSM; continue; }
220         if (!strcmp(argv[arg], "-w")) { ws = WS_ONLY; continue; }
221         if (!strcmp(argv[arg], "-W")) { ws = WS_RESET; continue; }
222         if (!strcmp(argv[arg], "-R")) { order *= -1; continue; }
223         if (!strcmp(argv[arg], "-h")) { usage(argv[0]); exit(0); }
224         fprintf(stderr, "Invalid argument \"%s\".\n", argv[arg]);
225         usage(argv[0]);
226         exit(EXIT_FAILURE);
227     }
228
229     get_mem_info(mem);
230     p_swap = pm_memusage_pswap_create(mem[MEMINFO_SWAP_TOTAL] * 1024);
231
232     error = pm_kernel_create(&ker);
233     if (error) {
234         fprintf(stderr, "Error creating kernel interface -- "
235                         "does this kernel have pagemap?\n");
236         exit(EXIT_FAILURE);
237     }
238
239     error = pm_kernel_pids(ker, &pids, &num_procs);
240     if (error) {
241         fprintf(stderr, "Error listing processes.\n");
242         exit(EXIT_FAILURE);
243     }
244
245     procs = calloc(num_procs, sizeof(struct proc_info*));
246     if (procs == NULL) {
247         fprintf(stderr, "calloc: %s", strerror(errno));
248         exit(EXIT_FAILURE);
249     }
250
251     for (i = 0; i < num_procs; i++) {
252         procs[i] = malloc(sizeof(struct proc_info));
253         if (procs[i] == NULL) {
254             fprintf(stderr, "malloc: %s\n", strerror(errno));
255             exit(EXIT_FAILURE);
256         }
257         procs[i]->pid = pids[i];
258         pm_memusage_zero(&procs[i]->usage);
259         pm_memusage_pswap_init_handle(&procs[i]->usage, p_swap);
260         error = pm_process_create(ker, pids[i], &proc);
261         if (error) {
262             fprintf(stderr, "warning: could not create process interface for %d\n", pids[i]);
263             continue;
264         }
265
266         switch (ws) {
267         case WS_OFF:
268             error = pm_process_usage_flags(proc, &procs[i]->usage, flags_mask,
269                                            required_flags);
270             break;
271         case WS_ONLY:
272             error = pm_process_workingset(proc, &procs[i]->usage, 0);
273             break;
274         case WS_RESET:
275             error = pm_process_workingset(proc, NULL, 1);
276             break;
277         }
278
279         if (error) {
280             fprintf(stderr, "warning: could not read usage for %d\n", pids[i]);
281         }
282
283         if (ws != WS_RESET && procs[i]->usage.swap) {
284             has_swap = true;
285         }
286
287         pm_process_destroy(proc);
288     }
289
290     free(pids);
291
292     if (ws == WS_RESET) exit(0);
293
294     j = 0;
295     for (i = 0; i < num_procs; i++) {
296         if (procs[i]->usage.vss) {
297             procs[j++] = procs[i];
298         } else {
299             free(procs[i]);
300         }
301     }
302     num_procs = j;
303
304     qsort(procs, num_procs, sizeof(procs[0]), compfn);
305
306     if (has_swap) {
307         uint64_t zram_mem_used = get_zram_mem_used();
308         if (zram_mem_used) {
309             mem[MEMINFO_ZRAM_TOTAL] = zram_mem_used/1024;
310             zram_cr = (float) mem[MEMINFO_ZRAM_TOTAL] /
311                     (mem[MEMINFO_SWAP_TOTAL] - mem[MEMINFO_SWAP_FREE]);
312             has_zram = true;
313         }
314     }
315
316     printf("%5s  ", "PID");
317     if (ws) {
318         printf("%7s  %7s  %7s  ", "WRss", "WPss", "WUss");
319         if (has_swap) {
320             printf("%7s  %7s  %7s  ", "WSwap", "WPSwap", "WUSwap");
321             if (has_zram) {
322                 printf("%7s  ", "WZSwap");
323             }
324         }
325     } else {
326         printf("%8s  %7s  %7s  %7s  ", "Vss", "Rss", "Pss", "Uss");
327         if (has_swap) {
328             printf("%7s  %7s  %7s  ", "Swap", "PSwap", "USwap");
329             if (has_zram) {
330                 printf("%7s  ", "ZSwap");
331             }
332         }
333     }
334
335     printf("%s\n", "cmdline");
336
337     total_pss = 0;
338     total_uss = 0;
339     total_swap = 0;
340     total_pswap = 0;
341     total_uswap = 0;
342     total_zswap = 0;
343
344     for (i = 0; i < num_procs; i++) {
345         if (getprocname(procs[i]->pid, cmdline, (int)sizeof(cmdline)) < 0) {
346             /*
347              * Something is probably seriously wrong if writing to the stack
348              * failed.
349              */
350             free(procs[i]);
351             continue;
352         }
353
354         total_pss += procs[i]->usage.pss;
355         total_uss += procs[i]->usage.uss;
356         total_swap += procs[i]->usage.swap;
357
358         printf("%5d  ", procs[i]->pid);
359
360         if (ws) {
361             printf("%6zuK  %6zuK  %6zuK  ",
362                 procs[i]->usage.rss / 1024,
363                 procs[i]->usage.pss / 1024,
364                 procs[i]->usage.uss / 1024
365             );
366         } else {
367             printf("%7zuK  %6zuK  %6zuK  %6zuK  ",
368                 procs[i]->usage.vss / 1024,
369                 procs[i]->usage.rss / 1024,
370                 procs[i]->usage.pss / 1024,
371                 procs[i]->usage.uss / 1024
372             );
373         }
374
375         if (has_swap) {
376             pm_swapusage_t su;
377
378             pm_memusage_pswap_get_usage(&procs[i]->usage, &su);
379             printf("%6zuK  ", procs[i]->usage.swap / 1024);
380             printf("%6zuK  ", su.proportional / 1024);
381             printf("%6zuK  ", su.unique / 1024);
382             total_pswap += su.proportional;
383             total_uswap += su.unique;
384             pm_memusage_pswap_free(&procs[i]->usage);
385             if (has_zram) {
386                 size_t zpswap = su.proportional * zram_cr;
387                 printf("%6zuK  ", zpswap / 1024);
388                 total_zswap += zpswap;
389             }
390         }
391
392         printf("%s\n", cmdline);
393
394         free(procs[i]);
395     }
396
397     free(procs);
398     pm_memusage_pswap_destroy(p_swap);
399
400     /* Print the separator line */
401     printf("%5s  ", "");
402
403     if (ws) {
404         printf("%7s  %7s  %7s  ", "", "------", "------");
405     } else {
406         printf("%8s  %7s  %7s  %7s  ", "", "", "------", "------");
407     }
408
409     if (has_swap) {
410         printf("%7s  %7s  %7s  ", "------", "------", "------");
411         if (has_zram) {
412             printf("%7s  ", "------");
413         }
414     }
415
416     printf("%s\n", "------");
417
418     /* Print the total line */
419     printf("%5s  ", "");
420     if (ws) {
421         printf("%7s  %6" PRIu64 "K  %6" PRIu64 "K  ",
422             "", total_pss / 1024, total_uss / 1024);
423     } else {
424         printf("%8s  %7s  %6" PRIu64 "K  %6" PRIu64 "K  ",
425             "", "", total_pss / 1024, total_uss / 1024);
426     }
427
428     if (has_swap) {
429         printf("%6" PRIu64 "K  ", total_swap / 1024);
430         printf("%6" PRIu64 "K  ", total_pswap / 1024);
431         printf("%6" PRIu64 "K  ", total_uswap / 1024);
432         if (has_zram) {
433             printf("%6" PRIu64 "K  ", total_zswap / 1024);
434         }
435     }
436
437     printf("TOTAL\n");
438
439     printf("\n");
440
441     if (has_swap) {
442         printf("ZRAM: %" PRIu64 "K physical used for %" PRIu64 "K in swap "
443                 "(%" PRIu64 "K total swap)\n",
444                 mem[MEMINFO_ZRAM_TOTAL], (mem[MEMINFO_SWAP_TOTAL] - mem[MEMINFO_SWAP_FREE]),
445                 mem[MEMINFO_SWAP_TOTAL]);
446     }
447     printf(" RAM: %" PRIu64 "K total, %" PRIu64 "K free, %" PRIu64 "K buffers, "
448             "%" PRIu64 "K cached, %" PRIu64 "K shmem, %" PRIu64 "K slab\n",
449             mem[MEMINFO_TOTAL], mem[MEMINFO_FREE], mem[MEMINFO_BUFFERS],
450             mem[MEMINFO_CACHED], mem[MEMINFO_SHMEM], mem[MEMINFO_SLAB]);
451
452     return 0;
453 }
454
455 static void usage(char *myname) {
456     fprintf(stderr, "Usage: %s [ -W ] [ -v | -r | -p | -u | -s | -h ]\n"
457                     "    -v  Sort by VSS.\n"
458                     "    -r  Sort by RSS.\n"
459                     "    -p  Sort by PSS.\n"
460                     "    -u  Sort by USS.\n"
461                     "    -s  Sort by swap.\n"
462                     "        (Default sort order is PSS.)\n"
463                     "    -R  Reverse sort order (default is descending).\n"
464                     "    -c  Only show cached (storage backed) pages\n"
465                     "    -C  Only show non-cached (ram/swap backed) pages\n"
466                     "    -k  Only show pages collapsed by KSM\n"
467                     "    -w  Display statistics for working set only.\n"
468                     "    -W  Reset working set of all processes.\n"
469                     "    -h  Display this help screen.\n",
470     myname);
471 }
472
473 /*
474  * Get the process name for a given PID. Inserts the process name into buffer
475  * buf of length len. The size of the buffer must be greater than zero to get
476  * any useful output.
477  *
478  * Note that fgets(3) only declares length as an int, so our buffer size is
479  * also declared as an int.
480  *
481  * Returns 0 on success, a positive value on partial success, and -1 on
482  * failure. Other interesting values:
483  *   1 on failure to create string to examine proc cmdline entry
484  *   2 on failure to open proc cmdline entry
485  *   3 on failure to read proc cmdline entry
486  */
487 static int getprocname(pid_t pid, char *buf, int len) {
488     char *filename;
489     FILE *f;
490     int rc = 0;
491     static const char* unknown_cmdline = "<unknown>";
492
493     if (len <= 0) {
494         return -1;
495     }
496
497     if (asprintf(&filename, "/proc/%d/cmdline", pid) < 0) {
498         rc = 1;
499         goto exit;
500     }
501
502     f = fopen(filename, "r");
503     if (f == NULL) {
504         rc = 2;
505         goto releasefilename;
506     }
507
508     if (fgets(buf, len, f) == NULL) {
509         rc = 3;
510         goto closefile;
511     }
512
513 closefile:
514     (void) fclose(f);
515 releasefilename:
516     free(filename);
517 exit:
518     if (rc != 0) {
519         /*
520          * The process went away before we could read its process name. Try
521          * to give the user "<unknown>" here, but otherwise they get to look
522          * at a blank.
523          */
524         if (strlcpy(buf, unknown_cmdline, (size_t)len) >= (size_t)len) {
525             rc = 4;
526         }
527     }
528
529     return rc;
530 }
531
532 static int numcmp(uint64_t a, uint64_t b) {
533     if (a < b) return -1;
534     if (a > b) return 1;
535     return 0;
536 }
537
538 #define create_sort(field, compfn) \
539     static int sort_by_ ## field (const void *a, const void *b) { \
540         return order * compfn( \
541             (*((struct proc_info**)a))->usage.field, \
542             (*((struct proc_info**)b))->usage.field \
543         ); \
544     }
545
546 create_sort(vss, numcmp)
547 create_sort(rss, numcmp)
548 create_sort(pss, numcmp)
549 create_sort(uss, numcmp)
550 create_sort(swap, numcmp)