7e127739cb7d386ef9246ac8f5db9dc0e142e8cf
[platform/upstream/busybox.git] / procps / pstree.c
1 /*
2  * pstree.c - display process tree
3  *
4  * Copyright (C) 1993-2002 Werner Almesberger
5  * Copyright (C) 2002-2009 Craig Small
6  * Copyright (C) 2010 Lauri Kasanen
7  *
8  * Based on pstree (PSmisc) 22.13.
9  *
10  * Licensed under GPLv2, see file LICENSE in this source tree.
11  */
12
13 //config:config PSTREE
14 //config:       bool "pstree"
15 //config:       default y
16 //config:       help
17 //config:         Display a tree of processes.
18
19 //applet:IF_PSTREE(APPLET(pstree, _BB_DIR_USR_BIN, _BB_SUID_DROP))
20
21 //kbuild:lib-$(CONFIG_PSTREE) += pstree.o
22
23 //usage:#define pstree_trivial_usage
24 //usage:        "[-p] [PID|USER]"
25 //usage:#define pstree_full_usage "\n\n"
26 //usage:       "Display process tree, optionally start from USER or PID\n"
27 //usage:     "\nOptions:"
28 //usage:     "\n        -p      Show pids"
29
30 #include "libbb.h"
31
32 #define PROC_BASE "/proc"
33
34 #define OPT_PID  (1 << 0)
35
36 struct child;
37
38 typedef struct proc {
39         char comm[COMM_LEN + 1];
40 //      char flags; - unused, delete?
41         pid_t pid;
42         uid_t uid;
43         struct child *children;
44         struct proc *parent;
45         struct proc *next;
46 } PROC;
47
48 /* For flags above */
49 //#define PFLAG_THREAD  0x01
50
51 typedef struct child {
52         PROC *child;
53         struct child *next;
54 } CHILD;
55
56 #define empty_2  "  "
57 #define branch_2 "|-"
58 #define vert_2   "| "
59 #define last_2   "`-"
60 #define single_3 "---"
61 #define first_3  "-+-"
62
63 struct globals {
64         /* 0-based. IOW: the number of chars we printer on current line */
65         unsigned cur_x;
66         unsigned output_width;
67
68         /* The buffers will be dynamically increased in size as needed */
69         unsigned capacity;
70         unsigned *width;
71         uint8_t *more;
72
73         PROC *list;
74
75         smallint dumped; /* used by dump_by_user */
76 };
77 #define G (*ptr_to_globals)
78 #define INIT_G() do { \
79         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
80 } while (0)
81
82
83 /*
84  * Allocates additional buffer space for width and more as needed.
85  * The first call will allocate the first buffer.
86  *
87  * bufindex  the index that will be used after the call to this function.
88  */
89 static void ensure_buffer_capacity(int bufindex)
90 {
91         if (bufindex >= G.capacity) {
92                 G.capacity += 0x100;
93                 G.width = xrealloc(G.width, G.capacity * sizeof(G.width[0]));
94                 G.more = xrealloc(G.more, G.capacity * sizeof(G.more[0]));
95         }
96 }
97
98 #if ENABLE_FEATURE_CLEAN_UP
99 static void maybe_free_buffers(void)
100 {
101         free(G.width);
102         free(G.more);
103 }
104 #else
105 # define maybe_free_buffers() ((void)0)
106 #endif
107
108 /* NB: this function is never called with "bad" chars
109  * (control chars or chars >= 0x7f)
110  */
111 static void out_char(char c)
112 {
113         G.cur_x++;
114         if (G.cur_x > G.output_width)
115                 return;
116         if (G.cur_x == G.output_width)
117                 c = '+';
118         putchar(c);
119 }
120
121 /* NB: this function is never called with "bad" chars
122  * (control chars or chars >= 0x7f)
123  */
124 static void out_string(const char *str)
125 {
126         while (*str)
127                 out_char(*str++);
128 }
129
130 static void out_newline(void)
131 {
132         putchar('\n');
133         G.cur_x = 0;
134 }
135
136 static PROC *find_proc(pid_t pid)
137 {
138         PROC *walk;
139
140         for (walk = G.list; walk; walk = walk->next)
141                 if (walk->pid == pid)
142                         break;
143
144         return walk;
145 }
146
147 static PROC *new_proc(const char *comm, pid_t pid, uid_t uid)
148 {
149         PROC *new = xzalloc(sizeof(*new));
150
151         strcpy(new->comm, comm);
152         new->pid = pid;
153         new->uid = uid;
154         new->next = G.list;
155
156         G.list = new;
157         return G.list;
158 }
159
160 static void add_child(PROC *parent, PROC *child)
161 {
162         CHILD *new, **walk;
163         int cmp;
164
165         new = xmalloc(sizeof(*new));
166
167         new->child = child;
168         for (walk = &parent->children; *walk; walk = &(*walk)->next) {
169                 cmp = strcmp((*walk)->child->comm, child->comm);
170                 if (cmp > 0)
171                         break;
172                 if (cmp == 0 && (*walk)->child->uid > child->uid)
173                         break;
174         }
175         new->next = *walk;
176         *walk = new;
177 }
178
179 static void add_proc(const char *comm, pid_t pid, pid_t ppid,
180                         uid_t uid /*, char isthread*/)
181 {
182         PROC *this, *parent;
183
184         this = find_proc(pid);
185         if (!this)
186                 this = new_proc(comm, pid, uid);
187         else {
188                 strcpy(this->comm, comm);
189                 this->uid = uid;
190         }
191
192         if (pid == ppid)
193                 ppid = 0;
194 //      if (isthread)
195 //              this->flags |= PFLAG_THREAD;
196
197         parent = find_proc(ppid);
198         if (!parent)
199                 parent = new_proc("?", ppid, 0);
200
201         add_child(parent, this);
202         this->parent = parent;
203 }
204
205 static int tree_equal(const PROC *a, const PROC *b)
206 {
207         const CHILD *walk_a, *walk_b;
208
209         if (strcmp(a->comm, b->comm) != 0)
210                 return 0;
211         if ((option_mask32 /*& OPT_PID*/) && a->pid != b->pid)
212                 return 0;
213
214         for (walk_a = a->children, walk_b = b->children;
215           walk_a && walk_b;
216           walk_a = walk_a->next, walk_b = walk_b->next
217         ) {
218                 if (!tree_equal(walk_a->child, walk_b->child))
219                         return 0;
220         }
221
222         return !(walk_a || walk_b);
223 }
224
225 static int out_args(const char *mystr)
226 {
227         const char *here;
228         int strcount = 0;
229         char tmpstr[5];
230
231         for (here = mystr; *here; here++) {
232                 if (*here == '\\') {
233                         out_string("\\\\");
234                         strcount += 2;
235                 } else if (*here >= ' ' && *here < 0x7f) {
236                         out_char(*here);
237                         strcount++;
238                 } else {
239                         sprintf(tmpstr, "\\%03o", (unsigned char) *here);
240                         out_string(tmpstr);
241                         strcount += 4;
242                 }
243         }
244
245         return strcount;
246 }
247
248 static void
249 dump_tree(PROC *current, int level, int rep, int leaf, int last, int closing)
250 {
251         CHILD *walk, *next, **scan;
252         int lvl, i, add, offset, count, comm_len, first;
253         char tmp[sizeof(int)*3 + 4];
254
255         if (!current)
256                 return;
257
258         if (!leaf) {
259                 for (lvl = 0; lvl < level; lvl++) {
260                         i = G.width[lvl] + 1;
261                         while (--i >= 0)
262                                 out_char(' ');
263
264                         if (lvl == level - 1) {
265                                 if (last) {
266                                         out_string(last_2);
267                                 } else {
268                                         out_string(branch_2);
269                                 }
270                         } else {
271                                 if (G.more[lvl + 1]) {
272                                         out_string(vert_2);
273                                 } else {
274                                         out_string(empty_2);
275                                 }
276                         }
277                 }
278         }
279
280         add = 0;
281         if (rep > 1) {
282                 add += sprintf(tmp, "%d*[", rep);
283                 out_string(tmp);
284         }
285         comm_len = out_args(current->comm);
286         if (option_mask32 /*& OPT_PID*/) {
287                 comm_len += sprintf(tmp, "(%d)", (int)current->pid);
288                 out_string(tmp);
289         }
290         offset = G.cur_x;
291
292         if (!current->children) {
293                 while (closing--)
294                         out_char(']');
295                 out_newline();
296         }
297         ensure_buffer_capacity(level);
298         G.more[level] = !last;
299
300         G.width[level] = comm_len + G.cur_x - offset + add;
301         if (G.cur_x >= G.output_width) {
302                 //out_string(first_3); - why? it won't print anything
303                 //out_char('+');
304                 out_newline();
305                 return;
306         }
307
308         first = 1;
309         for (walk = current->children; walk; walk = next) {
310                 count = 0;
311                 next = walk->next;
312                 scan = &walk->next;
313                 while (*scan) {
314                         if (!tree_equal(walk->child, (*scan)->child))
315                                 scan = &(*scan)->next;
316                         else {
317                                 if (next == *scan)
318                                         next = (*scan)->next;
319                                 count++;
320                                 *scan = (*scan)->next;
321                         }
322                 }
323                 if (first) {
324                         out_string(next ? first_3 : single_3);
325                         first = 0;
326                 }
327
328                 dump_tree(walk->child, level + 1, count + 1,
329                                 walk == current->children, !next,
330                                 closing + (count ? 1 : 0));
331         }
332 }
333
334 static void dump_by_user(PROC *current, uid_t uid)
335 {
336         const CHILD *walk;
337
338         if (!current)
339                 return;
340
341         if (current->uid == uid) {
342                 if (G.dumped)
343                         putchar('\n');
344                 dump_tree(current, 0, 1, 1, 1, 0);
345                 G.dumped = 1;
346                 return;
347         }
348         for (walk = current->children; walk; walk = walk->next)
349                 dump_by_user(walk->child, uid);
350 }
351
352 static void handle_thread(const char *comm, pid_t pid, pid_t ppid, uid_t uid)
353 {
354         char threadname[COMM_LEN + 2];
355         sprintf(threadname, "{%.*s}", COMM_LEN - 2, comm);
356         add_proc(threadname, pid, ppid, uid/*, 1*/);
357 }
358
359 static void mread_proc(void)
360 {
361         procps_status_t *p = NULL;
362         pid_t parent = 0;
363         int flags = PSSCAN_COMM | PSSCAN_PID | PSSCAN_PPID | PSSCAN_UIDGID | PSSCAN_TASKS;
364
365         while ((p = procps_scan(p, flags)) != NULL) {
366 #if ENABLE_FEATURE_SHOW_THREADS
367                 if (p->pid != p->main_thread_pid)
368                         handle_thread(p->comm, p->pid, parent, p->uid);
369                 else
370 #endif
371                 {
372                         add_proc(p->comm, p->pid, p->ppid, p->uid/*, 0*/);
373                         parent = p->pid;
374                 }
375         }
376 }
377
378 int pstree_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
379 int pstree_main(int argc UNUSED_PARAM, char **argv)
380 {
381         pid_t pid = 1;
382         long uid = 0;
383
384         INIT_G();
385
386         get_terminal_width_height(1, &G.output_width, NULL);
387
388         getopt32(argv, "p");
389         argv += optind;
390
391         if (argv[0]) {
392                 if (argv[1])
393                         bb_show_usage();
394                 if (argv[0][0] >= '0' && argv[0][0] <= '9') {
395                         pid = xatoi(argv[0]);
396                 } else {
397                         uid = xuname2uid(argv[0]);
398                 }
399         }
400
401         mread_proc();
402
403         if (!uid)
404                 dump_tree(find_proc(pid), 0, 1, 1, 1, 0);
405         else {
406                 dump_by_user(find_proc(1), uid);
407                 if (!G.dumped) {
408                         bb_error_msg_and_die("no processes found");
409                 }
410         }
411
412         maybe_free_buffers();
413         return 0;
414 }