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