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"
18 //usage: "\n -o COL1,COL2=HEADER Select columns for display"
19 //usage: IF_FEATURE_SHOW_THREADS(
20 //usage: "\n -T Show threads"
23 //usage:#else /* !ENABLE_DESKTOP */
25 //usage:#if !ENABLE_SELINUX && !ENABLE_FEATURE_PS_WIDE
26 //usage:#define USAGE_PS "\nThis version of ps accepts no options"
30 //usage:#define ps_trivial_usage
32 //usage:#define ps_full_usage "\n\n"
33 //usage: "Show list of processes\n"
36 //usage: "\n -Z Show selinux context"
38 //usage: IF_FEATURE_PS_WIDE(
39 //usage: "\n w Wide output"
42 //usage:#endif /* ENABLE_DESKTOP */
44 //usage:#define ps_example_usage
46 //usage: " PID Uid Gid State Command\n"
47 //usage: " 1 root root S init\n"
48 //usage: " 2 root root S [kflushd]\n"
49 //usage: " 3 root root S [kupdate]\n"
50 //usage: " 4 root root S [kpiod]\n"
51 //usage: " 5 root root S [kswapd]\n"
52 //usage: " 742 andersen andersen S [bash]\n"
53 //usage: " 743 andersen andersen S -bash\n"
54 //usage: " 745 root root S [getty]\n"
55 //usage: " 2990 andersen andersen R ps\n"
59 /* Absolute maximum on output line length */
60 enum { MAX_WIDTH = 2*1024 };
64 #include <sys/times.h> /* for times() */
70 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html
71 * specifies (for XSI-conformant systems) following default columns
72 * (l and f mark columns shown with -l and -f respectively):
73 * F l Flags (octal and additive) associated with the process (??)
74 * S l The state of the process
75 * UID f,l The user ID; the login name is printed with -f
77 * PPID f,l The parent process
78 * C f,l Processor utilization
79 * PRI l The priority of the process; higher numbers mean lower priority
81 * ADDR l The address of the process
82 * SZ l The size in blocks of the core image of the process
83 * WCHAN l The event for which the process is waiting or sleeping
84 * STIME f Starting time of the process
85 * TTY The controlling terminal for the process
86 * TIME The cumulative execution time for the process
87 * CMD The command name; the full command line is shown with -f
90 # define SELINUX_O_PREFIX "label,"
91 # define DEFAULT_O_STR (SELINUX_O_PREFIX "pid,user" IF_FEATURE_PS_TIME(",time") ",args")
93 # define DEFAULT_O_STR ("pid,user" IF_FEATURE_PS_TIME(",time") ",args")
100 void (*f)(char *buf, int size, const procps_status_t *ps);
110 unsigned terminal_width;
111 #if ENABLE_FEATURE_PS_TIME
113 unsigned long long seconds_since_boot;
115 char default_o[sizeof(DEFAULT_O_STR)];
117 #define G (*(struct globals*)&bb_common_bufsiz1)
119 #define out_cnt (G.out_cnt )
120 #define print_header (G.print_header )
121 #define need_flags (G.need_flags )
122 #define buffer (G.buffer )
123 #define terminal_width (G.terminal_width )
124 #define kernel_HZ (G.kernel_HZ )
125 #define seconds_since_boot (G.seconds_since_boot)
126 #define default_o (G.default_o )
127 #define INIT_G() do { } while (0)
129 #if ENABLE_FEATURE_PS_TIME
130 /* for ELF executables, notes are pushed before environment and args */
131 static ptrdiff_t find_elf_note(ptrdiff_t findme)
133 ptrdiff_t *ep = (ptrdiff_t *) environ;
138 if (ep[0] == findme) {
146 #if ENABLE_FEATURE_PS_UNUSUAL_SYSTEMS
147 static unsigned get_HZ_by_waiting(void)
149 struct timeval tv1, tv2;
150 unsigned t1, t2, r, hz;
151 unsigned cnt = cnt; /* for compiler */
156 /* Wait for times() to reach new tick */
161 gettimeofday(&tv2, NULL);
165 tv1.tv_usec = tv2.tv_usec;
167 /* Wait exactly one times() tick */
171 gettimeofday(&tv2, NULL);
173 /* Calculate ticks per sec, rounding up to even */
174 diff = tv2.tv_usec - tv1.tv_usec;
175 if (diff <= 0) diff += 1000000;
176 hz = 1000000u / (unsigned)diff;
179 /* Count how many same hz values we saw */
185 } while (cnt < 3); /* exit if saw 3 same values */
190 static inline unsigned get_HZ_by_waiting(void)
197 static unsigned get_kernel_HZ(void)
205 /* Works for ELF only, Linux 2.4.0+ */
206 kernel_HZ = find_elf_note(AT_CLKTCK);
207 if (kernel_HZ == (unsigned)-1)
208 kernel_HZ = get_HZ_by_waiting();
210 //if (open_read_close("/proc/uptime", buf, sizeof(buf)) <= 0)
211 // bb_perror_msg_and_die("can't read %s", "/proc/uptime");
212 //buf[sizeof(buf)-1] = '\0';
213 ///sscanf(buf, "%llu", &seconds_since_boot);
215 seconds_since_boot = info.uptime;
221 /* Print value to buf, max size+1 chars (including trailing '\0') */
223 static void func_user(char *buf, int size, const procps_status_t *ps)
226 safe_strncpy(buf, get_cached_username(ps->uid), size+1);
228 /* "compatible" version, but it's larger */
229 /* procps 2.18 shows numeric UID if name overflows the field */
230 /* TODO: get_cached_username() returns numeric string if
231 * user has no passwd record, we will display it
232 * left-justified here; too long usernames are shown
233 * as _right-justified_ IDs. Is it worth fixing? */
234 const char *user = get_cached_username(ps->uid);
235 if (strlen(user) <= size)
236 safe_strncpy(buf, user, size+1);
238 sprintf(buf, "%*u", size, (unsigned)ps->uid);
242 static void func_group(char *buf, int size, const procps_status_t *ps)
244 safe_strncpy(buf, get_cached_groupname(ps->gid), size+1);
247 static void func_comm(char *buf, int size, const procps_status_t *ps)
249 safe_strncpy(buf, ps->comm, size+1);
252 static void func_stat(char *buf, int size, const procps_status_t *ps)
254 safe_strncpy(buf, ps->state, size+1);
257 static void func_args(char *buf, int size, const procps_status_t *ps)
259 read_cmdline(buf, size+1, ps->pid, ps->comm);
262 static void func_pid(char *buf, int size, const procps_status_t *ps)
264 sprintf(buf, "%*u", size, ps->pid);
267 static void func_ppid(char *buf, int size, const procps_status_t *ps)
269 sprintf(buf, "%*u", size, ps->ppid);
272 static void func_pgid(char *buf, int size, const procps_status_t *ps)
274 sprintf(buf, "%*u", size, ps->pgid);
277 static void put_lu(char *buf, int size, unsigned long u)
281 /* see http://en.wikipedia.org/wiki/Tera */
282 smart_ulltoa4(u, buf4, " mgtpezy");
284 sprintf(buf, "%.*s", size, buf4);
287 static void func_vsz(char *buf, int size, const procps_status_t *ps)
289 put_lu(buf, size, ps->vsz);
292 static void func_rss(char *buf, int size, const procps_status_t *ps)
294 put_lu(buf, size, ps->rss);
297 static void func_tty(char *buf, int size, const procps_status_t *ps)
301 if (ps->tty_major) /* tty field of "0" means "no tty" */
302 snprintf(buf, size+1, "%u,%u", ps->tty_major, ps->tty_minor);
305 #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
307 static void func_rgroup(char *buf, int size, const procps_status_t *ps)
309 safe_strncpy(buf, get_cached_groupname(ps->rgid), size+1);
312 static void func_ruser(char *buf, int size, const procps_status_t *ps)
314 safe_strncpy(buf, get_cached_username(ps->ruid), size+1);
317 static void func_nice(char *buf, int size, const procps_status_t *ps)
319 sprintf(buf, "%*d", size, ps->niceness);
324 #if ENABLE_FEATURE_PS_TIME
326 static void func_etime(char *buf, int size, const procps_status_t *ps)
328 /* elapsed time [[dd-]hh:]mm:ss; here only mm:ss */
332 mm = ps->start_time / get_kernel_HZ();
333 /* must be after get_kernel_HZ()! */
334 mm = seconds_since_boot - mm;
337 snprintf(buf, size+1, "%3lu:%02u", mm, ss);
340 static void func_time(char *buf, int size, const procps_status_t *ps)
342 /* cumulative time [[dd-]hh:]mm:ss; here only mm:ss */
346 mm = (ps->utime + ps->stime) / get_kernel_HZ();
349 snprintf(buf, size+1, "%3lu:%02u", mm, ss);
355 static void func_label(char *buf, int size, const procps_status_t *ps)
357 safe_strncpy(buf, ps->context ? ps->context : "unknown", size+1);
362 static void func_nice(char *buf, int size, const procps_status_t *ps)
367 static void func_pcpu(char *buf, int size, const procps_status_t *ps)
372 static const ps_out_t out_spec[] = {
373 /* Mandated by http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html: */
374 { 8 , "user" ,"USER" ,func_user ,PSSCAN_UIDGID },
375 { 8 , "group" ,"GROUP" ,func_group ,PSSCAN_UIDGID },
376 { 16 , "comm" ,"COMMAND",func_comm ,PSSCAN_COMM },
377 { MAX_WIDTH , "args" ,"COMMAND",func_args ,PSSCAN_COMM },
378 { 5 , "pid" ,"PID" ,func_pid ,PSSCAN_PID },
379 { 5 , "ppid" ,"PPID" ,func_ppid ,PSSCAN_PPID },
380 { 5 , "pgid" ,"PGID" ,func_pgid ,PSSCAN_PGID },
381 #if ENABLE_FEATURE_PS_TIME
382 { sizeof("ELAPSED")-1, "etime" ,"ELAPSED",func_etime ,PSSCAN_START_TIME },
384 #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
385 { 5 , "nice" ,"NI" ,func_nice ,PSSCAN_NICE },
386 { 8 , "rgroup","RGROUP" ,func_rgroup,PSSCAN_RUIDGID },
387 { 8 , "ruser" ,"RUSER" ,func_ruser ,PSSCAN_RUIDGID },
388 // { 5 , "pcpu" ,"%CPU" ,func_pcpu ,PSSCAN_ },
390 #if ENABLE_FEATURE_PS_TIME
391 { 6 , "time" ,"TIME" ,func_time ,PSSCAN_STIME | PSSCAN_UTIME },
393 { 6 , "tty" ,"TT" ,func_tty ,PSSCAN_TTY },
394 { 4 , "vsz" ,"VSZ" ,func_vsz ,PSSCAN_VSZ },
395 /* Not mandated, but useful: */
396 { 4 , "stat" ,"STAT" ,func_stat ,PSSCAN_STAT },
397 { 4 , "rss" ,"RSS" ,func_rss ,PSSCAN_RSS },
399 { 35 , "label" ,"LABEL" ,func_label ,PSSCAN_CONTEXT },
403 static ps_out_t* new_out_t(void)
405 out = xrealloc_vector(out, 2, out_cnt);
406 return &out[out_cnt++];
409 static const ps_out_t* find_out_spec(const char *name)
412 char buf[ARRAY_SIZE(out_spec)*7 + 1];
415 for (i = 0; i < ARRAY_SIZE(out_spec); i++) {
416 if (strncmp(name, out_spec[i].name6, 6) == 0)
418 p += sprintf(p, "%.6s,", out_spec[i].name6);
421 bb_error_msg_and_die("bad -o argument '%s', supported arguments: %s", name, buf);
424 static void parse_o(char* opt)
427 // POSIX: "-o is blank- or comma-separated list" (FIXME)
430 comma = strchr(opt, ',');
431 equal = strchr(opt, '=');
432 if (comma && (!equal || equal > comma)) {
434 *new_out_t() = *find_out_spec(opt);
441 // opt points to last spec in comma separated list.
442 // This one can have =HEADER part.
446 *new = *find_out_spec(opt);
449 new->header = equal + 1;
450 // POSIX: the field widths shall be ... at least as wide as
451 // the header text (default or overridden value).
452 // If the header text is null, such as -o user=,
453 // the field width shall be at least as wide as the
454 // default header text
455 if (new->header[0]) {
456 new->width = strlen(new->header);
463 static void alloc_line_buffer(void)
467 for (i = 0; i < out_cnt; i++) {
468 need_flags |= out[i].ps_flags;
469 if (out[i].header[0]) {
472 width += out[i].width + 1; /* "FIELD " */
473 if ((int)(width - terminal_width) > 0) {
474 /* The rest does not fit on the screen */
475 //out[i].width -= (width - terminal_width - 1);
481 if (!is_selinux_enabled())
482 need_flags &= ~PSSCAN_CONTEXT;
484 buffer = xmalloc(width + 1); /* for trailing \0 */
487 static void format_header(void)
500 if (++i == out_cnt) /* do not pad last field */
502 p += sprintf(p, "%-*s ", op->width, op->header);
504 strcpy(p, op->header);
506 printf("%.*s\n", terminal_width, buffer);
509 static void format_process(const procps_status_t *ps)
514 if (out_cnt) while (1) {
515 out[i].f(p, out[i].width, ps);
516 // POSIX: Any field need not be meaningful in all
517 // implementations. In such a case a hyphen ( '-' )
518 // should be output in place of the field value.
525 len = out[i].width - len + 1;
526 if (++i == out_cnt) /* do not pad last field */
528 p += sprintf(p, "%*s", len, "");
530 printf("%.*s\n", terminal_width, buffer);
533 int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
534 int ps_main(int argc UNUSED_PARAM, char **argv)
537 llist_t* opt_o = NULL;
548 OPT_T = (1 << 8) * ENABLE_FEATURE_SHOW_THREADS,
554 // -a Write information for all processes associated with terminals
555 // Implementations may omit session leaders from this list
556 // -A Write information for all processes
557 // -d Write information for all processes, except session leaders
558 // -e Write information for all processes (equivalent to -A)
559 // -f Generate a full listing
560 // -l Generate a long listing
561 // -o col1,col2,col3=header
562 // Select which columns to display
563 /* We allow (and ignore) most of the above. FIXME.
564 * -T is picked for threads (POSIX hasn't it standardized).
565 * procps v3.2.7 supports -T and shows tids as SPID column,
566 * it also supports -L where it shows tids as LWP column.
568 opt_complementary = "o::";
569 opt = getopt32(argv, "Zo:aAdefl"IF_FEATURE_SHOW_THREADS("T"), &opt_o);
572 parse_o(llist_pop(&opt_o));
575 /* Below: parse_o() needs char*, NOT const char*... */
577 if (!(opt & OPT_Z) || !is_selinux_enabled()) {
578 /* no -Z or no SELinux: do not show LABEL */
579 strcpy(default_o, DEFAULT_O_STR + sizeof(SELINUX_O_PREFIX)-1);
583 strcpy(default_o, DEFAULT_O_STR);
587 #if ENABLE_FEATURE_SHOW_THREADS
589 need_flags |= PSSCAN_TASKS;
592 /* Was INT_MAX, but some libc's go belly up with printf("%.*s")
593 * and such large widths */
594 terminal_width = MAX_WIDTH;
596 get_terminal_width_height(0, &terminal_width, NULL);
597 if (--terminal_width > MAX_WIDTH)
598 terminal_width = MAX_WIDTH;
604 while ((p = procps_scan(p, need_flags)) != NULL) {
612 #else /* !ENABLE_DESKTOP */
615 int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
616 int ps_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
619 int psscan_flags = PSSCAN_PID | PSSCAN_UIDGID
620 | PSSCAN_STATE | PSSCAN_VSZ | PSSCAN_COMM;
621 unsigned terminal_width IF_NOT_FEATURE_PS_WIDE(= 79);
623 OPT_Z = (1 << 0) * ENABLE_SELINUX,
624 OPT_T = (1 << ENABLE_SELINUX) * ENABLE_FEATURE_SHOW_THREADS,
627 /* If we support any options, parse argv */
628 #if ENABLE_SELINUX || ENABLE_FEATURE_SHOW_THREADS || ENABLE_FEATURE_PS_WIDE
629 # if ENABLE_FEATURE_PS_WIDE
630 /* -w is a bit complicated */
632 opt_complementary = "-:ww";
633 opts = getopt32(argv, IF_SELINUX("Z")IF_FEATURE_SHOW_THREADS("T")"w", &w_count);
634 /* if w is given once, GNU ps sets the width to 132,
635 * if w is given more than once, it is "unlimited"
638 terminal_width = (w_count == 1) ? 132 : MAX_WIDTH;
640 get_terminal_width_height(0, &terminal_width, NULL);
642 if (--terminal_width > MAX_WIDTH)
643 terminal_width = MAX_WIDTH;
646 /* -w is not supported, only -Z and/or -T */
647 opt_complementary = "-";
648 opts = getopt32(argv, IF_SELINUX("Z")IF_FEATURE_SHOW_THREADS("T"));
653 if ((opts & OPT_Z) && is_selinux_enabled()) {
654 psscan_flags = PSSCAN_PID | PSSCAN_CONTEXT
655 | PSSCAN_STATE | PSSCAN_COMM;
656 puts(" PID CONTEXT STAT COMMAND");
660 puts(" PID USER VSZ STAT COMMAND");
663 psscan_flags |= PSSCAN_TASKS;
667 while ((p = procps_scan(p, psscan_flags)) != NULL) {
670 if (psscan_flags & PSSCAN_CONTEXT) {
671 len = printf("%5u %-32.32s %s ",
673 p->context ? p->context : "unknown",
678 const char *user = get_cached_username(p->uid);
680 // len = printf("%5u %-8.8s %s ",
681 // p->pid, user, p->state);
685 smart_ulltoa5(p->vsz, buf6, " mgtpezy");
687 len = printf("%5u %-8.8s %s %s ",
688 p->pid, user, buf6, p->state);
693 int sz = terminal_width - len;
695 read_cmdline(buf, sz, p->pid, p->comm);
699 if (ENABLE_FEATURE_CLEAN_UP)
700 clear_username_cache();
704 #endif /* !ENABLE_DESKTOP */