ps: fix yet another buglet from recent ulltoa conversion :(
[oweals/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 the GPL version 2, see the file LICENSE in this tarball.
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 //#include <sys/sysinfo.h> /* for sysinfo() */
21 #ifndef AT_CLKTCK
22 #define AT_CLKTCK 17
23 #endif
24
25
26 #if ENABLE_SELINUX
27 #define SELINIX_O_PREFIX "label,"
28 #define DEFAULT_O_STR    (SELINIX_O_PREFIX "pid,user" USE_FEATURE_PS_TIME(",time") ",args")
29 #else
30 #define DEFAULT_O_STR    ("pid,user" USE_FEATURE_PS_TIME(",time") ",args")
31 #endif
32
33 typedef struct {
34         uint16_t width;
35         char name[6];
36         const char *header;
37         void (*f)(char *buf, int size, const procps_status_t *ps);
38         int ps_flags;
39 } ps_out_t;
40
41 struct globals {
42         ps_out_t* out;
43         int out_cnt;
44         int print_header;
45         int need_flags;
46         char *buffer;
47         unsigned terminal_width;
48 #if ENABLE_FEATURE_PS_TIME
49         unsigned kernel_HZ;
50         unsigned long long seconds_since_boot;
51 #endif
52         char default_o[sizeof(DEFAULT_O_STR)];
53 };
54 #define G (*(struct globals*)&bb_common_bufsiz1)
55 #define out                (G.out               )
56 #define out_cnt            (G.out_cnt           )
57 #define print_header       (G.print_header      )
58 #define need_flags         (G.need_flags        )
59 #define buffer             (G.buffer            )
60 #define terminal_width     (G.terminal_width    )
61 #define kernel_HZ          (G.kernel_HZ         )
62 #define seconds_since_boot (G.seconds_since_boot)
63 #define default_o          (G.default_o         )
64
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)
68 {
69         ptrdiff_t *ep = (ptrdiff_t *) environ;
70
71         while (*ep++);
72         while (*ep) {
73                 if (ep[0] == findme) {
74                         return ep[1];
75                 }
76                 ep += 2;
77         }
78         return -1;
79 }
80
81 #if ENABLE_FEATURE_PS_UNUSUAL_SYSTEMS
82 static unsigned get_HZ_by_waiting(void)
83 {
84         struct timeval tv1, tv2;
85         unsigned t1, t2, r, hz;
86         unsigned cnt = cnt; /* for compiler */
87         int diff;
88
89         r = 0;
90
91         /* Wait for times() to reach new tick */
92         t1 = times(NULL);
93         do {
94                 t2 = times(NULL);
95         } while (t2 == t1);
96         gettimeofday(&tv2, NULL);
97
98         do {
99                 t1 = t2;
100                 tv1.tv_usec = tv2.tv_usec;
101
102                 /* Wait exactly one times() tick */
103                 do {
104                         t2 = times(NULL);
105                 } while (t2 == t1);
106                 gettimeofday(&tv2, NULL);
107
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;
112                 hz = (hz+1) & ~1;
113
114                 /* Count how many same hz values we saw */
115                 if (r != hz) {
116                         r = hz;
117                         cnt = 0;
118                 }
119                 cnt++;
120         } while (cnt < 3); /* exit if saw 3 same values */
121
122         return r;
123 }
124 #else
125 static inline unsigned get_HZ_by_waiting(void)
126 {
127         /* Better method? */
128         return 100;
129 }
130 #endif
131
132 static unsigned get_kernel_HZ(void)
133 {
134         //char buf[64];
135         struct sysinfo info;
136
137         if (kernel_HZ)
138                 return kernel_HZ;
139
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();
144
145         //if (open_read_close("/proc/uptime", buf, sizeof(buf) <= 0)
146         //      bb_perror_msg_and_die("cannot read %s", "/proc/uptime");
147         //buf[sizeof(buf)-1] = '\0';
148         ///sscanf(buf, "%llu", &seconds_since_boot);
149         sysinfo(&info);
150         seconds_since_boot = info.uptime;
151
152         return kernel_HZ;
153 }
154 #endif
155
156 /* Print value to buf, max size+1 chars (including trailing '\0') */
157
158 static void func_user(char *buf, int size, const procps_status_t *ps)
159 {
160         safe_strncpy(buf, get_cached_username(ps->uid), size+1);
161 }
162
163 static void func_comm(char *buf, int size, const procps_status_t *ps)
164 {
165         safe_strncpy(buf, ps->comm, size+1);
166 }
167
168 static void func_args(char *buf, int size, const procps_status_t *ps)
169 {
170         read_cmdline(buf, size, ps->pid, ps->comm);
171 }
172
173 static void func_pid(char *buf, int size, const procps_status_t *ps)
174 {
175         sprintf(buf, "%*u", size, ps->pid);
176 }
177
178 static void func_ppid(char *buf, int size, const procps_status_t *ps)
179 {
180         sprintf(buf, "%*u", size, ps->ppid);
181 }
182
183 static void func_pgid(char *buf, int size, const procps_status_t *ps)
184 {
185         sprintf(buf, "%*u", size, ps->pgid);
186 }
187
188 static void put_lu(char *buf, int size, unsigned long u)
189 {
190         char buf4[5];
191
192         /* see http://en.wikipedia.org/wiki/Tera */
193         smart_ulltoa4(u, buf4, " mgtpezy");
194         buf4[4] = '\0';
195         sprintf(buf, "%.*s", size, buf4);
196 }
197
198 static void func_vsz(char *buf, int size, const procps_status_t *ps)
199 {
200         put_lu(buf, size, ps->vsz);
201 }
202
203 static void func_rss(char *buf, int size, const procps_status_t *ps)
204 {
205         put_lu(buf, size, ps->rss);
206 }
207
208 static void func_tty(char *buf, int size, const procps_status_t *ps)
209 {
210         buf[0] = '?';
211         buf[1] = '\0';
212         if (ps->tty_major) /* tty field of "0" means "no tty" */
213                 snprintf(buf, size+1, "%u,%u", ps->tty_major, ps->tty_minor);
214 }
215
216 #if ENABLE_FEATURE_PS_TIME
217 static void func_etime(char *buf, int size, const procps_status_t *ps)
218 {
219         /* elapsed time [[dd-]hh:]mm:ss; here only mm:ss */
220         unsigned long mm;
221         unsigned ss;
222
223         mm = ps->start_time / get_kernel_HZ();
224         /* must be after get_kernel_HZ()! */
225         mm = seconds_since_boot - mm;
226         ss = mm % 60;
227         mm /= 60;
228         snprintf(buf, size+1, "%3lu:%02u", mm, ss);
229 }
230
231 static void func_time(char *buf, int size, const procps_status_t *ps)
232 {
233         /* cumulative time [[dd-]hh:]mm:ss; here only mm:ss */
234         unsigned long mm;
235         unsigned ss;
236
237         mm = (ps->utime + ps->stime) / get_kernel_HZ();
238         ss = mm % 60;
239         mm /= 60;
240         snprintf(buf, size+1, "%3lu:%02u", mm, ss);
241 }
242 #endif
243
244 #if ENABLE_SELINUX
245 static void func_label(char *buf, int size, const procps_status_t *ps)
246 {
247         safe_strncpy(buf, ps->context ? ps->context : "unknown", size+1);
248 }
249 #endif
250
251 /*
252 static void func_nice(char *buf, int size, const procps_status_t *ps)
253 {
254         ps->???
255 }
256
257 static void func_pcpu(char *buf, int size, const procps_status_t *ps)
258 {
259 }
260 */
261
262 static const ps_out_t out_spec[] = {
263 // Mandated by POSIX:
264         { 8                  , "user"  ,"USER"   ,func_user  ,PSSCAN_UIDGID  },
265         { 16                 , "comm"  ,"COMMAND",func_comm  ,PSSCAN_COMM    },
266         { 256                , "args"  ,"COMMAND",func_args  ,PSSCAN_COMM    },
267         { 5                  , "pid"   ,"PID"    ,func_pid   ,PSSCAN_PID     },
268         { 5                  , "ppid"  ,"PPID"   ,func_ppid  ,PSSCAN_PPID    },
269         { 5                  , "pgid"  ,"PGID"   ,func_pgid  ,PSSCAN_PGID    },
270 #if ENABLE_FEATURE_PS_TIME
271         { sizeof("ELAPSED")-1, "etime" ,"ELAPSED",func_etime ,PSSCAN_START_TIME },
272 #endif
273 //      { sizeof("GROUP"  )-1, "group" ,"GROUP"  ,func_group ,PSSCAN_UIDGID  },
274 //      { sizeof("NI"     )-1, "nice"  ,"NI"     ,func_nice  ,PSSCAN_        },
275 //      { sizeof("%CPU"   )-1, "pcpu"  ,"%CPU"   ,func_pcpu  ,PSSCAN_        },
276 //      { sizeof("RGROUP" )-1, "rgroup","RGROUP" ,func_rgroup,PSSCAN_UIDGID  },
277 //      { sizeof("RUSER"  )-1, "ruser" ,"RUSER"  ,func_ruser ,PSSCAN_UIDGID  },
278 #if ENABLE_FEATURE_PS_TIME
279         { 6                  , "time"  ,"TIME"   ,func_time  ,PSSCAN_STIME | PSSCAN_UTIME },
280 #endif
281         { 6                  , "tty"   ,"TT"     ,func_tty   ,PSSCAN_TTY     },
282         { 4                  , "vsz"   ,"VSZ"    ,func_vsz   ,PSSCAN_VSZ     },
283 // Not mandated by POSIX, but useful:
284         { 4                  , "rss"   ,"RSS"    ,func_rss   ,PSSCAN_RSS     },
285 #if ENABLE_SELINUX
286         { 35                 , "label" ,"LABEL"  ,func_label ,PSSCAN_CONTEXT },
287 #endif
288 };
289
290 static ps_out_t* new_out_t(void)
291 {
292         int i = out_cnt++;
293         out = xrealloc(out, out_cnt * sizeof(*out));
294         return &out[i];
295 }
296
297 static const ps_out_t* find_out_spec(const char *name)
298 {
299         int i;
300         for (i = 0; i < ARRAY_SIZE(out_spec); i++) {
301                 if (!strcmp(name, out_spec[i].name))
302                         return &out_spec[i];
303         }
304         bb_error_msg_and_die("bad -o argument '%s'", name);
305 }
306
307 static void parse_o(char* opt)
308 {
309         ps_out_t* new;
310         // POSIX: "-o is blank- or comma-separated list" (FIXME)
311         char *comma, *equal;
312         while (1) {
313                 comma = strchr(opt, ',');
314                 equal = strchr(opt, '=');
315                 if (comma && (!equal || equal > comma)) {
316                         *comma = '\0';
317                         *new_out_t() = *find_out_spec(opt);
318                         *comma = ',';
319                         opt = comma + 1;
320                         continue;
321                 }
322                 break;
323         }
324         // opt points to last spec in comma separated list.
325         // This one can have =HEADER part.
326         new = new_out_t();
327         if (equal)
328                 *equal = '\0';
329         *new = *find_out_spec(opt);
330         if (equal) {
331                 *equal = '=';
332                 new->header = equal + 1;
333                 // POSIX: the field widths shall be ... at least as wide as
334                 // the header text (default or overridden value).
335                 // If the header text is null, such as -o user=,
336                 // the field width shall be at least as wide as the
337                 // default header text
338                 if (new->header[0]) {
339                         new->width = strlen(new->header);
340                         print_header = 1;
341                 }
342         } else
343                 print_header = 1;
344 }
345
346 static void post_process(void)
347 {
348         int i;
349         int width = 0;
350         for (i = 0; i < out_cnt; i++) {
351                 need_flags |= out[i].ps_flags;
352                 if (out[i].header[0]) {
353                         print_header = 1;
354                 }
355                 width += out[i].width + 1; /* "FIELD " */
356         }
357 #if ENABLE_SELINUX
358         if (!is_selinux_enabled())
359                 need_flags &= ~PSSCAN_CONTEXT;
360 #endif
361         buffer = xmalloc(width + 1); /* for trailing \0 */
362 }
363
364 static void format_header(void)
365 {
366         int i;
367         ps_out_t* op;
368         char *p;
369
370         if (!print_header)
371                 return;
372         p = buffer;
373         i = 0;
374         if (out_cnt) {
375                 while (1) {
376                         op = &out[i];
377                         if (++i == out_cnt) /* do not pad last field */
378                                 break;
379                         p += sprintf(p, "%-*s ", op->width, op->header);
380                 }
381                 strcpy(p, op->header);
382         }
383         printf("%.*s\n", terminal_width, buffer);
384 }
385
386 static void format_process(const procps_status_t *ps)
387 {
388         int i, len;
389         char *p = buffer;
390         i = 0;
391         if (out_cnt) while (1) {
392                 out[i].f(p, out[i].width, ps);
393                 // POSIX: Any field need not be meaningful in all
394                 // implementations. In such a case a hyphen ( '-' )
395                 // should be output in place of the field value.
396                 if (!p[0]) {
397                         p[0] = '-';
398                         p[1] = '\0';
399                 }
400                 len = strlen(p);
401                 p += len;
402                 len = out[i].width - len + 1;
403                 if (++i == out_cnt) /* do not pad last field */
404                         break;
405                 p += sprintf(p, "%*s", len, "");
406         }
407         printf("%.*s\n", terminal_width, buffer);
408 }
409
410 int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
411 int ps_main(int argc, char **argv)
412 {
413         procps_status_t *p;
414         llist_t* opt_o = NULL;
415         USE_SELINUX(int opt;)
416
417         // POSIX:
418         // -a  Write information for all processes associated with terminals
419         //     Implementations may omit session leaders from this list
420         // -A  Write information for all processes
421         // -d  Write information for all processes, except session leaders
422         // -e  Write information for all processes (equivalent to -A.)
423         // -f  Generate a full listing
424         // -l  Generate a long listing
425         // -o col1,col2,col3=header
426         //     Select which columns to display
427         /* We allow (and ignore) most of the above. FIXME */
428         opt_complementary = "o::";
429         USE_SELINUX(opt =) getopt32(argv, "Zo:aAdefl", &opt_o);
430         if (opt_o) {
431                 do {
432                         parse_o(opt_o->data);
433                         opt_o = opt_o->link;
434                 } while (opt_o);
435         } else {
436                 /* Below: parse_o() needs char*, NOT const char*... */
437 #if ENABLE_SELINUX
438                 if (!(opt & 1) || !is_selinux_enabled()) {
439                         /* no -Z or no SELinux: do not show LABEL */
440                         strcpy(default_o, DEFAULT_O_STR + sizeof(SELINIX_O_PREFIX)-1);
441                 } else
442 #endif
443                 {
444                         strcpy(default_o, DEFAULT_O_STR);
445                 }
446                 parse_o(default_o);
447         }
448         post_process();
449
450         /* Was INT_MAX, but some libc's go belly up with printf("%.*s")
451          * and such large widths */
452         terminal_width = MAX_WIDTH;
453         if (isatty(1)) {
454                 get_terminal_width_height(0, &terminal_width, NULL);
455                 if (--terminal_width > MAX_WIDTH)
456                         terminal_width = MAX_WIDTH;
457         }
458         format_header();
459
460         p = NULL;
461         while ((p = procps_scan(p, need_flags))) {
462                 format_process(p);
463         }
464
465         return EXIT_SUCCESS;
466 }
467
468
469 #else /* !ENABLE_DESKTOP */
470
471
472 int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
473 int ps_main(int argc, char **argv)
474 {
475         procps_status_t *p = NULL;
476         int len;
477         SKIP_SELINUX(const) int use_selinux = 0;
478         USE_SELINUX(int i;)
479 #if !ENABLE_FEATURE_PS_WIDE
480         enum { terminal_width = 79 };
481 #else
482         int terminal_width;
483         int w_count = 0;
484 #endif
485
486 #if ENABLE_FEATURE_PS_WIDE || ENABLE_SELINUX
487 #if ENABLE_FEATURE_PS_WIDE
488         opt_complementary = "-:ww";
489         USE_SELINUX(i =) getopt32(argv, USE_SELINUX("Z") "w", &w_count);
490         /* if w is given once, GNU ps sets the width to 132,
491          * if w is given more than once, it is "unlimited"
492          */
493         if (w_count) {
494                 terminal_width = (w_count==1) ? 132 : MAX_WIDTH;
495         } else {
496                 get_terminal_width_height(0, &terminal_width, NULL);
497                 /* Go one less... */
498                 if (--terminal_width > MAX_WIDTH)
499                         terminal_width = MAX_WIDTH;
500         }
501 #else /* only ENABLE_SELINUX */
502         i = getopt32(argv, "Z");
503 #endif
504 #if ENABLE_SELINUX
505         if ((i & 1) && is_selinux_enabled())
506                 use_selinux = PSSCAN_CONTEXT;
507 #endif
508 #endif /* ENABLE_FEATURE_PS_WIDE || ENABLE_SELINUX */
509
510         if (use_selinux)
511                 puts("  PID CONTEXT                          STAT COMMAND");
512         else
513                 puts("  PID USER       VSZ STAT COMMAND");
514
515         while ((p = procps_scan(p, 0
516                         | PSSCAN_PID
517                         | PSSCAN_UIDGID
518                         | PSSCAN_STATE
519                         | PSSCAN_VSZ
520                         | PSSCAN_COMM
521                         | use_selinux
522         ))) {
523 #if ENABLE_SELINUX
524                 if (use_selinux) {
525                         len = printf("%5u %-32.32s %s  ",
526                                         p->pid,
527                                         p->context ? p->context : "unknown",
528                                         p->state);
529                 } else
530 #endif
531                 {
532                         const char *user = get_cached_username(p->uid);
533                         //if (p->vsz == 0)
534                         //      len = printf("%5u %-8.8s        %s ",
535                         //              p->pid, user, p->state);
536                         //else
537                         {
538                                 char buf6[6];
539                                 smart_ulltoa5(p->vsz, buf6, " mgtpezy");
540                                 buf6[5] = '\0';
541                                 len = printf("%5u %-8.8s %s %s  ",
542                                         p->pid, user, buf6, p->state);
543                         }
544                 }
545
546                 {
547                         int sz = terminal_width - len;
548                         char buf[sz + 1];
549                         read_cmdline(buf, sz, p->pid, p->comm);
550                         puts(buf);
551                 }
552         }
553         if (ENABLE_FEATURE_CLEAN_UP)
554                 clear_username_cache();
555         return EXIT_SUCCESS;
556 }
557
558 #endif /* ENABLE_DESKTOP */