1 /* vi: set sw=4 ts=4: */
3 * Mini ps implementation(s) for busybox
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>
9 * Licensed under GPLv2, see file LICENSE in this source tree.
12 //usage:#if ENABLE_DESKTOP
14 //usage:#define ps_trivial_usage
15 //usage: "[-o COL1,COL2=HEADER]" IF_FEATURE_SHOW_THREADS(" [-T]")
16 //usage:#define ps_full_usage "\n\n"
17 //usage: "Show list of processes\n"
19 //usage: "\n -o COL1,COL2=HEADER Select columns for display"
20 //usage: IF_FEATURE_SHOW_THREADS(
21 //usage: "\n -T Show threads"
24 //usage:#else /* !ENABLE_DESKTOP */
26 //usage:#if !ENABLE_SELINUX && !ENABLE_FEATURE_PS_WIDE
27 //usage:#define USAGE_PS "\nThis version of ps accepts no options"
29 //usage:#define USAGE_PS "\nOptions:"
32 //usage:#define ps_trivial_usage
34 //usage:#define ps_full_usage "\n\n"
35 //usage: "Show list of processes\n"
38 //usage: "\n -Z Show selinux context"
40 //usage: IF_FEATURE_PS_WIDE(
41 //usage: "\n w Wide output"
44 //usage:#endif /* ENABLE_DESKTOP */
46 //usage:#define ps_example_usage
48 //usage: " PID Uid Gid State Command\n"
49 //usage: " 1 root root S init\n"
50 //usage: " 2 root root S [kflushd]\n"
51 //usage: " 3 root root S [kupdate]\n"
52 //usage: " 4 root root S [kpiod]\n"
53 //usage: " 5 root root S [kswapd]\n"
54 //usage: " 742 andersen andersen S [bash]\n"
55 //usage: " 743 andersen andersen S -bash\n"
56 //usage: " 745 root root S [getty]\n"
57 //usage: " 2990 andersen andersen R ps\n"
61 /* Absolute maximum on output line length */
62 enum { MAX_WIDTH = 2*1024 };
66 #include <sys/times.h> /* for times() */
72 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html
73 * specifies (for XSI-conformant systems) following default columns
74 * (l and f mark columns shown with -l and -f respectively):
75 * F l Flags (octal and additive) associated with the process (??)
76 * S l The state of the process
77 * UID f,l The user ID; the login name is printed with -f
79 * PPID f,l The parent process
80 * C f,l Processor utilization
81 * PRI l The priority of the process; higher numbers mean lower priority
83 * ADDR l The address of the process
84 * SZ l The size in blocks of the core image of the process
85 * WCHAN l The event for which the process is waiting or sleeping
86 * STIME f Starting time of the process
87 * TTY The controlling terminal for the process
88 * TIME The cumulative execution time for the process
89 * CMD The command name; the full command line is shown with -f
92 # define SELINUX_O_PREFIX "label,"
93 # define DEFAULT_O_STR (SELINUX_O_PREFIX "pid,user" IF_FEATURE_PS_TIME(",time") ",args")
95 # define DEFAULT_O_STR ("pid,user" IF_FEATURE_PS_TIME(",time") ",args")
102 void (*f)(char *buf, int size, const procps_status_t *ps);
112 unsigned terminal_width;
113 #if ENABLE_FEATURE_PS_TIME
115 unsigned long long seconds_since_boot;
117 char default_o[sizeof(DEFAULT_O_STR)];
119 #define G (*(struct globals*)&bb_common_bufsiz1)
121 #define out_cnt (G.out_cnt )
122 #define print_header (G.print_header )
123 #define need_flags (G.need_flags )
124 #define buffer (G.buffer )
125 #define terminal_width (G.terminal_width )
126 #define kernel_HZ (G.kernel_HZ )
127 #define seconds_since_boot (G.seconds_since_boot)
128 #define default_o (G.default_o )
129 #define INIT_G() do { } while (0)
131 #if ENABLE_FEATURE_PS_TIME
132 /* for ELF executables, notes are pushed before environment and args */
133 static ptrdiff_t find_elf_note(ptrdiff_t findme)
135 ptrdiff_t *ep = (ptrdiff_t *) environ;
140 if (ep[0] == findme) {
148 #if ENABLE_FEATURE_PS_UNUSUAL_SYSTEMS
149 static unsigned get_HZ_by_waiting(void)
151 struct timeval tv1, tv2;
152 unsigned t1, t2, r, hz;
153 unsigned cnt = cnt; /* for compiler */
158 /* Wait for times() to reach new tick */
163 gettimeofday(&tv2, NULL);
167 tv1.tv_usec = tv2.tv_usec;
169 /* Wait exactly one times() tick */
173 gettimeofday(&tv2, NULL);
175 /* Calculate ticks per sec, rounding up to even */
176 diff = tv2.tv_usec - tv1.tv_usec;
177 if (diff <= 0) diff += 1000000;
178 hz = 1000000u / (unsigned)diff;
181 /* Count how many same hz values we saw */
187 } while (cnt < 3); /* exit if saw 3 same values */
192 static inline unsigned get_HZ_by_waiting(void)
199 static unsigned get_kernel_HZ(void)
207 /* Works for ELF only, Linux 2.4.0+ */
208 kernel_HZ = find_elf_note(AT_CLKTCK);
209 if (kernel_HZ == (unsigned)-1)
210 kernel_HZ = get_HZ_by_waiting();
212 //if (open_read_close("/proc/uptime", buf, sizeof(buf)) <= 0)
213 // bb_perror_msg_and_die("can't read %s", "/proc/uptime");
214 //buf[sizeof(buf)-1] = '\0';
215 ///sscanf(buf, "%llu", &seconds_since_boot);
217 seconds_since_boot = info.uptime;
223 /* Print value to buf, max size+1 chars (including trailing '\0') */
225 static void func_user(char *buf, int size, const procps_status_t *ps)
228 safe_strncpy(buf, get_cached_username(ps->uid), size+1);
230 /* "compatible" version, but it's larger */
231 /* procps 2.18 shows numeric UID if name overflows the field */
232 /* TODO: get_cached_username() returns numeric string if
233 * user has no passwd record, we will display it
234 * left-justified here; too long usernames are shown
235 * as _right-justified_ IDs. Is it worth fixing? */
236 const char *user = get_cached_username(ps->uid);
237 if (strlen(user) <= size)
238 safe_strncpy(buf, user, size+1);
240 sprintf(buf, "%*u", size, (unsigned)ps->uid);
244 static void func_group(char *buf, int size, const procps_status_t *ps)
246 safe_strncpy(buf, get_cached_groupname(ps->gid), size+1);
249 static void func_comm(char *buf, int size, const procps_status_t *ps)
251 safe_strncpy(buf, ps->comm, size+1);
254 static void func_stat(char *buf, int size, const procps_status_t *ps)
256 safe_strncpy(buf, ps->state, size+1);
259 static void func_args(char *buf, int size, const procps_status_t *ps)
261 read_cmdline(buf, size+1, ps->pid, ps->comm);
264 static void func_pid(char *buf, int size, const procps_status_t *ps)
266 sprintf(buf, "%*u", size, ps->pid);
269 static void func_ppid(char *buf, int size, const procps_status_t *ps)
271 sprintf(buf, "%*u", size, ps->ppid);
274 static void func_pgid(char *buf, int size, const procps_status_t *ps)
276 sprintf(buf, "%*u", size, ps->pgid);
279 static void put_lu(char *buf, int size, unsigned long u)
283 /* see http://en.wikipedia.org/wiki/Tera */
284 smart_ulltoa4(u, buf4, " mgtpezy");
286 sprintf(buf, "%.*s", size, buf4);
289 static void func_vsz(char *buf, int size, const procps_status_t *ps)
291 put_lu(buf, size, ps->vsz);
294 static void func_rss(char *buf, int size, const procps_status_t *ps)
296 put_lu(buf, size, ps->rss);
299 static void func_tty(char *buf, int size, const procps_status_t *ps)
303 if (ps->tty_major) /* tty field of "0" means "no tty" */
304 snprintf(buf, size+1, "%u,%u", ps->tty_major, ps->tty_minor);
307 #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
309 static void func_rgroup(char *buf, int size, const procps_status_t *ps)
311 safe_strncpy(buf, get_cached_groupname(ps->rgid), size+1);
314 static void func_ruser(char *buf, int size, const procps_status_t *ps)
316 safe_strncpy(buf, get_cached_username(ps->ruid), size+1);
319 static void func_nice(char *buf, int size, const procps_status_t *ps)
321 sprintf(buf, "%*d", size, ps->niceness);
326 #if ENABLE_FEATURE_PS_TIME
328 static void func_etime(char *buf, int size, const procps_status_t *ps)
330 /* elapsed time [[dd-]hh:]mm:ss; here only mm:ss */
334 mm = ps->start_time / get_kernel_HZ();
335 /* must be after get_kernel_HZ()! */
336 mm = seconds_since_boot - mm;
339 snprintf(buf, size+1, "%3lu:%02u", mm, ss);
342 static void func_time(char *buf, int size, const procps_status_t *ps)
344 /* cumulative time [[dd-]hh:]mm:ss; here only mm:ss */
348 mm = (ps->utime + ps->stime) / get_kernel_HZ();
351 snprintf(buf, size+1, "%3lu:%02u", mm, ss);
357 static void func_label(char *buf, int size, const procps_status_t *ps)
359 safe_strncpy(buf, ps->context ? ps->context : "unknown", size+1);
364 static void func_nice(char *buf, int size, const procps_status_t *ps)
369 static void func_pcpu(char *buf, int size, const procps_status_t *ps)
374 static const ps_out_t out_spec[] = {
375 /* Mandated by http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html: */
376 { 8 , "user" ,"USER" ,func_user ,PSSCAN_UIDGID },
377 { 8 , "group" ,"GROUP" ,func_group ,PSSCAN_UIDGID },
378 { 16 , "comm" ,"COMMAND",func_comm ,PSSCAN_COMM },
379 { MAX_WIDTH , "args" ,"COMMAND",func_args ,PSSCAN_COMM },
380 { 5 , "pid" ,"PID" ,func_pid ,PSSCAN_PID },
381 { 5 , "ppid" ,"PPID" ,func_ppid ,PSSCAN_PPID },
382 { 5 , "pgid" ,"PGID" ,func_pgid ,PSSCAN_PGID },
383 #if ENABLE_FEATURE_PS_TIME
384 { sizeof("ELAPSED")-1, "etime" ,"ELAPSED",func_etime ,PSSCAN_START_TIME },
386 #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
387 { 5 , "nice" ,"NI" ,func_nice ,PSSCAN_NICE },
388 { 8 , "rgroup","RGROUP" ,func_rgroup,PSSCAN_RUIDGID },
389 { 8 , "ruser" ,"RUSER" ,func_ruser ,PSSCAN_RUIDGID },
390 // { 5 , "pcpu" ,"%CPU" ,func_pcpu ,PSSCAN_ },
392 #if ENABLE_FEATURE_PS_TIME
393 { 6 , "time" ,"TIME" ,func_time ,PSSCAN_STIME | PSSCAN_UTIME },
395 { 6 , "tty" ,"TT" ,func_tty ,PSSCAN_TTY },
396 { 4 , "vsz" ,"VSZ" ,func_vsz ,PSSCAN_VSZ },
397 /* Not mandated, but useful: */
398 { 4 , "stat" ,"STAT" ,func_stat ,PSSCAN_STAT },
399 { 4 , "rss" ,"RSS" ,func_rss ,PSSCAN_RSS },
401 { 35 , "label" ,"LABEL" ,func_label ,PSSCAN_CONTEXT },
405 static ps_out_t* new_out_t(void)
407 out = xrealloc_vector(out, 2, out_cnt);
408 return &out[out_cnt++];
411 static const ps_out_t* find_out_spec(const char *name)
414 char buf[ARRAY_SIZE(out_spec)*7 + 1];
417 for (i = 0; i < ARRAY_SIZE(out_spec); i++) {
418 if (strncmp(name, out_spec[i].name6, 6) == 0)
420 p += sprintf(p, "%.6s,", out_spec[i].name6);
423 bb_error_msg_and_die("bad -o argument '%s', supported arguments: %s", name, buf);
426 static void parse_o(char* opt)
429 // POSIX: "-o is blank- or comma-separated list" (FIXME)
432 comma = strchr(opt, ',');
433 equal = strchr(opt, '=');
434 if (comma && (!equal || equal > comma)) {
436 *new_out_t() = *find_out_spec(opt);
443 // opt points to last spec in comma separated list.
444 // This one can have =HEADER part.
448 *new = *find_out_spec(opt);
451 new->header = equal + 1;
452 // POSIX: the field widths shall be ... at least as wide as
453 // the header text (default or overridden value).
454 // If the header text is null, such as -o user=,
455 // the field width shall be at least as wide as the
456 // default header text
457 if (new->header[0]) {
458 new->width = strlen(new->header);
465 static void alloc_line_buffer(void)
469 for (i = 0; i < out_cnt; i++) {
470 need_flags |= out[i].ps_flags;
471 if (out[i].header[0]) {
474 width += out[i].width + 1; /* "FIELD " */
475 if ((int)(width - terminal_width) > 0) {
476 /* The rest does not fit on the screen */
477 //out[i].width -= (width - terminal_width - 1);
483 if (!is_selinux_enabled())
484 need_flags &= ~PSSCAN_CONTEXT;
486 buffer = xmalloc(width + 1); /* for trailing \0 */
489 static void format_header(void)
502 if (++i == out_cnt) /* do not pad last field */
504 p += sprintf(p, "%-*s ", op->width, op->header);
506 strcpy(p, op->header);
508 printf("%.*s\n", terminal_width, buffer);
511 static void format_process(const procps_status_t *ps)
516 if (out_cnt) while (1) {
517 out[i].f(p, out[i].width, ps);
518 // POSIX: Any field need not be meaningful in all
519 // implementations. In such a case a hyphen ( '-' )
520 // should be output in place of the field value.
527 len = out[i].width - len + 1;
528 if (++i == out_cnt) /* do not pad last field */
530 p += sprintf(p, "%*s", len, "");
532 printf("%.*s\n", terminal_width, buffer);
535 int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
536 int ps_main(int argc UNUSED_PARAM, char **argv)
539 llist_t* opt_o = NULL;
550 OPT_T = (1 << 8) * ENABLE_FEATURE_SHOW_THREADS,
556 // -a Write information for all processes associated with terminals
557 // Implementations may omit session leaders from this list
558 // -A Write information for all processes
559 // -d Write information for all processes, except session leaders
560 // -e Write information for all processes (equivalent to -A)
561 // -f Generate a full listing
562 // -l Generate a long listing
563 // -o col1,col2,col3=header
564 // Select which columns to display
565 /* We allow (and ignore) most of the above. FIXME.
566 * -T is picked for threads (POSIX hasn't it standardized).
567 * procps v3.2.7 supports -T and shows tids as SPID column,
568 * it also supports -L where it shows tids as LWP column.
570 opt_complementary = "o::";
571 opt = getopt32(argv, "Zo:aAdefl"IF_FEATURE_SHOW_THREADS("T"), &opt_o);
574 parse_o(llist_pop(&opt_o));
577 /* Below: parse_o() needs char*, NOT const char*... */
579 if (!(opt & OPT_Z) || !is_selinux_enabled()) {
580 /* no -Z or no SELinux: do not show LABEL */
581 strcpy(default_o, DEFAULT_O_STR + sizeof(SELINUX_O_PREFIX)-1);
585 strcpy(default_o, DEFAULT_O_STR);
589 #if ENABLE_FEATURE_SHOW_THREADS
591 need_flags |= PSSCAN_TASKS;
594 /* Was INT_MAX, but some libc's go belly up with printf("%.*s")
595 * and such large widths */
596 terminal_width = MAX_WIDTH;
598 get_terminal_width_height(0, &terminal_width, NULL);
599 if (--terminal_width > MAX_WIDTH)
600 terminal_width = MAX_WIDTH;
606 while ((p = procps_scan(p, need_flags)) != NULL) {
614 #else /* !ENABLE_DESKTOP */
617 int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
618 int ps_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
621 int psscan_flags = PSSCAN_PID | PSSCAN_UIDGID
622 | PSSCAN_STATE | PSSCAN_VSZ | PSSCAN_COMM;
623 unsigned terminal_width IF_NOT_FEATURE_PS_WIDE(= 79);
625 OPT_Z = (1 << 0) * ENABLE_SELINUX,
626 OPT_T = (1 << ENABLE_SELINUX) * ENABLE_FEATURE_SHOW_THREADS,
629 /* If we support any options, parse argv */
630 #if ENABLE_SELINUX || ENABLE_FEATURE_SHOW_THREADS || ENABLE_FEATURE_PS_WIDE
631 # if ENABLE_FEATURE_PS_WIDE
632 /* -w is a bit complicated */
634 opt_complementary = "-:ww";
635 opts = getopt32(argv, IF_SELINUX("Z")IF_FEATURE_SHOW_THREADS("T")"w", &w_count);
636 /* if w is given once, GNU ps sets the width to 132,
637 * if w is given more than once, it is "unlimited"
640 terminal_width = (w_count == 1) ? 132 : MAX_WIDTH;
642 get_terminal_width_height(0, &terminal_width, NULL);
644 if (--terminal_width > MAX_WIDTH)
645 terminal_width = MAX_WIDTH;
648 /* -w is not supported, only -Z and/or -T */
649 opt_complementary = "-";
650 opts = getopt32(argv, IF_SELINUX("Z")IF_FEATURE_SHOW_THREADS("T"));
655 if ((opts & OPT_Z) && is_selinux_enabled()) {
656 psscan_flags = PSSCAN_PID | PSSCAN_CONTEXT
657 | PSSCAN_STATE | PSSCAN_COMM;
658 puts(" PID CONTEXT STAT COMMAND");
662 puts(" PID USER VSZ STAT COMMAND");
665 psscan_flags |= PSSCAN_TASKS;
669 while ((p = procps_scan(p, psscan_flags)) != NULL) {
672 if (psscan_flags & PSSCAN_CONTEXT) {
673 len = printf("%5u %-32.32s %s ",
675 p->context ? p->context : "unknown",
680 const char *user = get_cached_username(p->uid);
682 // len = printf("%5u %-8.8s %s ",
683 // p->pid, user, p->state);
687 smart_ulltoa5(p->vsz, buf6, " mgtpezy");
689 len = printf("%5u %-8.8s %s %s ",
690 p->pid, user, buf6, p->state);
695 int sz = terminal_width - len;
697 read_cmdline(buf, sz, p->pid, p->comm);
701 if (ENABLE_FEATURE_CLEAN_UP)
702 clear_username_cache();
706 #endif /* !ENABLE_DESKTOP */