• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* ps.c - show process list
2  *
3  * Copyright 2015 Rob Landley <rob@landley.net>
4  *
5  * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html
6  * And http://kernel.org/doc/Documentation/filesystems/proc.txt Table 1-4
7  * And linux kernel source fs/proc/array.c function do_task_stat()
8  *
9  * Deviations from posix: no -n because /proc/self/wchan exists; we use -n to
10  * mean "show numeric users and groups" instead.
11  * Posix says default output should have field named "TTY" but if you "-o tty"
12  * the same field should be called "TT" which is _INSANE_ and I'm not doing it.
13  * Similarly -f outputs USER but calls it UID (we call it USER).
14  * It also says that -o "args" and "comm" should behave differently but use
15  * the same title, which is not the same title as the default output. (No.)
16  * Select by session id is -s not -g. Posix doesn't say truncated fields
17  * should end with "+" but it's pretty common behavior.
18  *
19  * Posix defines -o ADDR as "The address of the process" but the process
20  * start address is a constant on any elf system with mmu. The procps ADDR
21  * field always prints "-" with an alignment of 1, which is why it has 11
22  * characters left for "cmd" in in 80 column "ps -l" mode. On x86-64 you
23  * need 12 chars, leaving nothing for cmd: I.E. posix 2008 ps -l mode can't
24  * be sanely implemented on 64 bit Linux systems. In procps there's ps -y
25  * which changes -l by removing the "F" column and swapping RSS for ADDR,
26  * leaving 9 chars for cmd, so we're using that as our -l output.
27  *
28  * Added a bunch of new -o fields posix doesn't mention, and we don't
29  * label "ps -o command,args,comm" as "COMMAND COMMAND COMMAND". We don't
30  * output argv[0] unmodified for -o comm or -o args (but procps violates
31  * posix for -o comm anyway, it's stat[2] not argv[0]).
32  *
33  * Note: iotop is STAYROOT so it can read other process's /proc/$PID/io
34  *       files (why they're not globally readable when the rest of proc
35  *       data is...?) and get a global I/O picture. Normal top is NOT,
36  *       even though you can -o AIO there, to give sysadmins the option
37  *       to reduce security exposure.)
38  *
39  * TODO: ps aux (att & bsd style "ps -ax" vs "ps ax" behavior difference)
40  * TODO: switch -fl to -y
41  * TODO: thread support /proc/$d/task/%d/stat (and -o stat has "l")
42  * TODO: iotop: Window size change: respond immediately. Why not padding
43  *       at right edge? (Not adjusting to screen size at all? Header wraps?)
44  * TODO: top: thread support and SMP
45  * TODO: pgrep -f only searches the amount of cmdline that fits in toybuf.
46  * TODO: pgrep qemu-system-i386 never matches because one char too long
47 
48 USE_PS(NEWTOY(ps, "k(sort)*P(ppid)*aAdeflMno*O*p(pid)*s*t*Tu*U*g*G*wZ[!ol][+Ae][!oO]", TOYFLAG_BIN))
49 // stayroot because iotop needs root to read other process' proc/$$/io
50 // TOP and IOTOP have a large common option block used for common processing,
51 // the default values are different but the flags are in the same order.
52 USE_TOP(NEWTOY(top, ">0O*h" "Hk*o*p*u*s#<1d%<100=3000m#n#<1bq[!oO]", TOYFLAG_USR|TOYFLAG_BIN))
53 USE_IOTOP(NEWTOY(iotop, ">0AaKO" "Hk*o*p*u*s#<1=7d%<100=3000m#n#<1bq", TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_STAYROOT))
54 USE_PGREP(NEWTOY(pgrep, "acld:u*U*t*s*P*g*G*fnovxL:[-no]", TOYFLAG_USR|TOYFLAG_BIN))
55 USE_PKILL(NEWTOY(pkill,    "?Vu*U*t*s*P*g*G*fnovxl:[-no]", TOYFLAG_USR|TOYFLAG_BIN))
56 
57 config PS
58   bool "ps"
59   default y
60   help
61     usage: ps [-AadefLlnwZ] [-gG GROUP,] [-k FIELD,] [-o FIELD,] [-p PID,] [-t TTY,] [-uU USER,]
62 
63     List processes.
64 
65     Which processes to show (-gGuUpPt selections may be comma separated lists):
66 
67     -A  All					-a  Has terminal not session leader
68     -d  All but session leaders		-e  Synonym for -A
69     -g  In GROUPs				-G  In real GROUPs (before sgid)
70     -p  PIDs (--pid)			-P  Parent PIDs (--ppid)
71     -s  In session IDs			-t  Attached to selected TTYs
72     -T  Show threads also			-u  Owned by selected USERs
73     -U  Real USERs (before suid)
74 
75     Output modifiers:
76 
77     -k  Sort FIELDs (-FIELD to reverse)	-M  Measure/pad future field widths
78     -n  Show numeric USER and GROUP		-w  Wide output (don't truncate fields)
79 
80     Which FIELDs to show. (-o HELP for list, default = -o PID,TTY,TIME,CMD)
81 
82     -f  Full listing (-o USER:12=UID,PID,PPID,C,STIME,TTY,TIME,ARGS=CMD)
83     -l  Long listing (-o F,S,UID,PID,PPID,C,PRI,NI,ADDR,SZ,WCHAN,TTY,TIME,CMD)
84     -o  Output FIELDs instead of defaults, each with optional :size and =title
85     -O  Add FIELDS to defaults
86     -Z  Include LABEL
87 
88 config TOP
89   bool "top"
90   default y
91   help
92     usage: top [-Hhbq] [-k FIELD,] [-o FIELD,] [-s SORT] [-n NUMBER] [-m LINES] [-d SECONDS] [-p PID,] [-u USER,]
93 
94     Show process activity in real time.
95 
96     -H	Show threads
97     -h	Usage graphs instead of text
98     -k	Fallback sort FIELDS (default -S,-%CPU,-ETIME,-PID)
99     -o	Show FIELDS (def PID,USER,PR,NI,VIRT,RES,SHR,S,%CPU,%MEM,TIME+,CMDLINE)
100     -O	Add FIELDS (replacing PR,NI,VIRT,RES,SHR,S from default)
101     -s	Sort by field number (1-X, default 9)
102     -b	Batch mode (no tty)
103     -d	Delay SECONDS between each cycle (default 3)
104     -m	Maximum number of tasks to show
105     -n	Exit after NUMBER iterations
106     -p	Show these PIDs
107     -u	Show these USERs
108     -q	Quiet (no header lines)
109 
110     Cursor UP/DOWN or LEFT/RIGHT to move list, SHIFT LEFT/RIGHT to change sort,
111     space to force update, R to reverse sort, Q to exit.
112 
113 # Requires CONFIG_IRQ_TIME_ACCOUNTING in the kernel for /proc/$$/io
114 config IOTOP
115   bool "iotop"
116   default y
117   help
118     usage: iotop [-AaKObq] [-n NUMBER] [-d SECONDS] [-p PID,] [-u USER,]
119 
120     Rank processes by I/O.
121 
122     -A	All I/O, not just disk
123     -a	Accumulated I/O (not percentage)
124     -H	Show threads
125     -K	Kilobytes
126     -k	Fallback sort FIELDS (default -[D]IO,-ETIME,-PID)
127     -m	Maximum number of tasks to show
128     -O	Only show processes doing I/O
129     -o	Show FIELDS (default PID,PR,USER,[D]READ,[D]WRITE,SWAP,[D]IO,COMM)
130     -s	Sort by field number (0-X, default 6)
131     -b	Batch mode (no tty)
132     -d	Delay SECONDS between each cycle (default 3)
133     -n	Exit after NUMBER iterations
134     -p	Show these PIDs
135     -u	Show these USERs
136     -q	Quiet (no header lines)
137 
138     Cursor LEFT/RIGHT to change sort, UP/DOWN move list, space to force
139     update, R to reverse sort, Q to exit.
140 
141 config PGREP
142   bool "pgrep"
143   default y
144   help
145     usage: pgrep [-aclfnovx] [-d DELIM] [-L SIGNAL] [PATTERN] [-G GID,] [-g PGRP,] [-P PPID,] [-s SID,] [-t TERM,] [-U UID,] [-u EUID,]
146 
147     Search for process(es). PATTERN is an extended regular expression checked
148     against command names.
149 
150     -a	Show the full command line
151     -c	Show only count of matches
152     -d	Use DELIM instead of newline
153     -L	Send SIGNAL instead of printing name
154     -l	Show command name
155     -f	Check full command line for PATTERN
156     -G	Match real Group ID(s)
157     -g	Match Process Group(s) (0 is current user)
158     -n	Newest match only
159     -o	Oldest match only
160     -P	Match Parent Process ID(s)
161     -s	Match Session ID(s) (0 for current)
162     -t	Match Terminal(s)
163     -U	Match real User ID(s)
164     -u	Match effective User ID(s)
165     -v	Negate the match
166     -x	Match whole command (not substring)
167 
168 config PKILL
169   bool "pkill"
170   default y
171   help
172     usage: pkill [-fnovx] [-SIGNAL|-l SIGNAL] [PATTERN] [-G GID,] [-g PGRP,] [-P PPID,] [-s SID,] [-t TERM,] [-U UID,] [-u EUID,]
173 
174     -l	Send SIGNAL (default SIGTERM)
175     -V	Verbose
176     -f	Check full command line for PATTERN
177     -G	Match real Group ID(s)
178     -g	Match Process Group(s) (0 is current user)
179     -n	Newest match only
180     -o	Oldest match only
181     -P	Match Parent Process ID(s)
182     -s	Match Session ID(s) (0 for current)
183     -t	Match Terminal(s)
184     -U	Match real User ID(s)
185     -u	Match effective User ID(s)
186     -v	Negate the match
187     -x	Match whole command (not substring)
188 */
189 
190 #define FOR_ps
191 #include "toys.h"
192 
193 GLOBALS(
194   union {
195     struct {
196       struct arg_list *G, *g, *U, *u, *t, *s, *p, *O, *o, *P, *k;
197     } ps;
198     struct {
199       long n, m, d, s;
200       struct arg_list *u, *p, *o, *k, *O;
201     } top;
202     struct {
203       char *L;
204       struct arg_list *G, *g, *P, *s, *t, *U, *u;
205       char *d;
206 
207       void *regexes, *snapshot;
208       int signal;
209       pid_t self, match;
210     } pgrep;
211   };
212 
213   struct ps_ptr_len {
214     void *ptr;
215     long len;
216   } gg, GG, pp, PP, ss, tt, uu, UU;
217   struct dirtree *threadparent;
218   unsigned width, height, scroll;
219   dev_t tty;
220   void *fields, *kfields;
221   long long ticks, bits, time;
222   int kcount, forcek, sortpos, pidlen;
223   int (*match_process)(long long *slot);
224   void (*show_process)(void *tb);
225 )
226 
227 // Linked list of -o fields selected for display, in order, with :len and =title
228 
229 struct ofields {
230   struct ofields *next, *prev;
231   short which, len, reverse;
232   char *title;
233 };
234 
235 /* The function get_ps() reads all the data about one process, saving it in
236  * toybox as a struct procpid. Simple ps calls then pass toybuf directly to
237  * show_ps(), but features like sorting append a copy to a linked list
238  * for further processing once all processes have been read.
239  *
240  * struct procpid contains a slot[] array of 64 bit values, with the following
241  * data at each position in the array. Most is read from /proc/$PID/stat (see
242  * https://kernel.org/doc/Documentation/filesystems/proc.txt table 1-4) but
243  * we replace several fields with don't use with other data. */
244 
245 enum {
246  SLOT_pid,      /*process id*/            SLOT_ppid,      // parent process id
247  SLOT_pgrp,     /*process group*/         SLOT_sid,       // session id
248  SLOT_ttynr,    /*tty the process uses*/  SLOT_ttypgrp,   // pgrp of the tty
249  SLOT_flags,    /*task flags*/            SLOT_minflt,    // minor faults
250  SLOT_cminflt,  /*minor faults+child*/    SLOT_majflt,    // major faults
251  SLOT_cmajflt,  /*major faults+child*/    SLOT_utime,     // user+kernel jiffies
252  SLOT_stime,    /*kernel mode jiffies*/   SLOT_cutime,    // utime+child utime
253  SLOT_cstime,   /*stime+child*/           SLOT_priority,  // priority level
254  SLOT_nice,     /*nice level*/            SLOT_numthreads,// thread count
255  SLOT_vmlck,    /*locked memory*/         SLOT_starttime, // jiffies after boot
256  SLOT_vsize,    /*virtual memory size*/   SLOT_rss,       // resident set size
257  SLOT_rsslim,   /*limit in bytes on rss*/ SLOT_startcode, // code segment addr
258  SLOT_endcode,  /*code segment address*/  SLOT_startstack,// stack address
259  SLOT_esp,      /*task stack pointer*/    SLOT_eip,       // instruction pointer
260  SLOT_iobytes,  /*All I/O bytes*/         SLOT_diobytes,  // disk I/O bytes
261  SLOT_utime2,   /*relative utime (top)*/  SLOT_uid,       // user id
262  SLOT_ruid,     /*real user id*/          SLOT_gid,       // group id
263  SLOT_rgid,     /*real group id*/         SLOT_exitsig,   // sent to parent
264  SLOT_taskcpu,  /*CPU running on*/        SLOT_rtprio,    // realtime priority
265  SLOT_policy,   /*man sched_setscheduler*/SLOT_blkioticks,// IO wait time
266  SLOT_gtime,    /*guest jiffies of task*/ SLOT_cgtime,    // gtime+child
267  SLOT_startbss, /*data/bss address*/      SLOT_endbss,    // end addr data+bss
268 // end of /proc/$PID/stat fields
269  SLOT_upticks,  /*uptime-starttime*/      SLOT_argv0len,  // argv[0] length
270  SLOT_uptime,   /*sysinfo.uptime*/        SLOT_totalram,  // sysinfo.totalram
271  SLOT_vsz,      /*Virtual mem Size*/      SLOT_shr,       // Shared memory
272  SLOT_pcy,      /*Android sched pol*/     SLOT_rchar,     // All bytes read
273  SLOT_wchar,    /*All bytes written*/     SLOT_rbytes,    // Disk bytes read
274  SLOT_wbytes,   /*Disk bytes written*/    SLOT_swap,      // Swap pages used
275  SLOT_bits,     /*32 or 64*/              SLOT_tid,       // Thread ID
276  SLOT_tcount,   /*Thread count*/
277 
278  SLOT_count /* Size of array */
279 };
280 
281 /* In addition to slot[], carevup contains 6 string fields to display
282    command name, tty device, selinux label... They're stored one after the
283    other in str[] (separated by null terminators), and offset[] contains the
284    starting position of each string after the first (which is always 0). */
285 
286 // Data layout in toybuf
287 struct procpid {
288   long long slot[SLOT_count]; // data (see enum above)
289   unsigned short offset[6];   // offset of fields in str[] (skip CMD, always 0)
290   char state;
291   char pcy[3];                // Android scheduling policy
292   char str[];                 // CMD, TTY, WCHAN, LABEL, COMM, ARGS, NAME
293 };
294 
295 /* The typos[] array lists all the types understood by "ps -o", I.E all the
296  * columns ps and top know how to display. Each entry has:
297  *
298  * name: the column name, displayed at top and used to select column with -o
299  *
300  * width: the display width. Fields are padded to this width when displaying
301  *        to a terminal (negative means right justified). Strings are truncated
302  *        to fit, numerical fields are padded but not truncated (although
303  *        the display code reclaims unused padding from later fields to try to
304  *        get the overflow back).
305  *
306  * slot: which slot[] out of procpid. Negative means it's a string field.
307  *       value|XX requests extra display/sort processing.
308  *
309  * The TAGGED_ARRAY plumbing produces an enum of indexes, the "tag" is the
310  * first string argument and the prefix is the first argument to TAGGED_ARRAY
311  * so in this case "NAME" becomes PS_NAME which is the offset into typos[]
312  * for that entry, and also _PS_NAME (the bit position, 1<<PS_NAME).
313  * We record active columns in TT.bits, ala:
314  *
315  *   if (TT.bits & _PS_NAME) printf("-o included PS_NAME");
316  */
317 
318 #define XX 64 // force string representation for sorting, etc
319 
320 // TODO: Android uses -30 for LABEL, but ideally it would auto-size.
321 struct typography {
322   char *name, *help;
323   signed char width, slot;
324 } static const typos[] = TAGGED_ARRAY(PS,
325   // Numbers. (What's in slot[] is what's displayed, sorted numerically.)
326   {"PID", "Process ID", 6, SLOT_pid},
327   {"PPID", "Parent Process ID", 6, SLOT_ppid},
328   {"PRI", "Priority (dynamic 0 to 139)", 3, SLOT_priority},
329   {"NI", "Niceness (static 19 to -20)", 3, SLOT_nice},
330   {"ADDR", "Instruction pointer", 4+sizeof(long), SLOT_eip},
331   {"SZ", "4k pages to swap out", 5, SLOT_vsize},
332   {"RSS", "Resident Set Size (DRAM pages)", 6, SLOT_rss},
333   {"PGID", "Process Group ID", 5, SLOT_pgrp},
334   {"VSZ", "Virtual memory size (1k units)", 7, SLOT_vsize},
335   {"MAJFL", "Major page faults", 6, SLOT_majflt},
336   {"MINFL", "Minor page faults", 6, SLOT_minflt},
337   {"PR", "Prio Reversed (dyn 39-0, RT)", 2, SLOT_priority},
338   {"PSR", "Processor last executed on", 3, SLOT_taskcpu},
339   {"RTPRIO", "Realtime priority", 6, SLOT_rtprio},
340   {"SCH", "Scheduling policy (0=other, 1=fifo, 2=rr, 3=batch, 4=iso, 5=idle)",
341    3, SLOT_policy},
342   {"CPU", "Which processor running on", 3, SLOT_taskcpu},
343   {"TID", "Thread ID", 5, SLOT_tid},
344   {"TCNT", "Thread count", 4, SLOT_tcount},
345   {"BIT", "32 or 64", 3, SLOT_bits},
346 
347   // String fields (-1 is procpid->str, rest are str+offset[1-slot])
348   {"TTY", "Controlling terminal", -8, -2},
349   {"WCHAN", "Wait location in kernel", -6, -3},
350   {"LABEL", "Security label", -30, -4},
351   {"COMM", "EXE filename (/proc/PID/exe)", -27, -5},
352   {"NAME", "Process name (PID's argv[0])", -27, -7},
353   {"COMMAND", "EXE path (/proc/PID/exe)", -27, -5},
354   {"CMDLINE", "Command line (argv[])", -27, -6},
355   {"ARGS", "CMDLINE minus initial path", -27, -6},
356   {"CMD", "Thread name (/proc/TID/stat:2)", -15, -1},
357 
358   // user/group (may call getpwuid() or similar)
359   {"UID", "User id", 5, SLOT_uid},
360   {"USER", "User name", -12, XX|SLOT_uid},
361   {"RUID", "Real (before suid) user ID", 4, SLOT_ruid},
362   {"RUSER", "Real (before suid) user name", -8, XX|SLOT_ruid},
363   {"GID", "Group ID", 8, SLOT_gid},
364   {"GROUP", "Group name", -8, XX|SLOT_gid},
365   {"RGID", "Real (before sgid) Group ID", 4, SLOT_rgid},
366   {"RGROUP", "Real (before sgid) group name", -8, XX|SLOT_rgid},
367 
368   // clock displays (00:00:00)
369   {"TIME", "CPU time consumed", 8, SLOT_utime},
370   {"ELAPSED", "Elapsed time since PID start", 11, SLOT_starttime},
371   {"TIME+", "CPU time (high precision)", 9, SLOT_utime},
372 
373   // Percentage displays (fixed point, one decimal digit. 123 -> 12.3)
374   {"C", "Total %CPU used since start", 1, SLOT_utime2},
375   {"%VSZ", "VSZ as % of physical memory", 5, SLOT_vsize},
376   {"%MEM", "RSS as % of physical memory", 5, SLOT_rss},
377   {"%CPU", "Percentage of CPU time used", 4, SLOT_utime2},
378 
379   // human_readable (function human_readable() in lib, 1.23M, 1.4G, etc)
380   {"VIRT", "Virtual memory size", 4, SLOT_vsz},
381   {"RES", "Short RSS", 4, SLOT_rss},
382   {"SHR", "Shared memory", 4, SLOT_shr},
383   {"READ", "Data read", 6, SLOT_rchar},
384   {"WRITE", "Data written", 6, SLOT_wchar},
385   {"IO", "Data I/O", 6, SLOT_iobytes},
386   {"DREAD", "Data read from disk", 6, SLOT_rbytes},
387   {"DWRITE", "Data written to disk", 6, SLOT_wbytes},
388   {"SWAP", "Swap I/O", 6, SLOT_swap},
389   {"DIO", "Disk I/O", 6, SLOT_diobytes},
390 
391   // Misc (special cases)
392   {"STIME", "Start time (ISO 8601)", 5, SLOT_starttime},
393   {"F", "Flags 1=FORKNOEXEC 4=SUPERPRIV", 1, XX|SLOT_flags},
394   {"S", "Process state:\n"
395    "\t  R (running) S (sleeping) D (device I/O) T (stopped)  t (trace stop)\n"
396    "\t  X (dead)    Z (zombie)   P (parked)     I (idle)\n"
397    "\t  Also between Linux 2.6.33 and 3.13:\n"
398    "\t  x (dead)    K (wakekill) W (waking)\n",
399    -1, XX},
400   {"STAT", "Process state (S) plus:\n"
401    "\t  < high priority          N low priority L locked memory\n"
402    "\t  s session leader         + foreground   l multithreaded",
403    -5, XX},
404   {"PCY", "Android scheduling policy", 3, XX|SLOT_pcy},
405 );
406 
407 // Show sorted "-o help" text for fields listed in toybuf[len]
help_fields(int len,int multi)408 static void help_fields(int len, int multi)
409 {
410   int i, j, k, left = 0;
411   struct typography *t;
412 
413   // Quick and dirty sort of toybuf[] entries (see TODO below)
414   for (j = len; j--; ) {
415     k = -1;
416 
417     for (i=0; i<j; i++) {
418       if (strcmp(typos[toybuf[i]].name, typos[toybuf[i+1]].name)>0) {
419         k = toybuf[i];
420         toybuf[i] = toybuf[i+1];
421         toybuf[i+1] = k;
422       }
423     }
424     if (k == -1) break;
425   }
426 
427   // Display loop
428   for (i = j = 0; i<len; i++, j++) {
429     t = (void *)(typos+toybuf[i]);
430     if (strlen(t->help)>30) {
431       if (multi) printf("  %-8s%s\n", t->name, t->help);
432       else j--;
433     } else if (!multi) {
434       left = !(j&1);
435       printf("  %-8s%*s%c"+2*!left, t->name, -30*left, t->help, 10+22*left);
436     }
437   }
438   if (!multi && left) xputc('\n');
439 }
440 
441 // Print help text for each -o field, with categories.
help_help(void)442 static void help_help(void)
443 {
444   int i, jump = PS_CMD+1-PS_COMM;
445 
446   // TODO: sort the array of -o types so they're already alphabetical and
447   // don't need sorting here. A regex to find everything that currently cares
448   // about symbol order might be: "which *[><]=* *PS"
449 
450   // First show the half-dozen variants of command line display.
451 
452   printf("Command line field types:\n\n");
453   for (i = 0; i<jump; i++) toybuf[i] = PS_COMM+i;
454   help_fields(jump, 0);
455 
456   // Show the rest of the -o types, starting with the ones that don't columnize
457 
458   printf("\nProcess attribute field types:\n\n");
459   for (i = 0; i<ARRAY_LEN(typos)-jump; i++) toybuf[i] = i+(i>=PS_COMM)*jump;
460   help_fields(ARRAY_LEN(typos)-jump, 1);
461   help_fields(ARRAY_LEN(typos)-jump, 0);
462 
463   xexit();
464 }
465 
466 // process match filter for top/ps/pgrep: Return 0 to discard, nonzero to keep
shared_match_process(long long * slot)467 static int shared_match_process(long long *slot)
468 {
469   struct ps_ptr_len match[] = {
470     {&TT.gg, SLOT_gid}, {&TT.GG, SLOT_rgid}, {&TT.pp, SLOT_pid},
471     {&TT.PP, SLOT_ppid}, {&TT.ss, SLOT_sid}, {&TT.tt, SLOT_ttynr},
472     {&TT.uu, SLOT_uid}, {&TT.UU, SLOT_ruid}
473   };
474   int i, j;
475   long *ll = 0;
476 
477   // Do we have -g -G -p -P -s -t -u -U options selecting processes?
478   for (i = 0; i < ARRAY_LEN(match); i++) {
479     struct ps_ptr_len *mm = match[i].ptr;
480 
481     if (mm->len) {
482       ll = mm->ptr;
483       for (j = 0; j<mm->len; j++) if (ll[j] == slot[match[i].len]) return 1;
484     }
485   }
486 
487   return ll ? 0 : -1;
488 }
489 
490 // process match filter for ps: Return 0 to discard, nonzero to keep
ps_match_process(long long * slot)491 static int ps_match_process(long long *slot)
492 {
493   int i = shared_match_process(slot);
494 
495   if (i>0) return 1;
496   // If we had selections and didn't match them, don't display
497   if (!i) return 0;
498 
499   // Filter implicit categories for other display types
500   if ((FLAG(a)||FLAG(d)) && slot[SLOT_sid]==*slot) return 0;
501   if (FLAG(a) && !slot[SLOT_ttynr]) return 0;
502   if (!(FLAG(a)||FLAG(d)||FLAG(A)||FLAG(e)) && TT.tty!=slot[SLOT_ttynr])
503     return 0;
504 
505   return 1;
506 }
507 
508 // Generate display string (260 bytes at end of toybuf) from struct ofield
string_field(struct procpid * tb,struct ofields * field)509 static char *string_field(struct procpid *tb, struct ofields *field)
510 {
511   char *buf = toybuf+sizeof(toybuf)-260, *out = buf, *s;
512   int which = field->which, sl = typos[which].slot;
513   long long *slot = tb->slot, ll = (sl >= 0) ? slot[sl&(XX-1)] : 0;
514 
515   // numbers, mostly from /proc/$PID/stat
516   if (which <= PS_BIT) {
517     char *fmt = "%lld";
518 
519     if (which==PS_PRI) ll = 39-ll;
520     if (which==PS_ADDR) fmt = "%llx";
521     else if (which==PS_SZ) ll >>= 12;
522     else if (which==PS_RSS) ll <<= 2;
523     else if (which==PS_VSZ) ll >>= 10;
524     else if (which==PS_PR && ll<-9) fmt="RT";
525     else if ((which==PS_RTPRIO || which==PS_BIT) && ll == 0) fmt="-";
526     sprintf(out, fmt, ll);
527 
528   // String fields
529   } else if (sl < 0) {
530     out = tb->str;
531     sl *= -1;
532     // First string slot has offset 0, others are offset[-slot-2]
533     if (--sl) out += tb->offset[--sl];
534     if (which==PS_ARGS || which==PS_COMM) {
535       int i;
536 
537       s = out;
538       for (i = 0; (which==PS_ARGS) ? i < slot[SLOT_argv0len] : out[i]; i++)
539         if (out[i] == '/') s = out+i+1;
540       out = s;
541     }
542     if (which>=PS_COMM && !*out) sprintf(out = buf, "[%s]", tb->str);
543 
544   // user/group
545   } else if (which <= PS_RGROUP) {
546     sprintf(out, "%lld", ll);
547     if (sl&XX) {
548       if (which > PS_RUSER) {
549         struct group *gr = bufgetgrgid(ll);
550 
551         if (gr) out = gr->gr_name;
552       } else {
553         struct passwd *pw = bufgetpwuid(ll);
554 
555         if (pw) out = pw->pw_name;
556       }
557     }
558 
559   // Clock displays
560   } else if (which <= PS_TIME_) {
561     int unit = 60, pad = 2, j = TT.ticks;
562     time_t seconds;
563 
564     if (which!=PS_TIME_) unit *= 60*24;
565     else pad = 0;
566     // top adjusts slot[SLOT_upticks], we want original meaning.
567     if (which==PS_ELAPSED) ll = (slot[SLOT_uptime]*j)-slot[SLOT_starttime];
568     seconds = ll/j;
569 
570     // Output days-hours:mins:secs, skipping non-required fields with zero
571     // TIME has 3 required fields, ETIME has 2. (Posix!) TIME+ is from top
572     for (s = 0, j = 2*(which==PS_TIME_); j<4; j++) {
573       if (!s && (seconds>unit || j == 1+(which!=PS_TIME))) s = out;
574       if (s) {
575         s += sprintf(s, j ? "%0*ld": "%*ld", pad, (long)(seconds/unit));
576         pad = 2;
577         if ((*s = "-::"[j])) s++;
578       }
579       seconds %= unit;
580       unit /= j ? 60 : 24;
581     }
582     if (which==PS_TIME_ && s-out<8)
583       sprintf(s, ".%02lld", (100*(ll%TT.ticks))/TT.ticks);
584 
585   // Percentage displays
586   } else if (which <= PS__CPU) {
587     ll = slot[sl&(XX-1)]*1000;
588     if (which==PS__VSZ || which==PS__MEM)
589       ll /= slot[SLOT_totalram]/((which==PS__VSZ) ? 1024 : 4096);
590     else if (slot[SLOT_upticks]) ll /= slot[SLOT_upticks];
591     sl = ll;
592     if (which==PS_C) sl += 5;
593     sprintf(out, "%d", sl/10);
594     if (which!=PS_C && sl<1000) sprintf(out+strlen(out), ".%d", sl%10);
595 
596   // Human readable
597   } else if (which <= PS_DIO) {
598     int i = abs(field->len);
599 
600     if (i<4) i = 4;
601     s = out;
602     if ((ll = slot[typos[which].slot])<0) {
603       ll = -ll;
604       *s++ = '-';
605       if (i>4) i--;
606     }
607     if (which <= PS_SHR) ll *= sysconf(_SC_PAGESIZE);
608     if (TT.forcek) sprintf(out, "%lldk", ll/1024);
609     else human_readable_long(s, ll, i-1, 0, 0);
610 
611   // Posix doesn't specify what flags should say. Man page says
612   // 1 for PF_FORKNOEXEC and 4 for PF_SUPERPRIV from linux/sched.h
613   } else if (which==PS_F) sprintf(out, "%llo", (slot[SLOT_flags]>>6)&5);
614   else if (which==PS_S || which==PS_STAT) {
615     s = out;
616     *s++ = tb->state;
617     if (which==PS_STAT) {
618       // TODO l = multithreaded
619       if (slot[SLOT_nice]<0) *s++ = '<';
620       else if (slot[SLOT_nice]>0) *s++ = 'N';
621       if (slot[SLOT_sid]==*slot) *s++ = 's';
622       if (slot[SLOT_vmlck]) *s++ = 'L';
623       if (slot[SLOT_ttypgrp]==*slot) *s++ = '+';
624     }
625     *s = 0;
626   } else if (which==PS_STIME) {
627     time_t t = time(0)-slot[SLOT_uptime]+slot[SLOT_starttime]/TT.ticks;
628 
629     // Padding behavior's a bit odd: default field size is just hh:mm.
630     // Increasing stime:size reveals more data at left until full,
631     // so move start address so yyyy-mm-dd hh:mm revealed on left at :16,
632     // then add :ss on right for :19.
633     strftime(out, 260, "%F %T", localtime(&t));
634     out = out+strlen(out)-3-abs(field->len);
635     if (out<buf) out = buf;
636 
637   } else if (which==PS_PCY) sprintf(out, "%.2s", tb->pcy);
638   else if (CFG_TOYBOX_DEBUG) error_exit("bad which %d", which);
639 
640   return out;
641 }
642 
643 // Display process data that get_ps() read from /proc, formatting via TT.fields
show_ps(void * p)644 static void show_ps(void *p)
645 {
646   struct procpid *tb = p;
647   struct ofields *field = TT.fields;
648   int pad, len, width = TT.width, abslen, sign, olen, scroll, extra = 0;
649 
650   // Skip TT.scroll many fields (but not last one)
651   for (scroll = TT.scroll; scroll && field->next; scroll--) field = field->next;
652 
653   // Loop through fields to display
654   for (; field; field = field->next) {
655     char *out = string_field(tb, field);
656 
657     // Output the field, appropriately padded
658 
659     // Minimum one space between each field
660     if (width<2) break;
661     if (field != TT.fields) {
662       putchar(' ');
663       width--;
664     }
665 
666     // Don't truncate number fields, but try to reclaim extra offset from later
667     // fields that can naturally be shorter
668     abslen = abs(field->len);
669     sign = field->len<0 ? -1 : 1;
670     olen = (TT.tty) ? utf8len(out) : strlen(out);
671     if ((field->which<=PS_BIT || FLAG(w)) && olen>abslen) {
672       // overflow but remember by how much
673       extra += olen-abslen;
674       abslen = olen;
675     } else if (extra && olen<abslen) {
676       int unused = abslen-olen;
677 
678       // If later fields have slack space, take back overflow
679       if (unused>extra) unused = extra;
680       abslen -= unused;
681       extra -= unused;
682     }
683     if (abslen>width) abslen = width;
684     len = pad = abslen;
685     pad *= sign;
686 
687     // If last field is left justified, no trailing spaces.
688     if (!field->next && sign<0) {
689       pad = -1;
690       len = width;
691     }
692 
693     // If we truncated a left-justified field, show + instead of last char
694     if (olen>len && len>1 && sign<0) {
695       width--;
696       len--;
697       if (field->next) pad++;
698       abslen = 0;
699     }
700 
701     if (TT.tty) width -= draw_trim(out, pad, len);
702     else width -= printf("%*.*s", pad, len, out);
703     if (!abslen) putchar('+');
704     if (!width) break;
705   }
706   putchar(TT.time ? '\r' : '\n');
707 }
708 
709 // dirtree callback: read data about a process, then display or store it.
710 // Fills toybuf with struct procpid and either DIRTREE_SAVEs a copy to ->extra
711 // (in -k mode) or calls show_ps directly on toybuf (for low memory systems).
get_ps(struct dirtree * new)712 static int get_ps(struct dirtree *new)
713 {
714   struct {
715     char *name;     // Path under /proc/$PID directory
716     long long bits; // Only fetch extra data if an -o field is displaying it
717   } fetch[] = {
718     // sources for procpid->offset[] data
719     {"fd/", _PS_TTY}, {"wchan", _PS_WCHAN}, {"attr/current", _PS_LABEL},
720     {"exe", _PS_COMMAND|_PS_COMM}, {"cmdline", _PS_CMDLINE|_PS_ARGS|_PS_NAME},
721     {"", _PS_NAME}
722   };
723   struct procpid *tb = (void *)toybuf;
724   long long *slot = tb->slot;
725   char *name, *s, *buf = tb->str, *end = 0;
726   FILE *fp;
727   struct sysinfo si;
728   int i, j, fd;
729   off_t len;
730 
731   // Recurse one level into /proc children, skip non-numeric entries
732   if (!new->parent)
733     return DIRTREE_RECURSE|DIRTREE_SHUTUP|DIRTREE_PROC
734       |(DIRTREE_SAVE*(TT.threadparent||!TT.show_process));
735 
736   // Grab PID and figure out if we're a thread or a process
737   memset(slot, 0, sizeof(tb->slot));
738   slot[SLOT_tid] = *slot = atol(new->name);
739   if (TT.threadparent && TT.threadparent->extra) {
740     struct procpid *tb2 = (struct procpid *)TT.threadparent->extra;
741 
742     *slot = *tb2->slot;
743     // Parent also shows up as a thread, but we need to reread task/stat fields
744     // to get non-collated info for just parent thread (vs whole process).
745     if (*slot == slot[SLOT_tid]) slot = tb2->slot;
746   }
747   fd = dirtree_parentfd(new);
748 
749   // Read /proc/$PID/stat into half of toybuf.
750   len = 2048;
751   sprintf(buf, "%lld/stat", slot[SLOT_tid]);
752   if (!readfileat(fd, buf, buf, &len)) return 0;
753 
754   // parse oddball fields: the first field is same as new->name (skip it)
755   // and the second and third (name and state) are the only non-numeric fields.
756   // Name has (parentheses) around it, and can have embedded ')' so match
757   // _last_ ')' (VFS limits filenames to 255 bytes max, sanity check that).
758   // TODO: kernel task struct actually limits name to 16 chars?
759   if (!(name = strchr(buf, '('))) return 0;
760   for (s = ++name; *s; s++) if (*s == ')') end = s;
761   if (!end || end-name>255) return 0;
762   if (1>sscanf(s = end, ") %c%n", &tb->state, &i)) return 0;
763 
764   // All remaining fields should be numeric, parse them into slot[] array
765   // (skipping first 3 stat fields and first slot[], both were handled above)
766   // yes this means the alignment's off: stat[4] becomes slot[1]
767   for (j = SLOT_ppid; j<SLOT_upticks; j++)
768     if (1>sscanf(s += i, " %lld%n", slot+j, &i)) break;
769 
770   // Now we've read the data, move status and name right after slot[] array,
771   // and convert low chars to ? for non-tty display while we're at it.
772   for (i = 0; i<end-name; i++)
773     if ((tb->str[i] = name[i]) < ' ')
774       if (!TT.tty) tb->str[i] = '?';
775   buf = tb->str+i;
776   *buf++ = 0;
777   len = sizeof(toybuf)-(buf-toybuf);
778 
779   // Overwrite useless/obsolete stat fields with more interesting data.
780 
781   // save uid, ruid, gid, gid, and rgid int slots 31-34 (we don't use sigcatch
782   // or numeric wchan, and the remaining two are always zero), and vmlck into
783   // 18 (which is "obsolete, always 0" from stat)
784   slot[SLOT_uid] = new->st.st_uid;
785   slot[SLOT_gid] = new->st.st_gid;
786 
787   // TIME and TIME+ use combined value, ksort needs 'em added.
788   slot[SLOT_utime] += slot[SLOT_stime];
789   slot[SLOT_utime2] = slot[SLOT_utime];
790 
791   // Do we need to read "status"?
792   if ((TT.bits&(_PS_RGROUP|_PS_RUSER|_PS_STAT|_PS_RUID|_PS_RGID|_PS_SWAP
793                |_PS_IO|_PS_DIO)) || TT.GG.len || TT.UU.len)
794   {
795     off_t temp = len;
796 
797     sprintf(buf, "%lld/status", slot[SLOT_tid]);
798     if (!readfileat(fd, buf, buf, &temp)) *buf = 0;
799     s = strafter(buf, "\nUid:");
800     slot[SLOT_ruid] = s ? atol(s) : new->st.st_uid;
801     s = strafter(buf, "\nGid:");
802     slot[SLOT_rgid] = s ? atol(s) : new->st.st_gid;
803     if ((s = strafter(buf, "\nVmLck:"))) slot[SLOT_vmlck] = atoll(s)*1024;
804     if ((s = strafter(buf, "\nVmSwap:"))) slot[SLOT_swap] = atoll(s)*1024;
805   }
806 
807   // Do we need to read "io"?
808   if (TT.bits&(_PS_READ|_PS_WRITE|_PS_DREAD|_PS_DWRITE|_PS_IO|_PS_DIO)) {
809     off_t temp = len;
810 
811     sprintf(buf, "%lld/io", slot[SLOT_tid]);
812     if (!readfileat(fd, buf, buf, &temp)) *buf = 0;
813     if ((s = strafter(buf, "rchar:"))) slot[SLOT_rchar] = atoll(s);
814     if ((s = strafter(buf, "wchar:"))) slot[SLOT_wchar] = atoll(s);
815     if ((s = strafter(buf, "read_bytes:"))) slot[SLOT_rbytes] = atoll(s);
816     if ((s = strafter(buf, "write_bytes:"))) slot[SLOT_wbytes] = atoll(s);
817     slot[SLOT_iobytes] = slot[SLOT_rchar]+slot[SLOT_wchar]+slot[SLOT_swap];
818     slot[SLOT_diobytes] = slot[SLOT_rbytes]+slot[SLOT_wbytes]+slot[SLOT_swap];
819   }
820 
821   // If we were updating thread parent with its own task info, we're done.
822   if (slot != tb->slot) return 0;
823 
824   // We now know enough to skip processes we don't care about.
825   if (TT.match_process && !TT.match_process(slot)) return 0;
826 
827   // /proc data is generated as it's read, so for maximum accuracy on slow
828   // systems (or ps | more) we re-fetch uptime as we fetch each /proc line.
829   sysinfo(&si);
830   slot[SLOT_uptime] = si.uptime;
831   slot[SLOT_totalram] = si.totalram;
832   slot[SLOT_upticks] = slot[SLOT_uptime]*TT.ticks - slot[SLOT_starttime];
833 
834   // Do we need to read "statm"?
835   if (TT.bits&(_PS_VIRT|_PS_SHR)) {
836     off_t temp = len;
837 
838     sprintf(buf, "%lld/statm", slot[SLOT_tid]);
839     if (!readfileat(fd, buf, buf, &temp)) *buf = 0;
840 
841     // Skip redundant RSS field, we got it from stat.
842     slot[SLOT_vsz] = slot[SLOT_shr] = 0;
843     sscanf(buf, "%lld %*d %lld", &slot[SLOT_vsz], &slot[SLOT_shr]);
844   }
845 
846   // Do we need to read "exe"?
847   if (TT.bits&_PS_BIT) {
848     off_t temp = 6;
849 
850     sprintf(buf, "%lld/exe", slot[SLOT_tid]);
851     if (readfileat(fd, buf, buf, &temp) && !smemcmp(buf, "\177ELF", 4)) {
852       if (buf[4] == 1) slot[SLOT_bits] = 32;
853       else if (buf[4] == 2) slot[SLOT_bits] = 64;
854     }
855   }
856 
857   // Do we need Android scheduling policy?
858   if (TT.bits&_PS_PCY) {
859     // Find the cpuset line in "/proc/$pid/cgroup", extract the final field,
860     // and translate it to one of Android's traditional 2-char names.
861     // TODO: if other Linux systems start using cgroups, conditionalize this.
862     sprintf(buf, "/proc/%lld/cgroup", slot[SLOT_tid]);
863     if ((fp = fopen(buf, "re"))) {
864       char *s, *line;
865       while ((line = xgetline(fp))) {
866         if ((s = strstr(line, ":cpuset:/"))) {
867           s += strlen(":cpuset:/");
868           sprintf(tb->pcy, "%.2s","? fgfg  bgtarswicd"+2*anystr(s, (char *[]){
869             "", "foreground", "system-background", "background", "top-app",
870             "restricted", "foreground_window", "camera-daemon", 0}));
871         }
872         free(line);
873       }
874       fclose(fp);
875     } else strcpy(tb->pcy, "-");
876   }
877 
878   // Done using buf[] (tb->str) as scratch space, now read string data,
879   // saving consective null terminated strings. (Save starting offsets into
880   // str->offset to avoid strlen() loop to find relevant string.)
881 
882   // Fetch string data while parentfd still available, appending to buf.
883   // (There's well over 3k of toybuf left. We could dynamically malloc, but
884   // it'd almost never get used, querying length of a proc file is awkward,
885   // fixed buffer is nommu friendly... Wait for somebody to complain. :)
886 
887   // The fetch[] array at the start of the function says what file to read
888   // and what -o display field outputs it (to skip the ones we don't need).
889 
890   slot[SLOT_argv0len] = 0;
891   for (j = 0; j<ARRAY_LEN(fetch); j++) {
892     tb->offset[j] = buf-(tb->str);
893     if (!(TT.bits&fetch[j].bits)) {
894       *buf++ = 0;
895       continue;
896     }
897 
898     // Determine available space: reserve 256 bytes (guaranteed minimum) for
899     // each string we haven't checked yet, tb->str starts after the numeric
900     // arrays in struct procpid, and we reserve 260 bytes scratch space at the
901     // end of toybuf for output conversion in string_field(). Other than that,
902     // each use all available space, and future strings that don't use their
903     // guaranteed minimum add to the pool.
904     len = sizeof(toybuf)-256*(ARRAY_LEN(fetch)-j)-(buf-toybuf)-260;
905     sprintf(buf, "%lld/%s", slot[SLOT_tid], fetch[j].name);
906 
907     // For exe (j==3) readlink() instead of reading file's contents
908     // for -o NAME (j==5) copy data from threadparent (PID) into thread (TID).
909     if (j==3 || j==5) {
910       struct procpid *ptb = 0;
911       int k;
912 
913       // Thread doesn't have exe or argv[0], so use parent's
914       if (TT.threadparent && TT.threadparent->extra)
915         ptb = (void *)TT.threadparent->extra;
916 
917       if (j==3 && !ptb) len = readlinkat0(fd, buf, buf, len);
918       else {
919         if (j==3) i = strlen(s = ptb->str+ptb->offset[3]);
920         else {
921           if (!ptb || slot[SLOT_argv0len]) ptb = tb;
922           i = ptb->slot[SLOT_argv0len];
923           s = ptb->str+ptb->offset[4];
924           while (-1!=(k = stridx(s, '/')) && k<i) {
925             s += k+1;
926             i -= k+1;
927           }
928         }
929         if (i<len) len = i;
930         memcpy(buf, s, len);
931         buf[len] = 0;
932       }
933 
934     // Turning stat's SLOT_ttynr into a string is an outright heuristic ordeal.
935     } else if (!j) {
936       int rdev = slot[SLOT_ttynr];
937       struct stat st;
938 
939       // Call no tty "?" rather than "0:0".
940       strcpy(buf, "?");
941       if (rdev) {
942         // Can we readlink() our way to a name?
943         for (i = 0; i<3; i++) {
944           sprintf(buf, "%lld/fd/%i", slot[SLOT_tid], i);
945           if (!fstatat(fd, buf, &st, 0) && S_ISCHR(st.st_mode)
946             && st.st_rdev == rdev && (len = readlinkat0(fd, buf, buf, len)))
947               break;
948         }
949 
950         // Couldn't find it, try all the tty drivers.
951         if (i == 3) {
952           int tty_major = 0, maj = dev_major(rdev), min = dev_minor(rdev);
953 
954           if ((fp = fopen("/proc/tty/drivers", "r"))) {
955             while (fscanf(fp, "%*s %256s %d %*s %*s", buf, &tty_major) == 2) {
956               // TODO: we could parse the minor range too.
957               if (tty_major == maj) {
958                 len = strlen(buf);
959                 len += sprintf(buf+len, "%d", min);
960                 if (!stat(buf, &st) && S_ISCHR(st.st_mode) && st.st_rdev==rdev)
961                   break;
962               }
963               tty_major = 0;
964             }
965             fclose(fp);
966           }
967 
968           // Really couldn't find it, so just show major:minor.
969           if (!tty_major) len = sprintf(buf, "%d:%d", maj, min);
970         }
971 
972         s = buf;
973         if (strstart(&s, "/dev/")) memmove(buf, s, len -= 4);
974       }
975 
976     // For the rest, the data we want is in a file we can just read.
977     } else {
978       int temp = 0;
979 
980       // When command has no arguments, don't space over the NUL
981       if (readfileat(fd, buf, buf, &len) && len>0) {
982 
983         // Trim trailing whitespace and NUL bytes
984         while (len)
985           if (!buf[len-1] || isspace(buf[len-1])) buf[--len] = 0;
986           else break;
987 
988         // Turn NUL to space, other low ascii to ? (in non-tty mode), except
989         // cmdline has a trailing NUL that we don't want to turn to space.
990         for (i=0; i<len-1; i++) {
991           char c = buf[i];
992 
993           if (!c) {
994             if (!temp) temp = i;
995             c = ' ';
996           } else if (!TT.tty && c<' ') c = '?';
997           buf[i] = c;
998         }
999       } else *buf = len = 0;
1000 
1001       // Store end of argv[0] so ARGS and CMDLINE can differ.
1002       // We do it for each file string slot but last is cmdline, which sticks.
1003       slot[SLOT_argv0len] = temp ? : len;  // Position of _first_ NUL
1004     }
1005 
1006     // Each case above calculated/retained len, so we don't need to re-strlen.
1007     buf += len+1;
1008   }
1009 
1010   // Record that we saw another process, and display/return now if appropriate
1011   TT.kcount++;
1012   if (TT.show_process && !TT.threadparent) {
1013     TT.show_process(tb);
1014 
1015     return 0;
1016   }
1017 
1018   // We're retaining data (probably to sort it), save copy in list.
1019   s = xmalloc(buf-toybuf);
1020   new->extra = (long)s;
1021   memcpy(s, toybuf, buf-toybuf);
1022 
1023   return DIRTREE_SAVE;
1024 }
1025 
1026 // wrapper for get_ps() that also collects threads under each processes
get_threads(struct dirtree * new)1027 static int get_threads(struct dirtree *new)
1028 {
1029   struct dirtree *dt;
1030   struct procpid *tb;
1031   unsigned pid, kcount;
1032 
1033   if (!new->parent) return get_ps(new);
1034   pid = atol(new->name);
1035 
1036   TT.threadparent = new;
1037   if (!get_ps(new)) {
1038     // it exited out from under us
1039     TT.threadparent = 0;
1040 
1041     return 0;
1042   }
1043 
1044   // Recurse down into tasks, retaining thread groups.
1045   // Disable show_process at least until we can calculate tcount
1046   kcount = TT.kcount;
1047   sprintf(toybuf, "/proc/%u/task", pid);
1048   new->child = dirtree_flagread(toybuf, DIRTREE_SHUTUP|DIRTREE_PROC, get_ps);
1049   if (new->child == DIRTREE_ABORTVAL) new->child = 0;
1050   TT.threadparent = 0;
1051   kcount = TT.kcount-kcount+1;
1052   tb = (void *)new->extra;
1053   tb->slot[SLOT_tcount] = kcount;
1054 
1055   // Fill out tid and thread count for each entry in group (if it didn't exit
1056   // out from under us again; asynchronous reads of unlocked data are fun!)
1057   if (new->child) for (dt = new->child->child; dt; dt = dt->next) {
1058     tb = (void *)dt->extra;
1059     tb->slot[SLOT_pid] = pid;
1060     tb->slot[SLOT_tcount] = kcount;
1061   }
1062 
1063   // Save or display
1064   if (!TT.show_process) return DIRTREE_SAVE;
1065   TT.show_process((void *)new->extra);
1066   if ((dt = new->child)) {
1067     new->child = 0;
1068     while (dt->child) {
1069       new = dt->child->next;
1070       TT.show_process((void *)dt->child->extra);
1071       free(dt->child);
1072       dt->child = new;
1073     }
1074     free(dt);
1075   }
1076 
1077   return 0;
1078 }
1079 
1080 // Parse one FIELD argument (with optional =name :width) into struct ofields
parse_ko(void * data,char * type,int length)1081 static char *parse_ko(void *data, char *type, int length)
1082 {
1083   struct ofields *field;
1084   char *width, *title, *end, *s;
1085   int i, j, k;
1086 
1087   // Caller's WOULD_EXIT catches -o help and prints help
1088   if (length==4 && !strncasecmp(type, "HELP", length)) xexit();
1089 
1090   // Get title, length of title, type, end of type, and display width
1091 
1092   // Chip off =name to display
1093   if ((end = strchr(type, '=')) && length>(end-type)) {
1094     title = end+1;
1095     length -= (end-type)+1;
1096   } else {
1097     end = type+length;
1098     title = 0;
1099   }
1100 
1101   // Chip off :width to display
1102   if ((width = strchr(type, ':')) && width<end) {
1103     if (!title) length = width-type;
1104   } else width = 0;
1105 
1106   // Allocate structure plus extra space to append a copy of title data
1107   // (this way it's same lifetime, freeing struct automatically frees title)
1108   field = xzalloc(sizeof(struct ofields)+(length+1)*!!title);
1109   if (title) {
1110     memcpy(field->title = (char *)(field+1), title, length);
1111     field->title[field->len = length] = 0;
1112   }
1113 
1114   if (width) {
1115     field->len = strtol(++width, &title, 10);
1116     if (!isdigit(*width) || title != end) return title;
1117     end = --width;
1118   }
1119 
1120   // Find type
1121   field->reverse = 1;
1122   if (*type == '-') field->reverse = -1;
1123   else if (*type != '+') type--;
1124   type++;
1125   for (i = 0; i<ARRAY_LEN(typos); i++) {
1126     field->which = i;
1127     for (j = 0; j<2; j++) {
1128       if (!j) s = typos[i].name;
1129       // posix requires alternate names for some fields
1130       else if (-1==(k = stridx((char []){PS_NI, PS_SCH, PS_ELAPSED, PS__CPU,
1131         PS_VSZ, PS_USER, 0}, i))) continue;
1132       else
1133         s = ((char *[]){"NICE", "SCHED", "ETIME", "PCPU", "VSIZE", "UNAME"})[k];
1134 
1135       if (!strncasecmp(type, s, end-type) && strlen(s)==end-type) break;
1136     }
1137     if (j!=2) break;
1138   }
1139   if (i==ARRAY_LEN(typos)) return type;
1140   if (!field->title) field->title = typos[field->which].name;
1141   k = i<2 ? TT.pidlen : typos[field->which].width;
1142   if (!field->len) field->len = k;
1143   else if (k<0) field->len *= -1;
1144   dlist_add_nomalloc(data, (void *)field);
1145 
1146   return 0;
1147 }
1148 
1149 // Write FIELD list into display header string (truncating at blen),
1150 // and return bitfield of which FIELDs are used.
get_headers(struct ofields * field,char * buf,int blen)1151 static long long get_headers(struct ofields *field, char *buf, int blen)
1152 {
1153   long long bits = 0;
1154   int len = 0, scroll;
1155 
1156   // Skip TT.scroll many fields (but not last one)
1157   for (scroll = TT.scroll; scroll && field->next; scroll--) field = field->next;
1158 
1159   for (; field; field = field->next) {
1160     len += snprintf(buf+len, blen-len, " %*s"+!bits, field->len,
1161       field->title);
1162     bits |= 1LL<<field->which;
1163   }
1164 
1165   return bits;
1166 }
1167 
1168 // Parse command line options -p -s -t -u -U -g -G
parse_rest(void * data,char * str,int len)1169 static char *parse_rest(void *data, char *str, int len)
1170 {
1171   struct ps_ptr_len *pl = (struct ps_ptr_len *)data;
1172   long *ll = pl->ptr;
1173   char *end;
1174   int num = 0;
1175 
1176   // Allocate next chunk of data
1177   if (!(15&pl->len))
1178     ll = pl->ptr = xrealloc(pl->ptr, sizeof(long)*(pl->len+16));
1179 
1180   // Parse numerical input
1181   if (isdigit(*str)) {
1182     ll[pl->len] = xstrtol(str, &end, 10);
1183     if (end==(len+str)) num++;
1184     // For pkill, -s 0 represents pkill's session id.
1185     if (pl==&TT.ss && ll[pl->len]==0) ll[pl->len] = getsid(0);
1186   }
1187 
1188   // PID can't be zero but SID can be 0 before the init task calls setsid().
1189   if (pl==&TT.pp || pl==&TT.ss) {
1190     if (num && ll[pl->len]>-(pl==&TT.ss)) {
1191       pl->len++;
1192 
1193       return 0;
1194     }
1195   } else if (pl==&TT.tt) {
1196     // -t pts = 12,pts/12 tty = /dev/tty2,tty2,S0
1197     if (!num) {
1198       if (strstart(&str, strcpy(toybuf, "/dev/"))) len -= 5;
1199       if (strstart(&str, "pts/")) {
1200         len -= 4;
1201         num++;
1202       } else if (strstart(&str, "tty")) len -= 3;
1203     }
1204     if (len<256 && (!(end = strchr(str, '/')) || end-str>len)) {
1205       struct stat st;
1206 
1207       end = toybuf + sprintf(toybuf, "/dev/%s", num ? "pts/" : "tty");
1208       memcpy(end, str, len);
1209       end[len] = 0;
1210       xstat(toybuf, &st);
1211       ll[pl->len++] = st.st_rdev;
1212 
1213       return 0;
1214     }
1215   } else if (len<255) {
1216     char name[256];
1217 
1218     if (num) {
1219       pl->len++;
1220 
1221       return 0;
1222     }
1223 
1224     memcpy(name, str, len);
1225     name[len] = 0;
1226     if (pl==&TT.gg || pl==&TT.GG) {
1227       struct group *gr = getgrnam(name);
1228       if (gr) {
1229         ll[pl->len++] = gr->gr_gid;
1230 
1231         return 0;
1232       }
1233     } else if (pl==&TT.uu || pl==&TT.UU) {
1234       struct passwd *pw = getpwnam(name);
1235       if (pw) {
1236         ll[pl->len++] = pw->pw_uid;
1237 
1238         return 0;
1239       }
1240     }
1241   }
1242 
1243   // Return error
1244   return str;
1245 }
1246 
1247 // sort processes by FIELD(s) listed in option -k
ksort(void * aa,void * bb)1248 static int ksort(void *aa, void *bb)
1249 {
1250   struct ofields *field;
1251   struct procpid *ta = *(struct procpid **)aa, *tb = *(struct procpid **)bb;
1252   int ret = 0, slot;
1253 
1254   for (field = TT.kfields; field && !ret; field = field->next) {
1255     slot = typos[field->which].slot;
1256 
1257     // Can we do numeric sort?
1258     if (!(slot&XX)) {
1259       if (ta->slot[slot]<tb->slot[slot]) ret = -1;
1260       if (ta->slot[slot]>tb->slot[slot]) ret = 1;
1261     }
1262 
1263     // fallback to string sort
1264     if (!ret) {
1265       memccpy(toybuf, string_field(ta, field), 0, 2048);
1266       toybuf[2048] = 0;
1267       ret = strcmp(toybuf, string_field(tb, field));
1268     }
1269     ret *= field->reverse;
1270   }
1271 
1272   return ret;
1273 }
1274 
1275 // Collect ->extra field from leaf nodes DIRTREE_SAVEd by get_ps() into array
1276 // (recursion because tree from get_thread() isn't flat list of siblings)
collate_leaves(struct procpid ** tb,struct dirtree * dt)1277 static struct procpid **collate_leaves(struct procpid **tb, struct dirtree *dt)
1278 {
1279   while (dt) {
1280     struct dirtree *next = dt->next;
1281 
1282     if (dt->extra) *(tb++) = (void *)dt->extra;
1283     if (dt->child) tb = collate_leaves(tb, dt->child);
1284     free(dt);
1285     dt = next;
1286   }
1287 
1288   return tb;
1289 }
1290 
1291 // Allocate struct procpid array of length count and populate it with ->extra
1292 // fields from dirtree leaf nodes. (top diffs old & new array to show changes)
collate(int count,struct dirtree * dt)1293 static struct procpid **collate(int count, struct dirtree *dt)
1294 {
1295   struct procpid **tbsort = xmalloc(count*sizeof(struct procpid *));
1296 
1297   collate_leaves(tbsort, dt);
1298 
1299   return tbsort;
1300 }
1301 
1302 // parse command line arguments (ala -k -o) with a comma separated FIELD list
default_ko(char * s,void * fields,char * err,struct arg_list * arg)1303 static void default_ko(char *s, void *fields, char *err, struct arg_list *arg)
1304 {
1305   struct arg_list def;
1306   int x;
1307 
1308   memset(&def, 0, sizeof(struct arg_list));
1309   def.arg = s;
1310   WOULD_EXIT(x, comma_args(arg ? arg : &def, fields, err, parse_ko));
1311   if (x) help_help();
1312 }
1313 
common_setup(void)1314 static void common_setup(void)
1315 {
1316   char buf[128];
1317   int i;
1318 
1319   TT.ticks = sysconf(_SC_CLK_TCK); // units for starttime/uptime
1320 
1321   if (-1 != (i = tty_fd())) {
1322     struct stat st;
1323 
1324     if (!fstat(i, &st)) TT.tty = st.st_rdev;
1325   }
1326 
1327   if (readfile("/proc/sys/kernel/pid_max", buf, 128))
1328     while (isdigit(buf[TT.pidlen])) TT.pidlen++;
1329   else TT.pidlen = 6;
1330 }
1331 
ps_main(void)1332 void ps_main(void)
1333 {
1334   char **arg;
1335   struct dirtree *dt;
1336   char *not_o;
1337   int i;
1338 
1339   common_setup();
1340 
1341   // If we can't query terminal size pad to 80 but do -w
1342   TT.width = 80;
1343   if (!isatty(1) || !terminal_size(&TT.width, 0)) toys.optflags |= FLAG_w;
1344   if (FLAG(w)) TT.width = 99999;
1345 
1346   // parse command line options other than -o
1347   comma_args(TT.ps.P, &TT.PP, "bad -P", parse_rest);
1348   comma_args(TT.ps.p, &TT.pp, "bad -p", parse_rest);
1349   comma_args(TT.ps.t, &TT.tt, "bad -t", parse_rest);
1350   comma_args(TT.ps.s, &TT.ss, "bad -s", parse_rest);
1351   comma_args(TT.ps.u, &TT.uu, "bad -u", parse_rest);
1352   comma_args(TT.ps.U, &TT.UU, "bad -U", parse_rest);
1353   comma_args(TT.ps.g, &TT.gg, "bad -g", parse_rest);
1354   comma_args(TT.ps.G, &TT.GG, "bad -G", parse_rest);
1355   comma_args(TT.ps.k, &TT.kfields, "bad -k", parse_ko);
1356   dlist_terminate(TT.kfields);
1357 
1358   // It's undocumented, but traditionally extra arguments are extra -p args
1359   for (arg = toys.optargs; *arg; arg++)
1360     if (parse_rest(&TT.pp, *arg, strlen(*arg))) error_exit("bad %s", *arg);
1361 
1362   // Figure out which fields to display
1363   not_o = "%sTTY,TIME,CMD";
1364   if (FLAG(f))
1365     sprintf(not_o = toybuf+128,
1366       "USER:12=UID,%%sPPID,%s,STIME,TTY,TIME,ARGS=CMD", FLAG(T) ? "TCNT" :"C");
1367   else if (FLAG(l))
1368     not_o = "F,S,UID,%sPPID,C,PRI,NI,BIT,SZ,WCHAN,TTY,TIME,CMD";
1369   else if (CFG_TOYBOX_ON_ANDROID)
1370     sprintf(not_o = toybuf+128,
1371             "USER,%%sPPID,VSIZE:10,RSS,WCHAN:10,ADDR:10,S,%s",
1372             FLAG(T) ? "CMD" : "NAME");
1373   sprintf(toybuf, not_o, FLAG(T) ? "PID,TID," : "PID,");
1374 
1375   // Init TT.fields. This only uses toybuf if TT.ps.o is NULL
1376   if (FLAG(Z)) default_ko("LABEL", &TT.fields, 0, 0);
1377   default_ko(toybuf, &TT.fields, "bad -o", TT.ps.o);
1378 
1379   if (TT.ps.O) {
1380     if (TT.fields) TT.fields = ((struct ofields *)TT.fields)->prev;
1381     comma_args(TT.ps.O, &TT.fields, "bad -O", parse_ko);
1382     if (TT.fields) TT.fields = ((struct ofields *)TT.fields)->next;
1383   }
1384   dlist_terminate(TT.fields);
1385 
1386   // -f and -n change the meaning of some fields
1387   if (FLAG(f)||FLAG(n)) {
1388     struct ofields *field;
1389 
1390     for (field = TT.fields; field; field = field->next) {
1391       if (FLAG(n) && field->which>=PS_UID
1392         && field->which<=PS_RGROUP && (typos[field->which].slot&XX))
1393           field->which--;
1394     }
1395   }
1396 
1397   // Calculate seen fields bit array, and if we aren't deferring printing
1398   // print headers now (for low memory/nommu systems).
1399   TT.bits = get_headers(TT.fields, toybuf, sizeof(toybuf));
1400   if (!FLAG(M)) printf("%.*s\n", TT.width, toybuf);
1401   if (!(FLAG(k)||FLAG(M))) TT.show_process = show_ps;
1402   TT.match_process = ps_match_process;
1403   dt = dirtree_flagread("/proc", DIRTREE_SHUTUP|DIRTREE_PROC,
1404     (FLAG(T) || (TT.bits&(_PS_TID|_PS_TCNT)))
1405       ? get_threads : get_ps);
1406 
1407   if ((dt != DIRTREE_ABORTVAL) && (FLAG(k)||FLAG(M))) {
1408     struct procpid **tbsort = collate(TT.kcount, dt);
1409 
1410     if (FLAG(M)) {
1411       for (i = 0; i<TT.kcount; i++) {
1412         struct ofields *field;
1413 
1414         for (field = TT.fields; field; field = field->next) {
1415           int len = strlen(string_field(tbsort[i], field));
1416 
1417           if (abs(field->len)<len) field->len = (field->len<0) ? -len : len;
1418         }
1419       }
1420 
1421       // Now that we've recalculated field widths, re-pad headers again
1422       get_headers(TT.fields, toybuf, sizeof(toybuf));
1423       printf("%.*s\n", TT.width, toybuf);
1424     }
1425 
1426     if (FLAG(k)) qsort(tbsort, TT.kcount, sizeof(void *), (void *)ksort);
1427     for (i = 0; i<TT.kcount; i++) {
1428       show_ps(tbsort[i]);
1429       free(tbsort[i]);
1430     }
1431     if (CFG_TOYBOX_FREE) free(tbsort);
1432   }
1433 
1434   if (!TT.kcount) toys.exitval = 1;
1435   if (CFG_TOYBOX_FREE) {
1436     free(TT.gg.ptr);
1437     free(TT.GG.ptr);
1438     free(TT.pp.ptr);
1439     free(TT.PP.ptr);
1440     free(TT.ss.ptr);
1441     free(TT.tt.ptr);
1442     free(TT.uu.ptr);
1443     free(TT.UU.ptr);
1444     llist_traverse(TT.fields, free);
1445   }
1446 }
1447 
1448 #define FOR_top
1449 #include "generated/flags.h"
1450 
1451 // select which of the -o fields to sort by
setsort(int pos)1452 static void setsort(int pos)
1453 {
1454   struct ofields *field, *field2;
1455   int i = 0;
1456 
1457   if (pos<0) pos = 0;
1458 
1459   for (field = TT.fields; field; field = field->next) {
1460     if ((TT.sortpos = i++)<pos && field->next) continue;
1461     field2 = TT.kfields;
1462     field2->which = field->which;
1463     field2->len = field->len;
1464     break;
1465   }
1466 }
1467 
1468 // If we have both, adjust slot[deltas[]] to be relative to previous
1469 // measurement rather than process start. Stomping old.data is fine
1470 // because we free it after displaying.
merge_deltas(long long * oslot,long long * nslot,int milis)1471 static int merge_deltas(long long *oslot, long long *nslot, int milis)
1472 {
1473   char deltas[] = {SLOT_utime2, SLOT_iobytes, SLOT_diobytes, SLOT_rchar,
1474                    SLOT_wchar, SLOT_rbytes, SLOT_wbytes, SLOT_swap};
1475   int i;
1476 
1477   for (i = 0; i<ARRAY_LEN(deltas); i++)
1478     oslot[deltas[i]] = nslot[deltas[i]] - oslot[deltas[i]];
1479   oslot[SLOT_upticks] = (milis*TT.ticks)/1000;
1480 
1481   return 1;
1482 }
1483 
header_line(int line,int rev)1484 static int header_line(int line, int rev)
1485 {
1486   if (!line) return 0;
1487 
1488   if (FLAG(b)) puts(toybuf);
1489   else {
1490     printf("%s%-*.*s%s\r\n", rev?"\e[7m":"", rev?TT.width:0, TT.width, toybuf,
1491       rev?"\e[0m":"");
1492   }
1493 
1494   return line-1;
1495 }
1496 
top_cursor_cleanup(void)1497 static void top_cursor_cleanup(void)
1498 {
1499   xputsn("\e[?25h");
1500 }
1501 
1502 // Show a three color bar graph. spans: 0 total size, 1used, 2 nice, 3 sys
bargraph(char * label,unsigned width,unsigned long span[4])1503 static void bargraph(char *label, unsigned width, unsigned long span[4])
1504 {
1505   char percent[16];
1506   long long ll;
1507   unsigned i, color, len;
1508 
1509   if (!*span) ++*span;
1510   i = ((span[1]+(unsigned long long)span[2]+span[3])*1000)/ *span;
1511   len = sprintf(percent, "%u.%u", i/10, i%10);
1512 
1513   printf("%s[", label);
1514   for (ll = i = color = 0; i<width; i++) {
1515     while (ll<1 && color<4) {
1516       if (color++!=3) {
1517         ll += span[color]*width;
1518         if (ll<*span/2) continue;
1519       }
1520       // green, red, blue, grey
1521       if (color==4) printf("\e[1;2;37m");
1522       else printf("\e[%um", (char[]){32,34,31}[color-1]);
1523       break;
1524     }
1525     if (color<4) ll -= *span;
1526     printf("%c", width-i>len ? (color==4 ? ' ' : '|') : percent[len-(width-i)]);
1527   }
1528   printf("\e[0m]");
1529 }
1530 
top_common(int (* filter)(long long * oslot,long long * nslot,int milis))1531 static void top_common(
1532   int (*filter)(long long *oslot, long long *nslot, int milis))
1533 {
1534   long long timeout = 0, now, stats[16];
1535   struct proclist {
1536     struct procpid **tb;
1537     int count;
1538     long long whence;
1539   } plist[2], *plold, *plnew, old, new, mix;
1540   char scratch[16], *pos, *cpufields[] = {"user", "nice", "sys", "idle",
1541     "iow", "irq", "sirq", "host"};
1542   unsigned tock = 0;
1543   int i, lines, topoff = 0, done = 0;
1544 
1545   if (!TT.fields) perror_exit("no -o");
1546 
1547   // Avoid flicker and hide the cursor in interactive mode.
1548   if (!FLAG(b)) {
1549     sigatexit(top_cursor_cleanup);
1550     xputsn("\e[?25l");
1551   }
1552 
1553   toys.signal = SIGWINCH;
1554   TT.bits = get_headers(TT.fields, toybuf, sizeof(toybuf));
1555   *scratch = 0;
1556   memset(plist, 0, sizeof(plist));
1557   memset(stats, 0, sizeof(stats));
1558   do {
1559     struct dirtree *dt;
1560     int recalc = 1;
1561 
1562     plold = plist+(tock++&1);
1563     plnew = plist+(tock&1);
1564     plnew->whence = millitime();
1565     dt = dirtree_flagread("/proc", DIRTREE_SHUTUP|DIRTREE_PROC,
1566       (FLAG(H) || (TT.bits&(_PS_TID|_PS_TCNT))) ? get_threads : get_ps);
1567     if (dt == DIRTREE_ABORTVAL) error_exit("no /proc");
1568     plnew->tb = collate(plnew->count = TT.kcount, dt);
1569     TT.kcount = 0;
1570 
1571     if (readfile("/proc/stat", pos = toybuf, sizeof(toybuf))) {
1572       long long *st = stats+8*(tock&1);
1573 
1574       // user nice system idle iowait irq softirq host
1575       sscanf(pos, "cpu %lld %lld %lld %lld %lld %lld %lld %lld",
1576         st, st+1, st+2, st+3, st+4, st+5, st+6, st+7);
1577     }
1578 
1579     // First time, wait a quarter of a second to collect a little delta data.
1580     if (!plold->tb) {
1581       msleep(250);
1582       continue;
1583     }
1584 
1585     // Collate old and new into "mix", depends on /proc read in pid sort order
1586     old = *plold;
1587     new = *plnew;
1588     mix.tb = xmalloc((old.count+new.count)*sizeof(struct procpid));
1589     mix.count = 0;
1590 
1591     while (old.count || new.count) {
1592       struct procpid *otb = old.count ? *old.tb : 0,
1593                      *ntb = new.count ? *new.tb : 0;
1594 
1595       // If we just have old for this process, it exited. Discard it.
1596       if (old.count && (!new.count || *otb->slot < *ntb->slot)) {
1597         old.tb++;
1598         old.count--;
1599 
1600         continue;
1601       }
1602 
1603       // If we just have new, use it verbatim
1604       if (!old.count || *otb->slot > *ntb->slot) mix.tb[mix.count] = ntb;
1605       else {
1606         // Keep or discard
1607         if (filter(otb->slot, ntb->slot, new.whence-old.whence)) {
1608           mix.tb[mix.count] = otb;
1609           mix.count++;
1610         }
1611         old.tb++;
1612         old.count--;
1613       }
1614       new.tb++;
1615       new.count--;
1616     }
1617 
1618     // Don't re-fetch data if it's not time yet, just re-display existing data.
1619     for (;;) {
1620       char was, is;
1621 
1622       if (recalc) {
1623         qsort(mix.tb, mix.count, sizeof(struct procpid *), (void *)ksort);
1624         if (!FLAG(b)) {
1625           printf("\e[H\e[J");
1626           if (toys.signal) {
1627             toys.signal = 0;
1628             terminal_probesize(&TT.width, &TT.height);
1629           }
1630         }
1631         if (TT.top.m) TT.height = TT.top.m+5;
1632         lines = TT.height;
1633       }
1634       if (recalc && !FLAG(q)) {
1635         // Display "top" header.
1636         if (*toys.which->name == 't') {
1637           struct ofields field;
1638           char hr[4][32];
1639           long long ll, up = 0;
1640           long run[6];
1641           int j, k, cpus = sysconf(_SC_NPROCESSORS_CONF);
1642 
1643 
1644           // Count running, sleeping, stopped, zombie processes.
1645           // The kernel has more states (and different sets in different
1646           // versions), so we need to map them. (R)unning and (Z)ombie are
1647           // easy enough, and since "stopped" is rare (just T and t as of
1648           // Linux 4.20), we assume everything else is "sleeping".
1649           field.which = PS_S;
1650           memset(run, 0, sizeof(run));
1651           for (i = 0; i<mix.count; i++)
1652             run[1+stridx("RTtZ", *string_field(mix.tb[i], &field))]++;
1653           sprintf(toybuf,
1654             "%ss: %d total, %3ld running, %3ld sleeping, %3ld stopped, "
1655             "%3ld zombie", FLAG(H) ? "Thread" : "Task", mix.count, run[1],
1656             run[0], run[2]+run[3], run[4]);
1657           lines = header_line(lines, 0);
1658 
1659           if (readfile("/proc/meminfo", toybuf+256, sizeof(toybuf)-256)) {
1660             for (i = 0; i<6; i++) {
1661               j = i%3;
1662               pos = strafter(toybuf+256, (char *[]){"MemTotal:","\nMemFree:",
1663                     "\nBuffers:","\nSwapTotal:","\nSwapFree:","\nCached:"}[i]);
1664               run[i] = pos ? atol(pos) : 0;
1665               if (FLAG(h)) continue;
1666               k = (*run>=10000000);
1667               human_readable_long(hr[j+!!j], run[i]>>(10*k), 9, k+1, HR_NODOT);
1668               if (j==1) human_readable_long(hr[1], (run[i-1]-run[i])>>(10*k),
1669                 8, k+1, HR_NODOT);
1670               else if (j==2) {
1671                 sprintf(toybuf, " %s:%10s total,%10s used,%10s free,%10s %s",
1672                   (i<3) ? " Mem" : "Swap", hr[0], hr[1], hr[2], hr[3],
1673                   (i<3) ? "buffers" : "cached");
1674                 lines = header_line(lines, 0);
1675               }
1676             }
1677             if (FLAG(h)) {
1678               unsigned long swp[] = {run[3], 0, 0, run[3]-run[4]},
1679                 mem[] = {run[0], run[0]-run[1]-run[2]-run[5], run[2], run[5]};
1680 
1681               bargraph("Mem", 34, mem);
1682               bargraph(" Swp", 34, swp);
1683               xprintf("\r\n");
1684             }
1685           }
1686           pos = toybuf;
1687           pos += sprintf(pos, "%d%%cpu", cpus*100);
1688           j = 4+(cpus>10);
1689 
1690           // If a processor goes idle it's powered down and its idle ticks don't
1691           // advance, so calculate idle time as potential time - used.
1692           if (mix.count) up = mix.tb[0]->slot[SLOT_upticks];
1693           if (!up) up = 1;
1694           now = up*cpus;
1695           ll = stats[3] = stats[11] = 0;
1696           for (i = 0; i<8; i++) ll += stats[i]-stats[i+8];
1697           stats[3] = now - llabs(ll);
1698 
1699           for (i = 0; i<8; i++) {
1700             ll = (llabs(stats[i]-stats[i+8])*1000)/up;
1701             pos += sprintf(pos, "% *lld%%%s", j, (ll+5)/10, cpufields[i]);
1702           }
1703         // Display "iotop" header.
1704         } else {
1705           struct ofields *field;
1706           struct procpid tb;
1707 
1708           memset(&tb, 0, sizeof(struct procpid));
1709           pos = stpcpy(toybuf, "Totals:");
1710           for (field = TT.fields; field; field = field->next) {
1711             long long ll, bits = 0;
1712             int slot = typos[field->which].slot&(XX-1);
1713 
1714             if (field->which<PS_C || field->which>PS_DIO) continue;
1715             ll = 1LL<<field->which;
1716             if (bits&ll) continue;
1717             bits |= ll;
1718             for (i=0; i<mix.count; i++)
1719               tb.slot[slot] += mix.tb[i]->slot[slot];
1720             pos += snprintf(pos, sizeof(toybuf)/2-(pos-toybuf),
1721               " %s: %*s,", typos[field->which].name,
1722               field->len, string_field(&tb, field));
1723           }
1724           *--pos = 0;
1725         }
1726 
1727         lines = header_line(lines, 0);
1728         // print line of header labels for currently displayed fields
1729         get_headers(TT.fields, pos = toybuf, sizeof(toybuf));
1730         for (i = 0, is = ' '; *pos; pos++) {
1731           was = is;
1732           is = *pos;
1733           if (isspace(was) && !isspace(is) && i++==TT.sortpos && pos!=toybuf)
1734             pos[-1] = '[';
1735           if (!isspace(was) && isspace(is) && i==TT.sortpos+1) *pos = ']';
1736         }
1737         if (FLAG(b)) while (isspace(*(pos-1))) --pos;
1738         *pos = 0;
1739         lines = header_line(lines, 1);
1740       }
1741       if (!recalc && !FLAG(b)) printf("\e[%dH\e[J", 1+TT.height-lines);
1742 
1743       for (i = 0; i<lines && i+topoff<mix.count; i++) {
1744         // Running processes are shown in bold.
1745         int bold = !FLAG(b) && mix.tb[i+topoff]->state == 'R';
1746 
1747         if (!FLAG(b) && i) putchar('\n');
1748         if (bold) printf("\e[1m");
1749         show_ps(mix.tb[i+topoff]);
1750         if (bold) printf("\e[m");
1751       }
1752 
1753       if (TT.top.n && !--TT.top.n) {
1754         done++;
1755         break;
1756       }
1757 
1758       now = millitime();
1759       if (timeout<=now) timeout = new.whence+TT.top.d;
1760       if (timeout<=now || timeout>now+TT.top.d) timeout = now+TT.top.d;
1761 
1762       fflush(stdout);
1763 
1764       // In batch mode, we ignore the keyboard.
1765       if (FLAG(b)) {
1766         msleep(timeout-now);
1767         // Make an obvious gap between datasets.
1768         xputs("\n\n");
1769         break;
1770       }
1771 
1772       recalc = 1;
1773       i = scan_key_getsize(scratch, timeout-now, &TT.width, &TT.height);
1774       if (i==-1 || i==3 || toupper(i)=='Q') {
1775         done++;
1776         break;
1777       }
1778       if (i==-2) break;
1779       if (i==-3) continue;
1780 
1781       // Flush unknown escape sequences.
1782       if (i==27) while (0<scan_key_getsize(scratch, 0, &TT.width, &TT.height));
1783       else if (i=='\r' || i==' ') {
1784         timeout = 0;
1785         break;
1786       } else if (toupper(i)=='R')
1787         ((struct ofields *)TT.kfields)->reverse *= -1;
1788       else {
1789         i -= 256;
1790         if (i == (KEY_SHIFT|KEY_LEFT)) setsort(TT.sortpos-1);
1791         else if (i == (KEY_SHIFT|KEY_RIGHT)) setsort(TT.sortpos+1);
1792         else if (i == KEY_RIGHT) TT.scroll++;
1793         else if (i == KEY_LEFT && TT.scroll) TT.scroll--;
1794         else if (recalc-- && i == KEY_UP) topoff--;
1795         else if (i == KEY_DOWN) topoff++;
1796         else if (i == KEY_PGDN) topoff += lines;
1797         else if (i == KEY_PGUP) topoff -= lines;
1798         else continue;
1799         if (topoff<0) topoff = 0;
1800         if (topoff>mix.count) topoff = mix.count;
1801       }
1802     }
1803 
1804     free(mix.tb);
1805     for (i=0; i<plold->count; i++) free(plold->tb[i]);
1806     free(plold->tb);
1807   } while (!done);
1808 
1809   if (!FLAG(b)) tty_reset();
1810 }
1811 
top_setup(char * defo,char * defk)1812 static void top_setup(char *defo, char *defk)
1813 {
1814   common_setup();
1815 
1816   // Are we doing "batch" output or interactive?
1817   if (FLAG(b)) TT.width = TT.height = 99999;
1818   else {
1819     // Grab starting time, make terminal raw, switch off cursor,
1820     // set signal handler to put terminal/cursor back to normal at exit.
1821     TT.time = millitime();
1822     start_redraw(&TT.width, &TT.height);
1823   }
1824 
1825   comma_args(TT.top.u, &TT.uu, "bad -u", parse_rest);
1826   comma_args(TT.top.p, &TT.pp, "bad -p", parse_rest);
1827   TT.match_process = shared_match_process;
1828 
1829   default_ko(defo, &TT.fields, "bad -o", TT.top.o);
1830   dlist_terminate(TT.fields);
1831 
1832   // First (dummy) sort field is overwritten by setsort()
1833   default_ko("-S", &TT.kfields, 0, 0);
1834   default_ko(defk, &TT.kfields, "bad -k", TT.top.k);
1835   dlist_terminate(TT.kfields);
1836   setsort(TT.top.s-1);
1837 }
1838 
top_main(void)1839 void top_main(void)
1840 {
1841   sprintf(toybuf, "%cID,USER,%s%%CPU,%%MEM,TIME+,%s", FLAG(H) ? 'T' : 'P',
1842     TT.top.O ? "" : "PR,NI,VIRT,RES,SHR,S,",
1843     FLAG(H) ? "CMD:15=THREAD,NAME=PROCESS" : "ARGS");
1844   if (!TT.top.s) TT.top.s = TT.top.O ? 3 : 9;
1845   top_setup(toybuf, "-%CPU,-ETIME,-PID");
1846   if (TT.top.O) {
1847     struct ofields *field = TT.fields;
1848 
1849     field = field->next->next;
1850     comma_args(TT.top.O, &field, "bad -O", parse_ko);
1851   }
1852 
1853   top_common(merge_deltas);
1854 }
1855 
1856 #define FOR_iotop
1857 #include "generated/flags.h"
1858 
1859 // Compare old and new proces lists to measure changes
iotop_filter(long long * oslot,long long * nslot,int milis)1860 static int iotop_filter(long long *oslot, long long *nslot, int milis)
1861 {
1862   // Current I/O, or accumulated since process start?
1863   if (!FLAG(a)) merge_deltas(oslot, nslot, milis);
1864   else oslot[SLOT_upticks] = ((millitime()-TT.time)*TT.ticks)/1000;
1865 
1866   return !FLAG(O) || oslot[SLOT_iobytes+!FLAG(A)];
1867 }
1868 
iotop_main(void)1869 void iotop_main(void)
1870 {
1871   char *s1 = 0, *s2 = 0, *d = "D"+FLAG(A);
1872 
1873   if (FLAG(K)) TT.forcek++;
1874 
1875   top_setup(s1 = xmprintf("PID,PR,USER,%sREAD,%sWRITE,SWAP,%sIO,COMM",d,d,d),
1876     s2 = xmprintf("-%sIO,-ETIME,-PID",d));
1877   free(s1);
1878   free(s2);
1879   top_common(iotop_filter);
1880 }
1881 
1882 // pkill's plumbing wraps pgrep's and thus mostly takes place in pgrep's flag
1883 // context, so force pgrep's flags on even when building pkill standalone.
1884 // (All the pgrep/pkill functions drop out when building ps standalone.)
1885 #define FORCE_FLAGS
1886 #define FOR_pgrep
1887 #include "generated/flags.h"
1888 
1889 struct regex_list {
1890   struct regex_list *next;
1891   regex_t reg;
1892 };
1893 
do_pgk(struct procpid * tb)1894 static void do_pgk(struct procpid *tb)
1895 {
1896   if (TT.pgrep.signal) {
1897     if (kill(*tb->slot, TT.pgrep.signal)) {
1898       char *s = num_to_sig(TT.pgrep.signal);
1899 
1900       if (!s) sprintf(s = toybuf, "%d", TT.pgrep.signal);
1901       perror_msg("%s->%lld", s, *tb->slot);
1902     }
1903   }
1904   if (!FLAG(c) && (!TT.pgrep.signal || TT.tty)) {
1905     printf("%lld", *tb->slot);
1906     if (FLAG(a)|FLAG(l)) printf(" %s", tb->str+tb->offset[4]*FLAG(a));
1907     printf("%s", TT.pgrep.d ? TT.pgrep.d : "\n");
1908   }
1909 }
1910 
match_pgrep(void * p)1911 static void match_pgrep(void *p)
1912 {
1913   struct procpid *tb = p;
1914   regmatch_t match;
1915   struct regex_list *reg;
1916   char *name = tb->str+tb->offset[4]*FLAG(f);
1917 
1918   // Never match ourselves.
1919   if (TT.pgrep.self == *tb->slot) return;
1920 
1921   if (TT.pgrep.regexes) {
1922     for (reg = TT.pgrep.regexes; reg; reg = reg->next) {
1923       if (regexec(&reg->reg, name, 1, &match, 0)) continue;
1924       if (FLAG(x))
1925         if (match.rm_so || match.rm_eo!=strlen(name)) continue;
1926       break;
1927     }
1928     if (!FLAG(v) == !reg) return;
1929   }
1930 
1931   // pgrep should return success if there's a match.
1932   toys.exitval = 0;
1933 
1934   // Repurpose a field for -c count.
1935   TT.sortpos++;
1936   if (FLAG(n)||FLAG(o)) {
1937     long long ll = tb->slot[SLOT_starttime];
1938 
1939     if (FLAG(o)) ll *= -1;
1940     if (TT.time && TT.time>ll) return;
1941     TT.time = ll;
1942     free(TT.pgrep.snapshot);
1943     TT.pgrep.snapshot = xmemdup(toybuf, (name+strlen(name)+1)-toybuf);
1944   } else do_pgk(tb);
1945 }
1946 
pgrep_match_process(long long * slot)1947 static int pgrep_match_process(long long *slot)
1948 {
1949   return !FLAG(v) == !!shared_match_process(slot);
1950 }
1951 
pgrep_main(void)1952 void pgrep_main(void)
1953 {
1954   char **arg;
1955   struct regex_list *reg;
1956 
1957   TT.pgrep.self = getpid();
1958 
1959   // No signal names start with "L", so no need for "L: " in optstr.
1960   if (TT.pgrep.L && 1>(TT.pgrep.signal = sig_to_num(TT.pgrep.L)))
1961     error_exit("bad -L '%s'", TT.pgrep.L);
1962 
1963   comma_args(TT.pgrep.G, &TT.GG, "bad -G", parse_rest);
1964   comma_args(TT.pgrep.g, &TT.gg, "bad -g", parse_rest);
1965   comma_args(TT.pgrep.P, &TT.PP, "bad -P", parse_rest);
1966   comma_args(TT.pgrep.s, &TT.ss, "bad -s", parse_rest);
1967   comma_args(TT.pgrep.t, &TT.tt, "bad -t", parse_rest);
1968   comma_args(TT.pgrep.U, &TT.UU, "bad -U", parse_rest);
1969   comma_args(TT.pgrep.u, &TT.uu, "bad -u", parse_rest);
1970 
1971   if ((toys.optflags&(FLAG_x|FLAG_f)) ||
1972       !(toys.optflags&(FLAG_G|FLAG_g|FLAG_P|FLAG_s|FLAG_t|FLAG_U|FLAG_u)))
1973     if (!toys.optc) help_exit("No PATTERN");
1974 
1975   if (FLAG(f)|FLAG(a)) TT.bits |= _PS_CMDLINE;
1976   for (arg = toys.optargs; *arg; arg++) {
1977     reg = xmalloc(sizeof(struct regex_list));
1978     xregcomp(&reg->reg, *arg, REG_EXTENDED);
1979     reg->next = TT.pgrep.regexes;
1980     TT.pgrep.regexes = reg;
1981   }
1982   TT.match_process = pgrep_match_process;
1983   TT.show_process = match_pgrep;
1984 
1985   // pgrep should return failure if there are no matches.
1986   toys.exitval = 1;
1987 
1988   dirtree_flagread("/proc", DIRTREE_SHUTUP|DIRTREE_PROC, get_ps);
1989   if (FLAG(c)) printf("%d\n", TT.sortpos);
1990   if (TT.pgrep.snapshot) {
1991     do_pgk(TT.pgrep.snapshot);
1992     if (CFG_TOYBOX_FREE) free(TT.pgrep.snapshot);
1993   }
1994   if (TT.pgrep.d) xputc('\n');
1995 }
1996 
1997 #define FOR_pkill
1998 #include "generated/flags.h"
1999 
pkill_main(void)2000 void pkill_main(void)
2001 {
2002   char **args = toys.optargs;
2003 
2004   if (!FLAG(l) && *args && **args=='-') TT.pgrep.L = *(args++)+1;
2005   if (!TT.pgrep.L) TT.pgrep.signal = SIGTERM;
2006   if (FLAG(V)) TT.tty = 1;
2007   pgrep_main();
2008 }
2009