Home | History | Annotate | Download | only in toolbox
      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 
     52 struct proc_info {
     53     struct proc_info *next;
     54     pid_t pid;
     55     pid_t tid;
     56     uid_t uid;
     57     gid_t gid;
     58     char name[PROC_NAME_LEN];
     59     char tname[THREAD_NAME_LEN];
     60     char state;
     61     long unsigned utime;
     62     long unsigned stime;
     63     long unsigned delta_utime;
     64     long unsigned delta_stime;
     65     long unsigned delta_time;
     66     long vss;
     67     long rss;
     68     int num_threads;
     69     char policy[32];
     70 };
     71 
     72 struct proc_list {
     73     struct proc_info **array;
     74     int size;
     75 };
     76 
     77 #define die(...) { fprintf(stderr, __VA_ARGS__); exit(EXIT_FAILURE); }
     78 
     79 #define INIT_PROCS 50
     80 #define THREAD_MULT 8
     81 static struct proc_info **old_procs, **new_procs;
     82 static int num_old_procs, num_new_procs;
     83 static struct proc_info *free_procs;
     84 static int num_used_procs, num_free_procs;
     85 
     86 static int max_procs, delay, iterations, threads;
     87 
     88 static struct cpu_info old_cpu, new_cpu;
     89 
     90 static struct proc_info *alloc_proc(void);
     91 static void free_proc(struct proc_info *proc);
     92 static void read_procs(void);
     93 static int read_stat(char *filename, struct proc_info *proc);
     94 static void read_policy(int pid, struct proc_info *proc);
     95 static void add_proc(int proc_num, struct proc_info *proc);
     96 static int read_cmdline(char *filename, struct proc_info *proc);
     97 static int read_status(char *filename, struct proc_info *proc);
     98 static void print_procs(void);
     99 static struct proc_info *find_old_proc(pid_t pid, pid_t tid);
    100 static void free_old_procs(void);
    101 static int (*proc_cmp)(const void *a, const void *b);
    102 static int proc_cpu_cmp(const void *a, const void *b);
    103 static int proc_vss_cmp(const void *a, const void *b);
    104 static int proc_rss_cmp(const void *a, const void *b);
    105 static int proc_thr_cmp(const void *a, const void *b);
    106 static int numcmp(long long a, long long b);
    107 static void usage(char *cmd);
    108 
    109 int top_main(int argc, char *argv[]) {
    110     int i;
    111 
    112     num_used_procs = num_free_procs = 0;
    113 
    114     max_procs = 0;
    115     delay = 3;
    116     iterations = -1;
    117     proc_cmp = &proc_cpu_cmp;
    118     for (i = 1; i < argc; i++) {
    119         if (!strcmp(argv[i], "-m")) {
    120             if (i + 1 >= argc) {
    121                 fprintf(stderr, "Option -m expects an argument.\n");
    122                 usage(argv[0]);
    123                 exit(EXIT_FAILURE);
    124             }
    125             max_procs = atoi(argv[++i]);
    126             continue;
    127         }
    128         if (!strcmp(argv[i], "-n")) {
    129             if (i + 1 >= argc) {
    130                 fprintf(stderr, "Option -n expects an argument.\n");
    131                 usage(argv[0]);
    132                 exit(EXIT_FAILURE);
    133             }
    134             iterations = atoi(argv[++i]);
    135             continue;
    136         }
    137         if (!strcmp(argv[i], "-d")) {
    138             if (i + 1 >= argc) {
    139                 fprintf(stderr, "Option -d expects an argument.\n");
    140                 usage(argv[0]);
    141                 exit(EXIT_FAILURE);
    142             }
    143             delay = atoi(argv[++i]);
    144             continue;
    145         }
    146         if (!strcmp(argv[i], "-s")) {
    147             if (i + 1 >= argc) {
    148                 fprintf(stderr, "Option -s expects an argument.\n");
    149                 usage(argv[0]);
    150                 exit(EXIT_FAILURE);
    151             }
    152             ++i;
    153             if (!strcmp(argv[i], "cpu")) { proc_cmp = &proc_cpu_cmp; continue; }
    154             if (!strcmp(argv[i], "vss")) { proc_cmp = &proc_vss_cmp; continue; }
    155             if (!strcmp(argv[i], "rss")) { proc_cmp = &proc_rss_cmp; continue; }
    156             if (!strcmp(argv[i], "thr")) { proc_cmp = &proc_thr_cmp; continue; }
    157             fprintf(stderr, "Invalid argument \"%s\" for option -s.\n", argv[i]);
    158             exit(EXIT_FAILURE);
    159         }
    160         if (!strcmp(argv[i], "-t")) { threads = 1; continue; }
    161         if (!strcmp(argv[i], "-h")) {
    162             usage(argv[0]);
    163             exit(EXIT_SUCCESS);
    164         }
    165         fprintf(stderr, "Invalid argument \"%s\".\n", argv[i]);
    166         usage(argv[0]);
    167         exit(EXIT_FAILURE);
    168     }
    169 
    170     if (threads && proc_cmp == &proc_thr_cmp) {
    171         fprintf(stderr, "Sorting by threads per thread makes no sense!\n");
    172         exit(EXIT_FAILURE);
    173     }
    174 
    175     free_procs = NULL;
    176 
    177     num_new_procs = num_old_procs = 0;
    178     new_procs = old_procs = NULL;
    179 
    180     read_procs();
    181     while ((iterations == -1) || (iterations-- > 0)) {
    182         old_procs = new_procs;
    183         num_old_procs = num_new_procs;
    184         memcpy(&old_cpu, &new_cpu, sizeof(old_cpu));
    185         sleep(delay);
    186         read_procs();
    187         print_procs();
    188         free_old_procs();
    189     }
    190 
    191     return 0;
    192 }
    193 
    194 static struct proc_info *alloc_proc(void) {
    195     struct proc_info *proc;
    196 
    197     if (free_procs) {
    198         proc = free_procs;
    199         free_procs = free_procs->next;
    200         num_free_procs--;
    201     } else {
    202         proc = malloc(sizeof(*proc));
    203         if (!proc) die("Could not allocate struct process_info.\n");
    204     }
    205 
    206     num_used_procs++;
    207 
    208     return proc;
    209 }
    210 
    211 static void free_proc(struct proc_info *proc) {
    212     proc->next = free_procs;
    213     free_procs = proc;
    214 
    215     num_used_procs--;
    216     num_free_procs++;
    217 }
    218 
    219 #define MAX_LINE 256
    220 
    221 static void read_procs(void) {
    222     DIR *proc_dir, *task_dir;
    223     struct dirent *pid_dir, *tid_dir;
    224     char filename[64];
    225     FILE *file;
    226     int proc_num;
    227     struct proc_info *proc;
    228     pid_t pid, tid;
    229 
    230     int i;
    231 
    232     proc_dir = opendir("/proc");
    233     if (!proc_dir) die("Could not open /proc.\n");
    234 
    235     new_procs = calloc(INIT_PROCS * (threads ? THREAD_MULT : 1), sizeof(struct proc_info *));
    236     num_new_procs = INIT_PROCS * (threads ? THREAD_MULT : 1);
    237 
    238     file = fopen("/proc/stat", "r");
    239     if (!file) die("Could not open /proc/stat.\n");
    240     fscanf(file, "cpu  %lu %lu %lu %lu %lu %lu %lu", &new_cpu.utime, &new_cpu.ntime, &new_cpu.stime,
    241             &new_cpu.itime, &new_cpu.iowtime, &new_cpu.irqtime, &new_cpu.sirqtime);
    242     fclose(file);
    243 
    244     proc_num = 0;
    245     while ((pid_dir = readdir(proc_dir))) {
    246         if (!isdigit(pid_dir->d_name[0]))
    247             continue;
    248 
    249         pid = atoi(pid_dir->d_name);
    250 
    251         struct proc_info cur_proc;
    252 
    253         if (!threads) {
    254             proc = alloc_proc();
    255 
    256             proc->pid = proc->tid = pid;
    257 
    258             sprintf(filename, "/proc/%d/stat", pid);
    259             read_stat(filename, proc);
    260 
    261             sprintf(filename, "/proc/%d/cmdline", pid);
    262             read_cmdline(filename, proc);
    263 
    264             sprintf(filename, "/proc/%d/status", pid);
    265             read_status(filename, proc);
    266 
    267             read_policy(pid, proc);
    268 
    269             proc->num_threads = 0;
    270         } else {
    271             sprintf(filename, "/proc/%d/cmdline", pid);
    272             read_cmdline(filename, &cur_proc);
    273 
    274             sprintf(filename, "/proc/%d/status", pid);
    275             read_status(filename, &cur_proc);
    276 
    277             proc = NULL;
    278         }
    279 
    280         sprintf(filename, "/proc/%d/task", pid);
    281         task_dir = opendir(filename);
    282         if (!task_dir) continue;
    283 
    284         while ((tid_dir = readdir(task_dir))) {
    285             if (!isdigit(tid_dir->d_name[0]))
    286                 continue;
    287 
    288             if (threads) {
    289                 tid = atoi(tid_dir->d_name);
    290 
    291                 proc = alloc_proc();
    292 
    293                 proc->pid = pid; proc->tid = tid;
    294 
    295                 sprintf(filename, "/proc/%d/task/%d/stat", pid, tid);
    296                 read_stat(filename, proc);
    297 
    298                 read_policy(tid, proc);
    299 
    300                 strcpy(proc->name, cur_proc.name);
    301                 proc->uid = cur_proc.uid;
    302                 proc->gid = cur_proc.gid;
    303 
    304                 add_proc(proc_num++, proc);
    305             } else {
    306                 proc->num_threads++;
    307             }
    308         }
    309 
    310         closedir(task_dir);
    311 
    312         if (!threads)
    313             add_proc(proc_num++, proc);
    314     }
    315 
    316     for (i = proc_num; i < num_new_procs; i++)
    317         new_procs[i] = NULL;
    318 
    319     closedir(proc_dir);
    320 }
    321 
    322 static int read_stat(char *filename, struct proc_info *proc) {
    323     FILE *file;
    324     char buf[MAX_LINE], *open_paren, *close_paren;
    325     int res, idx;
    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, " %c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
    343                  "%lu %lu %*d %*d %*d %*d %*d %*d %*d %lu %ld",
    344                  &proc->state, &proc->utime, &proc->stime, &proc->vss, &proc->rss);
    345 
    346     return 0;
    347 }
    348 
    349 static void add_proc(int proc_num, struct proc_info *proc) {
    350     int i;
    351 
    352     if (proc_num >= num_new_procs) {
    353         new_procs = realloc(new_procs, 2 * num_new_procs * sizeof(struct proc_info *));
    354         if (!new_procs) die("Could not expand procs array.\n");
    355         for (i = num_new_procs; i < 2 * num_new_procs; i++)
    356             new_procs[i] = NULL;
    357         num_new_procs = 2 * num_new_procs;
    358     }
    359     new_procs[proc_num] = proc;
    360 }
    361 
    362 static int read_cmdline(char *filename, struct proc_info *proc) {
    363     FILE *file;
    364     char line[MAX_LINE];
    365 
    366     line[0] = '\0';
    367     file = fopen(filename, "r");
    368     if (!file) return 1;
    369     fgets(line, MAX_LINE, file);
    370     fclose(file);
    371     if (strlen(line) > 0) {
    372         strncpy(proc->name, line, PROC_NAME_LEN);
    373         proc->name[PROC_NAME_LEN-1] = 0;
    374     } else
    375         proc->name[0] = 0;
    376     return 0;
    377 }
    378 
    379 static void read_policy(int pid, struct proc_info *proc) {
    380     SchedPolicy p;
    381     if (get_sched_policy(pid, &p) < 0)
    382         strcpy(proc->policy, "unk");
    383     else {
    384         if (p == SP_BACKGROUND)
    385             strcpy(proc->policy, "bg");
    386         else if (p == SP_FOREGROUND)
    387             strcpy(proc->policy, "fg");
    388         else
    389             strcpy(proc->policy, "er");
    390     }
    391 }
    392 
    393 static int read_status(char *filename, struct proc_info *proc) {
    394     FILE *file;
    395     char line[MAX_LINE];
    396     unsigned int uid, gid;
    397 
    398     file = fopen(filename, "r");
    399     if (!file) return 1;
    400     while (fgets(line, MAX_LINE, file)) {
    401         sscanf(line, "Uid: %u", &uid);
    402         sscanf(line, "Gid: %u", &gid);
    403     }
    404     fclose(file);
    405     proc->uid = uid; proc->gid = gid;
    406     return 0;
    407 }
    408 
    409 static void print_procs(void) {
    410     int i;
    411     struct proc_info *old_proc, *proc;
    412     long unsigned total_delta_time;
    413     struct passwd *user;
    414     struct group *group;
    415     char *user_str, user_buf[20];
    416     char *group_str, group_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 %4s %1s %5s %7s %7s %3s %-8s %s\n", "PID", "CPU%", "S", "#THR", "VSS", "RSS", "PCY", "UID", "Name");
    458     else
    459         printf("%5s %5s %4s %1s %7s %7s %3s %-8s %-15s %s\n", "PID", "TID", "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         group = getgrgid(proc->gid);
    468         if (user && user->pw_name) {
    469             user_str = user->pw_name;
    470         } else {
    471             snprintf(user_buf, 20, "%d", proc->uid);
    472             user_str = user_buf;
    473         }
    474         if (group && group->gr_name) {
    475             group_str = group->gr_name;
    476         } else {
    477             snprintf(group_buf, 20, "%d", proc->gid);
    478             group_str = group_buf;
    479         }
    480         if (!threads)
    481             printf("%5d %3ld%% %c %5d %6ldK %6ldK %3s %-8.8s %s\n", proc->pid, proc->delta_time * 100 / total_delta_time, proc->state, proc->num_threads,
    482                 proc->vss / 1024, proc->rss * getpagesize() / 1024, proc->policy, user_str, proc->name[0] != 0 ? proc->name : proc->tname);
    483         else
    484             printf("%5d %5d %3ld%% %c %6ldK %6ldK %3s %-8.8s %-15s %s\n", proc->pid, proc->tid, proc->delta_time * 100 / total_delta_time, proc->state,
    485                 proc->vss / 1024, proc->rss * getpagesize() / 1024, proc->policy, user_str, proc->tname, proc->name);
    486     }
    487 }
    488 
    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 
    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 
    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 
    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 
    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 
    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 
    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 
    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