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