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.
14 /* Absolute maximum on output line length */
15 enum { MAX_WIDTH = 2*1024 };
19 #include <sys/times.h> /* for times() */
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
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
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
45 # define SELINUX_O_PREFIX "label,"
46 # define DEFAULT_O_STR (SELINUX_O_PREFIX "pid,user" IF_FEATURE_PS_TIME(",time") ",args")
48 # define DEFAULT_O_STR ("pid,user" IF_FEATURE_PS_TIME(",time") ",args")
55 void (*f)(char *buf, int size, const procps_status_t *ps);
65 unsigned terminal_width;
66 #if ENABLE_FEATURE_PS_TIME
68 unsigned long long seconds_since_boot;
70 char default_o[sizeof(DEFAULT_O_STR)];
72 #define G (*(struct globals*)&bb_common_bufsiz1)
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)
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)
88 ptrdiff_t *ep = (ptrdiff_t *) environ;
93 if (ep[0] == findme) {
101 #if ENABLE_FEATURE_PS_UNUSUAL_SYSTEMS
102 static unsigned get_HZ_by_waiting(void)
104 struct timeval tv1, tv2;
105 unsigned t1, t2, r, hz;
106 unsigned cnt = cnt; /* for compiler */
111 /* Wait for times() to reach new tick */
116 gettimeofday(&tv2, NULL);
120 tv1.tv_usec = tv2.tv_usec;
122 /* Wait exactly one times() tick */
126 gettimeofday(&tv2, NULL);
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;
134 /* Count how many same hz values we saw */
140 } while (cnt < 3); /* exit if saw 3 same values */
145 static inline unsigned get_HZ_by_waiting(void)
152 static unsigned get_kernel_HZ(void)
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();
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);
170 seconds_since_boot = info.uptime;
176 /* Print value to buf, max size+1 chars (including trailing '\0') */
178 static void func_user(char *buf, int size, const procps_status_t *ps)
181 safe_strncpy(buf, get_cached_username(ps->uid), size+1);
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);
193 sprintf(buf, "%*u", size, (unsigned)ps->uid);
197 static void func_group(char *buf, int size, const procps_status_t *ps)
199 safe_strncpy(buf, get_cached_groupname(ps->gid), size+1);
202 static void func_comm(char *buf, int size, const procps_status_t *ps)
204 safe_strncpy(buf, ps->comm, size+1);
207 static void func_stat(char *buf, int size, const procps_status_t *ps)
209 safe_strncpy(buf, ps->state, size+1);
212 static void func_args(char *buf, int size, const procps_status_t *ps)
214 read_cmdline(buf, size+1, ps->pid, ps->comm);
217 static void func_pid(char *buf, int size, const procps_status_t *ps)
219 sprintf(buf, "%*u", size, ps->pid);
222 static void func_ppid(char *buf, int size, const procps_status_t *ps)
224 sprintf(buf, "%*u", size, ps->ppid);
227 static void func_pgid(char *buf, int size, const procps_status_t *ps)
229 sprintf(buf, "%*u", size, ps->pgid);
232 static void put_lu(char *buf, int size, unsigned long u)
236 /* see http://en.wikipedia.org/wiki/Tera */
237 smart_ulltoa4(u, buf4, " mgtpezy");
239 sprintf(buf, "%.*s", size, buf4);
242 static void func_vsz(char *buf, int size, const procps_status_t *ps)
244 put_lu(buf, size, ps->vsz);
247 static void func_rss(char *buf, int size, const procps_status_t *ps)
249 put_lu(buf, size, ps->rss);
252 static void func_tty(char *buf, int size, const procps_status_t *ps)
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);
260 #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
262 static void func_rgroup(char *buf, int size, const procps_status_t *ps)
264 safe_strncpy(buf, get_cached_groupname(ps->rgid), size+1);
267 static void func_ruser(char *buf, int size, const procps_status_t *ps)
269 safe_strncpy(buf, get_cached_username(ps->ruid), size+1);
272 static void func_nice(char *buf, int size, const procps_status_t *ps)
274 sprintf(buf, "%*d", size, ps->niceness);
279 #if ENABLE_FEATURE_PS_TIME
281 static void func_etime(char *buf, int size, const procps_status_t *ps)
283 /* elapsed time [[dd-]hh:]mm:ss; here only mm:ss */
287 mm = ps->start_time / get_kernel_HZ();
288 /* must be after get_kernel_HZ()! */
289 mm = seconds_since_boot - mm;
292 snprintf(buf, size+1, "%3lu:%02u", mm, ss);
295 static void func_time(char *buf, int size, const procps_status_t *ps)
297 /* cumulative time [[dd-]hh:]mm:ss; here only mm:ss */
301 mm = (ps->utime + ps->stime) / get_kernel_HZ();
304 snprintf(buf, size+1, "%3lu:%02u", mm, ss);
310 static void func_label(char *buf, int size, const procps_status_t *ps)
312 safe_strncpy(buf, ps->context ? ps->context : "unknown", size+1);
317 static void func_nice(char *buf, int size, const procps_status_t *ps)
322 static void func_pcpu(char *buf, int size, const procps_status_t *ps)
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 },
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_ },
345 #if ENABLE_FEATURE_PS_TIME
346 { 6 , "time" ,"TIME" ,func_time ,PSSCAN_STIME | PSSCAN_UTIME },
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 },
354 { 35 , "label" ,"LABEL" ,func_label ,PSSCAN_CONTEXT },
358 static ps_out_t* new_out_t(void)
360 out = xrealloc_vector(out, 2, out_cnt);
361 return &out[out_cnt++];
364 static const ps_out_t* find_out_spec(const char *name)
367 char buf[ARRAY_SIZE(out_spec)*7 + 1];
370 for (i = 0; i < ARRAY_SIZE(out_spec); i++) {
371 if (strncmp(name, out_spec[i].name6, 6) == 0)
373 p += sprintf(p, "%.6s,", out_spec[i].name6);
376 bb_error_msg_and_die("bad -o argument '%s', supported arguments: %s", name, buf);
379 static void parse_o(char* opt)
382 // POSIX: "-o is blank- or comma-separated list" (FIXME)
385 comma = strchr(opt, ',');
386 equal = strchr(opt, '=');
387 if (comma && (!equal || equal > comma)) {
389 *new_out_t() = *find_out_spec(opt);
396 // opt points to last spec in comma separated list.
397 // This one can have =HEADER part.
401 *new = *find_out_spec(opt);
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);
418 static void alloc_line_buffer(void)
422 for (i = 0; i < out_cnt; i++) {
423 need_flags |= out[i].ps_flags;
424 if (out[i].header[0]) {
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);
436 if (!is_selinux_enabled())
437 need_flags &= ~PSSCAN_CONTEXT;
439 buffer = xmalloc(width + 1); /* for trailing \0 */
442 static void format_header(void)
455 if (++i == out_cnt) /* do not pad last field */
457 p += sprintf(p, "%-*s ", op->width, op->header);
459 strcpy(p, op->header);
461 printf("%.*s\n", terminal_width, buffer);
464 static void format_process(const procps_status_t *ps)
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.
480 len = out[i].width - len + 1;
481 if (++i == out_cnt) /* do not pad last field */
483 p += sprintf(p, "%*s", len, "");
485 printf("%.*s\n", terminal_width, buffer);
488 int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
489 int ps_main(int argc UNUSED_PARAM, char **argv)
492 llist_t* opt_o = NULL;
503 OPT_T = (1 << 8) * ENABLE_FEATURE_SHOW_THREADS,
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.
523 opt_complementary = "o::";
524 opt = getopt32(argv, "Zo:aAdefl"IF_FEATURE_SHOW_THREADS("T"), &opt_o);
527 parse_o(llist_pop(&opt_o));
530 /* Below: parse_o() needs char*, NOT const char*... */
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);
538 strcpy(default_o, DEFAULT_O_STR);
542 #if ENABLE_FEATURE_SHOW_THREADS
544 need_flags |= PSSCAN_TASKS;
547 /* Was INT_MAX, but some libc's go belly up with printf("%.*s")
548 * and such large widths */
549 terminal_width = MAX_WIDTH;
551 get_terminal_width_height(0, &terminal_width, NULL);
552 if (--terminal_width > MAX_WIDTH)
553 terminal_width = MAX_WIDTH;
559 while ((p = procps_scan(p, need_flags)) != NULL) {
567 #else /* !ENABLE_DESKTOP */
570 int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
571 int ps_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
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);
578 OPT_Z = (1 << 0) * ENABLE_SELINUX,
579 OPT_T = (1 << ENABLE_SELINUX) * ENABLE_FEATURE_SHOW_THREADS,
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 */
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"
593 terminal_width = (w_count == 1) ? 132 : MAX_WIDTH;
595 get_terminal_width_height(0, &terminal_width, NULL);
597 if (--terminal_width > MAX_WIDTH)
598 terminal_width = MAX_WIDTH;
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"));
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");
615 puts(" PID USER VSZ STAT COMMAND");
618 psscan_flags |= PSSCAN_TASKS;
622 while ((p = procps_scan(p, psscan_flags)) != NULL) {
625 if (psscan_flags & PSSCAN_CONTEXT) {
626 len = printf("%5u %-32.32s %s ",
628 p->context ? p->context : "unknown",
633 const char *user = get_cached_username(p->uid);
635 // len = printf("%5u %-8.8s %s ",
636 // p->pid, user, p->state);
640 smart_ulltoa5(p->vsz, buf6, " mgtpezy");
642 len = printf("%5u %-8.8s %s %s ",
643 p->pid, user, buf6, p->state);
648 int sz = terminal_width - len;
650 read_cmdline(buf, sz, p->pid, p->comm);
654 if (ENABLE_FEATURE_CLEAN_UP)
655 clear_username_cache();
659 #endif /* !ENABLE_DESKTOP */