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