-
Notifications
You must be signed in to change notification settings - Fork 11
/
pq.cc
1849 lines (1654 loc) · 51.3 KB
/
pq.cc
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
// pq - query process/thread attributes
//
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: © 2020 Georg Sauthoff <[email protected]>
#include <algorithm> // search(), find()
#include <charconv> // to_chars(), from_chars()
#include <functional> // default_searcher
#include <vector>
#include <string>
#include <string_view>
#include <unordered_map>
#include <array>
#include <memory> // unique_ptr
#include <optional>
#include <regex> // requires GCC > 4.8
#include <ixxx/util.hh>
#include <ixxx/ansi.hh>
#include <ixxx/posix.hh>
#include <ixxx/linux.hh>
#include <ixxx/sys_error.hh>
#include <stdlib.h> // exit()
#include <string.h> // strlen(), memcmp(), memchr(), ...
#include <fcntl.h> // O_RDONLY
#include <unistd.h> // getopt()
#include <sys/epoll.h> // epoll_event
#include <sys/signalfd.h> // signalfd_siginfo
#include <assert.h>
#include "syscalls.hh"
using namespace std;
// cf. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88545
template <typename Itr, typename T>
inline Itr fast_find(Itr b, Itr e, const T &v)
{
auto t = memchr(&*b, v, e-b);
if (t)
return Itr(t);
else
return e;
}
template <typename Itr, typename T>
inline Itr fast_rfind(Itr b, Itr e, const T &v)
{
auto t = memrchr(&*b, v, e-b);
if (t)
return Itr(t);
else
return e;
}
inline string_view nth_col(const string_view &v, unsigned x)
{
auto p = v.begin();
for (unsigned i = 0; i < x; ++i) {
for ( ; p != v.end() && (*p != '\t' && *p != ' '); ++p)
;
for ( ; p != v.end() && (*p == '\t' || *p == ' '); ++p)
;
}
auto ws = { '\t', ' ', '\n' };
auto e = find_first_of(p, v.end(), begin(ws), end(ws));
return string_view(p, e - p);
}
enum class Column {
AFFINITY , // /proc/$pid/status::Cpus_allowed_list
CLS , // scheduling class, proc/$pid/stat
CMD , // /proc/$pid/commandline
COMM , // /proc/comm or /proc/$pid/status::Name or /proc/$pid/stat
CPU , // last run on this CPU, /proc/$pid/stat::processor
CWBYTE , // /proc/$pid/io::cancelled_write_bytes
CWD , //
ENV , //
EPOCH , // clock_gettime()
EXE , //
FDS , // ls /proc/$pid/fd | wc -l
FDSIZE , // /proc/$pid/status::FDSize
FLAGS , // process flags, /proc/$pid/stat
GID , // effective ...
HELP , // dummy, displays column help ...
HUGEPAGES , // /proc/$pid/status::HugetlbPages
LOGINUID , // /proc/$pid/loginuid
MAJFLT , // major page faults /proc/$pid/status
MINFLT , // minor page faults /proc/$pid/status
NICE , // /proc/$pid/stat
NS , // UNIX epoch time in ns
NUMAGID , // NUMA group ID, /proc/$pid/status::Ngid
NVCTX , // non-voluntary context switches /proc/$pid/status
PID , //
PPID , //
RBYTE , // /proc/$pid/io::read_bytes
RCHAR , // /proc/$pid/io::rchar
RSS , //
RTPRIO , // /proc/$pid/stat
SLACK , // /proc/$pid/timerslack_ns
STACK , //
STATE , // /proc/$pid/status or /proc/$pid/stat
STIME , // start time /proc/$pid/stat
SYSCALL , // /proc/$pid/syscall
SYSCR , // /proc/$pid/io::syscr
SYSCW , // /proc/$pid/io::syscw
THREADS , //
TID , //
UID , // effective ...
UMASK , //
USER , //
VCTX , // voluntary context switches /proc/$pid/status
VSIZE , //
WBYTE , // /proc/$pid/io::write_bytes
WCHAN , // /proc/$pid/wchan
WCHAR , // /proc/$pid/io::wchar
END_OF_ENUM // just a sentinel for this enum ...
// TODO:
//
// /proc/$pid/status: THP_enabled, CoreDumping, VmSwap, ...
// /proc/$pid/limits
// /proc/$pid/cgroup
// /proc/$pid/auxv
// real uid/gid
};
static const string_view col2header[] = {
"aff" , // AFFINITY
"cls" , // CLS
"cmd" , // CMD
"comm" , // COMM
"cpu" , // CPU
"cwbyte" , // CWBYTE
"cwd" , // CWD
"env" , // ENV
"epoch" , // EPOCH
"exe" , // EXE
"fds" , // FDS
"fdsz" , // FDSIZE
"flags" , // FLAGS
"gid" , // GID
"XXXhelp" , // HELP
"hugepages" , // HUGEPAGES
"loginuid" , // LOGINUID
"majflt" , // MAJFLT
"minflt" , // MINFLT
"nice" , // NICE
"ns" , // NS
"nid" , // NUMAGID
"nvctx" , // NVCTX
"pid" , // PID
"ppid" , // PPID
"rbyte" , // RBYTE
"rchar" , // RCHAR
"rss" , // RSS
"pri" , // RTPRIO
"slack" , // SLACK
"stack" , // STACK
"state" , // STATE
"stime" , // STIME
"syscall" , // SYSCALL
"syscr" , // SYSCR
"syscw" , // SYSCW
"threads" , // THREADS
"tid" , // TID
"uid" , // UID
"umask" , // UMASK
"user" , // USER
"vctx" , // VCTX
"vsize" , // VSIZE
"wbyte" , // WBYTE
"wchan" , // WCHAN
"wchar" // WCHAR
};
static_assert(sizeof col2header / sizeof col2header[0] == static_cast<size_t>(Column::END_OF_ENUM));
static const char * const col2help[] = {
"CPU (core) affinity, i.e. task only runs on those cores" , // AFFINITY
"scheduling class", // CLS
"command line, i.e. the argument vector" , // CMD
"process/thread name" , // COMM
"last ran on that CPU (core)" , // CPU
"write bytes, cancelled" , // CWBYTE
"current wording directory" , // CWD
"display an environment variable, e.g. env:MYID" , // ENV
"unix time at traversal time, i.e. seconds since the epoch", // EPOCH
"process' executable" , // EXE
"number of open files" , // FDS
"number of allocated file descriptor slots" , // FDSIZE
"process flags (e.g. PF_KTHREAD, PF_WQ_WORKER or PF_NO_SETAFFINITY)", // FLAGS
"group ID" , // GID
"XXXhelp", // HELP
"#hugepages" , // HUGEPAGES
"login user ID or 2**32-1 if daemon etc." , // LOGINUID
"major page faults" , // MAJFLT
"minor page faults" , // MINFLT
"process niceness", // NICE
"nanoseconds since the epoch", // NS
"NUMA group ID" , // NUMAGID
"non-voluntary context switches" , // NVCTX
"process ID" , // PID
"parent process ID" , // PPID
"bytes read, actually", // RBYTE
"bytes read", // RCHAR
"resident size set in KiB" , // RSS
"realtime priority (1-99)", // RTPRIO
"current timer slack value of a thread in ns", // SLACK
"top of stack function the task is executing/blocked on (requires root)" , // STACK
"state the process is in, e.g. running, sleeping etc." , // STATE
"start time in ISO format" , // STIME
"current syscall the task is executing/blocked on, if any" , // SYSCALL
"number of read syscalls" , // SYSCR
"number of write syscalls" , // SYSCW
"number of threads of that process/the process the thread is part of" , // THREADS
"thread ID" , // TID
"(effective) user ID" , // UID
"user file creation mask" , // UMASK
"(effective) user name", // USER
"number of voluntary context-switches" , // VCTX
"virtual memory usage in KiB" , // VSIZE
"bytes written, actually", // WBYTE
"kernel function the task waits for, cf. stack (some kernels doesn't support it - e.g. Fedora's doesn't)", // WCHAN
"bytes written" // WCHAR
};
static_assert(sizeof col2header / sizeof col2header[0] == sizeof col2help / sizeof col2help[0]);
static const unsigned col2width[] = {
5 , // AFFINITY
3 , // CLS
15 , // CMD
15 , // COMM
3 , // CPU
11 , // CWBYTE
15 , // CWD
8 , // ENV
10 , // EPOCH
10 , // EXE
3 , // FDS
3 , // FDSIZE
5 , // FLAGS
4 , // GID
0 , // HELP
10 , // HUGEPAGES
10 , // LOGINUID
10 , // MAJFLT
10 , // MINFLT
4 , // NICE
19 , // NS
3 , // NUMAGID
10 , // NVCTX
7 , // PID
7 , // PPID
11, // RBYTE
11, // RCHAR
8 , // RSS
3 , // RTPRIO
5 , // SLACK
10 , // STACK
10 , // STATE
10 , // STIME
10 , // SYSCALL
8 , // SYSCR
8 , // SYSCW
7 , // THREADS
7 , // TID
4 , // UID
4 , // UMASK
8 , // USER
10 , // VCTX
8 , // VSIZE
11 , // WBYTE
10 , // WCHAN
11 // WCHAR
};
static_assert(sizeof col2header / sizeof col2header[0] == sizeof col2width / sizeof col2width[0]);
static const unordered_map<string_view, Column> str2column = {
{ "pid" , Column::PID },
{ "tid" , Column::TID },
{ "comm" , Column::COMM },
{ "name" , Column::COMM },
{ "epoch" , Column::EPOCH },
{ "exe" , Column::EXE },
{ "affinity" , Column::AFFINITY },
{ "aff" , Column::AFFINITY },
{ "cores" , Column::AFFINITY },
{ "wchan" , Column::WCHAN },
{ "wchar" , Column::WCHAR },
{ "wbyte" , Column::WBYTE },
{ "syscall" , Column::SYSCALL },
{ "scall" , Column::SYSCALL },
{ "ecall" , Column::SYSCALL },
{ "syscr" , Column::SYSCR },
{ "syscw" , Column::SYSCW },
{ "state" , Column::STATE },
{ "cmd" , Column::CMD },
{ "cmdline" , Column::CMD },
{ "cmdline" , Column::CMD },
{ "cwd" , Column::CWD },
{ "cpu" , Column::CPU },
{ "psr" , Column::CPU },
{ "core" , Column::CPU },
{ "cwbyte" , Column::CWBYTE },
{ "gid" , Column::GID },
{ "egid" , Column::GID },
{ "uid" , Column::UID },
{ "euid" , Column::UID },
{ "help" , Column::HELP },
{ "hugepages" , Column::HUGEPAGES },
{ "hpages" , Column::HUGEPAGES },
{ "threads" , Column::THREADS },
{ "slack" , Column::SLACK },
{ "stack" , Column::STACK },
{ "ppid" , Column::PPID },
{ "rbyte" , Column::RBYTE },
{ "rchar" , Column::RCHAR },
{ "stime" , Column::STIME },
{ "start" , Column::STIME },
{ "nvctx" , Column::NVCTX },
{ "nctx" , Column::NVCTX },
{ "vctx" , Column::VCTX },
{ "minfault" , Column::MINFLT },
{ "minflt" , Column::MINFLT },
{ "majfault" , Column::MAJFLT },
{ "majflt" , Column::MAJFLT },
{ "umask" , Column::UMASK },
{ "loginuid" , Column::LOGINUID },
{ "luid" , Column::LOGINUID },
{ "rss" , Column::RSS },
{ "vsize" , Column::VSIZE },
{ "vmem" , Column::VSIZE },
{ "fds" , Column::FDS },
{ "fdsize" , Column::FDSIZE },
{ "numagid" , Column::NUMAGID },
{ "numa" , Column::NUMAGID },
{ "ngid" , Column::NUMAGID },
{ "nid" , Column::NUMAGID },
{ "user" , Column::USER },
{ "usr" , Column::USER },
{ "rtprio" , Column::RTPRIO },
{ "prio" , Column::RTPRIO },
{ "pri" , Column::RTPRIO },
{ "cls" , Column::CLS },
{ "class" , Column::CLS },
{ "policy" , Column::CLS },
{ "sched" , Column::CLS },
{ "nice" , Column::NICE },
{ "ns" , Column::NS },
{ "flags" , Column::FLAGS },
{ "pf" , Column::FLAGS }
};
enum Show_Tasks {
BOTH,
KERNEL,
USER
};
static time_t get_boot_time()
{
array<char, 64> buf;
ixxx::util::FD fd("/proc/uptime", O_RDONLY);
size_t n = ixxx::util::read_all(fd, buf);
char *b = buf.data();
char *e = b + n;
e = fast_find(b, e, '.');
struct timespec tp;
ixxx::posix::clock_gettime(CLOCK_REALTIME_COARSE, &tp);
size_t off = 0;
auto r = from_chars(b, e, off);
if (r.ptr != e)
throw runtime_error("uptime parse error");
time_t boot_time_s = tp.tv_sec - off;
return boot_time_s;
}
static size_t parse_uid(const char *s)
{
size_t uid = 0;
auto e = s + strlen(s);
if (e == s)
throw runtime_error("empty uid/user");
if (*s < '0' || *s > '9') {
struct passwd pass;
struct passwd *res;
array<char, 4 * 1024> buf;
ixxx::posix::getpwnam_r(s, &pass, buf.data(), buf.size(), &res);
if (!res)
throw runtime_error("user not found");
uid = pass.pw_uid;
} else {
auto r = from_chars(s, e, uid);
if (r.ptr != e)
throw runtime_error("uid parse error");
}
return uid;
}
struct Args {
vector<size_t> pids ;
bool all_pids {false} ;
optional<size_t> uid ;
string regex_str ;
Show_Tasks show_tasks {Show_Tasks::BOTH} ;
bool traverse_threads {false} ;
bool show_header {true} ;
vector<Column> columns ;
vector<string> env_vars ;
time_t boot_time_s {0} ;
unsigned clock_ticks {0} ;
unsigned interval_s {0} ;
unsigned count {0} ;
char delim {0} ;
void parse(int argc, char **argv);
private:
void init_default_columns();
};
static void help(FILE *o, const char *argv0)
{
fprintf(o, "%s - query process and thread attributes\n"
"Usage: %s [-o COL1 COL2..] [-p PID1 PID2..] [OPTS]\n"
"\n"
"Options:\n"
" -a list all processes\n"
" -c N repeat N times, if -i is set (default: unlimited)\n"
" -d CHAR delimit columns by character instead of whitespace\n"
" -e REGEX filter by regular expression (match against COMM)\n"
" -h display this help\n"
" -H omit header row\n"
" -i X repeat output after X seconds\n"
" -k only list kernel threads\n"
" -K only list user tasks\n"
" -o COL.. columns to display (use `-o help` to get a list)\n"
" -p PID.. only list the specified processes/threads\n"
" -t also list threads\n"
" -u USER filter by user/uid\n"
"\n"
"2020, Georg Sauthoff <[email protected]>, GPLv3+\n"
,
argv0,
argv0);
}
static void help_col(FILE *o)
{
fprintf(o, "Available columns:\n"
"\n");
unordered_map<Column, vector<string>> aliases;
for (auto &x : str2column) {
auto &q = aliases[x.second];
q.reserve(10);
if (col2header[static_cast<unsigned>(x.second)] != x.first)
q.emplace_back(x.first);
}
for (unsigned i = 0; i < sizeof col2header / sizeof col2header[0]; ++i) {
if (i == static_cast<unsigned>(Column::HELP))
continue;
fprintf(o, " ");
fwrite(col2header[i].data(), 1, col2header[i].size(), o);
fprintf(o, " - %s", col2help[i]);
auto &v = aliases[Column(i)];
if (!v.empty()) {
if (v.size() == 1)
fprintf(o, " (Alias: ");
else
fprintf(o, " (Aliases: ");
auto a = v.begin();
auto b = v.end();
fprintf(o, "%s", (*a).c_str());
++a;
for (; a != b; ++a)
fprintf(o, ", %s", (*a).c_str());
fputc(')', o);
}
fputc('\n', o);
}
}
void Args::init_default_columns()
{
auto const default_columns = { Column::PID, Column::TID, Column::PPID,
Column::AFFINITY, Column::CPU, Column::CLS, Column::RTPRIO,
Column::NICE, Column::SYSCALL, Column::RSS, Column::COMM };
columns = default_columns;
env_vars.resize(columns.size());
}
// Not using Boost Program Options because of its atrocious API
// and slow compile times.
// Not using cxxopts because of its API being similar to Boost PO.
// Not using CLI11 because of its ultra slow compile times.
// (cf. https://github.com/CLIUtils/CLI11/issues/194)
void Args::parse(int argc, char **argv)
{
enum State { IN_PID_LIST, IN_COL_LIST };
char c = 0;
State state = IN_PID_LIST;
// '-' prefix: no reordering of arguments, non-option arguments are
// returned as argument to the 1 option
// ':': preceding opting takes a mandatory argument
while ((c = getopt(argc, argv, "-ae:c:d:Hhi:Kkoptu:")) != -1) {
switch (c) {
case '?':
fprintf(stderr, "unexpected option character: %c\n", optopt);
exit(1);
break;
case 'a':
all_pids = true;
break;
case 'c':
count = atoi(optarg);
if (!interval_s)
interval_s = 1;
break;
case 'd':
delim = *optarg;
break;
case 'e':
regex_str = optarg;
break;
case 'H':
show_header = false;
break;
case 'h':
help(stdout, argv[0]);
exit(0);
break;
case 'i':
interval_s = atoi(optarg);
break;
case 'K':
show_tasks = Show_Tasks::USER;
break;
case 'k':
show_tasks = Show_Tasks::KERNEL;
break;
case 'o':
state = IN_COL_LIST;
break;
case 'p':
state = IN_PID_LIST;
break;
case 't':
traverse_threads = true;
break;
case 'u':
all_pids = true;
uid = parse_uid(optarg);
break;
case 1:
switch (state) {
case IN_PID_LIST:
{
size_t pid;
auto e = optarg + strlen(optarg);
auto r = from_chars(optarg, e, pid);
if (r.ec != std::errc() || r.ptr != e) {
fprintf(stderr, "Invalid pid: %s\n", optarg);
exit(1);
}
pids.push_back(pid);
}
break;
case IN_COL_LIST:
if (strlen(optarg) > 4 && !memcmp(optarg, "env:", 4)) {
columns.push_back(Column::ENV);
env_vars.emplace_back(optarg + 4);
} else if (*optarg) {
if (*optarg == '+') {
++optarg;
init_default_columns();
if (!*optarg)
continue;
}
try {
columns.push_back(str2column.at(string_view(optarg)));
} catch (const out_of_range &) {
fprintf(stderr, "Unknown column: %s\n", optarg);
exit(1);
}
env_vars.emplace_back();
} else {
fprintf(stderr, "empty column\n");
exit(1);
}
if (columns.back() == Column::HELP) {
help_col(stdout);
exit(0);
}
if (columns.back() == Column::STIME) {
try {
boot_time_s = get_boot_time();
clock_ticks = ixxx::posix::sysconf(_SC_CLK_TCK);
} catch (...) {
fprintf(stderr, "Can't read /proc/uptime\n");
exit(1);
}
}
break;
default:
fprintf(stderr, "spurious positional argument: %s\n", optarg);
exit(1);
}
break;
}
}
if (pids.empty() && !all_pids) {
if (regex_str.empty()) {
fprintf(stderr, "Either specify one or more PIDs or -a or -e\n");
exit(1);
} else {
all_pids = true;
}
}
if (columns.empty())
init_default_columns();
}
struct Process;
typedef string_view (Process::*Process_Attr)();
struct Process {
public:
size_t pid {0} ;
size_t tid {0} ;
time_t boot_time_s ;
unsigned clock_ticks {0} ;
private:
string fn { "/proc/" } ;
size_t fn_stem {6} ;
char epsilon[1] {0} ;
// we could also use std::vector, however we would need
// to switch it from value to default initialization
// to eliminate superfluous initializations
// (such as in: https://github.com/gsauthof/libxfsx/blob/91979ec5f2bc56f3d0dd06ac0b8ff6658d889cfb/xfsx/raw_vector.hh#L7)
// as a bonus we save some overheads in memory management
array<char, 4*1024> environ_arr ;
array<char, 4*1024> stat_arr ;
array<char, 4*1024> status_arr ;
array<char, 4*1024> misc_arr ;
array<char, 4*1024> io_arr ;
string_view environ ;
string_view stat ;
string_view status ;
string_view misc ;
string_view io ;
array<char, 1024> buffer ;
unordered_map<size_t, string> username_cache ;
public:
Process() =default;
Process(const Process &) =delete;
Process &operator=(const Process &) =delete;
void set_pid(size_t pid, size_t tid);
const char *getenv(const string &s);
unsigned flags();
string_view comm();
string_view epoch();
string_view ns();
string_view exe();
string_view wchan();
string_view wchar();
string_view wbyte();
string_view cwbyte();
string_view affinity();
string_view syscall();
string_view syscr();
string_view syscw();
string_view loginuid();
string_view state();
string_view cls();
string_view cmd();
string_view cpu();
string_view cwd();
string_view gid();
string_view uid();
string_view hugepages();
string_view threads();
string_view slack();
string_view stack();
string_view ppid();
string_view rchar();
string_view rbyte();
string_view stime();
string_view nvctx();
string_view vctx();
string_view minflt();
string_view majflt();
string_view umask();
string_view user();
string_view rss();
string_view rtprio();
string_view vsize();
string_view fds();
string_view fdsize();
string_view numagid();
string_view nice();
string_view pflags();
string_view column(Column c);
private:
template <size_t N>
void read_proc(const char *q, array<char, N> &src,
string_view &dst, bool prefix = false);
string_view read_key_value(const string_view &status, const string_view &q);
string_view read_status(const string_view &q);
string_view read_io(const string_view &q);
string_view read_stat(unsigned i);
string_view read_link(const char *q);
};
Process_Attr process_attrs[] = {
&Process::affinity , // AFFINITY
&Process::cls , // CLS
&Process::cmd , // CMD
&Process::comm , // COMM
&Process::cpu , // CPU
&Process::cwbyte , // CWBYTE
&Process::cwd , // CWD
nullptr , // ENV
&Process::epoch , // EXE
&Process::exe , // EXE
&Process::fds , // FDS
&Process::fdsize , // FDSIZE
&Process::pflags , // FLAGS
&Process::gid , // GID
nullptr , // HELP - dummy - never called
&Process::hugepages , // HUGEPAGES
&Process::loginuid , // LOGINUID
&Process::majflt , // MAJFLT
&Process::minflt , // MINFLT
&Process::nice , // NICE
&Process::ns , // NS
&Process::numagid , // NUMAGID
&Process::nvctx , // NVCTX
nullptr , // PID
&Process::ppid , // PPID
&Process::rbyte , // RBYTE
&Process::rchar , // RCHAR
&Process::rss , // RSS
&Process::rtprio , // RTPRIO
&Process::slack , // SLACK
&Process::stack , // STACK
&Process::state , // STATE
&Process::stime , // STIME
&Process::syscall , // SYSCALL
&Process::syscr , // SYSCR
&Process::syscw , // SYSCW
&Process::threads , // THREADS
nullptr , // TID
&Process::uid , // UID
&Process::umask , // UMASK
&Process::user , // USER
&Process::vctx , // VCTX
&Process::vsize , // VSIZE
&Process::wbyte , // WBYTE
&Process::wchan , // WCHAN
&Process::wchar // WCHAR
};
string_view Process::column(Column c)
{
Process_Attr fn = process_attrs[static_cast<unsigned>(c)];
return (this->*fn)();
}
void Process::set_pid(size_t pid, size_t tid)
{
this->pid = pid;
this->tid = tid;
fn.resize(fn_stem);
array<char, 20> buf;
to_chars_result r = to_chars(buf.begin(), buf.end(), pid == tid ? pid : tid);
fn.append(buf.begin(), r.ptr);
fn.push_back('/');
environ = string_view(environ_arr.begin(), 0);
stat = string_view(stat_arr.begin() , 0);
status = string_view(status_arr.begin() , 0);
io = string_view(io_arr.begin() , 0);
}
template <size_t N>
void Process::read_proc(const char *q, array<char, N> &src,
string_view &dst, bool prefix)
{
if (!dst.empty())
return;
size_t l = fn.size();
fn.append(q);
size_t n = 0;
if (prefix) {
++n;
src[0] = '\n';
}
try {
ixxx::util::FD fd(fn, O_RDONLY);
n += ixxx::util::read_all(fd, src.begin() + n, src.size() - n);
} catch (...) {
src[0] = ' ';
n = 1;
}
dst = string_view(src.begin(), n);
fn.resize(l);
}
string_view Process::read_key_value(const string_view &status, const string_view &q)
{
auto p = search(status.begin(), status.end(),
std::default_searcher(q.begin(), q.end()));
if (p == status.end())
return string_view();
p += q.size();
auto e = fast_find(p, status.end(), '\n');
for ( ; p != e && (*p == ' ' || *p == '\t'); ++p)
;
return string_view(&*p, e-p);
}
string_view Process::read_status(const string_view &q)
{
read_proc("status", status_arr, status, true);
return read_key_value(status, q);
}
string_view Process::read_io(const string_view &q)
{
read_proc("io", io_arr, io, true);
return read_key_value(io, q);
}
// NB: The stat fields are space delimited. However, the 2nd field (comm)
// is enclosed by parentheses because comm itself may contain spaces
// and parantheses. Since none of the following fields might contain a ')'
// it's sufficient to handle the 2nd field in a special way by
// scanning for the terminating ')' by searching from the right.
string_view Process::read_stat(unsigned k)
{
read_proc("stat", stat_arr, stat);
auto p = stat.begin();
unsigned i = 0;
if (i < k) {
p = fast_find(p, stat.end(), '(');
if (p != stat.end())
++p;
++i;
if (i < k) {
p = fast_rfind(p, stat.end(), ')');
if (p != stat.end())
++p;
for (; i < k; ++i) {
p = fast_find(p, stat.end(), ' ');
if (p != stat.end())
++p;
}
} else {
auto e = fast_rfind(p, stat.end(), ')');
return string_view(p, e-p);
}
}
auto e = fast_find(p, stat.end(), ' ');
return string_view(p, e-p);
}
const char *Process::getenv(const string &s)
{
read_proc("environ", environ_arr, environ);
auto p = search(environ.begin(), environ.end(),
std::default_searcher(s.begin(), s.end()));
if (p == environ.end())
return epsilon;
auto m = p + s.size();
if (m == environ.end() || *m != '=')
return epsilon;
++m;
return &*m;
}
string_view Process::read_link(const char *q)
{
size_t l = fn.size();
fn.append(q);
size_t n = 0;
try {
n = ixxx::posix::readlink(fn, buffer);
} catch (const ixxx::readlink_error &e) {
// ignore
}
fn.resize(l);
return string_view(buffer.data(), n);
}
// cf. https://elixir.bootlin.com/linux/v5.8.9/source/include/linux/sched.h#L1506
enum Process_Flags {
PF_KTHREAD = 0x00200000
};
// cf. https://elixir.bootlin.com/linux/v5.8.9/source/include/linux/sched.h#L1483
static const string_view pf2str[] = {
"0x0" ,
"PF_IDLE" , // 0x00000002 /* I am an IDLE thread */
"PF_EXITING" , // 0x00000004 /* Getting shut down */
"0x8" ,
"PF_VCPU" , // 0x00000010 /* I'm a virtual CPU */
"PF_WQ_WORKER" , // 0x00000020 /* I'm a workqueue worker */
"PF_FORKNOEXEC" , // 0x00000040 /* Forked but didn't exec */
"PF_MCE_PROCESS" , // 0x00000080 /* Process policy on mce errors */
"PF_SUPERPRIV" , // 0x00000100 /* Used super-user privileges */
"PF_DUMPCORE" , // 0x00000200 /* Dumped core */
"PF_SIGNALED" , // 0x00000400 /* Killed by a signal */
"PF_MEMALLOC" , // 0x00000800 /* Allocating memory */
"PF_NPROC_EXCEEDED" , // 0x00001000 /* set_user() noticed that RLIMIT_NPROC was exceeded */
"PF_USED_MATH" , // 0x00002000 /* If unset the fpu must be initialized before use */
"PF_USED_ASYNC" , // 0x00004000 /* Used async_schedule*(), used by module init */
"PF_NOFREEZE" , // 0x00008000 /* This thread should not be frozen */
"PF_FROZEN" , // 0x00010000 /* Frozen for system suspend */
"PF_KSWAPD" , // 0x00020000 /* I am kswapd */
"PF_MEMALLOC_NOFS" , // 0x00040000 /* All allocation requests will inherit GFP_NOFS */
"PF_MEMALLOC_NOIO" , // 0x00080000 /* All allocation requests will inherit GFP_NOIO */
"PF_LOCAL_THROTTLE" , // 0x00100000 /* Throttle writes only against the bdi I write to, I am cleaning dirty pages from some other bdi. */
"PF_KTHREAD" , // 0x00200000 /* I am a kernel thread */
"PF_RANDOMIZE" , // 0x00400000 /* Randomize virtual address space */
"PF_SWAPWRITE" , // 0x00800000 /* Allowed to write to swap */
"0x1000000" ,
"PF_UMH" , // 0x02000000 /* I'm an Usermodehelper process */
"PF_NO_SETAFFINITY" , // 0x04000000 /* Userland is not allowed to meddle with cpus_mask */
"PF_MCE_EARLY" , // 0x08000000 /* Early kill for mce process policy */
"PF_MEMALLOC_NOCMA" , // 0x10000000 /* All allocation request will have _GFP_MOVABLE cleared */
"PF_IO_WORKER" , // 0x20000000 /* Task is an IO worker */
"PF_FREEZER_SKIP" , // 0x40000000 /* Freezer should not count it as freezable */
"PF_SUSPEND_TASK" // 0x80000000 /* This thread called freeze_processes() and should not be frozen */
};
unsigned Process::flags()
{
auto x = read_stat(8);
unsigned r = 0;
from_chars(x.begin(), x.end(), r);
return r;
}
string_view Process::pflags()
{
unsigned f = flags();
unsigned m = 1;
char *p = misc_arr.data();
for (unsigned i = 0; i < 32; ++i, m<<=1) {
if (m & f) {
if (p != misc_arr.data()) {
*p++ = '|';