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