procps: remove all global variables
[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  *
7  * Licensed under the GPL version 2, see the file LICENSE in this tarball.
8  */
9
10 #include "busybox.h"
11
12 #if ENABLE_DESKTOP
13
14 /* Print value to buf, max size+1 chars (including trailing '\0') */
15
16 static void func_user(char *buf, int size, const procps_status_t *ps)
17 {
18         safe_strncpy(buf, get_cached_username(ps->uid), size+1);
19 }
20
21 static void func_comm(char *buf, int size, const procps_status_t *ps)
22 {
23         safe_strncpy(buf, ps->comm, size+1);
24 }
25
26 static void func_args(char *buf, int size, const procps_status_t *ps)
27 {
28         buf[0] = '\0';
29         if (ps->cmd)
30                 safe_strncpy(buf, ps->cmd, size+1);
31         else if (size >= 2)
32                 sprintf(buf, "[%.*s]", size-2, ps->comm);
33 }
34
35 static void func_pid(char *buf, int size, const procps_status_t *ps)
36 {
37         sprintf(buf, "%*u", size, ps->pid);
38 }
39
40 static void func_ppid(char *buf, int size, const procps_status_t *ps)
41 {
42         sprintf(buf, "%*u", size, ps->ppid);
43 }
44
45 static void func_pgid(char *buf, int size, const procps_status_t *ps)
46 {
47         sprintf(buf, "%*u", size, ps->pgid);
48 }
49
50 static void func_vsz(char *buf, int size, const procps_status_t *ps)
51 {
52         char buf5[5];
53         smart_ulltoa5( ((unsigned long long)ps->vsz) << 10, buf5);
54         sprintf(buf, "%.*s", size, buf5);
55 }
56
57 static void func_rss(char *buf, int size, const procps_status_t *ps)
58 {
59         char buf5[5];
60         smart_ulltoa5( ((unsigned long long)ps->rss) << 10, buf5);
61         sprintf(buf, "%.*s", size, buf5);
62 }
63
64 static void func_tty(char *buf, int size, const procps_status_t *ps)
65 {
66         safe_strncpy(buf, ps->tty_str, size+1);
67 }
68 /*
69 static void func_nice(char *buf, int size, const procps_status_t *ps)
70 {
71         ps->???
72 }
73
74 static void func_etime(char *buf, int size, const procps_status_t *ps)
75 {
76         elapled time [[dd-]hh:]mm:ss
77 }
78
79 static void func_time(char *buf, int size, const procps_status_t *ps)
80 {
81         cumulative time [[dd-]hh:]mm:ss
82 }
83
84 static void func_pcpu(char *buf, int size, const procps_status_t *ps)
85 {
86 }
87 */
88
89 typedef struct {
90         uint16_t width;
91         char name[6];
92         const char *header;
93         void (*f)(char *buf, int size, const procps_status_t *ps);
94         int ps_flags;
95 } ps_out_t;
96
97 static const ps_out_t out_spec[] = {
98 // Mandated by POSIX:
99         { 8                  , "user"  ,"USER"   ,func_user  ,PSSCAN_UIDGID          },
100         { 16                 , "comm"  ,"COMMAND",func_comm  ,PSSCAN_COMM            },
101         { 256                , "args"  ,"COMMAND",func_args  ,PSSCAN_CMD|PSSCAN_COMM },
102         { 5                  , "pid"   ,"PID"    ,func_pid   ,PSSCAN_PID             },
103         { 5                  , "ppid"  ,"PPID"   ,func_ppid  ,PSSCAN_PPID            },
104         { 5                  , "pgid"  ,"PGID"   ,func_pgid  ,PSSCAN_PGID            },
105 //      { sizeof("ELAPSED")-1, "etime" ,"ELAPSED",func_etime ,PSSCAN_                },
106 //      { sizeof("GROUP"  )-1, "group" ,"GROUP"  ,func_group ,PSSCAN_UIDGID          },
107 //      { sizeof("NI"     )-1, "nice"  ,"NI"     ,func_nice  ,PSSCAN_                },
108 //      { sizeof("%CPU"   )-1, "pcpu"  ,"%CPU"   ,func_pcpu  ,PSSCAN_                },
109 //      { sizeof("RGROUP" )-1, "rgroup","RGROUP" ,func_rgroup,PSSCAN_UIDGID          },
110 //      { sizeof("RUSER"  )-1, "ruser" ,"RUSER"  ,func_ruser ,PSSCAN_UIDGID          },
111 //      { sizeof("TIME"   )-1, "time"  ,"TIME"   ,func_time  ,PSSCAN_                },
112         { 6                  , "tty"   ,"TT"     ,func_tty   ,PSSCAN_TTY             },
113         { 4                  , "vsz"   ,"VSZ"    ,func_vsz   ,PSSCAN_VSZ             },
114 // Not mandated by POSIX, but useful:
115         { 4                  , "rss"   ,"RSS"    ,func_rss   ,PSSCAN_RSS             },
116 };
117
118 #define VEC_SIZE(v) ( sizeof(v) / sizeof((v)[0]) )
119
120 #define DEFAULT_O_STR "pid,user" /* TODO: ,vsz,stat */ ",args"
121
122 struct globals {
123         ps_out_t* out;
124         int out_cnt;
125         int print_header;
126         int need_flags;
127         char *buffer;
128         unsigned terminal_width;
129         char default_o[sizeof(DEFAULT_O_STR)];
130 };
131 #define G (*(struct globals*)&bb_common_bufsiz1)
132 #define out            (G.out           )
133 #define out_cnt        (G.out_cnt       )
134 #define print_header   (G.print_header  )
135 #define need_flags     (G.need_flags    )
136 #define buffer         (G.buffer        )
137 #define terminal_width (G.terminal_width)
138 #define default_o      (G.default_o     )
139
140 static ps_out_t* new_out_t(void)
141 {
142         int i = out_cnt++;
143         out = xrealloc(out, out_cnt * sizeof(*out));
144         return &out[i];
145 }
146
147 static const ps_out_t* find_out_spec(const char *name)
148 {
149         int i;
150         for (i = 0; i < VEC_SIZE(out_spec); i++) {
151                 if (!strcmp(name, out_spec[i].name))
152                         return &out_spec[i];
153         }
154         bb_error_msg_and_die("bad -o argument '%s'", name);
155 }
156
157 static void parse_o(char* opt)
158 {
159         ps_out_t* new;
160         // POSIX: "-o is blank- or comma-separated list" (FIXME)
161         char *comma, *equal;
162         while (1) {
163                 comma = strchr(opt, ',');
164                 equal = strchr(opt, '=');
165                 if (comma && (!equal || equal > comma)) {
166                         *comma = '\0';
167                         *new_out_t() = *find_out_spec(opt);
168                         *comma = ',';
169                         opt = comma + 1;
170                         continue;
171                 }
172                 break;
173         }
174         // opt points to last spec in comma separated list.
175         // This one can have =HEADER part.
176         new = new_out_t();
177         if (equal)
178                 *equal = '\0';
179         *new = *find_out_spec(opt);
180         if (equal) {
181                 *equal = '=';
182                 new->header = equal + 1;
183                 // POSIX: the field widths shall be ... at least as wide as
184                 // the header text (default or overridden value).
185                 // If the header text is null, such as -o user=,
186                 // the field width shall be at least as wide as the
187                 // default header text
188                 if (new->header[0]) {
189                         new->width = strlen(new->header);
190                         print_header = 1;
191                 }
192         } else
193                 print_header = 1;
194 }
195
196 static void post_process(void)
197 {
198         int i;
199         int width = 0;
200         for (i = 0; i < out_cnt; i++) {
201                 need_flags |= out[i].ps_flags;
202                 if (out[i].header[0]) {
203                         print_header = 1;
204                 }
205                 width += out[i].width + 1; /* "FIELD " */
206         }
207         buffer = xmalloc(width + 1); /* for trailing \0 */
208 }
209
210 static void format_header(void)
211 {
212         int i;
213         ps_out_t* op;
214         char *p;
215
216         if (!print_header)
217                 return;
218         p = buffer;
219         i = 0;
220         if (out_cnt) {
221                 while (1) {
222                         op = &out[i];
223                         if (++i == out_cnt) /* do not pad last field */
224                                 break;
225                         p += sprintf(p, "%-*s ", op->width, op->header);
226                 }
227                 strcpy(p, op->header);
228         }
229         printf("%.*s\n", terminal_width, buffer);
230 }
231
232 static void format_process(const procps_status_t *ps)
233 {
234         int i, len;
235         char *p = buffer;
236         i = 0;
237         if (out_cnt) while (1) {
238                 out[i].f(p, out[i].width, ps);
239                 // POSIX: Any field need not be meaningful in all
240                 // implementations. In such a case a hyphen ( '-' )
241                 // should be output in place of the field value.
242                 if (!p[0]) {
243                         p[0] = '-';
244                         p[1] = '\0';
245                 }
246                 len = strlen(p);
247                 p += len;
248                 len = out[i].width - len + 1;
249                 if (++i == out_cnt) /* do not pad last field */
250                         break;
251                 p += sprintf(p, "%*s", len, "");
252         }
253         printf("%.*s\n", terminal_width, buffer);
254 }
255
256 int ps_main(int argc, char **argv);
257 int ps_main(int argc, char **argv)
258 {
259         procps_status_t *p;
260         llist_t* opt_o = NULL;
261
262         /* Cannot be const: parse_o() will choke */
263         strcpy(default_o, DEFAULT_O_STR);
264
265         // POSIX:
266         // -a  Write information for all processes associated with terminals
267         //     Implementations may omit session leaders from this list
268         // -A  Write information for all processes
269         // -d  Write information for all processes, except session leaders
270         // -e  Write information for all processes (equivalent to -A.)
271         // -f  Generate a full listing
272         // -l  Generate a long listing
273         // -o col1,col2,col3=header
274         //     Select which columns to display
275         /* We allow (and ignore) most of the above. FIXME */
276         opt_complementary = "o::";
277         getopt32(argc, argv, "o:aAdefl", &opt_o);
278         if (opt_o) {
279                 do {
280                         parse_o(opt_o->data);
281                         opt_o = opt_o->link;
282                 } while (opt_o);
283         } else
284                 parse_o(default_o);
285         post_process();
286
287         /* Was INT_MAX, but some libc's go belly up with printf("%.*s")
288          * and such large widths */
289         terminal_width = 30000;
290         if (isatty(1)) {
291                 get_terminal_width_height(1, &terminal_width, NULL);
292                 terminal_width--;
293         }
294         format_header();
295
296         p = NULL;
297         while ((p = procps_scan(p, need_flags))) {
298                 format_process(p);
299         }
300
301         return EXIT_SUCCESS;
302 }
303
304
305 #else /* !ENABLE_DESKTOP */
306
307
308 int ps_main(int argc, char **argv);
309 int ps_main(int argc, char **argv)
310 {
311         procps_status_t *p = NULL;
312         int i, len;
313         SKIP_SELINUX(const) int use_selinux = 0;
314         USE_SELINUX(security_context_t sid = NULL;)
315 #if !ENABLE_FEATURE_PS_WIDE
316         enum { terminal_width = 79 };
317 #else
318         int terminal_width;
319         int w_count = 0;
320 #endif
321
322 #if ENABLE_FEATURE_PS_WIDE || ENABLE_SELINUX
323 #if ENABLE_FEATURE_PS_WIDE
324         opt_complementary = "-:ww";
325         USE_SELINUX(i =) getopt32(argc, argv, USE_SELINUX("Z") "w", &w_count);
326         /* if w is given once, GNU ps sets the width to 132,
327          * if w is given more than once, it is "unlimited"
328          */
329         if (w_count) {
330                 terminal_width = (w_count==1) ? 132 : INT_MAX;
331         } else {
332                 get_terminal_width_height(1, &terminal_width, NULL);
333                 /* Go one less... */
334                 terminal_width--;
335         }
336 #else /* only ENABLE_SELINUX */
337         i = getopt32(argc, argv, "Z");
338 #endif
339 #if ENABLE_SELINUX
340         if ((i & 1) && is_selinux_enabled())
341                 use_selinux = 1;
342 #endif
343 #endif /* ENABLE_FEATURE_PS_WIDE || ENABLE_SELINUX */
344
345         if (use_selinux)
346                 puts("  PID Context                          Stat Command");
347         else
348                 puts("  PID  Uid        VSZ Stat Command");
349
350         while ((p = procps_scan(p, 0
351                         | PSSCAN_PID
352                         | PSSCAN_UIDGID
353                         | PSSCAN_STATE
354                         | PSSCAN_VSZ
355                         | PSSCAN_CMD
356         ))) {
357                 char *namecmd = p->cmd;
358 #if ENABLE_SELINUX
359                 if (use_selinux) {
360                         char sbuf[128];
361                         len = sizeof(sbuf);
362
363                         if (is_selinux_enabled()) {
364                                 if (getpidcon(p->pid, &sid) < 0)
365                                         sid = NULL;
366                         }
367
368                         if (sid) {
369                                 /* I assume sid initialized with NULL */
370                                 len = strlen(sid) + 1;
371                                 safe_strncpy(sbuf, sid, len);
372                                 freecon(sid);
373                                 sid = NULL;
374                         } else {
375                                 safe_strncpy(sbuf, "unknown", 7);
376                         }
377                         len = printf("%5u %-32s %s ", p->pid, sbuf, p->state);
378                 } else
379 #endif
380                 {
381                         const char *user = get_cached_username(p->uid);
382                         if (p->vsz == 0)
383                                 len = printf("%5u %-8s        %s ",
384                                         p->pid, user, p->state);
385                         else
386                                 len = printf("%5u %-8s %6ld %s ",
387                                         p->pid, user, p->vsz, p->state);
388                 }
389
390                 i = terminal_width-len;
391
392                 if (namecmd && namecmd[0]) {
393                         if (i < 0)
394                                 i = 0;
395                         if (strlen(namecmd) > (size_t)i)
396                                 namecmd[i] = 0;
397                         puts(namecmd);
398                 } else {
399                         namecmd = p->comm;
400                         if (i < 2)
401                                 i = 2;
402                         if (strlen(namecmd) > ((size_t)i-2))
403                                 namecmd[i-2] = 0;
404                         printf("[%s]\n", namecmd);
405                 }
406         }
407         if (ENABLE_FEATURE_CLEAN_UP)
408                 clear_username_cache();
409         return EXIT_SUCCESS;
410 }
411
412 #endif /* ENABLE_DESKTOP */