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 the GPL version 2, see the file LICENSE in this tarball.
14 /* Absolute maximum on output line length */
15 enum { MAX_WIDTH = 2*1024 };
19 #include <sys/times.h> /* for times() */
26 #define SELINUX_O_PREFIX "label,"
27 #define DEFAULT_O_STR (SELINUX_O_PREFIX "pid,user" IF_FEATURE_PS_TIME(",time") ",args")
29 #define DEFAULT_O_STR ("pid,user" IF_FEATURE_PS_TIME(",time") ",args")
36 void (*f)(char *buf, int size, const procps_status_t *ps);
46 unsigned terminal_width;
47 #if ENABLE_FEATURE_PS_TIME
49 unsigned long long seconds_since_boot;
51 char default_o[sizeof(DEFAULT_O_STR)];
53 #define G (*(struct globals*)&bb_common_bufsiz1)
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)
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)
69 ptrdiff_t *ep = (ptrdiff_t *) environ;
73 if (ep[0] == findme) {
81 #if ENABLE_FEATURE_PS_UNUSUAL_SYSTEMS
82 static unsigned get_HZ_by_waiting(void)
84 struct timeval tv1, tv2;
85 unsigned t1, t2, r, hz;
86 unsigned cnt = cnt; /* for compiler */
91 /* Wait for times() to reach new tick */
96 gettimeofday(&tv2, NULL);
100 tv1.tv_usec = tv2.tv_usec;
102 /* Wait exactly one times() tick */
106 gettimeofday(&tv2, NULL);
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;
114 /* Count how many same hz values we saw */
120 } while (cnt < 3); /* exit if saw 3 same values */
125 static inline unsigned get_HZ_by_waiting(void)
132 static unsigned get_kernel_HZ(void)
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();
145 //if (open_read_close("/proc/uptime", buf, sizeof(buf)) <= 0)
146 // bb_perror_msg_and_die("can't read %s", "/proc/uptime");
147 //buf[sizeof(buf)-1] = '\0';
148 ///sscanf(buf, "%llu", &seconds_since_boot);
150 seconds_since_boot = info.uptime;
156 /* Print value to buf, max size+1 chars (including trailing '\0') */
158 static void func_user(char *buf, int size, const procps_status_t *ps)
161 safe_strncpy(buf, get_cached_username(ps->uid), size+1);
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);
173 sprintf(buf, "%*u", size, (unsigned)ps->uid);
177 static void func_group(char *buf, int size, const procps_status_t *ps)
179 safe_strncpy(buf, get_cached_groupname(ps->gid), size+1);
182 static void func_comm(char *buf, int size, const procps_status_t *ps)
184 safe_strncpy(buf, ps->comm, size+1);
187 static void func_args(char *buf, int size, const procps_status_t *ps)
189 read_cmdline(buf, size+1, ps->pid, ps->comm);
192 static void func_pid(char *buf, int size, const procps_status_t *ps)
194 sprintf(buf, "%*u", size, ps->pid);
197 static void func_ppid(char *buf, int size, const procps_status_t *ps)
199 sprintf(buf, "%*u", size, ps->ppid);
202 static void func_pgid(char *buf, int size, const procps_status_t *ps)
204 sprintf(buf, "%*u", size, ps->pgid);
207 static void put_lu(char *buf, int size, unsigned long u)
211 /* see http://en.wikipedia.org/wiki/Tera */
212 smart_ulltoa4(u, buf4, " mgtpezy");
214 sprintf(buf, "%.*s", size, buf4);
217 static void func_vsz(char *buf, int size, const procps_status_t *ps)
219 put_lu(buf, size, ps->vsz);
222 static void func_rss(char *buf, int size, const procps_status_t *ps)
224 put_lu(buf, size, ps->rss);
227 static void func_tty(char *buf, int size, const procps_status_t *ps)
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);
235 #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
237 static void func_rgroup(char *buf, int size, const procps_status_t *ps)
239 safe_strncpy(buf, get_cached_groupname(ps->rgid), size+1);
242 static void func_ruser(char *buf, int size, const procps_status_t *ps)
244 safe_strncpy(buf, get_cached_username(ps->ruid), size+1);
247 static void func_nice(char *buf, int size, const procps_status_t *ps)
249 sprintf(buf, "%*d", size, ps->niceness);
254 #if ENABLE_FEATURE_PS_TIME
256 static void func_etime(char *buf, int size, const procps_status_t *ps)
258 /* elapsed time [[dd-]hh:]mm:ss; here only mm:ss */
262 mm = ps->start_time / get_kernel_HZ();
263 /* must be after get_kernel_HZ()! */
264 mm = seconds_since_boot - mm;
267 snprintf(buf, size+1, "%3lu:%02u", mm, ss);
270 static void func_time(char *buf, int size, const procps_status_t *ps)
272 /* cumulative time [[dd-]hh:]mm:ss; here only mm:ss */
276 mm = (ps->utime + ps->stime) / get_kernel_HZ();
279 snprintf(buf, size+1, "%3lu:%02u", mm, ss);
285 static void func_label(char *buf, int size, const procps_status_t *ps)
287 safe_strncpy(buf, ps->context ? ps->context : "unknown", size+1);
292 static void func_nice(char *buf, int size, const procps_status_t *ps)
297 static void func_pcpu(char *buf, int size, const procps_status_t *ps)
302 static const ps_out_t out_spec[] = {
303 // Mandated by POSIX:
304 { 8 , "user" ,"USER" ,func_user ,PSSCAN_UIDGID },
305 { 8 , "group" ,"GROUP" ,func_group ,PSSCAN_UIDGID },
306 { 16 , "comm" ,"COMMAND",func_comm ,PSSCAN_COMM },
307 { MAX_WIDTH , "args" ,"COMMAND",func_args ,PSSCAN_COMM },
308 { 5 , "pid" ,"PID" ,func_pid ,PSSCAN_PID },
309 { 5 , "ppid" ,"PPID" ,func_ppid ,PSSCAN_PPID },
310 { 5 , "pgid" ,"PGID" ,func_pgid ,PSSCAN_PGID },
311 #if ENABLE_FEATURE_PS_TIME
312 { sizeof("ELAPSED")-1, "etime" ,"ELAPSED",func_etime ,PSSCAN_START_TIME },
314 #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
315 { 5 , "nice" ,"NI" ,func_nice ,PSSCAN_NICE },
316 { 8 , "rgroup","RGROUP" ,func_rgroup,PSSCAN_RUIDGID },
317 { 8 , "ruser" ,"RUSER" ,func_ruser ,PSSCAN_RUIDGID },
318 // { 5 , "pcpu" ,"%CPU" ,func_pcpu ,PSSCAN_ },
320 #if ENABLE_FEATURE_PS_TIME
321 { 6 , "time" ,"TIME" ,func_time ,PSSCAN_STIME | PSSCAN_UTIME },
323 { 6 , "tty" ,"TT" ,func_tty ,PSSCAN_TTY },
324 { 4 , "vsz" ,"VSZ" ,func_vsz ,PSSCAN_VSZ },
325 // Not mandated by POSIX, but useful:
326 { 4 , "rss" ,"RSS" ,func_rss ,PSSCAN_RSS },
328 { 35 , "label" ,"LABEL" ,func_label ,PSSCAN_CONTEXT },
332 static ps_out_t* new_out_t(void)
334 out = xrealloc_vector(out, 2, out_cnt);
335 return &out[out_cnt++];
338 static const ps_out_t* find_out_spec(const char *name)
342 char buf[ARRAY_SIZE(out_spec)*7 + 1];
346 for (i = 0; i < ARRAY_SIZE(out_spec); i++) {
347 if (strncmp(name, out_spec[i].name6, 6) == 0)
350 p += sprintf(p, "%.6s,", out_spec[i].name6);
355 bb_error_msg_and_die("bad -o argument '%s', supported arguments: %s", name, buf);
357 bb_error_msg_and_die("bad -o argument '%s'");
361 static void parse_o(char* opt)
364 // POSIX: "-o is blank- or comma-separated list" (FIXME)
367 comma = strchr(opt, ',');
368 equal = strchr(opt, '=');
369 if (comma && (!equal || equal > comma)) {
371 *new_out_t() = *find_out_spec(opt);
378 // opt points to last spec in comma separated list.
379 // This one can have =HEADER part.
383 *new = *find_out_spec(opt);
386 new->header = equal + 1;
387 // POSIX: the field widths shall be ... at least as wide as
388 // the header text (default or overridden value).
389 // If the header text is null, such as -o user=,
390 // the field width shall be at least as wide as the
391 // default header text
392 if (new->header[0]) {
393 new->width = strlen(new->header);
400 static void alloc_line_buffer(void)
404 for (i = 0; i < out_cnt; i++) {
405 need_flags |= out[i].ps_flags;
406 if (out[i].header[0]) {
409 width += out[i].width + 1; /* "FIELD " */
410 if ((int)(width - terminal_width) > 0) {
411 /* The rest does not fit on the screen */
412 //out[i].width -= (width - terminal_width - 1);
418 if (!is_selinux_enabled())
419 need_flags &= ~PSSCAN_CONTEXT;
421 buffer = xmalloc(width + 1); /* for trailing \0 */
424 static void format_header(void)
437 if (++i == out_cnt) /* do not pad last field */
439 p += sprintf(p, "%-*s ", op->width, op->header);
441 strcpy(p, op->header);
443 printf("%.*s\n", terminal_width, buffer);
446 static void format_process(const procps_status_t *ps)
451 if (out_cnt) while (1) {
452 out[i].f(p, out[i].width, ps);
453 // POSIX: Any field need not be meaningful in all
454 // implementations. In such a case a hyphen ( '-' )
455 // should be output in place of the field value.
462 len = out[i].width - len + 1;
463 if (++i == out_cnt) /* do not pad last field */
465 p += sprintf(p, "%*s", len, "");
467 printf("%.*s\n", terminal_width, buffer);
470 int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
471 int ps_main(int argc UNUSED_PARAM, char **argv)
474 llist_t* opt_o = NULL;
485 OPT_T = (1 << 8) * ENABLE_FEATURE_SHOW_THREADS,
491 // -a Write information for all processes associated with terminals
492 // Implementations may omit session leaders from this list
493 // -A Write information for all processes
494 // -d Write information for all processes, except session leaders
495 // -e Write information for all processes (equivalent to -A)
496 // -f Generate a full listing
497 // -l Generate a long listing
498 // -o col1,col2,col3=header
499 // Select which columns to display
500 /* We allow (and ignore) most of the above. FIXME.
501 * -T is picked for threads (POSIX hasn't it standardized).
502 * procps v3.2.7 supports -T and shows tids as SPID column,
503 * it also supports -L where it shows tids as LWP column.
505 opt_complementary = "o::";
506 opt = getopt32(argv, "Zo:aAdefl"IF_FEATURE_SHOW_THREADS("T"), &opt_o);
509 parse_o(llist_pop(&opt_o));
512 /* Below: parse_o() needs char*, NOT const char*... */
514 if (!(opt & OPT_Z) || !is_selinux_enabled()) {
515 /* no -Z or no SELinux: do not show LABEL */
516 strcpy(default_o, DEFAULT_O_STR + sizeof(SELINUX_O_PREFIX)-1);
520 strcpy(default_o, DEFAULT_O_STR);
524 #if ENABLE_FEATURE_SHOW_THREADS
526 need_flags |= PSSCAN_TASKS;
529 /* Was INT_MAX, but some libc's go belly up with printf("%.*s")
530 * and such large widths */
531 terminal_width = MAX_WIDTH;
533 get_terminal_width_height(0, &terminal_width, NULL);
534 if (--terminal_width > MAX_WIDTH)
535 terminal_width = MAX_WIDTH;
541 while ((p = procps_scan(p, need_flags)) != NULL) {
549 #else /* !ENABLE_DESKTOP */
552 int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
553 int ps_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
556 int psscan_flags = PSSCAN_PID | PSSCAN_UIDGID
557 | PSSCAN_STATE | PSSCAN_VSZ | PSSCAN_COMM;
558 unsigned terminal_width IF_NOT_FEATURE_PS_WIDE(= 79);
560 OPT_Z = (1 << 0) * ENABLE_SELINUX,
561 OPT_T = (1 << ENABLE_SELINUX) * ENABLE_FEATURE_SHOW_THREADS,
564 /* If we support any options, parse argv */
565 #if ENABLE_SELINUX || ENABLE_FEATURE_SHOW_THREADS || ENABLE_FEATURE_PS_WIDE
566 # if ENABLE_FEATURE_PS_WIDE
567 /* -w is a bit complicated */
569 opt_complementary = "-:ww";
570 opts = getopt32(argv, IF_SELINUX("Z")IF_FEATURE_SHOW_THREADS("T")"w", &w_count);
571 /* if w is given once, GNU ps sets the width to 132,
572 * if w is given more than once, it is "unlimited"
575 terminal_width = (w_count == 1) ? 132 : MAX_WIDTH;
577 get_terminal_width_height(0, &terminal_width, NULL);
579 if (--terminal_width > MAX_WIDTH)
580 terminal_width = MAX_WIDTH;
583 /* -w is not supported, only -Z and/or -T */
584 opt_complementary = "-";
585 opts = getopt32(argv, IF_SELINUX("Z")IF_FEATURE_SHOW_THREADS("T"));
590 if ((opts & OPT_Z) && is_selinux_enabled()) {
591 psscan_flags = PSSCAN_PID | PSSCAN_CONTEXT
592 | PSSCAN_STATE | PSSCAN_COMM;
593 puts(" PID CONTEXT STAT COMMAND");
597 puts(" PID USER VSZ STAT COMMAND");
600 psscan_flags |= PSSCAN_TASKS;
604 while ((p = procps_scan(p, psscan_flags)) != NULL) {
607 if (psscan_flags & PSSCAN_CONTEXT) {
608 len = printf("%5u %-32.32s %s ",
610 p->context ? p->context : "unknown",
615 const char *user = get_cached_username(p->uid);
617 // len = printf("%5u %-8.8s %s ",
618 // p->pid, user, p->state);
622 smart_ulltoa5(p->vsz, buf6, " mgtpezy");
624 len = printf("%5u %-8.8s %s %s ",
625 p->pid, user, buf6, p->state);
630 int sz = terminal_width - len;
632 read_cmdline(buf, sz, p->pid, p->comm);
636 if (ENABLE_FEATURE_CLEAN_UP)
637 clear_username_cache();
641 #endif /* !ENABLE_DESKTOP */