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 <inttypes.h>
36 #include <pwd.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <sys/types.h>
41 #include <unistd.h>
42
43 #include <cutils/sched_policy.h>
44
45 struct cpu_info {
46 long unsigned utime, ntime, stime, itime;
47 long unsigned iowtime, irqtime, sirqtime;
48 };
49
50 #define PROC_NAME_LEN 64
51 #define THREAD_NAME_LEN 32
52 #define POLICY_NAME_LEN 4
53
54 struct proc_info {
55 struct proc_info *next;
56 pid_t pid;
57 pid_t tid;
58 uid_t uid;
59 gid_t gid;
60 char name[PROC_NAME_LEN];
61 char tname[THREAD_NAME_LEN];
62 char state;
63 uint64_t utime;
64 uint64_t stime;
65 char pr[3];
66 long ni;
67 uint64_t delta_utime;
68 uint64_t delta_stime;
69 uint64_t delta_time;
70 uint64_t vss;
71 uint64_t rss;
72 int num_threads;
73 char policy[POLICY_NAME_LEN];
74 };
75
76 struct proc_list {
77 struct proc_info **array;
78 int size;
79 };
80
81 #define die(...) { fprintf(stderr, __VA_ARGS__); exit(EXIT_FAILURE); }
82
83 #define INIT_PROCS 50
84 #define THREAD_MULT 8
85 static struct proc_info **old_procs, **new_procs;
86 static int num_old_procs, num_new_procs;
87 static struct proc_info *free_procs;
88 static int num_used_procs, num_free_procs;
89
90 static int max_procs, delay, iterations, threads;
91
92 static struct cpu_info old_cpu, new_cpu;
93
94 static struct proc_info *alloc_proc(void);
95 static void free_proc(struct proc_info *proc);
96 static void read_procs(void);
97 static int read_stat(char *filename, struct proc_info *proc);
98 static void read_policy(int pid, struct proc_info *proc);
99 static void add_proc(int proc_num, struct proc_info *proc);
100 static int read_cmdline(char *filename, struct proc_info *proc);
101 static int read_status(char *filename, struct proc_info *proc);
102 static void print_procs(void);
103 static struct proc_info *find_old_proc(pid_t pid, pid_t tid);
104 static void free_old_procs(void);
105 static int (*proc_cmp)(const void *a, const void *b);
106 static int proc_cpu_cmp(const void *a, const void *b);
107 static int proc_vss_cmp(const void *a, const void *b);
108 static int proc_rss_cmp(const void *a, const void *b);
109 static int proc_thr_cmp(const void *a, const void *b);
110 static int numcmp(long long a, long long b);
111 static void usage(char *cmd);
112
top_main(int argc,char * argv[])113 int top_main(int argc, char *argv[]) {
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 (int 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], "-H") || !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 read_procs();
188 print_procs();
189 free_old_procs();
190 fflush(stdout);
191 if (iterations != 0) sleep(delay);
192 }
193
194 return 0;
195 }
196
alloc_proc(void)197 static struct proc_info *alloc_proc(void) {
198 struct proc_info *proc;
199
200 if (free_procs) {
201 proc = free_procs;
202 free_procs = free_procs->next;
203 num_free_procs--;
204 } else {
205 proc = malloc(sizeof(*proc));
206 if (!proc) die("Could not allocate struct process_info.\n");
207 }
208
209 num_used_procs++;
210
211 return proc;
212 }
213
free_proc(struct proc_info * proc)214 static void free_proc(struct proc_info *proc) {
215 proc->next = free_procs;
216 free_procs = proc;
217
218 num_used_procs--;
219 num_free_procs++;
220 }
221
222 #define MAX_LINE 256
223
read_procs(void)224 static void read_procs(void) {
225 DIR *proc_dir, *task_dir;
226 struct dirent *pid_dir, *tid_dir;
227 char filename[64];
228 FILE *file;
229 int proc_num;
230 struct proc_info *proc;
231 pid_t pid, tid;
232
233 int i;
234
235 proc_dir = opendir("/proc");
236 if (!proc_dir) die("Could not open /proc.\n");
237
238 new_procs = calloc(INIT_PROCS * (threads ? THREAD_MULT : 1), sizeof(struct proc_info *));
239 num_new_procs = INIT_PROCS * (threads ? THREAD_MULT : 1);
240
241 file = fopen("/proc/stat", "r");
242 if (!file) die("Could not open /proc/stat.\n");
243 fscanf(file, "cpu %lu %lu %lu %lu %lu %lu %lu", &new_cpu.utime, &new_cpu.ntime, &new_cpu.stime,
244 &new_cpu.itime, &new_cpu.iowtime, &new_cpu.irqtime, &new_cpu.sirqtime);
245 fclose(file);
246
247 proc_num = 0;
248 while ((pid_dir = readdir(proc_dir))) {
249 if (!isdigit(pid_dir->d_name[0]))
250 continue;
251
252 pid = atoi(pid_dir->d_name);
253
254 struct proc_info cur_proc;
255
256 if (!threads) {
257 proc = alloc_proc();
258
259 proc->pid = proc->tid = pid;
260
261 sprintf(filename, "/proc/%d/stat", pid);
262 read_stat(filename, proc);
263
264 sprintf(filename, "/proc/%d/cmdline", pid);
265 read_cmdline(filename, proc);
266
267 sprintf(filename, "/proc/%d/status", pid);
268 read_status(filename, proc);
269
270 read_policy(pid, proc);
271
272 proc->num_threads = 0;
273 } else {
274 sprintf(filename, "/proc/%d/cmdline", pid);
275 read_cmdline(filename, &cur_proc);
276
277 sprintf(filename, "/proc/%d/status", pid);
278 read_status(filename, &cur_proc);
279
280 proc = NULL;
281 }
282
283 sprintf(filename, "/proc/%d/task", pid);
284 task_dir = opendir(filename);
285 if (!task_dir) continue;
286
287 while ((tid_dir = readdir(task_dir))) {
288 if (!isdigit(tid_dir->d_name[0]))
289 continue;
290
291 if (threads) {
292 tid = atoi(tid_dir->d_name);
293
294 proc = alloc_proc();
295
296 proc->pid = pid; proc->tid = tid;
297
298 sprintf(filename, "/proc/%d/task/%d/stat", pid, tid);
299 read_stat(filename, proc);
300
301 read_policy(tid, proc);
302
303 strcpy(proc->name, cur_proc.name);
304 proc->uid = cur_proc.uid;
305 proc->gid = cur_proc.gid;
306
307 add_proc(proc_num++, proc);
308 } else {
309 proc->num_threads++;
310 }
311 }
312
313 closedir(task_dir);
314
315 if (!threads)
316 add_proc(proc_num++, proc);
317 }
318
319 for (i = proc_num; i < num_new_procs; i++)
320 new_procs[i] = NULL;
321
322 closedir(proc_dir);
323 }
324
read_stat(char * filename,struct proc_info * proc)325 static int read_stat(char *filename, struct proc_info *proc) {
326 FILE *file;
327 char buf[MAX_LINE], *open_paren, *close_paren;
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 long pr;
345 sscanf(close_paren + 1,
346 " %c "
347 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
348 "%" SCNu64 // utime %lu (14)
349 "%" SCNu64 // stime %lu (15)
350 "%*d %*d "
351 "%ld " // priority %ld (18)
352 "%ld " // nice %ld (19)
353 "%*d %*d %*d "
354 "%" SCNu64 // vsize %lu (23)
355 "%" SCNu64, // rss %ld (24)
356 &proc->state,
357 &proc->utime,
358 &proc->stime,
359 &pr,
360 &proc->ni,
361 &proc->vss,
362 &proc->rss);
363
364 // Translate the PR field.
365 if (pr < -9) strcpy(proc->pr, "RT");
366 else snprintf(proc->pr, sizeof(proc->pr), "%ld", pr);
367
368 return 0;
369 }
370
add_proc(int proc_num,struct proc_info * proc)371 static void add_proc(int proc_num, struct proc_info *proc) {
372 int i;
373
374 if (proc_num >= num_new_procs) {
375 new_procs = realloc(new_procs, 2 * num_new_procs * sizeof(struct proc_info *));
376 if (!new_procs) die("Could not expand procs array.\n");
377 for (i = num_new_procs; i < 2 * num_new_procs; i++)
378 new_procs[i] = NULL;
379 num_new_procs = 2 * num_new_procs;
380 }
381 new_procs[proc_num] = proc;
382 }
383
read_cmdline(char * filename,struct proc_info * proc)384 static int read_cmdline(char *filename, struct proc_info *proc) {
385 FILE *file;
386 char line[MAX_LINE];
387
388 line[0] = '\0';
389 file = fopen(filename, "r");
390 if (!file) return 1;
391 fgets(line, MAX_LINE, file);
392 fclose(file);
393 if (strlen(line) > 0) {
394 strncpy(proc->name, line, PROC_NAME_LEN);
395 proc->name[PROC_NAME_LEN-1] = 0;
396 } else
397 proc->name[0] = 0;
398 return 0;
399 }
400
read_policy(int pid,struct proc_info * proc)401 static void read_policy(int pid, struct proc_info *proc) {
402 SchedPolicy p;
403 if (get_sched_policy(pid, &p) < 0)
404 strlcpy(proc->policy, "unk", POLICY_NAME_LEN);
405 else {
406 strlcpy(proc->policy, get_sched_policy_name(p), POLICY_NAME_LEN);
407 proc->policy[2] = '\0';
408 }
409 }
410
read_status(char * filename,struct proc_info * proc)411 static int read_status(char *filename, struct proc_info *proc) {
412 FILE *file;
413 char line[MAX_LINE];
414 unsigned int uid, gid;
415
416 file = fopen(filename, "r");
417 if (!file) return 1;
418 while (fgets(line, MAX_LINE, file)) {
419 sscanf(line, "Uid: %u", &uid);
420 sscanf(line, "Gid: %u", &gid);
421 }
422 fclose(file);
423 proc->uid = uid; proc->gid = gid;
424 return 0;
425 }
426
print_procs(void)427 static void print_procs(void) {
428 static int call = 0;
429 int i;
430 struct proc_info *old_proc, *proc;
431 long unsigned total_delta_time;
432
433 for (i = 0; i < num_new_procs; i++) {
434 if (new_procs[i]) {
435 old_proc = find_old_proc(new_procs[i]->pid, new_procs[i]->tid);
436 if (old_proc) {
437 new_procs[i]->delta_utime = new_procs[i]->utime - old_proc->utime;
438 new_procs[i]->delta_stime = new_procs[i]->stime - old_proc->stime;
439 } else {
440 new_procs[i]->delta_utime = 0;
441 new_procs[i]->delta_stime = 0;
442 }
443 new_procs[i]->delta_time = new_procs[i]->delta_utime + new_procs[i]->delta_stime;
444 }
445 }
446
447 total_delta_time = (new_cpu.utime + new_cpu.ntime + new_cpu.stime + new_cpu.itime
448 + new_cpu.iowtime + new_cpu.irqtime + new_cpu.sirqtime)
449 - (old_cpu.utime + old_cpu.ntime + old_cpu.stime + old_cpu.itime
450 + old_cpu.iowtime + old_cpu.irqtime + old_cpu.sirqtime);
451
452 qsort(new_procs, num_new_procs, sizeof(struct proc_info *), proc_cmp);
453
454 if (call++ > 0) printf("\n\n\n");
455 printf("User %ld%%, System %ld%%, IOW %ld%%, IRQ %ld%%\n",
456 ((new_cpu.utime + new_cpu.ntime) - (old_cpu.utime + old_cpu.ntime)) * 100 / total_delta_time,
457 ((new_cpu.stime ) - (old_cpu.stime)) * 100 / total_delta_time,
458 ((new_cpu.iowtime) - (old_cpu.iowtime)) * 100 / total_delta_time,
459 ((new_cpu.irqtime + new_cpu.sirqtime)
460 - (old_cpu.irqtime + old_cpu.sirqtime)) * 100 / total_delta_time);
461 printf("User %ld + Nice %ld + Sys %ld + Idle %ld + IOW %ld + IRQ %ld + SIRQ %ld = %ld\n",
462 new_cpu.utime - old_cpu.utime,
463 new_cpu.ntime - old_cpu.ntime,
464 new_cpu.stime - old_cpu.stime,
465 new_cpu.itime - old_cpu.itime,
466 new_cpu.iowtime - old_cpu.iowtime,
467 new_cpu.irqtime - old_cpu.irqtime,
468 new_cpu.sirqtime - old_cpu.sirqtime,
469 total_delta_time);
470 printf("\n");
471 if (!threads)
472 printf("%5s %-8s %2s %3s %4s %1s %5s %7s %7s %3s %s\n", "PID", "USER", "PR", "NI", "CPU%", "S", "#THR", "VSS", "RSS", "PCY", "Name");
473 else
474 printf("%5s %5s %-8s %2s %3s %4s %1s %7s %7s %3s %-15s %s\n", "PID", "TID", "USER", "PR", "NI", "CPU%", "S", "VSS", "RSS", "PCY", "Thread", "Proc");
475
476 for (i = 0; i < num_new_procs; i++) {
477 proc = new_procs[i];
478
479 if (!proc || (max_procs && (i >= max_procs)))
480 break;
481 struct passwd* user = getpwuid(proc->uid);
482 char user_buf[20];
483 char* user_str;
484 if (user && user->pw_name) {
485 user_str = user->pw_name;
486 } else {
487 snprintf(user_buf, 20, "%d", proc->uid);
488 user_str = user_buf;
489 }
490 if (!threads) {
491 printf("%5d %-8.8s %2s %3ld %3" PRIu64 "%% %c %5d %6" PRIu64 "K %6" PRIu64 "K %3s %s\n",
492 proc->pid, user_str, proc->pr, proc->ni,
493 proc->delta_time * 100 / total_delta_time, proc->state, proc->num_threads,
494 proc->vss / 1024, proc->rss * getpagesize() / 1024, proc->policy,
495 proc->name[0] != 0 ? proc->name : proc->tname);
496 } else {
497 printf("%5d %5d %-8.8s %2s %3ld %3" PRIu64 "%% %c %6" PRIu64 "K %6" PRIu64 "K %3s %-15s %s\n",
498 proc->pid, proc->tid, user_str, proc->pr, proc->ni,
499 proc->delta_time * 100 / total_delta_time, proc->state,
500 proc->vss / 1024, proc->rss * getpagesize() / 1024, proc->policy,
501 proc->tname, proc->name);
502 }
503 }
504 }
505
find_old_proc(pid_t pid,pid_t tid)506 static struct proc_info *find_old_proc(pid_t pid, pid_t tid) {
507 int i;
508
509 for (i = 0; i < num_old_procs; i++)
510 if (old_procs[i] && (old_procs[i]->pid == pid) && (old_procs[i]->tid == tid))
511 return old_procs[i];
512
513 return NULL;
514 }
515
free_old_procs(void)516 static void free_old_procs(void) {
517 int i;
518
519 for (i = 0; i < num_old_procs; i++)
520 if (old_procs[i])
521 free_proc(old_procs[i]);
522
523 free(old_procs);
524 }
525
proc_cpu_cmp(const void * a,const void * b)526 static int proc_cpu_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->delta_time, pb->delta_time);
536 }
537
proc_vss_cmp(const void * a,const void * b)538 static int proc_vss_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->vss, pb->vss);
548 }
549
proc_rss_cmp(const void * a,const void * b)550 static int proc_rss_cmp(const void *a, const void *b) {
551 struct proc_info *pa, *pb;
552
553 pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
554
555 if (!pa && !pb) return 0;
556 if (!pa) return 1;
557 if (!pb) return -1;
558
559 return -numcmp(pa->rss, pb->rss);
560 }
561
proc_thr_cmp(const void * a,const void * b)562 static int proc_thr_cmp(const void *a, const void *b) {
563 struct proc_info *pa, *pb;
564
565 pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
566
567 if (!pa && !pb) return 0;
568 if (!pa) return 1;
569 if (!pb) return -1;
570
571 return -numcmp(pa->num_threads, pb->num_threads);
572 }
573
numcmp(long long a,long long b)574 static int numcmp(long long a, long long b) {
575 if (a < b) return -1;
576 if (a > b) return 1;
577 return 0;
578 }
579
usage(char * cmd)580 static void usage(char *cmd) {
581 fprintf(stderr, "Usage: %s [ -m max_procs ] [ -n iterations ] [ -d delay ] [ -s sort_column ] [ -t ] [ -h ]\n"
582 " -m num Maximum number of processes to display.\n"
583 " -n num Updates to show before exiting.\n"
584 " -d num Seconds to wait between updates.\n"
585 " -s col Column to sort by (cpu,vss,rss,thr).\n"
586 " -H Show threads instead of processes.\n"
587 " -h Display this help screen.\n",
588 cmd);
589 }
590