• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2008, The Android Open Source Project
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *  * Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  *  * Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in
12  *    the documentation and/or other materials provided with the
13  *    distribution.
14  *  * Neither the name of Google, Inc. nor the names of its contributors
15  *    may be used to endorse or promote products derived from this
16  *    software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
21  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
25  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
28  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <ctype.h>
33 #include <dirent.h>
34 #include <grp.h>
35 #include <pwd.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <sys/types.h>
40 #include <unistd.h>
41 
42 #include <cutils/sched_policy.h>
43 
44 struct cpu_info {
45     long unsigned utime, ntime, stime, itime;
46     long unsigned iowtime, irqtime, sirqtime;
47 };
48 
49 #define PROC_NAME_LEN 64
50 #define THREAD_NAME_LEN 32
51 #define POLICY_NAME_LEN 4
52 
53 struct proc_info {
54     struct proc_info *next;
55     pid_t pid;
56     pid_t tid;
57     uid_t uid;
58     gid_t gid;
59     char name[PROC_NAME_LEN];
60     char tname[THREAD_NAME_LEN];
61     char state;
62     long unsigned utime;
63     long unsigned stime;
64     long unsigned delta_utime;
65     long unsigned delta_stime;
66     long unsigned delta_time;
67     long vss;
68     long rss;
69     int prs;
70     int num_threads;
71     char policy[POLICY_NAME_LEN];
72 };
73 
74 struct proc_list {
75     struct proc_info **array;
76     int size;
77 };
78 
79 #define die(...) { fprintf(stderr, __VA_ARGS__); exit(EXIT_FAILURE); }
80 
81 #define INIT_PROCS 50
82 #define THREAD_MULT 8
83 static struct proc_info **old_procs, **new_procs;
84 static int num_old_procs, num_new_procs;
85 static struct proc_info *free_procs;
86 static int num_used_procs, num_free_procs;
87 
88 static int max_procs, delay, iterations, threads;
89 
90 static struct cpu_info old_cpu, new_cpu;
91 
92 static struct proc_info *alloc_proc(void);
93 static void free_proc(struct proc_info *proc);
94 static void read_procs(void);
95 static int read_stat(char *filename, struct proc_info *proc);
96 static void read_policy(int pid, struct proc_info *proc);
97 static void add_proc(int proc_num, struct proc_info *proc);
98 static int read_cmdline(char *filename, struct proc_info *proc);
99 static int read_status(char *filename, struct proc_info *proc);
100 static void print_procs(void);
101 static struct proc_info *find_old_proc(pid_t pid, pid_t tid);
102 static void free_old_procs(void);
103 static int (*proc_cmp)(const void *a, const void *b);
104 static int proc_cpu_cmp(const void *a, const void *b);
105 static int proc_vss_cmp(const void *a, const void *b);
106 static int proc_rss_cmp(const void *a, const void *b);
107 static int proc_thr_cmp(const void *a, const void *b);
108 static int numcmp(long long a, long long b);
109 static void usage(char *cmd);
110 
top_main(int argc,char * argv[])111 int top_main(int argc, char *argv[]) {
112     int i;
113 
114     num_used_procs = num_free_procs = 0;
115 
116     max_procs = 0;
117     delay = 3;
118     iterations = -1;
119     proc_cmp = &proc_cpu_cmp;
120     for (i = 1; i < argc; i++) {
121         if (!strcmp(argv[i], "-m")) {
122             if (i + 1 >= argc) {
123                 fprintf(stderr, "Option -m expects an argument.\n");
124                 usage(argv[0]);
125                 exit(EXIT_FAILURE);
126             }
127             max_procs = atoi(argv[++i]);
128             continue;
129         }
130         if (!strcmp(argv[i], "-n")) {
131             if (i + 1 >= argc) {
132                 fprintf(stderr, "Option -n expects an argument.\n");
133                 usage(argv[0]);
134                 exit(EXIT_FAILURE);
135             }
136             iterations = atoi(argv[++i]);
137             continue;
138         }
139         if (!strcmp(argv[i], "-d")) {
140             if (i + 1 >= argc) {
141                 fprintf(stderr, "Option -d expects an argument.\n");
142                 usage(argv[0]);
143                 exit(EXIT_FAILURE);
144             }
145             delay = atoi(argv[++i]);
146             continue;
147         }
148         if (!strcmp(argv[i], "-s")) {
149             if (i + 1 >= argc) {
150                 fprintf(stderr, "Option -s expects an argument.\n");
151                 usage(argv[0]);
152                 exit(EXIT_FAILURE);
153             }
154             ++i;
155             if (!strcmp(argv[i], "cpu")) { proc_cmp = &proc_cpu_cmp; continue; }
156             if (!strcmp(argv[i], "vss")) { proc_cmp = &proc_vss_cmp; continue; }
157             if (!strcmp(argv[i], "rss")) { proc_cmp = &proc_rss_cmp; continue; }
158             if (!strcmp(argv[i], "thr")) { proc_cmp = &proc_thr_cmp; continue; }
159             fprintf(stderr, "Invalid argument \"%s\" for option -s.\n", argv[i]);
160             exit(EXIT_FAILURE);
161         }
162         if (!strcmp(argv[i], "-t")) { threads = 1; continue; }
163         if (!strcmp(argv[i], "-h")) {
164             usage(argv[0]);
165             exit(EXIT_SUCCESS);
166         }
167         fprintf(stderr, "Invalid argument \"%s\".\n", argv[i]);
168         usage(argv[0]);
169         exit(EXIT_FAILURE);
170     }
171 
172     if (threads && proc_cmp == &proc_thr_cmp) {
173         fprintf(stderr, "Sorting by threads per thread makes no sense!\n");
174         exit(EXIT_FAILURE);
175     }
176 
177     free_procs = NULL;
178 
179     num_new_procs = num_old_procs = 0;
180     new_procs = old_procs = NULL;
181 
182     read_procs();
183     while ((iterations == -1) || (iterations-- > 0)) {
184         old_procs = new_procs;
185         num_old_procs = num_new_procs;
186         memcpy(&old_cpu, &new_cpu, sizeof(old_cpu));
187         sleep(delay);
188         read_procs();
189         print_procs();
190         free_old_procs();
191     }
192 
193     return 0;
194 }
195 
alloc_proc(void)196 static struct proc_info *alloc_proc(void) {
197     struct proc_info *proc;
198 
199     if (free_procs) {
200         proc = free_procs;
201         free_procs = free_procs->next;
202         num_free_procs--;
203     } else {
204         proc = malloc(sizeof(*proc));
205         if (!proc) die("Could not allocate struct process_info.\n");
206     }
207 
208     num_used_procs++;
209 
210     return proc;
211 }
212 
free_proc(struct proc_info * proc)213 static void free_proc(struct proc_info *proc) {
214     proc->next = free_procs;
215     free_procs = proc;
216 
217     num_used_procs--;
218     num_free_procs++;
219 }
220 
221 #define MAX_LINE 256
222 
read_procs(void)223 static void read_procs(void) {
224     DIR *proc_dir, *task_dir;
225     struct dirent *pid_dir, *tid_dir;
226     char filename[64];
227     FILE *file;
228     int proc_num;
229     struct proc_info *proc;
230     pid_t pid, tid;
231 
232     int i;
233 
234     proc_dir = opendir("/proc");
235     if (!proc_dir) die("Could not open /proc.\n");
236 
237     new_procs = calloc(INIT_PROCS * (threads ? THREAD_MULT : 1), sizeof(struct proc_info *));
238     num_new_procs = INIT_PROCS * (threads ? THREAD_MULT : 1);
239 
240     file = fopen("/proc/stat", "r");
241     if (!file) die("Could not open /proc/stat.\n");
242     fscanf(file, "cpu  %lu %lu %lu %lu %lu %lu %lu", &new_cpu.utime, &new_cpu.ntime, &new_cpu.stime,
243             &new_cpu.itime, &new_cpu.iowtime, &new_cpu.irqtime, &new_cpu.sirqtime);
244     fclose(file);
245 
246     proc_num = 0;
247     while ((pid_dir = readdir(proc_dir))) {
248         if (!isdigit(pid_dir->d_name[0]))
249             continue;
250 
251         pid = atoi(pid_dir->d_name);
252 
253         struct proc_info cur_proc;
254 
255         if (!threads) {
256             proc = alloc_proc();
257 
258             proc->pid = proc->tid = pid;
259 
260             sprintf(filename, "/proc/%d/stat", pid);
261             read_stat(filename, proc);
262 
263             sprintf(filename, "/proc/%d/cmdline", pid);
264             read_cmdline(filename, proc);
265 
266             sprintf(filename, "/proc/%d/status", pid);
267             read_status(filename, proc);
268 
269             read_policy(pid, proc);
270 
271             proc->num_threads = 0;
272         } else {
273             sprintf(filename, "/proc/%d/cmdline", pid);
274             read_cmdline(filename, &cur_proc);
275 
276             sprintf(filename, "/proc/%d/status", pid);
277             read_status(filename, &cur_proc);
278 
279             proc = NULL;
280         }
281 
282         sprintf(filename, "/proc/%d/task", pid);
283         task_dir = opendir(filename);
284         if (!task_dir) continue;
285 
286         while ((tid_dir = readdir(task_dir))) {
287             if (!isdigit(tid_dir->d_name[0]))
288                 continue;
289 
290             if (threads) {
291                 tid = atoi(tid_dir->d_name);
292 
293                 proc = alloc_proc();
294 
295                 proc->pid = pid; proc->tid = tid;
296 
297                 sprintf(filename, "/proc/%d/task/%d/stat", pid, tid);
298                 read_stat(filename, proc);
299 
300                 read_policy(tid, proc);
301 
302                 strcpy(proc->name, cur_proc.name);
303                 proc->uid = cur_proc.uid;
304                 proc->gid = cur_proc.gid;
305 
306                 add_proc(proc_num++, proc);
307             } else {
308                 proc->num_threads++;
309             }
310         }
311 
312         closedir(task_dir);
313 
314         if (!threads)
315             add_proc(proc_num++, proc);
316     }
317 
318     for (i = proc_num; i < num_new_procs; i++)
319         new_procs[i] = NULL;
320 
321     closedir(proc_dir);
322 }
323 
read_stat(char * filename,struct proc_info * proc)324 static int read_stat(char *filename, struct proc_info *proc) {
325     FILE *file;
326     char buf[MAX_LINE], *open_paren, *close_paren;
327     int res, idx;
328 
329     file = fopen(filename, "r");
330     if (!file) return 1;
331     fgets(buf, MAX_LINE, file);
332     fclose(file);
333 
334     /* Split at first '(' and last ')' to get process name. */
335     open_paren = strchr(buf, '(');
336     close_paren = strrchr(buf, ')');
337     if (!open_paren || !close_paren) return 1;
338 
339     *open_paren = *close_paren = '\0';
340     strncpy(proc->tname, open_paren + 1, THREAD_NAME_LEN);
341     proc->tname[THREAD_NAME_LEN-1] = 0;
342 
343     /* Scan rest of string. */
344     sscanf(close_paren + 1, " %c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
345                  "%lu %lu %*d %*d %*d %*d %*d %*d %*d %lu %ld "
346                  "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d",
347                  &proc->state, &proc->utime, &proc->stime, &proc->vss, &proc->rss, &proc->prs);
348 
349     return 0;
350 }
351 
add_proc(int proc_num,struct proc_info * proc)352 static void add_proc(int proc_num, struct proc_info *proc) {
353     int i;
354 
355     if (proc_num >= num_new_procs) {
356         new_procs = realloc(new_procs, 2 * num_new_procs * sizeof(struct proc_info *));
357         if (!new_procs) die("Could not expand procs array.\n");
358         for (i = num_new_procs; i < 2 * num_new_procs; i++)
359             new_procs[i] = NULL;
360         num_new_procs = 2 * num_new_procs;
361     }
362     new_procs[proc_num] = proc;
363 }
364 
read_cmdline(char * filename,struct proc_info * proc)365 static int read_cmdline(char *filename, struct proc_info *proc) {
366     FILE *file;
367     char line[MAX_LINE];
368 
369     line[0] = '\0';
370     file = fopen(filename, "r");
371     if (!file) return 1;
372     fgets(line, MAX_LINE, file);
373     fclose(file);
374     if (strlen(line) > 0) {
375         strncpy(proc->name, line, PROC_NAME_LEN);
376         proc->name[PROC_NAME_LEN-1] = 0;
377     } else
378         proc->name[0] = 0;
379     return 0;
380 }
381 
read_policy(int pid,struct proc_info * proc)382 static void read_policy(int pid, struct proc_info *proc) {
383     SchedPolicy p;
384     if (get_sched_policy(pid, &p) < 0)
385         strlcpy(proc->policy, "unk", POLICY_NAME_LEN);
386     else {
387         strlcpy(proc->policy, get_sched_policy_name(p), POLICY_NAME_LEN);
388         proc->policy[2] = '\0';
389     }
390 }
391 
read_status(char * filename,struct proc_info * proc)392 static int read_status(char *filename, struct proc_info *proc) {
393     FILE *file;
394     char line[MAX_LINE];
395     unsigned int uid, gid;
396 
397     file = fopen(filename, "r");
398     if (!file) return 1;
399     while (fgets(line, MAX_LINE, file)) {
400         sscanf(line, "Uid: %u", &uid);
401         sscanf(line, "Gid: %u", &gid);
402     }
403     fclose(file);
404     proc->uid = uid; proc->gid = gid;
405     return 0;
406 }
407 
print_procs(void)408 static void print_procs(void) {
409     int i;
410     struct proc_info *old_proc, *proc;
411     long unsigned total_delta_time;
412     struct passwd *user;
413     struct group *group;
414     char *user_str, user_buf[20];
415     char *group_str, group_buf[20];
416 
417     for (i = 0; i < num_new_procs; i++) {
418         if (new_procs[i]) {
419             old_proc = find_old_proc(new_procs[i]->pid, new_procs[i]->tid);
420             if (old_proc) {
421                 new_procs[i]->delta_utime = new_procs[i]->utime - old_proc->utime;
422                 new_procs[i]->delta_stime = new_procs[i]->stime - old_proc->stime;
423             } else {
424                 new_procs[i]->delta_utime = 0;
425                 new_procs[i]->delta_stime = 0;
426             }
427             new_procs[i]->delta_time = new_procs[i]->delta_utime + new_procs[i]->delta_stime;
428         }
429     }
430 
431     total_delta_time = (new_cpu.utime + new_cpu.ntime + new_cpu.stime + new_cpu.itime
432                         + new_cpu.iowtime + new_cpu.irqtime + new_cpu.sirqtime)
433                      - (old_cpu.utime + old_cpu.ntime + old_cpu.stime + old_cpu.itime
434                         + old_cpu.iowtime + old_cpu.irqtime + old_cpu.sirqtime);
435 
436     qsort(new_procs, num_new_procs, sizeof(struct proc_info *), proc_cmp);
437 
438     printf("\n\n\n");
439     printf("User %ld%%, System %ld%%, IOW %ld%%, IRQ %ld%%\n",
440             ((new_cpu.utime + new_cpu.ntime) - (old_cpu.utime + old_cpu.ntime)) * 100  / total_delta_time,
441             ((new_cpu.stime ) - (old_cpu.stime)) * 100 / total_delta_time,
442             ((new_cpu.iowtime) - (old_cpu.iowtime)) * 100 / total_delta_time,
443             ((new_cpu.irqtime + new_cpu.sirqtime)
444                     - (old_cpu.irqtime + old_cpu.sirqtime)) * 100 / total_delta_time);
445     printf("User %ld + Nice %ld + Sys %ld + Idle %ld + IOW %ld + IRQ %ld + SIRQ %ld = %ld\n",
446             new_cpu.utime - old_cpu.utime,
447             new_cpu.ntime - old_cpu.ntime,
448             new_cpu.stime - old_cpu.stime,
449             new_cpu.itime - old_cpu.itime,
450             new_cpu.iowtime - old_cpu.iowtime,
451             new_cpu.irqtime - old_cpu.irqtime,
452             new_cpu.sirqtime - old_cpu.sirqtime,
453             total_delta_time);
454     printf("\n");
455     if (!threads)
456         printf("%5s %2s %4s %1s %5s %7s %7s %3s %-8s %s\n", "PID", "PR", "CPU%", "S", "#THR", "VSS", "RSS", "PCY", "UID", "Name");
457     else
458         printf("%5s %5s %2s %4s %1s %7s %7s %3s %-8s %-15s %s\n", "PID", "TID", "PR", "CPU%", "S", "VSS", "RSS", "PCY", "UID", "Thread", "Proc");
459 
460     for (i = 0; i < num_new_procs; i++) {
461         proc = new_procs[i];
462 
463         if (!proc || (max_procs && (i >= max_procs)))
464             break;
465         user  = getpwuid(proc->uid);
466         group = getgrgid(proc->gid);
467         if (user && user->pw_name) {
468             user_str = user->pw_name;
469         } else {
470             snprintf(user_buf, 20, "%d", proc->uid);
471             user_str = user_buf;
472         }
473         if (group && group->gr_name) {
474             group_str = group->gr_name;
475         } else {
476             snprintf(group_buf, 20, "%d", proc->gid);
477             group_str = group_buf;
478         }
479         if (!threads)
480             printf("%5d %2d %3ld%% %c %5d %6ldK %6ldK %3s %-8.8s %s\n", proc->pid, proc->prs, proc->delta_time * 100 / total_delta_time, proc->state, proc->num_threads,
481                 proc->vss / 1024, proc->rss * getpagesize() / 1024, proc->policy, user_str, proc->name[0] != 0 ? proc->name : proc->tname);
482         else
483             printf("%5d %5d %2d %3ld%% %c %6ldK %6ldK %3s %-8.8s %-15s %s\n", proc->pid, proc->tid, proc->prs, proc->delta_time * 100 / total_delta_time, proc->state,
484                 proc->vss / 1024, proc->rss * getpagesize() / 1024, proc->policy, user_str, proc->tname, proc->name);
485     }
486 }
487 
find_old_proc(pid_t pid,pid_t tid)488 static struct proc_info *find_old_proc(pid_t pid, pid_t tid) {
489     int i;
490 
491     for (i = 0; i < num_old_procs; i++)
492         if (old_procs[i] && (old_procs[i]->pid == pid) && (old_procs[i]->tid == tid))
493             return old_procs[i];
494 
495     return NULL;
496 }
497 
free_old_procs(void)498 static void free_old_procs(void) {
499     int i;
500 
501     for (i = 0; i < num_old_procs; i++)
502         if (old_procs[i])
503             free_proc(old_procs[i]);
504 
505     free(old_procs);
506 }
507 
proc_cpu_cmp(const void * a,const void * b)508 static int proc_cpu_cmp(const void *a, const void *b) {
509     struct proc_info *pa, *pb;
510 
511     pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
512 
513     if (!pa && !pb) return 0;
514     if (!pa) return 1;
515     if (!pb) return -1;
516 
517     return -numcmp(pa->delta_time, pb->delta_time);
518 }
519 
proc_vss_cmp(const void * a,const void * b)520 static int proc_vss_cmp(const void *a, const void *b) {
521     struct proc_info *pa, *pb;
522 
523     pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
524 
525     if (!pa && !pb) return 0;
526     if (!pa) return 1;
527     if (!pb) return -1;
528 
529     return -numcmp(pa->vss, pb->vss);
530 }
531 
proc_rss_cmp(const void * a,const void * b)532 static int proc_rss_cmp(const void *a, const void *b) {
533     struct proc_info *pa, *pb;
534 
535     pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
536 
537     if (!pa && !pb) return 0;
538     if (!pa) return 1;
539     if (!pb) return -1;
540 
541     return -numcmp(pa->rss, pb->rss);
542 }
543 
proc_thr_cmp(const void * a,const void * b)544 static int proc_thr_cmp(const void *a, const void *b) {
545     struct proc_info *pa, *pb;
546 
547     pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
548 
549     if (!pa && !pb) return 0;
550     if (!pa) return 1;
551     if (!pb) return -1;
552 
553     return -numcmp(pa->num_threads, pb->num_threads);
554 }
555 
numcmp(long long a,long long b)556 static int numcmp(long long a, long long b) {
557     if (a < b) return -1;
558     if (a > b) return 1;
559     return 0;
560 }
561 
usage(char * cmd)562 static void usage(char *cmd) {
563     fprintf(stderr, "Usage: %s [ -m max_procs ] [ -n iterations ] [ -d delay ] [ -s sort_column ] [ -t ] [ -h ]\n"
564                     "    -m num  Maximum number of processes to display.\n"
565                     "    -n num  Updates to show before exiting.\n"
566                     "    -d num  Seconds to wait between updates.\n"
567                     "    -s col  Column to sort by (cpu,vss,rss,thr).\n"
568                     "    -t      Show threads instead of processes.\n"
569                     "    -h      Display this help screen.\n",
570         cmd);
571 }
572