• 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 
exit_top(int signal)111 static void exit_top(int signal) {
112   exit(EXIT_FAILURE);
113 }
114 
top_main(int argc,char * argv[])115 int top_main(int argc, char *argv[]) {
116     num_used_procs = num_free_procs = 0;
117 
118     signal(SIGPIPE, exit_top);
119 
120     max_procs = 0;
121     delay = 3;
122     iterations = -1;
123     proc_cmp = &proc_cpu_cmp;
124     for (int i = 1; i < argc; i++) {
125         if (!strcmp(argv[i], "-m")) {
126             if (i + 1 >= argc) {
127                 fprintf(stderr, "Option -m expects an argument.\n");
128                 usage(argv[0]);
129                 exit(EXIT_FAILURE);
130             }
131             max_procs = atoi(argv[++i]);
132             continue;
133         }
134         if (!strcmp(argv[i], "-n")) {
135             if (i + 1 >= argc) {
136                 fprintf(stderr, "Option -n expects an argument.\n");
137                 usage(argv[0]);
138                 exit(EXIT_FAILURE);
139             }
140             iterations = atoi(argv[++i]);
141             continue;
142         }
143         if (!strcmp(argv[i], "-d")) {
144             if (i + 1 >= argc) {
145                 fprintf(stderr, "Option -d expects an argument.\n");
146                 usage(argv[0]);
147                 exit(EXIT_FAILURE);
148             }
149             delay = atoi(argv[++i]);
150             continue;
151         }
152         if (!strcmp(argv[i], "-s")) {
153             if (i + 1 >= argc) {
154                 fprintf(stderr, "Option -s expects an argument.\n");
155                 usage(argv[0]);
156                 exit(EXIT_FAILURE);
157             }
158             ++i;
159             if (!strcmp(argv[i], "cpu")) { proc_cmp = &proc_cpu_cmp; continue; }
160             if (!strcmp(argv[i], "vss")) { proc_cmp = &proc_vss_cmp; continue; }
161             if (!strcmp(argv[i], "rss")) { proc_cmp = &proc_rss_cmp; continue; }
162             if (!strcmp(argv[i], "thr")) { proc_cmp = &proc_thr_cmp; continue; }
163             fprintf(stderr, "Invalid argument \"%s\" for option -s.\n", argv[i]);
164             exit(EXIT_FAILURE);
165         }
166         if (!strcmp(argv[i], "-t")) { threads = 1; continue; }
167         if (!strcmp(argv[i], "-h")) {
168             usage(argv[0]);
169             exit(EXIT_SUCCESS);
170         }
171         fprintf(stderr, "Invalid argument \"%s\".\n", argv[i]);
172         usage(argv[0]);
173         exit(EXIT_FAILURE);
174     }
175 
176     if (threads && proc_cmp == &proc_thr_cmp) {
177         fprintf(stderr, "Sorting by threads per thread makes no sense!\n");
178         exit(EXIT_FAILURE);
179     }
180 
181     free_procs = NULL;
182 
183     num_new_procs = num_old_procs = 0;
184     new_procs = old_procs = NULL;
185 
186     read_procs();
187     while ((iterations == -1) || (iterations-- > 0)) {
188         old_procs = new_procs;
189         num_old_procs = num_new_procs;
190         memcpy(&old_cpu, &new_cpu, sizeof(old_cpu));
191         sleep(delay);
192         read_procs();
193         print_procs();
194         free_old_procs();
195     }
196 
197     return 0;
198 }
199 
alloc_proc(void)200 static struct proc_info *alloc_proc(void) {
201     struct proc_info *proc;
202 
203     if (free_procs) {
204         proc = free_procs;
205         free_procs = free_procs->next;
206         num_free_procs--;
207     } else {
208         proc = malloc(sizeof(*proc));
209         if (!proc) die("Could not allocate struct process_info.\n");
210     }
211 
212     num_used_procs++;
213 
214     return proc;
215 }
216 
free_proc(struct proc_info * proc)217 static void free_proc(struct proc_info *proc) {
218     proc->next = free_procs;
219     free_procs = proc;
220 
221     num_used_procs--;
222     num_free_procs++;
223 }
224 
225 #define MAX_LINE 256
226 
read_procs(void)227 static void read_procs(void) {
228     DIR *proc_dir, *task_dir;
229     struct dirent *pid_dir, *tid_dir;
230     char filename[64];
231     FILE *file;
232     int proc_num;
233     struct proc_info *proc;
234     pid_t pid, tid;
235 
236     int i;
237 
238     proc_dir = opendir("/proc");
239     if (!proc_dir) die("Could not open /proc.\n");
240 
241     new_procs = calloc(INIT_PROCS * (threads ? THREAD_MULT : 1), sizeof(struct proc_info *));
242     num_new_procs = INIT_PROCS * (threads ? THREAD_MULT : 1);
243 
244     file = fopen("/proc/stat", "r");
245     if (!file) die("Could not open /proc/stat.\n");
246     fscanf(file, "cpu  %lu %lu %lu %lu %lu %lu %lu", &new_cpu.utime, &new_cpu.ntime, &new_cpu.stime,
247             &new_cpu.itime, &new_cpu.iowtime, &new_cpu.irqtime, &new_cpu.sirqtime);
248     fclose(file);
249 
250     proc_num = 0;
251     while ((pid_dir = readdir(proc_dir))) {
252         if (!isdigit(pid_dir->d_name[0]))
253             continue;
254 
255         pid = atoi(pid_dir->d_name);
256 
257         struct proc_info cur_proc;
258 
259         if (!threads) {
260             proc = alloc_proc();
261 
262             proc->pid = proc->tid = pid;
263 
264             sprintf(filename, "/proc/%d/stat", pid);
265             read_stat(filename, proc);
266 
267             sprintf(filename, "/proc/%d/cmdline", pid);
268             read_cmdline(filename, proc);
269 
270             sprintf(filename, "/proc/%d/status", pid);
271             read_status(filename, proc);
272 
273             read_policy(pid, proc);
274 
275             proc->num_threads = 0;
276         } else {
277             sprintf(filename, "/proc/%d/cmdline", pid);
278             read_cmdline(filename, &cur_proc);
279 
280             sprintf(filename, "/proc/%d/status", pid);
281             read_status(filename, &cur_proc);
282 
283             proc = NULL;
284         }
285 
286         sprintf(filename, "/proc/%d/task", pid);
287         task_dir = opendir(filename);
288         if (!task_dir) continue;
289 
290         while ((tid_dir = readdir(task_dir))) {
291             if (!isdigit(tid_dir->d_name[0]))
292                 continue;
293 
294             if (threads) {
295                 tid = atoi(tid_dir->d_name);
296 
297                 proc = alloc_proc();
298 
299                 proc->pid = pid; proc->tid = tid;
300 
301                 sprintf(filename, "/proc/%d/task/%d/stat", pid, tid);
302                 read_stat(filename, proc);
303 
304                 read_policy(tid, proc);
305 
306                 strcpy(proc->name, cur_proc.name);
307                 proc->uid = cur_proc.uid;
308                 proc->gid = cur_proc.gid;
309 
310                 add_proc(proc_num++, proc);
311             } else {
312                 proc->num_threads++;
313             }
314         }
315 
316         closedir(task_dir);
317 
318         if (!threads)
319             add_proc(proc_num++, proc);
320     }
321 
322     for (i = proc_num; i < num_new_procs; i++)
323         new_procs[i] = NULL;
324 
325     closedir(proc_dir);
326 }
327 
read_stat(char * filename,struct proc_info * proc)328 static int read_stat(char *filename, struct proc_info *proc) {
329     FILE *file;
330     char buf[MAX_LINE], *open_paren, *close_paren;
331 
332     file = fopen(filename, "r");
333     if (!file) return 1;
334     fgets(buf, MAX_LINE, file);
335     fclose(file);
336 
337     /* Split at first '(' and last ')' to get process name. */
338     open_paren = strchr(buf, '(');
339     close_paren = strrchr(buf, ')');
340     if (!open_paren || !close_paren) return 1;
341 
342     *open_paren = *close_paren = '\0';
343     strncpy(proc->tname, open_paren + 1, THREAD_NAME_LEN);
344     proc->tname[THREAD_NAME_LEN-1] = 0;
345 
346     /* Scan rest of string. */
347     sscanf(close_paren + 1, " %c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
348                  "%lu %lu %*d %*d %*d %*d %*d %*d %*d %lu %ld "
349                  "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d",
350                  &proc->state, &proc->utime, &proc->stime, &proc->vss, &proc->rss, &proc->prs);
351 
352     return 0;
353 }
354 
add_proc(int proc_num,struct proc_info * proc)355 static void add_proc(int proc_num, struct proc_info *proc) {
356     int i;
357 
358     if (proc_num >= num_new_procs) {
359         new_procs = realloc(new_procs, 2 * num_new_procs * sizeof(struct proc_info *));
360         if (!new_procs) die("Could not expand procs array.\n");
361         for (i = num_new_procs; i < 2 * num_new_procs; i++)
362             new_procs[i] = NULL;
363         num_new_procs = 2 * num_new_procs;
364     }
365     new_procs[proc_num] = proc;
366 }
367 
read_cmdline(char * filename,struct proc_info * proc)368 static int read_cmdline(char *filename, struct proc_info *proc) {
369     FILE *file;
370     char line[MAX_LINE];
371 
372     line[0] = '\0';
373     file = fopen(filename, "r");
374     if (!file) return 1;
375     fgets(line, MAX_LINE, file);
376     fclose(file);
377     if (strlen(line) > 0) {
378         strncpy(proc->name, line, PROC_NAME_LEN);
379         proc->name[PROC_NAME_LEN-1] = 0;
380     } else
381         proc->name[0] = 0;
382     return 0;
383 }
384 
read_policy(int pid,struct proc_info * proc)385 static void read_policy(int pid, struct proc_info *proc) {
386     SchedPolicy p;
387     if (get_sched_policy(pid, &p) < 0)
388         strlcpy(proc->policy, "unk", POLICY_NAME_LEN);
389     else {
390         strlcpy(proc->policy, get_sched_policy_name(p), POLICY_NAME_LEN);
391         proc->policy[2] = '\0';
392     }
393 }
394 
read_status(char * filename,struct proc_info * proc)395 static int read_status(char *filename, struct proc_info *proc) {
396     FILE *file;
397     char line[MAX_LINE];
398     unsigned int uid, gid;
399 
400     file = fopen(filename, "r");
401     if (!file) return 1;
402     while (fgets(line, MAX_LINE, file)) {
403         sscanf(line, "Uid: %u", &uid);
404         sscanf(line, "Gid: %u", &gid);
405     }
406     fclose(file);
407     proc->uid = uid; proc->gid = gid;
408     return 0;
409 }
410 
print_procs(void)411 static void print_procs(void) {
412     int i;
413     struct proc_info *old_proc, *proc;
414     long unsigned total_delta_time;
415     struct passwd *user;
416     char *user_str, user_buf[20];
417 
418     for (i = 0; i < num_new_procs; i++) {
419         if (new_procs[i]) {
420             old_proc = find_old_proc(new_procs[i]->pid, new_procs[i]->tid);
421             if (old_proc) {
422                 new_procs[i]->delta_utime = new_procs[i]->utime - old_proc->utime;
423                 new_procs[i]->delta_stime = new_procs[i]->stime - old_proc->stime;
424             } else {
425                 new_procs[i]->delta_utime = 0;
426                 new_procs[i]->delta_stime = 0;
427             }
428             new_procs[i]->delta_time = new_procs[i]->delta_utime + new_procs[i]->delta_stime;
429         }
430     }
431 
432     total_delta_time = (new_cpu.utime + new_cpu.ntime + new_cpu.stime + new_cpu.itime
433                         + new_cpu.iowtime + new_cpu.irqtime + new_cpu.sirqtime)
434                      - (old_cpu.utime + old_cpu.ntime + old_cpu.stime + old_cpu.itime
435                         + old_cpu.iowtime + old_cpu.irqtime + old_cpu.sirqtime);
436 
437     qsort(new_procs, num_new_procs, sizeof(struct proc_info *), proc_cmp);
438 
439     printf("\n\n\n");
440     printf("User %ld%%, System %ld%%, IOW %ld%%, IRQ %ld%%\n",
441             ((new_cpu.utime + new_cpu.ntime) - (old_cpu.utime + old_cpu.ntime)) * 100  / total_delta_time,
442             ((new_cpu.stime ) - (old_cpu.stime)) * 100 / total_delta_time,
443             ((new_cpu.iowtime) - (old_cpu.iowtime)) * 100 / total_delta_time,
444             ((new_cpu.irqtime + new_cpu.sirqtime)
445                     - (old_cpu.irqtime + old_cpu.sirqtime)) * 100 / total_delta_time);
446     printf("User %ld + Nice %ld + Sys %ld + Idle %ld + IOW %ld + IRQ %ld + SIRQ %ld = %ld\n",
447             new_cpu.utime - old_cpu.utime,
448             new_cpu.ntime - old_cpu.ntime,
449             new_cpu.stime - old_cpu.stime,
450             new_cpu.itime - old_cpu.itime,
451             new_cpu.iowtime - old_cpu.iowtime,
452             new_cpu.irqtime - old_cpu.irqtime,
453             new_cpu.sirqtime - old_cpu.sirqtime,
454             total_delta_time);
455     printf("\n");
456     if (!threads)
457         printf("%5s %2s %4s %1s %5s %7s %7s %3s %-8s %s\n", "PID", "PR", "CPU%", "S", "#THR", "VSS", "RSS", "PCY", "UID", "Name");
458     else
459         printf("%5s %5s %2s %4s %1s %7s %7s %3s %-8s %-15s %s\n", "PID", "TID", "PR", "CPU%", "S", "VSS", "RSS", "PCY", "UID", "Thread", "Proc");
460 
461     for (i = 0; i < num_new_procs; i++) {
462         proc = new_procs[i];
463 
464         if (!proc || (max_procs && (i >= max_procs)))
465             break;
466         user  = getpwuid(proc->uid);
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 (!threads)
474             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,
475                 proc->vss / 1024, proc->rss * getpagesize() / 1024, proc->policy, user_str, proc->name[0] != 0 ? proc->name : proc->tname);
476         else
477             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,
478                 proc->vss / 1024, proc->rss * getpagesize() / 1024, proc->policy, user_str, proc->tname, proc->name);
479     }
480 }
481 
find_old_proc(pid_t pid,pid_t tid)482 static struct proc_info *find_old_proc(pid_t pid, pid_t tid) {
483     int i;
484 
485     for (i = 0; i < num_old_procs; i++)
486         if (old_procs[i] && (old_procs[i]->pid == pid) && (old_procs[i]->tid == tid))
487             return old_procs[i];
488 
489     return NULL;
490 }
491 
free_old_procs(void)492 static void free_old_procs(void) {
493     int i;
494 
495     for (i = 0; i < num_old_procs; i++)
496         if (old_procs[i])
497             free_proc(old_procs[i]);
498 
499     free(old_procs);
500 }
501 
proc_cpu_cmp(const void * a,const void * b)502 static int proc_cpu_cmp(const void *a, const void *b) {
503     struct proc_info *pa, *pb;
504 
505     pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
506 
507     if (!pa && !pb) return 0;
508     if (!pa) return 1;
509     if (!pb) return -1;
510 
511     return -numcmp(pa->delta_time, pb->delta_time);
512 }
513 
proc_vss_cmp(const void * a,const void * b)514 static int proc_vss_cmp(const void *a, const void *b) {
515     struct proc_info *pa, *pb;
516 
517     pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
518 
519     if (!pa && !pb) return 0;
520     if (!pa) return 1;
521     if (!pb) return -1;
522 
523     return -numcmp(pa->vss, pb->vss);
524 }
525 
proc_rss_cmp(const void * a,const void * b)526 static int proc_rss_cmp(const void *a, const void *b) {
527     struct proc_info *pa, *pb;
528 
529     pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
530 
531     if (!pa && !pb) return 0;
532     if (!pa) return 1;
533     if (!pb) return -1;
534 
535     return -numcmp(pa->rss, pb->rss);
536 }
537 
proc_thr_cmp(const void * a,const void * b)538 static int proc_thr_cmp(const void *a, const void *b) {
539     struct proc_info *pa, *pb;
540 
541     pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
542 
543     if (!pa && !pb) return 0;
544     if (!pa) return 1;
545     if (!pb) return -1;
546 
547     return -numcmp(pa->num_threads, pb->num_threads);
548 }
549 
numcmp(long long a,long long b)550 static int numcmp(long long a, long long b) {
551     if (a < b) return -1;
552     if (a > b) return 1;
553     return 0;
554 }
555 
usage(char * cmd)556 static void usage(char *cmd) {
557     fprintf(stderr, "Usage: %s [ -m max_procs ] [ -n iterations ] [ -d delay ] [ -s sort_column ] [ -t ] [ -h ]\n"
558                     "    -m num  Maximum number of processes to display.\n"
559                     "    -n num  Updates to show before exiting.\n"
560                     "    -d num  Seconds to wait between updates.\n"
561                     "    -s col  Column to sort by (cpu,vss,rss,thr).\n"
562                     "    -t      Show threads instead of processes.\n"
563                     "    -h      Display this help screen.\n",
564         cmd);
565 }
566