/
ps.c
1989 lines (1697 loc) · 65.3 KB
/
ps.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ps.c - show process list
*
* Copyright 2015 Rob Landley <rob@landley.net>
*
* See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html
* And http://kernel.org/doc/Documentation/filesystems/proc.txt Table 1-4
* And linux kernel source fs/proc/array.c function do_task_stat()
*
* Deviations from posix: no -n because /proc/self/wchan exists; we use -n to
* mean "show numeric users and groups" instead.
* Posix says default output should have field named "TTY" but if you "-o tty"
* the same field should be called "TT" which is _INSANE_ and I'm not doing it.
* Similarly -f outputs USER but calls it UID (we call it USER).
* It also says that -o "args" and "comm" should behave differently but use
* the same title, which is not the same title as the default output. (No.)
* Select by session id is -s not -g. Posix doesn't say truncated fields
* should end with "+" but it's pretty common behavior.
*
* Posix defines -o ADDR as "The address of the process" but the process
* start address is a constant on any elf system with mmu. The procps ADDR
* field always prints "-" with an alignment of 1, which is why it has 11
* characters left for "cmd" in in 80 column "ps -l" mode. On x86-64 you
* need 12 chars, leaving nothing for cmd: I.E. posix 2008 ps -l mode can't
* be sanely implemented on 64 bit Linux systems. In procps there's ps -y
* which changes -l by removing the "F" column and swapping RSS for ADDR,
* leaving 9 chars for cmd, so we're using that as our -l output.
*
* Added a bunch of new -o fields posix doesn't mention, and we don't
* label "ps -o command,args,comm" as "COMMAND COMMAND COMMAND". We don't
* output argv[0] unmodified for -o comm or -o args (but procps violates
* posix for -o comm anyway, it's stat[2] not argv[0]).
*
* Note: iotop is STAYROOT so it can read other process's /proc/$PID/io
* files (why they're not globally readable when the rest of proc
* data is...?) and get a global I/O picture. Normal top is NOT,
* even though you can -o AIO there, to give sysadmins the option
* to reduce security exposure.)
*
* TODO: ps aux (att & bsd style "ps -ax" vs "ps ax" behavior difference)
* TODO: switch -fl to -y
* TODO: thread support /proc/$d/task/%d/stat (and -o stat has "l")
* TODO: iotop: Window size change: respond immediately. Why not padding
* at right edge? (Not adjusting to screen size at all? Header wraps?)
* TODO: top: thread support and SMP
* TODO: pgrep -f only searches the amount of cmdline that fits in toybuf.
* TODO: pgrep qemu-system-i386 never matches because one char too long
USE_PS(NEWTOY(ps, "k(sort)*P(ppid)*aAdeflMno*O*p(pid)*s*t*Tu*U*g*G*wZ[!ol][+Ae][!oO]", TOYFLAG_BIN))
// stayroot because iotop needs root to read other process' proc/$$/io
// TOP and IOTOP have a large common option block used for common processing,
// the default values are different but the flags are in the same order.
USE_TOP(NEWTOY(top, ">0O*h" "Hk*o*p*u*s#<1d%<100=3000m#n#<1bq[!oO]", TOYFLAG_USR|TOYFLAG_BIN))
USE_IOTOP(NEWTOY(iotop, ">0AaKO" "Hk*o*p*u*s#<1=7d%<100=3000m#n#<1bq", TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_STAYROOT))
USE_PGREP(NEWTOY(pgrep, "?cld:u*U*t*s*P*g*G*fnovxL:[-no]", TOYFLAG_USR|TOYFLAG_BIN))
USE_PKILL(NEWTOY(pkill, "?Vu*U*t*s*P*g*G*fnovxl:[-no]", TOYFLAG_USR|TOYFLAG_BIN))
config PS
bool "ps"
default y
help
usage: ps [-AadefLlnwZ] [-gG GROUP,] [-k FIELD,] [-o FIELD,] [-p PID,] [-t TTY,] [-uU USER,]
List processes.
Which processes to show (-gGuUpPt selections may be comma separated lists):
-A All -a Has terminal not session leader
-d All but session leaders -e Synonym for -A
-g In GROUPs -G In real GROUPs (before sgid)
-p PIDs (--pid) -P Parent PIDs (--ppid)
-s In session IDs -t Attached to selected TTYs
-T Show threads also -u Owned by selected USERs
-U Real USERs (before suid)
Output modifiers:
-k Sort FIELDs (-FIELD to reverse) -M Measure/pad future field widths
-n Show numeric USER and GROUP -w Wide output (don't truncate fields)
Which FIELDs to show. (-o HELP for list, default = -o PID,TTY,TIME,CMD)
-f Full listing (-o USER:12=UID,PID,PPID,C,STIME,TTY,TIME,ARGS=CMD)
-l Long listing (-o F,S,UID,PID,PPID,C,PRI,NI,ADDR,SZ,WCHAN,TTY,TIME,CMD)
-o Output FIELDs instead of defaults, each with optional :size and =title
-O Add FIELDS to defaults
-Z Include LABEL
config TOP
bool "top"
default y
help
usage: top [-Hhbq] [-k FIELD,] [-o FIELD,] [-s SORT] [-n NUMBER] [-m LINES] [-d SECONDS] [-p PID,] [-u USER,]
Show process activity in real time.
-H Show threads
-h Usage graphs instead of text
-k Fallback sort FIELDS (default -S,-%CPU,-ETIME,-PID)
-o Show FIELDS (def PID,USER,PR,NI,VIRT,RES,SHR,S,%CPU,%MEM,TIME+,CMDLINE)
-O Add FIELDS (replacing PR,NI,VIRT,RES,SHR,S from default)
-s Sort by field number (1-X, default 9)
-b Batch mode (no tty)
-d Delay SECONDS between each cycle (default 3)
-m Maximum number of tasks to show
-n Exit after NUMBER iterations
-p Show these PIDs
-u Show these USERs
-q Quiet (no header lines)
Cursor UP/DOWN or LEFT/RIGHT to move list, SHIFT LEFT/RIGHT to change sort,
space to force update, R to reverse sort, Q to exit.
# Requires CONFIG_IRQ_TIME_ACCOUNTING in the kernel for /proc/$$/io
config IOTOP
bool "iotop"
default y
help
usage: iotop [-AaKObq] [-n NUMBER] [-d SECONDS] [-p PID,] [-u USER,]
Rank processes by I/O.
-A All I/O, not just disk
-a Accumulated I/O (not percentage)
-H Show threads
-K Kilobytes
-k Fallback sort FIELDS (default -[D]IO,-ETIME,-PID)
-m Maximum number of tasks to show
-O Only show processes doing I/O
-o Show FIELDS (default PID,PR,USER,[D]READ,[D]WRITE,SWAP,[D]IO,COMM)
-s Sort by field number (0-X, default 6)
-b Batch mode (no tty)
-d Delay SECONDS between each cycle (default 3)
-n Exit after NUMBER iterations
-p Show these PIDs
-u Show these USERs
-q Quiet (no header lines)
Cursor LEFT/RIGHT to change sort, UP/DOWN move list, space to force
update, R to reverse sort, Q to exit.
config PGREP
bool "pgrep"
default y
help
usage: pgrep [-clfnovx] [-d DELIM] [-L SIGNAL] [PATTERN] [-G GID,] [-g PGRP,] [-P PPID,] [-s SID,] [-t TERM,] [-U UID,] [-u EUID,]
Search for process(es). PATTERN is an extended regular expression checked
against command names.
-c Show only count of matches
-d Use DELIM instead of newline
-L Send SIGNAL instead of printing name
-l Show command name
-f Check full command line for PATTERN
-G Match real Group ID(s)
-g Match Process Group(s) (0 is current user)
-n Newest match only
-o Oldest match only
-P Match Parent Process ID(s)
-s Match Session ID(s) (0 for current)
-t Match Terminal(s)
-U Match real User ID(s)
-u Match effective User ID(s)
-v Negate the match
-x Match whole command (not substring)
config PKILL
bool "pkill"
default y
help
usage: pkill [-fnovx] [-SIGNAL|-l SIGNAL] [PATTERN] [-G GID,] [-g PGRP,] [-P PPID,] [-s SID,] [-t TERM,] [-U UID,] [-u EUID,]
-l Send SIGNAL (default SIGTERM)
-V Verbose
-f Check full command line for PATTERN
-G Match real Group ID(s)
-g Match Process Group(s) (0 is current user)
-n Newest match only
-o Oldest match only
-P Match Parent Process ID(s)
-s Match Session ID(s) (0 for current)
-t Match Terminal(s)
-U Match real User ID(s)
-u Match effective User ID(s)
-v Negate the match
-x Match whole command (not substring)
*/
#define FOR_ps
#include "toys.h"
GLOBALS(
union {
struct {
struct arg_list *G, *g, *U, *u, *t, *s, *p, *O, *o, *P, *k;
} ps;
struct {
long n, m, d, s;
struct arg_list *u, *p, *o, *k, *O;
} top;
struct {
char *L;
struct arg_list *G, *g, *P, *s, *t, *U, *u;
char *d;
void *regexes, *snapshot;
int signal;
pid_t self, match;
} pgrep;
};
struct ps_ptr_len {
void *ptr;
long len;
} gg, GG, pp, PP, ss, tt, uu, UU;
struct dirtree *threadparent;
unsigned width, height, scroll;
dev_t tty;
void *fields, *kfields;
long long ticks, bits, time;
int kcount, forcek, sortpos, pidlen;
int (*match_process)(long long *slot);
void (*show_process)(void *tb);
)
// Linked list of -o fields selected for display, in order, with :len and =title
struct ofields {
struct ofields *next, *prev;
short which, len, reverse;
char *title;
};
/* The function get_ps() reads all the data about one process, saving it in
* toybox as a struct procpid. Simple ps calls then pass toybuf directly to
* show_ps(), but features like sorting append a copy to a linked list
* for further processing once all processes have been read.
*
* struct procpid contains a slot[] array of 64 bit values, with the following
* data at each position in the array. Most is read from /proc/$PID/stat (see
* https://kernel.org/doc/Documentation/filesystems/proc.txt table 1-4) but
* we replace several fields with don't use with other data. */
enum {
SLOT_pid, /*process id*/ SLOT_ppid, // parent process id
SLOT_pgrp, /*process group*/ SLOT_sid, // session id
SLOT_ttynr, /*tty the process uses*/ SLOT_ttypgrp, // pgrp of the tty
SLOT_flags, /*task flags*/ SLOT_minflt, // minor faults
SLOT_cminflt, /*minor faults+child*/ SLOT_majflt, // major faults
SLOT_cmajflt, /*major faults+child*/ SLOT_utime, // user+kernel jiffies
SLOT_stime, /*kernel mode jiffies*/ SLOT_cutime, // utime+child utime
SLOT_cstime, /*stime+child*/ SLOT_priority, // priority level
SLOT_nice, /*nice level*/ SLOT_numthreads,// thread count
SLOT_vmlck, /*locked memory*/ SLOT_starttime, // jiffies after boot
SLOT_vsize, /*virtual memory size*/ SLOT_rss, // resident set size
SLOT_rsslim, /*limit in bytes on rss*/ SLOT_startcode, // code segment addr
SLOT_endcode, /*code segment address*/ SLOT_startstack,// stack address
SLOT_esp, /*task stack pointer*/ SLOT_eip, // instruction pointer
SLOT_iobytes, /*All I/O bytes*/ SLOT_diobytes, // disk I/O bytes
SLOT_utime2, /*relative utime (top)*/ SLOT_uid, // user id
SLOT_ruid, /*real user id*/ SLOT_gid, // group id
SLOT_rgid, /*real group id*/ SLOT_exitsig, // sent to parent
SLOT_taskcpu, /*CPU running on*/ SLOT_rtprio, // realtime priority
SLOT_policy, /*man sched_setscheduler*/SLOT_blkioticks,// IO wait time
SLOT_gtime, /*guest jiffies of task*/ SLOT_cgtime, // gtime+child
SLOT_startbss, /*data/bss address*/ SLOT_endbss, // end addr data+bss
// end of /proc/$PID/stat fields
SLOT_upticks, /*uptime-starttime*/ SLOT_argv0len, // argv[0] length
SLOT_uptime, /*sysinfo.uptime*/ SLOT_totalram, // sysinfo.totalram
SLOT_vsz, /*Virtual mem Size*/ SLOT_shr, // Shared memory
SLOT_pcy, /*Android sched pol*/ SLOT_rchar, // All bytes read
SLOT_wchar, /*All bytes written*/ SLOT_rbytes, // Disk bytes read
SLOT_wbytes, /*Disk bytes written*/ SLOT_swap, // Swap pages used
SLOT_bits, /*32 or 64*/ SLOT_tid, // Thread ID
SLOT_tcount, /*Thread count*/
SLOT_count /* Size of array */
};
/* In addition to slot[], carevup contains 6 string fields to display
command name, tty device, selinux label... They're stored one after the
other in str[] (separated by null terminators), and offset[] contains the
starting position of each string after the first (which is always 0). */
// Data layout in toybuf
struct procpid {
long long slot[SLOT_count]; // data (see enum above)
unsigned short offset[6]; // offset of fields in str[] (skip CMD, always 0)
char state;
char str[]; // CMD, TTY, WCHAN, LABEL, COMM, ARGS, NAME
};
/* The typos[] array lists all the types understood by "ps -o", I.E all the
* columns ps and top know how to display. Each entry has:
*
* name: the column name, displayed at top and used to select column with -o
*
* width: the display width. Fields are padded to this width when displaying
* to a terminal (negative means right justified). Strings are truncated
* to fit, numerical fields are padded but not truncated (although
* the display code reclaims unused padding from later fields to try to
* get the overflow back).
*
* slot: which slot[] out of procpid. Negative means it's a string field.
* value|XX requests extra display/sort processing.
*
* The TAGGED_ARRAY plumbing produces an enum of indexes, the "tag" is the
* first string argument and the prefix is the first argument to TAGGED_ARRAY
* so in this case "NAME" becomes PS_NAME which is the offset into typos[]
* for that entry, and also _PS_NAME (the bit position, 1<<PS_NAME).
* We record active columns in TT.bits, ala:
*
* if (TT.bits & _PS_NAME) printf("-o included PS_NAME");
*/
#define XX 64 // force string representation for sorting, etc
// TODO: Android uses -30 for LABEL, but ideally it would auto-size.
struct typography {
char *name, *help;
signed char width, slot;
} static const typos[] = TAGGED_ARRAY(PS,
// Numbers. (What's in slot[] is what's displayed, sorted numerically.)
{"PID", "Process ID", 6, SLOT_pid},
{"PPID", "Parent Process ID", 6, SLOT_ppid},
{"PRI", "Priority (dynamic 0 to 139)", 3, SLOT_priority},
{"NI", "Niceness (static 19 to -20)", 3, SLOT_nice},
{"ADDR", "Instruction pointer", 4+sizeof(long), SLOT_eip},
{"SZ", "4k pages to swap out", 5, SLOT_vsize},
{"RSS", "Resident Set Size (DRAM pages)", 6, SLOT_rss},
{"PGID", "Process Group ID", 5, SLOT_pgrp},
{"VSZ", "Virtual memory size (1k units)", 7, SLOT_vsize},
{"MAJFL", "Major page faults", 6, SLOT_majflt},
{"MINFL", "Minor page faults", 6, SLOT_minflt},
{"PR", "Prio Reversed (dyn 39-0, RT)", 2, SLOT_priority},
{"PSR", "Processor last executed on", 3, SLOT_taskcpu},
{"RTPRIO", "Realtime priority", 6, SLOT_rtprio},
{"SCH", "Scheduling policy (0=other, 1=fifo, 2=rr, 3=batch, 4=iso, 5=idle)",
3, SLOT_policy},
{"CPU", "Which processor running on", 3, SLOT_taskcpu},
{"TID", "Thread ID", 5, SLOT_tid},
{"TCNT", "Thread count", 4, SLOT_tcount},
{"BIT", "32 or 64", 3, SLOT_bits},
// String fields (-1 is procpid->str, rest are str+offset[1-slot])
{"TTY", "Controlling terminal", -8, -2},
{"WCHAN", "Wait location in kernel", -6, -3},
{"LABEL", "Security label", -30, -4},
{"COMM", "EXE filename (/proc/PID/exe)", -27, -5},
{"NAME", "Process name (PID's argv[0])", -27, -7},
{"COMMAND", "EXE path (/proc/PID/exe)", -27, -5},
{"CMDLINE", "Command line (argv[])", -27, -6},
{"ARGS", "CMDLINE minus initial path", -27, -6},
{"CMD", "Thread name (/proc/TID/stat:2)", -15, -1},
// user/group (may call getpwuid() or similar)
{"UID", "User id", 5, SLOT_uid},
{"USER", "User name", -12, XX|SLOT_uid},
{"RUID", "Real (before suid) user ID", 4, SLOT_ruid},
{"RUSER", "Real (before suid) user name", -8, XX|SLOT_ruid},
{"GID", "Group ID", 8, SLOT_gid},
{"GROUP", "Group name", -8, XX|SLOT_gid},
{"RGID", "Real (before sgid) Group ID", 4, SLOT_rgid},
{"RGROUP", "Real (before sgid) group name", -8, XX|SLOT_rgid},
// clock displays (00:00:00)
{"TIME", "CPU time consumed", 8, SLOT_utime},
{"ELAPSED", "Elapsed time since PID start", 11, SLOT_starttime},
{"TIME+", "CPU time (high precision)", 9, SLOT_utime},
// Percentage displays (fixed point, one decimal digit. 123 -> 12.3)
{"C", "Total %CPU used since start", 1, SLOT_utime2},
{"%VSZ", "VSZ as % of physical memory", 5, SLOT_vsize},
{"%MEM", "RSS as % of physical memory", 5, SLOT_rss},
{"%CPU", "Percentage of CPU time used", 4, SLOT_utime2},
// human_readable (function human_readable() in lib, 1.23M, 1.4G, etc)
{"VIRT", "Virtual memory size", 4, SLOT_vsz},
{"RES", "Short RSS", 4, SLOT_rss},
{"SHR", "Shared memory", 4, SLOT_shr},
{"READ", "Data read", 6, SLOT_rchar},
{"WRITE", "Data written", 6, SLOT_wchar},
{"IO", "Data I/O", 6, SLOT_iobytes},
{"DREAD", "Data read from disk", 6, SLOT_rbytes},
{"DWRITE", "Data written to disk", 6, SLOT_wbytes},
{"SWAP", "Swap I/O", 6, SLOT_swap},
{"DIO", "Disk I/O", 6, SLOT_diobytes},
// Misc (special cases)
{"STIME", "Start time (ISO 8601)", 5, SLOT_starttime},
{"F", "Flags 1=FORKNOEXEC 4=SUPERPRIV", 1, XX|SLOT_flags},
{"S", "Process state:\n"
"\t R (running) S (sleeping) D (device I/O) T (stopped) t (trace stop)\n"
"\t X (dead) Z (zombie) P (parked) I (idle)\n"
"\t Also between Linux 2.6.33 and 3.13:\n"
"\t x (dead) K (wakekill) W (waking)\n",
-1, XX},
{"STAT", "Process state (S) plus:\n"
"\t < high priority N low priority L locked memory\n"
"\t s session leader + foreground l multithreaded",
-5, XX},
{"PCY", "Android scheduling policy", 3, XX|SLOT_pcy},
);
// Show sorted "-o help" text for fields listed in toybuf[len]
static void help_fields(int len, int multi)
{
int i, j, k, left = 0;
struct typography *t;
// Quick and dirty sort of toybuf[] entries (see TODO below)
for (j = len; j--; ) {
k = -1;
for (i=0; i<j; i++) {
if (strcmp(typos[toybuf[i]].name, typos[toybuf[i+1]].name)>0) {
k = toybuf[i];
toybuf[i] = toybuf[i+1];
toybuf[i+1] = k;
}
}
if (k == -1) break;
}
// Display loop
for (i = j = 0; i<len; i++, j++) {
t = (void *)(typos+toybuf[i]);
if (strlen(t->help)>30) {
if (multi) printf(" %-8s%s\n", t->name, t->help);
else j--;
} else if (!multi) {
left = !(j&1);
printf(" %-8s%*s%c"+2*!left, t->name, -30*left, t->help, 10+22*left);
}
}
if (!multi && left) xputc('\n');
}
// Print help text for each -o field, with categories.
static void help_help(void)
{
int i, jump = PS_CMD+1-PS_COMM;
// TODO: sort the array of -o types so they're already alphabetical and
// don't need sorting here. A regex to find everything that currently cares
// about symbol order might be: "which *[><]=* *PS"
// First show the half-dozen variants of command line display.
printf("Command line field types:\n\n");
for (i = 0; i<jump; i++) toybuf[i] = PS_COMM+i;
help_fields(jump, 0);
// Show the rest of the -o types, starting with the ones that don't columnize
printf("\nProcess attribute field types:\n\n");
for (i = 0; i<ARRAY_LEN(typos)-jump; i++) toybuf[i] = i+(i>=PS_COMM)*jump;
help_fields(ARRAY_LEN(typos)-jump, 1);
help_fields(ARRAY_LEN(typos)-jump, 0);
xexit();
}
// process match filter for top/ps/pgrep: Return 0 to discard, nonzero to keep
static int shared_match_process(long long *slot)
{
struct ps_ptr_len match[] = {
{&TT.gg, SLOT_gid}, {&TT.GG, SLOT_rgid}, {&TT.pp, SLOT_pid},
{&TT.PP, SLOT_ppid}, {&TT.ss, SLOT_sid}, {&TT.tt, SLOT_ttynr},
{&TT.uu, SLOT_uid}, {&TT.UU, SLOT_ruid}
};
int i, j;
long *ll = 0;
// Do we have -g -G -p -P -s -t -u -U options selecting processes?
for (i = 0; i < ARRAY_LEN(match); i++) {
struct ps_ptr_len *mm = match[i].ptr;
if (mm->len) {
ll = mm->ptr;
for (j = 0; j<mm->len; j++) if (ll[j] == slot[match[i].len]) return 1;
}
}
return ll ? 0 : -1;
}
// process match filter for ps: Return 0 to discard, nonzero to keep
static int ps_match_process(long long *slot)
{
int i = shared_match_process(slot);
if (i>0) return 1;
// If we had selections and didn't match them, don't display
if (!i) return 0;
// Filter implicit categories for other display types
if ((FLAG(a)||FLAG(d)) && slot[SLOT_sid]==*slot) return 0;
if (FLAG(a) && !slot[SLOT_ttynr]) return 0;
if (!(FLAG(a)||FLAG(d)||FLAG(A)||FLAG(e)) && TT.tty!=slot[SLOT_ttynr])
return 0;
return 1;
}
// Generate display string (260 bytes at end of toybuf) from struct ofield
static char *string_field(struct procpid *tb, struct ofields *field)
{
char *buf = toybuf+sizeof(toybuf)-260, *out = buf, *s;
int which = field->which, sl = typos[which].slot;
long long *slot = tb->slot, ll = (sl >= 0) ? slot[sl&(XX-1)] : 0;
// numbers, mostly from /proc/$PID/stat
if (which <= PS_BIT) {
char *fmt = "%lld";
if (which==PS_PRI) ll = 39-ll;
if (which==PS_ADDR) fmt = "%llx";
else if (which==PS_SZ) ll >>= 12;
else if (which==PS_RSS) ll <<= 2;
else if (which==PS_VSZ) ll >>= 10;
else if (which==PS_PR && ll<-9) fmt="RT";
else if ((which==PS_RTPRIO || which==PS_BIT) && ll == 0) fmt="-";
sprintf(out, fmt, ll);
// String fields
} else if (sl < 0) {
out = tb->str;
sl *= -1;
// First string slot has offset 0, others are offset[-slot-2]
if (--sl) out += tb->offset[--sl];
if (which==PS_ARGS || which==PS_COMM) {
int i;
s = out;
for (i = 0; (which==PS_ARGS) ? i < slot[SLOT_argv0len] : out[i]; i++)
if (out[i] == '/') s = out+i+1;
out = s;
}
if (which>=PS_COMM && !*out) sprintf(out = buf, "[%s]", tb->str);
// user/group
} else if (which <= PS_RGROUP) {
sprintf(out, "%lld", ll);
if (sl&XX) {
if (which > PS_RUSER) {
struct group *gr = bufgetgrgid(ll);
if (gr) out = gr->gr_name;
} else {
struct passwd *pw = bufgetpwuid(ll);
if (pw) out = pw->pw_name;
}
}
// Clock displays
} else if (which <= PS_TIME_) {
int unit = 60, pad = 2, j = TT.ticks;
time_t seconds;
if (which!=PS_TIME_) unit *= 60*24;
else pad = 0;
// top adjusts slot[SLOT_upticks], we want original meaning.
if (which==PS_ELAPSED) ll = (slot[SLOT_uptime]*j)-slot[SLOT_starttime];
seconds = ll/j;
// Output days-hours:mins:secs, skipping non-required fields with zero
// TIME has 3 required fields, ETIME has 2. (Posix!) TIME+ is from top
for (s = 0, j = 2*(which==PS_TIME_); j<4; j++) {
if (!s && (seconds>unit || j == 1+(which!=PS_TIME))) s = out;
if (s) {
s += sprintf(s, j ? "%0*ld": "%*ld", pad, (long)(seconds/unit));
pad = 2;
if ((*s = "-::"[j])) s++;
}
seconds %= unit;
unit /= j ? 60 : 24;
}
if (which==PS_TIME_ && s-out<8)
sprintf(s, ".%02lld", (100*(ll%TT.ticks))/TT.ticks);
// Percentage displays
} else if (which <= PS__CPU) {
ll = slot[sl&(XX-1)]*1000;
if (which==PS__VSZ || which==PS__MEM)
ll /= slot[SLOT_totalram]/((which==PS__VSZ) ? 1024 : 4096);
else if (slot[SLOT_upticks]) ll /= slot[SLOT_upticks];
sl = ll;
if (which==PS_C) sl += 5;
sprintf(out, "%d", sl/10);
if (which!=PS_C && sl<1000) sprintf(out+strlen(out), ".%d", sl%10);
// Human readable
} else if (which <= PS_DIO) {
int i = abs(field->len);
if (i<4) i = 4;
s = out;
if ((ll = slot[typos[which].slot])<0) {
ll = -ll;
*s++ = '-';
if (i>4) i--;
}
if (which <= PS_SHR) ll *= sysconf(_SC_PAGESIZE);
if (TT.forcek) sprintf(out, "%lldk", ll/1024);
else human_readable_long(s, ll, i-1, 0, 0);
// Posix doesn't specify what flags should say. Man page says
// 1 for PF_FORKNOEXEC and 4 for PF_SUPERPRIV from linux/sched.h
} else if (which==PS_F) sprintf(out, "%llo", (slot[SLOT_flags]>>6)&5);
else if (which==PS_S || which==PS_STAT) {
s = out;
*s++ = tb->state;
if (which==PS_STAT) {
// TODO l = multithreaded
if (slot[SLOT_nice]<0) *s++ = '<';
else if (slot[SLOT_nice]>0) *s++ = 'N';
if (slot[SLOT_sid]==*slot) *s++ = 's';
if (slot[SLOT_vmlck]) *s++ = 'L';
if (slot[SLOT_ttypgrp]==*slot) *s++ = '+';
}
*s = 0;
} else if (which==PS_STIME) {
time_t t = time(0)-slot[SLOT_uptime]+slot[SLOT_starttime]/TT.ticks;
// Padding behavior's a bit odd: default field size is just hh:mm.
// Increasing stime:size reveals more data at left until full,
// so move start address so yyyy-mm-dd hh:mm revealed on left at :16,
// then add :ss on right for :19.
strftime(out, 260, "%F %T", localtime(&t));
out = out+strlen(out)-3-abs(field->len);
if (out<buf) out = buf;
} else if (which==PS_PCY) sprintf(out, "%.2s", get_sched_policy_name(ll));
else if (CFG_TOYBOX_DEBUG) error_exit("bad which %d", which);
return out;
}
// Display process data that get_ps() read from /proc, formatting via TT.fields
static void show_ps(void *p)
{
struct procpid *tb = p;
struct ofields *field = TT.fields;
int pad, len, width = TT.width, abslen, sign, olen, scroll, extra = 0;
// Skip TT.scroll many fields (but not last one)
for (scroll = TT.scroll; scroll && field->next; scroll--) field = field->next;
// Loop through fields to display
for (; field; field = field->next) {
char *out = string_field(tb, field);
// Output the field, appropriately padded
// Minimum one space between each field
if (width<2) break;
if (field != TT.fields) {
putchar(' ');
width--;
}
// Don't truncate number fields, but try to reclaim extra offset from later
// fields that can naturally be shorter
abslen = abs(field->len);
sign = field->len<0 ? -1 : 1;
olen = (TT.tty) ? utf8len(out) : strlen(out);
if ((field->which<=PS_BIT || FLAG(w)) && olen>abslen) {
// overflow but remember by how much
extra += olen-abslen;
abslen = olen;
} else if (extra && olen<abslen) {
int unused = abslen-olen;
// If later fields have slack space, take back overflow
if (unused>extra) unused = extra;
abslen -= unused;
extra -= unused;
}
if (abslen>width) abslen = width;
len = pad = abslen;
pad *= sign;
// If last field is left justified, no trailing spaces.
if (!field->next && sign<0) {
pad = -1;
len = width;
}
// If we truncated a left-justified field, show + instead of last char
if (olen>len && len>1 && sign<0) {
width--;
len--;
if (field->next) pad++;
abslen = 0;
}
if (TT.tty) width -= draw_trim(out, pad, len);
else width -= printf("%*.*s", pad, len, out);
if (!abslen) putchar('+');
if (!width) break;
}
putchar(TT.time ? '\r' : '\n');
}
// dirtree callback: read data about a process, then display or store it.
// Fills toybuf with struct procpid and either DIRTREE_SAVEs a copy to ->extra
// (in -k mode) or calls show_ps directly on toybuf (for low memory systems).
static int get_ps(struct dirtree *new)
{
struct {
char *name; // Path under /proc/$PID directory
long long bits; // Only fetch extra data if an -o field is displaying it
} fetch[] = {
// sources for procpid->offset[] data
{"fd/", _PS_TTY}, {"wchan", _PS_WCHAN}, {"attr/current", _PS_LABEL},
{"exe", _PS_COMMAND|_PS_COMM}, {"cmdline", _PS_CMDLINE|_PS_ARGS|_PS_NAME},
{"", _PS_NAME}
};
struct procpid *tb = (void *)toybuf;
long long *slot = tb->slot;
char *name, *s, *buf = tb->str, *end = 0;
struct sysinfo si;
int i, j, fd;
off_t len;
// Recurse one level into /proc children, skip non-numeric entries
if (!new->parent)
return DIRTREE_RECURSE|DIRTREE_SHUTUP|DIRTREE_PROC
|(DIRTREE_SAVE*(TT.threadparent||!TT.show_process));
// Grab PID and figure out if we're a thread or a process
memset(slot, 0, sizeof(tb->slot));
slot[SLOT_tid] = *slot = atol(new->name);
if (TT.threadparent && TT.threadparent->extra) {
struct procpid *tb2 = (struct procpid *)TT.threadparent->extra;
*slot = *tb2->slot;
// Parent also shows up as a thread, but we need to reread task/stat fields
// to get non-collated info for just parent thread (vs whole process).
if (*slot == slot[SLOT_tid]) slot = tb2->slot;
}
fd = dirtree_parentfd(new);
// Read /proc/$PID/stat into half of toybuf.
len = 2048;
sprintf(buf, "%lld/stat", slot[SLOT_tid]);
if (!readfileat(fd, buf, buf, &len)) return 0;
// parse oddball fields: the first field is same as new->name (skip it)
// and the second and third (name and state) are the only non-numeric fields.
// Name has (parentheses) around it, and can have embedded ')' so match
// _last_ ')' (VFS limits filenames to 255 bytes max, sanity check that).
// TODO: kernel task struct actually limits name to 16 chars?
if (!(name = strchr(buf, '('))) return 0;
for (s = ++name; *s; s++) if (*s == ')') end = s;
if (!end || end-name>255) return 0;
if (1>sscanf(s = end, ") %c%n", &tb->state, &i)) return 0;
// All remaining fields should be numeric, parse them into slot[] array
// (skipping first 3 stat fields and first slot[], both were handled above)
// yes this means the alignment's off: stat[4] becomes slot[1]
for (j = SLOT_ppid; j<SLOT_upticks; j++)
if (1>sscanf(s += i, " %lld%n", slot+j, &i)) break;
// Now we've read the data, move status and name right after slot[] array,
// and convert low chars to ? for non-tty display while we're at it.
for (i = 0; i<end-name; i++)
if ((tb->str[i] = name[i]) < ' ')
if (!TT.tty) tb->str[i] = '?';
buf = tb->str+i;
*buf++ = 0;
len = sizeof(toybuf)-(buf-toybuf);
// Overwrite useless/obsolete stat fields with more interesting data.
// save uid, ruid, gid, gid, and rgid int slots 31-34 (we don't use sigcatch
// or numeric wchan, and the remaining two are always zero), and vmlck into
// 18 (which is "obsolete, always 0" from stat)
slot[SLOT_uid] = new->st.st_uid;
slot[SLOT_gid] = new->st.st_gid;
// TIME and TIME+ use combined value, ksort needs 'em added.
slot[SLOT_utime] += slot[SLOT_stime];
slot[SLOT_utime2] = slot[SLOT_utime];
// Do we need to read "status"?
if ((TT.bits&(_PS_RGROUP|_PS_RUSER|_PS_STAT|_PS_RUID|_PS_RGID|_PS_SWAP
|_PS_IO|_PS_DIO)) || TT.GG.len || TT.UU.len)
{
off_t temp = len;
sprintf(buf, "%lld/status", slot[SLOT_tid]);
if (!readfileat(fd, buf, buf, &temp)) *buf = 0;
s = strafter(buf, "\nUid:");
slot[SLOT_ruid] = s ? atol(s) : new->st.st_uid;
s = strafter(buf, "\nGid:");
slot[SLOT_rgid] = s ? atol(s) : new->st.st_gid;
if ((s = strafter(buf, "\nVmLck:"))) slot[SLOT_vmlck] = atoll(s)*1024;
if ((s = strafter(buf, "\nVmSwap:"))) slot[SLOT_swap] = atoll(s)*1024;
}
// Do we need to read "io"?
if (TT.bits&(_PS_READ|_PS_WRITE|_PS_DREAD|_PS_DWRITE|_PS_IO|_PS_DIO)) {
off_t temp = len;
sprintf(buf, "%lld/io", slot[SLOT_tid]);
if (!readfileat(fd, buf, buf, &temp)) *buf = 0;
if ((s = strafter(buf, "rchar:"))) slot[SLOT_rchar] = atoll(s);
if ((s = strafter(buf, "wchar:"))) slot[SLOT_wchar] = atoll(s);
if ((s = strafter(buf, "read_bytes:"))) slot[SLOT_rbytes] = atoll(s);
if ((s = strafter(buf, "write_bytes:"))) slot[SLOT_wbytes] = atoll(s);
slot[SLOT_iobytes] = slot[SLOT_rchar]+slot[SLOT_wchar]+slot[SLOT_swap];
slot[SLOT_diobytes] = slot[SLOT_rbytes]+slot[SLOT_wbytes]+slot[SLOT_swap];
}
// If we were updating thread parent with its own task info, we're done.
if (slot != tb->slot) return 0;
// We now know enough to skip processes we don't care about.
if (TT.match_process && !TT.match_process(slot)) return 0;
// /proc data is generated as it's read, so for maximum accuracy on slow
// systems (or ps | more) we re-fetch uptime as we fetch each /proc line.
sysinfo(&si);
slot[SLOT_uptime] = si.uptime;
slot[SLOT_totalram] = si.totalram;
slot[SLOT_upticks] = slot[SLOT_uptime]*TT.ticks - slot[SLOT_starttime];
// Do we need to read "statm"?
if (TT.bits&(_PS_VIRT|_PS_SHR)) {
off_t temp = len;
sprintf(buf, "%lld/statm", slot[SLOT_tid]);
if (!readfileat(fd, buf, buf, &temp)) *buf = 0;
// Skip redundant RSS field, we got it from stat.
slot[SLOT_vsz] = slot[SLOT_shr] = 0;
sscanf(buf, "%lld %*d %lld", &slot[SLOT_vsz], &slot[SLOT_shr]);
}
// Do we need to read "exe"?
if (TT.bits&_PS_BIT) {
off_t temp = 6;
sprintf(buf, "%lld/exe", slot[SLOT_tid]);
if (readfileat(fd, buf, buf, &temp) && !smemcmp(buf, "\177ELF", 4)) {
if (buf[4] == 1) slot[SLOT_bits] = 32;
else if (buf[4] == 2) slot[SLOT_bits] = 64;
}
}
// Do we need Android scheduling policy?
if (TT.bits&_PS_PCY)
get_sched_policy(slot[SLOT_tid], (void *)&slot[SLOT_pcy]);
// Done using buf[] (tb->str) as scratch space, now read string data,
// saving consective null terminated strings. (Save starting offsets into
// str->offset to avoid strlen() loop to find relevant string.)
// Fetch string data while parentfd still available, appending to buf.
// (There's well over 3k of toybuf left. We could dynamically malloc, but
// it'd almost never get used, querying length of a proc file is awkward,
// fixed buffer is nommu friendly... Wait for somebody to complain. :)
// The fetch[] array at the start of the function says what file to read
// and what -o display field outputs it (to skip the ones we don't need).
slot[SLOT_argv0len] = 0;
for (j = 0; j<ARRAY_LEN(fetch); j++) {
tb->offset[j] = buf-(tb->str);
if (!(TT.bits&fetch[j].bits)) {
*buf++ = 0;
continue;
}
// Determine available space: reserve 256 bytes (guaranteed minimum) for
// each string we haven't checked yet, tb->str starts after the numeric
// arrays in struct procpid, and we reserve 260 bytes scratch space at the
// end of toybuf for output conversion in string_field(). Other than that,
// each use all available space, and future strings that don't use their
// guaranteed minimum add to the pool.
len = sizeof(toybuf)-256*(ARRAY_LEN(fetch)-j)-(buf-toybuf)-260;
sprintf(buf, "%lld/%s", slot[SLOT_tid], fetch[j].name);
// For exe (j==3) readlink() instead of reading file's contents
// for -o NAME (j==5) copy data from threadparent (PID) into thread (TID).
if (j==3 || j==5) {
struct procpid *ptb = 0;
int k;
// Thread doesn't have exe or argv[0], so use parent's
if (TT.threadparent && TT.threadparent->extra)
ptb = (void *)TT.threadparent->extra;
if (j==3 && !ptb) len = readlinkat0(fd, buf, buf, len);
else {
if (j==3) i = strlen(s = ptb->str+ptb->offset[3]);
else {
if (!ptb || slot[SLOT_argv0len]) ptb = tb;
i = ptb->slot[SLOT_argv0len];
s = ptb->str+ptb->offset[4];
while (-1!=(k = stridx(s, '/')) && k<i) {
s += k+1;
i -= k+1;
}
}
if (i<len) len = i;
memcpy(buf, s, len);
buf[len] = 0;
}
// Turning stat's SLOT_ttynr into a string is an outright heuristic ordeal.
} else if (!j) {
int rdev = slot[SLOT_ttynr];
struct stat st;
// Call no tty "?" rather than "0:0".
strcpy(buf, "?");
if (rdev) {
// Can we readlink() our way to a name?
for (i = 0; i<3; i++) {
sprintf(buf, "%lld/fd/%i", slot[SLOT_tid], i);
if (!fstatat(fd, buf, &st, 0) && S_ISCHR(st.st_mode)
&& st.st_rdev == rdev && (len = readlinkat0(fd, buf, buf, len)))
break;
}
// Couldn't find it, try all the tty drivers.
if (i == 3) {
FILE *fp = fopen("/proc/tty/drivers", "r");
int tty_major = 0, maj = dev_major(rdev), min = dev_minor(rdev);
if (fp) {
while (fscanf(fp, "%*s %256s %d %*s %*s", buf, &tty_major) == 2) {
// TODO: we could parse the minor range too.
if (tty_major == maj) {
len = strlen(buf);
len += sprintf(buf+len, "%d", min);
if (!stat(buf, &st) && S_ISCHR(st.st_mode) && st.st_rdev==rdev)
break;
}
tty_major = 0;
}
fclose(fp);
}
// Really couldn't find it, so just show major:minor.
if (!tty_major) len = sprintf(buf, "%d:%d", maj, min);
}
s = buf;
if (strstart(&s, "/dev/")) memmove(buf, s, len -= 4);
}
// For the rest, the data we want is in a file we can just read.
} else {
int temp = 0;
// When command has no arguments, don't space over the NUL
if (readfileat(fd, buf, buf, &len) && len>0) {
// Trim trailing whitespace and NUL bytes
while (len)
if (!buf[len-1] || isspace(buf[len-1])) buf[--len] = 0;
else break;
// Turn NUL to space, other low ascii to ? (in non-tty mode), except
// cmdline has a trailing NUL that we don't want to turn to space.
for (i=0; i<len-1; i++) {
char c = buf[i];
if (!c) {
if (!temp) temp = i;
c = ' ';
} else if (!TT.tty && c<' ') c = '?';
buf[i] = c;
}
} else *buf = len = 0;
// Store end of argv[0] so ARGS and CMDLINE can differ.
// We do it for each file string slot but last is cmdline, which sticks.
slot[SLOT_argv0len] = temp ? : len; // Position of _first_ NUL
}
// Each case above calculated/retained len, so we don't need to re-strlen.
buf += len+1;
}
// Record that we saw another process, and display/return now if appropriate
TT.kcount++;
if (TT.show_process && !TT.threadparent) {
TT.show_process(tb);
return 0;
}
// We're retaining data (probably to sort it), save copy in list.
s = xmalloc(buf-toybuf);