ps,top: add an option to show threads. +260 bytes of code
[oweals/busybox.git] / procps / ps.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini ps implementation(s) for busybox
4  *
5  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
6  * Fix for SELinux Support:(c)2007 Hiroshi Shinji <shiroshi@my.email.ne.jp>
7  *                         (c)2007 Yuichi Nakamura <ynakam@hitachisoft.jp>
8  *
9  * Licensed under the GPL version 2, see the file LICENSE in this tarball.
10  */
11
12 #include "libbb.h"
13
14 /* Absolute maximum on output line length */
15 enum { MAX_WIDTH = 2*1024 };
16
17 #if ENABLE_DESKTOP
18
19 #include <sys/times.h> /* for times() */
20 #ifndef AT_CLKTCK
21 #define AT_CLKTCK 17
22 #endif
23
24
25 #if ENABLE_SELINUX
26 #define SELINUX_O_PREFIX "label,"
27 #define DEFAULT_O_STR    (SELINUX_O_PREFIX "pid,user" IF_FEATURE_PS_TIME(",time") ",args")
28 #else
29 #define DEFAULT_O_STR    ("pid,user" IF_FEATURE_PS_TIME(",time") ",args")
30 #endif
31
32 typedef struct {
33         uint16_t width;
34         char name6[6];
35         const char *header;
36         void (*f)(char *buf, int size, const procps_status_t *ps);
37         int ps_flags;
38 } ps_out_t;
39
40 struct globals {
41         ps_out_t* out;
42         int out_cnt;
43         int print_header;
44         int need_flags;
45         char *buffer;
46         unsigned terminal_width;
47 #if ENABLE_FEATURE_PS_TIME
48         unsigned kernel_HZ;
49         unsigned long long seconds_since_boot;
50 #endif
51         char default_o[sizeof(DEFAULT_O_STR)];
52 };
53 #define G (*(struct globals*)&bb_common_bufsiz1)
54 #define out                (G.out               )
55 #define out_cnt            (G.out_cnt           )
56 #define print_header       (G.print_header      )
57 #define need_flags         (G.need_flags        )
58 #define buffer             (G.buffer            )
59 #define terminal_width     (G.terminal_width    )
60 #define kernel_HZ          (G.kernel_HZ         )
61 #define seconds_since_boot (G.seconds_since_boot)
62 #define default_o          (G.default_o         )
63 #define INIT_G() do { } while (0)
64
65 #if ENABLE_FEATURE_PS_TIME
66 /* for ELF executables, notes are pushed before environment and args */
67 static ptrdiff_t find_elf_note(ptrdiff_t findme)
68 {
69         ptrdiff_t *ep = (ptrdiff_t *) environ;
70
71         while (*ep++);
72         while (*ep) {
73                 if (ep[0] == findme) {
74                         return ep[1];
75                 }
76                 ep += 2;
77         }
78         return -1;
79 }
80
81 #if ENABLE_FEATURE_PS_UNUSUAL_SYSTEMS
82 static unsigned get_HZ_by_waiting(void)
83 {
84         struct timeval tv1, tv2;
85         unsigned t1, t2, r, hz;
86         unsigned cnt = cnt; /* for compiler */
87         int diff;
88
89         r = 0;
90
91         /* Wait for times() to reach new tick */
92         t1 = times(NULL);
93         do {
94                 t2 = times(NULL);
95         } while (t2 == t1);
96         gettimeofday(&tv2, NULL);
97
98         do {
99                 t1 = t2;
100                 tv1.tv_usec = tv2.tv_usec;
101
102                 /* Wait exactly one times() tick */
103                 do {
104                         t2 = times(NULL);
105                 } while (t2 == t1);
106                 gettimeofday(&tv2, NULL);
107
108                 /* Calculate ticks per sec, rounding up to even */
109                 diff = tv2.tv_usec - tv1.tv_usec;
110                 if (diff <= 0) diff += 1000000;
111                 hz = 1000000u / (unsigned)diff;
112                 hz = (hz+1) & ~1;
113
114                 /* Count how many same hz values we saw */
115                 if (r != hz) {
116                         r = hz;
117                         cnt = 0;
118                 }
119                 cnt++;
120         } while (cnt < 3); /* exit if saw 3 same values */
121
122         return r;
123 }
124 #else
125 static inline unsigned get_HZ_by_waiting(void)
126 {
127         /* Better method? */
128         return 100;
129 }
130 #endif
131
132 static unsigned get_kernel_HZ(void)
133 {
134         //char buf[64];
135         struct sysinfo info;
136
137         if (kernel_HZ)
138                 return kernel_HZ;
139
140         /* Works for ELF only, Linux 2.4.0+ */
141         kernel_HZ = find_elf_note(AT_CLKTCK);
142         if (kernel_HZ == (unsigned)-1)
143                 kernel_HZ = get_HZ_by_waiting();
144
145         //if (open_read_close("/proc/uptime", buf, sizeof(buf) <= 0)
146         //      bb_perror_msg_and_die("cannot read %s", "/proc/uptime");
147         //buf[sizeof(buf)-1] = '\0';
148         ///sscanf(buf, "%llu", &seconds_since_boot);
149         sysinfo(&info);
150         seconds_since_boot = info.uptime;
151
152         return kernel_HZ;
153 }
154 #endif
155
156 /* Print value to buf, max size+1 chars (including trailing '\0') */
157
158 static void func_user(char *buf, int size, const procps_status_t *ps)
159 {
160 #if 1
161         safe_strncpy(buf, get_cached_username(ps->uid), size+1);
162 #else
163         /* "compatible" version, but it's larger */
164         /* procps 2.18 shows numeric UID if name overflows the field */
165         /* TODO: get_cached_username() returns numeric string if
166          * user has no passwd record, we will display it
167          * left-justified here; too long usernames are shown
168          * as _right-justified_ IDs. Is it worth fixing? */
169         const char *user = get_cached_username(ps->uid);
170         if (strlen(user) <= size)
171                 safe_strncpy(buf, user, size+1);
172         else
173                 sprintf(buf, "%*u", size, (unsigned)ps->uid);
174 #endif
175 }
176
177 static void func_group(char *buf, int size, const procps_status_t *ps)
178 {
179         safe_strncpy(buf, get_cached_groupname(ps->gid), size+1);
180 }
181
182 static void func_comm(char *buf, int size, const procps_status_t *ps)
183 {
184         safe_strncpy(buf, ps->comm, size+1);
185 }
186
187 static void func_args(char *buf, int size, const procps_status_t *ps)
188 {
189         read_cmdline(buf, size+1, ps->pid, ps->comm);
190 }
191
192 static void func_pid(char *buf, int size, const procps_status_t *ps)
193 {
194         sprintf(buf, "%*u", size, ps->pid);
195 }
196
197 static void func_ppid(char *buf, int size, const procps_status_t *ps)
198 {
199         sprintf(buf, "%*u", size, ps->ppid);
200 }
201
202 static void func_pgid(char *buf, int size, const procps_status_t *ps)
203 {
204         sprintf(buf, "%*u", size, ps->pgid);
205 }
206
207 static void put_lu(char *buf, int size, unsigned long u)
208 {
209         char buf4[5];
210
211         /* see http://en.wikipedia.org/wiki/Tera */
212         smart_ulltoa4(u, buf4, " mgtpezy");
213         buf4[4] = '\0';
214         sprintf(buf, "%.*s", size, buf4);
215 }
216
217 static void func_vsz(char *buf, int size, const procps_status_t *ps)
218 {
219         put_lu(buf, size, ps->vsz);
220 }
221
222 static void func_rss(char *buf, int size, const procps_status_t *ps)
223 {
224         put_lu(buf, size, ps->rss);
225 }
226
227 static void func_tty(char *buf, int size, const procps_status_t *ps)
228 {
229         buf[0] = '?';
230         buf[1] = '\0';
231         if (ps->tty_major) /* tty field of "0" means "no tty" */
232                 snprintf(buf, size+1, "%u,%u", ps->tty_major, ps->tty_minor);
233 }
234
235
236 #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
237
238 static void func_rgroup(char *buf, int size, const procps_status_t *ps)
239 {
240         safe_strncpy(buf, get_cached_groupname(ps->rgid), size+1);
241 }
242
243 static void func_ruser(char *buf, int size, const procps_status_t *ps)
244 {
245         safe_strncpy(buf, get_cached_username(ps->ruid), size+1);
246 }
247
248 static void func_nice(char *buf, int size, const procps_status_t *ps)
249 {
250         sprintf(buf, "%*d", size, ps->niceness);
251 }
252
253 #endif /* FEATURE_PS_ADDITIONAL_COLUMNS */
254
255 #if ENABLE_FEATURE_PS_TIME
256 static void func_etime(char *buf, int size, const procps_status_t *ps)
257 {
258         /* elapsed time [[dd-]hh:]mm:ss; here only mm:ss */
259         unsigned long mm;
260         unsigned ss;
261
262         mm = ps->start_time / get_kernel_HZ();
263         /* must be after get_kernel_HZ()! */
264         mm = seconds_since_boot - mm;
265         ss = mm % 60;
266         mm /= 60;
267         snprintf(buf, size+1, "%3lu:%02u", mm, ss);
268 }
269
270 static void func_time(char *buf, int size, const procps_status_t *ps)
271 {
272         /* cumulative time [[dd-]hh:]mm:ss; here only mm:ss */
273         unsigned long mm;
274         unsigned ss;
275
276         mm = (ps->utime + ps->stime) / get_kernel_HZ();
277         ss = mm % 60;
278         mm /= 60;
279         snprintf(buf, size+1, "%3lu:%02u", mm, ss);
280 }
281 #endif
282
283 #if ENABLE_SELINUX
284 static void func_label(char *buf, int size, const procps_status_t *ps)
285 {
286         safe_strncpy(buf, ps->context ? ps->context : "unknown", size+1);
287 }
288 #endif
289
290 /*
291 static void func_nice(char *buf, int size, const procps_status_t *ps)
292 {
293         ps->???
294 }
295
296 static void func_pcpu(char *buf, int size, const procps_status_t *ps)
297 {
298 }
299 */
300
301 static const ps_out_t out_spec[] = {
302 // Mandated by POSIX:
303         { 8                  , "user"  ,"USER"   ,func_user  ,PSSCAN_UIDGID  },
304         { 8                  , "group" ,"GROUP"  ,func_group ,PSSCAN_UIDGID  },
305         { 16                 , "comm"  ,"COMMAND",func_comm  ,PSSCAN_COMM    },
306         { 256                , "args"  ,"COMMAND",func_args  ,PSSCAN_COMM    },
307         { 5                  , "pid"   ,"PID"    ,func_pid   ,PSSCAN_PID     },
308         { 5                  , "ppid"  ,"PPID"   ,func_ppid  ,PSSCAN_PPID    },
309         { 5                  , "pgid"  ,"PGID"   ,func_pgid  ,PSSCAN_PGID    },
310 #if ENABLE_FEATURE_PS_TIME
311         { sizeof("ELAPSED")-1, "etime" ,"ELAPSED",func_etime ,PSSCAN_START_TIME },
312 #endif
313 #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
314         { 5                  , "nice"  ,"NI"     ,func_nice  ,PSSCAN_NICE    },
315         { 8                  , "rgroup","RGROUP" ,func_rgroup,PSSCAN_RUIDGID },
316         { 8                  , "ruser" ,"RUSER"  ,func_ruser ,PSSCAN_RUIDGID },
317 //      { 5                  , "pcpu"  ,"%CPU"   ,func_pcpu  ,PSSCAN_        },
318 #endif
319 #if ENABLE_FEATURE_PS_TIME
320         { 6                  , "time"  ,"TIME"   ,func_time  ,PSSCAN_STIME | PSSCAN_UTIME },
321 #endif
322         { 6                  , "tty"   ,"TT"     ,func_tty   ,PSSCAN_TTY     },
323         { 4                  , "vsz"   ,"VSZ"    ,func_vsz   ,PSSCAN_VSZ     },
324 // Not mandated by POSIX, but useful:
325         { 4                  , "rss"   ,"RSS"    ,func_rss   ,PSSCAN_RSS     },
326 #if ENABLE_SELINUX
327         { 35                 , "label" ,"LABEL"  ,func_label ,PSSCAN_CONTEXT },
328 #endif
329 };
330
331 static ps_out_t* new_out_t(void)
332 {
333         out = xrealloc_vector(out, 2, out_cnt);
334         return &out[out_cnt++];
335 }
336
337 static const ps_out_t* find_out_spec(const char *name)
338 {
339         unsigned i;
340         for (i = 0; i < ARRAY_SIZE(out_spec); i++) {
341                 if (!strncmp(name, out_spec[i].name6, 6))
342                         return &out_spec[i];
343         }
344         bb_error_msg_and_die("bad -o argument '%s'", name);
345 }
346
347 static void parse_o(char* opt)
348 {
349         ps_out_t* new;
350         // POSIX: "-o is blank- or comma-separated list" (FIXME)
351         char *comma, *equal;
352         while (1) {
353                 comma = strchr(opt, ',');
354                 equal = strchr(opt, '=');
355                 if (comma && (!equal || equal > comma)) {
356                         *comma = '\0';
357                         *new_out_t() = *find_out_spec(opt);
358                         *comma = ',';
359                         opt = comma + 1;
360                         continue;
361                 }
362                 break;
363         }
364         // opt points to last spec in comma separated list.
365         // This one can have =HEADER part.
366         new = new_out_t();
367         if (equal)
368                 *equal = '\0';
369         *new = *find_out_spec(opt);
370         if (equal) {
371                 *equal = '=';
372                 new->header = equal + 1;
373                 // POSIX: the field widths shall be ... at least as wide as
374                 // the header text (default or overridden value).
375                 // If the header text is null, such as -o user=,
376                 // the field width shall be at least as wide as the
377                 // default header text
378                 if (new->header[0]) {
379                         new->width = strlen(new->header);
380                         print_header = 1;
381                 }
382         } else
383                 print_header = 1;
384 }
385
386 static void post_process(void)
387 {
388         int i;
389         int width = 0;
390         for (i = 0; i < out_cnt; i++) {
391                 need_flags |= out[i].ps_flags;
392                 if (out[i].header[0]) {
393                         print_header = 1;
394                 }
395                 width += out[i].width + 1; /* "FIELD " */
396         }
397 #if ENABLE_SELINUX
398         if (!is_selinux_enabled())
399                 need_flags &= ~PSSCAN_CONTEXT;
400 #endif
401         buffer = xmalloc(width + 1); /* for trailing \0 */
402 }
403
404 static void format_header(void)
405 {
406         int i;
407         ps_out_t* op;
408         char *p;
409
410         if (!print_header)
411                 return;
412         p = buffer;
413         i = 0;
414         if (out_cnt) {
415                 while (1) {
416                         op = &out[i];
417                         if (++i == out_cnt) /* do not pad last field */
418                                 break;
419                         p += sprintf(p, "%-*s ", op->width, op->header);
420                 }
421                 strcpy(p, op->header);
422         }
423         printf("%.*s\n", terminal_width, buffer);
424 }
425
426 static void format_process(const procps_status_t *ps)
427 {
428         int i, len;
429         char *p = buffer;
430         i = 0;
431         if (out_cnt) while (1) {
432                 out[i].f(p, out[i].width, ps);
433                 // POSIX: Any field need not be meaningful in all
434                 // implementations. In such a case a hyphen ( '-' )
435                 // should be output in place of the field value.
436                 if (!p[0]) {
437                         p[0] = '-';
438                         p[1] = '\0';
439                 }
440                 len = strlen(p);
441                 p += len;
442                 len = out[i].width - len + 1;
443                 if (++i == out_cnt) /* do not pad last field */
444                         break;
445                 p += sprintf(p, "%*s", len, "");
446         }
447         printf("%.*s\n", terminal_width, buffer);
448 }
449
450 int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
451 int ps_main(int argc UNUSED_PARAM, char **argv)
452 {
453         procps_status_t *p;
454         llist_t* opt_o = NULL;
455         int opt;
456         enum {
457                 OPT_Z = (1 << 0),
458                 OPT_o = (1 << 1),
459                 OPT_a = (1 << 2),
460                 OPT_A = (1 << 3),
461                 OPT_d = (1 << 4),
462                 OPT_e = (1 << 5),
463                 OPT_f = (1 << 6),
464                 OPT_l = (1 << 7),
465                 OPT_T = (1 << 8) * ENABLE_FEATURE_SHOW_THREADS,
466         };
467
468         INIT_G();
469
470         // POSIX:
471         // -a  Write information for all processes associated with terminals
472         //     Implementations may omit session leaders from this list
473         // -A  Write information for all processes
474         // -d  Write information for all processes, except session leaders
475         // -e  Write information for all processes (equivalent to -A)
476         // -f  Generate a full listing
477         // -l  Generate a long listing
478         // -o col1,col2,col3=header
479         //     Select which columns to display
480         /* We allow (and ignore) most of the above. FIXME */
481         opt_complementary = "o::";
482         opt = getopt32(argv, "Zo:aAdefl" IF_FEATURE_SHOW_THREADS("T"), &opt_o);
483         if (opt_o) {
484                 do {
485                         parse_o(llist_pop(&opt_o));
486                 } while (opt_o);
487         } else {
488                 /* Below: parse_o() needs char*, NOT const char*... */
489 #if ENABLE_SELINUX
490                 if (!(opt & OPT_Z) || !is_selinux_enabled()) {
491                         /* no -Z or no SELinux: do not show LABEL */
492                         strcpy(default_o, DEFAULT_O_STR + sizeof(SELINUX_O_PREFIX)-1);
493                 } else
494 #endif
495                 {
496                         strcpy(default_o, DEFAULT_O_STR);
497                 }
498                 parse_o(default_o);
499         }
500         post_process();
501 #if ENABLE_FEATURE_SHOW_THREADS
502         if (opt & OPT_T)
503                 need_flags |= PSSCAN_TASKS;
504 #endif
505
506         /* Was INT_MAX, but some libc's go belly up with printf("%.*s")
507          * and such large widths */
508         terminal_width = MAX_WIDTH;
509         if (isatty(1)) {
510                 get_terminal_width_height(0, &terminal_width, NULL);
511                 if (--terminal_width > MAX_WIDTH)
512                         terminal_width = MAX_WIDTH;
513         }
514         format_header();
515
516         p = NULL;
517         while ((p = procps_scan(p, need_flags)) != NULL) {
518                 format_process(p);
519         }
520
521         return EXIT_SUCCESS;
522 }
523
524
525 #else /* !ENABLE_DESKTOP */
526
527
528 int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
529 int ps_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
530 {
531         procps_status_t *p = NULL;
532         int len;
533         IF_NOT_SELINUX(const) int use_selinux = 0;
534         IF_SELINUX(int i;)
535 #if !ENABLE_FEATURE_PS_WIDE
536         enum { terminal_width = 79 };
537 #else
538         unsigned terminal_width;
539         int w_count = 0;
540 #endif
541
542 #if ENABLE_FEATURE_PS_WIDE || ENABLE_SELINUX
543 #if ENABLE_FEATURE_PS_WIDE
544         opt_complementary = "-:ww";
545         IF_SELINUX(i =) getopt32(argv, IF_SELINUX("Z") "w", &w_count);
546         /* if w is given once, GNU ps sets the width to 132,
547          * if w is given more than once, it is "unlimited"
548          */
549         if (w_count) {
550                 terminal_width = (w_count==1) ? 132 : MAX_WIDTH;
551         } else {
552                 get_terminal_width_height(0, &terminal_width, NULL);
553                 /* Go one less... */
554                 if (--terminal_width > MAX_WIDTH)
555                         terminal_width = MAX_WIDTH;
556         }
557 #else /* only ENABLE_SELINUX */
558         i = getopt32(argv, "Z");
559 #endif
560 #if ENABLE_SELINUX
561         if ((i & 1) && is_selinux_enabled())
562                 use_selinux = PSSCAN_CONTEXT;
563 #endif
564 #endif /* ENABLE_FEATURE_PS_WIDE || ENABLE_SELINUX */
565
566         if (use_selinux)
567                 puts("  PID CONTEXT                          STAT COMMAND");
568         else
569                 puts("  PID USER       VSZ STAT COMMAND");
570
571         while ((p = procps_scan(p, 0
572                         | PSSCAN_PID
573                         | PSSCAN_UIDGID
574                         | PSSCAN_STATE
575                         | PSSCAN_VSZ
576                         | PSSCAN_COMM
577                         | use_selinux
578         )) != NULL) {
579 #if ENABLE_SELINUX
580                 if (use_selinux) {
581                         len = printf("%5u %-32.32s %s  ",
582                                         p->pid,
583                                         p->context ? p->context : "unknown",
584                                         p->state);
585                 } else
586 #endif
587                 {
588                         const char *user = get_cached_username(p->uid);
589                         //if (p->vsz == 0)
590                         //      len = printf("%5u %-8.8s        %s ",
591                         //              p->pid, user, p->state);
592                         //else
593                         {
594                                 char buf6[6];
595                                 smart_ulltoa5(p->vsz, buf6, " mgtpezy");
596                                 buf6[5] = '\0';
597                                 len = printf("%5u %-8.8s %s %s  ",
598                                         p->pid, user, buf6, p->state);
599                         }
600                 }
601
602                 {
603                         int sz = terminal_width - len;
604                         char buf[sz + 1];
605                         read_cmdline(buf, sz, p->pid, p->comm);
606                         puts(buf);
607                 }
608         }
609         if (ENABLE_FEATURE_CLEAN_UP)
610                 clear_username_cache();
611         return EXIT_SUCCESS;
612 }
613
614 #endif /* ENABLE_DESKTOP */