Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
849 lines (774 loc) · 33.4 KB
/
Copy pathmain.cpp
File metadata and controls
849 lines (774 loc) · 33.4 KB
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
#include "filters.hpp"
#include "types.hpp"
#include "view.hpp"
#include "renderer.hpp"
#include "capture.hpp"
#include "mock_generator.hpp"
#include "syscall_table.hpp"
#include "text_util.hpp"
#include "decode.hpp"
/*
* main.cpp
* Purpose: the userspace program. Owns the terminal, the device or the
* simulator, the filter store, the view, and the poll loop. Keys are
* dispatched from a map of lambdas. Records arrive as 176-byte blobs and
* are turned into UiEvent rows.
*/
#include <fcntl.h>
#include <poll.h>
#include <termios.h>
#include <csignal>
#include <signal.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/utsname.h>
#include <sys/wait.h>
#include <spawn.h>
#include <cerrno>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <memory>
#include <ctime>
#include <cstdint>
#include <cstdlib>
#include <exception>
#include <array>
#include <algorithm>
#include <cstdio>
#include <charconv>
#include <expected>
#include <functional>
#include <map>
#include <span>
#include <stdexcept>
#include <utility>
#include <vector>
// Compile-time check that the ring size is a power of two. The kernel
// indexes the ring with a mask; a non-power-of-two size would wrap wrong.
consteval bool sm_is_pow2(unsigned n) { return n && (n & (n - 1)) == 0; }
static_assert(sm_is_pow2(SM_EVENT_RING_SIZE), "ring size must be a power of two");
static_assert(SM_EVENT_SIZE == 176, "wire record drifted from 176 bytes");
// ==========================================
// Core RAII Hardware & Environment Wrappers
// ==========================================
class Fd {
public:
explicit Fd(int fd) : fd_(fd) {}
~Fd() { if (fd_ >= 0) ::close(fd_); }
Fd(const Fd &) = delete;
Fd &operator=(const Fd &) = delete;
Fd(Fd &&o) noexcept : fd_(o.fd_) { o.fd_ = -1; }
Fd &operator=(Fd &&o) noexcept {
if (this != &o) {
if (fd_ >= 0) ::close(fd_);
fd_ = o.fd_;
o.fd_ = -1;
}
return *this;
}
int get() const { return fd_; }
private:
int fd_;
};
class Terminal {
public:
Terminal() {
ok_ = tcgetattr(STDIN_FILENO, &orig_) == 0;
enter();
}
~Terminal() { leave(); }
// Raw-ish mode (no echo, no line buffering) plus the alternate screen.
// ISIG stays on, so Ctrl-C / Ctrl-\ / Ctrl-Z arrive as signals that the
// main loop handles (see namespace sig).
void enter() {
if (ok_) {
termios t = orig_;
t.c_lflag &= static_cast<tcflag_t>(~(ICANON | ECHO));
t.c_cc[VMIN] = 0;
t.c_cc[VTIME] = 0;
tcsetattr(STDIN_FILENO, TCSANOW, &t);
}
std::fwrite(tui::ansi::enter_tui_mode.data(), 1, tui::ansi::enter_tui_mode.size(), stdout);
std::fflush(stdout);
}
// Restores the terminal exactly as it was found.
void leave() {
if (ok_) {
tcsetattr(STDIN_FILENO, TCSANOW, &orig_);
}
std::fwrite(tui::ansi::exit_tui_mode.data(), 1, tui::ansi::exit_tui_mode.size(), stdout);
std::fflush(stdout);
}
Terminal(const Terminal &) = delete;
Terminal &operator=(const Terminal &) = delete;
private:
termios orig_{};
bool ok_ = false;
};
// ==========================================
// Signals
// ==========================================
// Handlers only set flags; the main loop (whose poll() they interrupt)
// does the work, so the terminal is always restored by normal code paths.
namespace sig {
volatile std::sig_atomic_t g_quit = 0;
volatile std::sig_atomic_t g_stop = 0;
volatile std::sig_atomic_t g_winch = 0;
extern "C" void on_quit(int) { g_quit = 1; }
extern "C" void on_stop(int) { g_stop = 1; }
extern "C" void on_winch(int) { g_winch = 1; }
static void set(int signo, void (*fn)(int)) {
struct sigaction sa{};
sa.sa_handler = fn;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0; // no SA_RESTART: poll() must return EINTR
sigaction(signo, &sa, nullptr);
}
static void install() {
for (int s : {SIGINT, SIGTERM, SIGHUP, SIGQUIT})
set(s, on_quit);
set(SIGTSTP, on_stop);
set(SIGWINCH, on_winch);
}
}
// ==========================================
// Input parser
// ==========================================
// Reads one key. Plain bytes come back as themselves (0..255); arrows,
// Home/End and PgUp/PgDn come back as Key values (all above 0xff). A lone
// ESC is told apart from the start of a sequence by waiting briefly for
// the rest, so a slow link does not turn an arrow into ESC + '[' + 'A'.
static int read_key() {
unsigned char b = 0;
ssize_t n = ::read(STDIN_FILENO, &b, sizeof(b));
if (n <= 0) return 0;
if (b != 0x1b) return b;
std::array<unsigned char, 8> seq{};
size_t len = 0;
while (len < seq.size()) {
pollfd pf{STDIN_FILENO, POLLIN, 0};
if (::poll(&pf, 1, len == 0 ? 50 : 10) <= 0) break;
if (::read(STDIN_FILENO, &seq[len], 1) != 1) break;
unsigned char c = seq[len++];
// A CSI/SS3 sequence ends with a byte in 0x40..0x7e (after the
// introducer itself).
if (len >= 2 && c >= 0x40 && c <= 0x7e) break;
if (len == 1 && c != '[' && c != 'O') break;
}
if (len < 2 || (seq[0] != '[' && seq[0] != 'O'))
return 0x1b;
const std::string_view s(reinterpret_cast<const char *>(seq.data() + 1), len - 1);
if (s == "A") return std::to_underlying(Key::Up);
if (s == "B") return std::to_underlying(Key::Down);
if (s == "H" || s == "1~" || s == "7~") return std::to_underlying(Key::Home);
if (s == "F" || s == "4~" || s == "8~") return std::to_underlying(Key::End);
if (s == "5~") return std::to_underlying(Key::PgUp);
if (s == "6~") return std::to_underlying(Key::PgDn);
return 0; // some other sequence (F-keys, Left/Right, ...): ignore it
}
// The lsof run behind the L key. Its own syscalls (and those of the
// helper process lsof forks) would otherwise flood the view, so records
// from that process, or named "lsof" and inside the run's time window,
// are dropped.
struct LsofRun {
int32_t pid = 0;
uint64_t t0_ns = 0;
uint64_t t1_ns = 0;
};
struct EventLoopContext {
IFilterStore *filters = nullptr;
Capture *cap = nullptr;
IView *view = nullptr;
LsofRun *lsof = nullptr;
};
static bool from_lsof_helper(const LsofRun &run, int32_t pid, std::string_view comm, uint64_t ts) {
if (run.pid <= 0) return false;
if (pid == run.pid) return true;
return comm == "lsof" && ts >= run.t0_ns && ts <= run.t1_ns;
}
// True for a 32-bit TUI on a 64-bit kernel. The generated name table is
// for the ABI the TUI was compiled for, so it names compat records then,
// and native records otherwise.
static bool tui_is_compat_abi() {
static const bool v = [] {
if (sizeof(void *) != 4) return false;
utsname u{};
return ::uname(&u) == 0 && std::strstr(u.machine, "64") != nullptr;
}();
return v;
}
static std::string display_syscall_name(int32_t nr, bool compat) {
if (compat == tui_is_compat_abi())
return syscall_name(nr);
return (compat ? "compat_" : "native_") + std::to_string(nr);
}
static int on_raw_kernel_event(const sm_event &raw, void *user_data) {
auto *ctx = static_cast<EventLoopContext*>(user_data);
UiEvent e;
e.pid = raw.pid;
e.compat = (raw.nr & SM_NR_COMPAT) != 0;
e.nr = raw.nr & ~SM_NR_COMPAT;
e.ts_ns = raw.ts_ns;
// comm and the path argument are attacker-controlled; never let them
// reach the terminal (or the capture file) as raw control bytes.
e.comm = sanitize_terminal(std::string_view(raw.comm, strnlen(raw.comm, SM_COMM_LEN)));
e.sys_name = display_syscall_name(e.nr, e.compat);
e.extra = sanitize_terminal(std::string_view(raw.arg_str, strnlen(raw.arg_str, SM_ARG_STR_LEN)));
if (ctx->lsof && from_lsof_helper(*ctx->lsof, e.pid, e.comm, e.ts_ns))
return 0;
if (ctx->filters->hidden(e.comm, e.pid, e.nr, e.sys_name)) {
return 0;
}
if (ctx->cap->active()) {
ctx->cap->write(e);
}
ctx->view->append(std::move(e));
return 0;
}
static void clear_overlay_area(IView &view, tui::UiState &state) {
state.overlay = tui::OverlayMode::None;
state.frame_cache.clear();
std::fputs("\033[5;1H\033[J", stdout);
std::fflush(stdout);
view.set_rows(view.count());
}
// lsof is looked up on PATH (plus the usual sbin directories, which a
// sudo PATH may lack) without starting a shell.
static bool check_lsof_presence() {
std::string path = "/usr/sbin:/sbin";
if (const char *p = std::getenv("PATH")) path = std::string(p) + ":" + path;
size_t start = 0;
while (start <= path.size()) {
size_t end = path.find(':', start);
if (end == std::string::npos) end = path.size();
std::string dir = path.substr(start, end - start);
if (dir.empty()) dir = ".";
if (::access((dir + "/lsof").c_str(), X_OK) == 0) return true;
start = end + 1;
}
return false;
}
static uint64_t wall_ns() {
timespec ts{};
clock_gettime(CLOCK_REALTIME, &ts);
return static_cast<uint64_t>(ts.tv_sec) * 1'000'000'000ULL + static_cast<uint64_t>(ts.tv_nsec);
}
// Runs "lsof -n -P -p <pid>" directly (no shell) and returns its output
// lines. run records the child so its records can be hidden.
static std::vector<std::string> run_lsof(int32_t pid, LsofRun &run) {
std::vector<std::string> lines;
int p[2];
if (::pipe2(p, O_CLOEXEC) != 0) return lines;
posix_spawn_file_actions_t fa;
posix_spawn_file_actions_init(&fa);
posix_spawn_file_actions_adddup2(&fa, p[1], STDOUT_FILENO);
posix_spawn_file_actions_addopen(&fa, STDERR_FILENO, "/dev/null", O_WRONLY, 0);
posix_spawn_file_actions_addopen(&fa, STDIN_FILENO, "/dev/null", O_RDONLY, 0);
std::string pid_str = std::to_string(pid);
char a0[] = "lsof", a1[] = "-n", a2[] = "-P", a3[] = "-p";
char *argv[] = {a0, a1, a2, a3, pid_str.data(), nullptr};
extern char **environ;
pid_t child = -1;
run.t0_ns = wall_ns();
int err = posix_spawnp(&child, "lsof", &fa, nullptr, argv, environ);
posix_spawn_file_actions_destroy(&fa);
::close(p[1]);
if (err != 0) { ::close(p[0]); return lines; }
run.pid = static_cast<int32_t>(child);
std::string buf;
std::array<char, 4096> chunk{};
ssize_t n;
while ((n = ::read(p[0], chunk.data(), chunk.size())) != 0) {
if (n < 0) { if (errno == EINTR) continue; break; }
buf.append(chunk.data(), static_cast<size_t>(n));
}
::close(p[0]);
int st = 0;
while (::waitpid(child, &st, 0) < 0 && errno == EINTR) {}
run.t1_ns = wall_ns();
size_t start = 0;
while (start < buf.size()) {
size_t end = buf.find('\n', start);
if (end == std::string::npos) end = buf.size();
std::string line = buf.substr(start, end - start);
if (!line.empty() && line.back() == '\r') line.pop_back();
if (!line.empty()) lines.push_back(sanitize_terminal(line));
start = end + 1;
}
return lines;
}
static void populate_lsof_buffer(const IView &view, tui::UiState &state, LsofRun &run) {
const UiEvent *selected = nullptr;
for (int32_t i = 0; i < view.count(); ++i) {
if (view.top() + i == view.sel()) {
selected = view.row(i);
break;
}
}
if (!selected || selected->pid <= 0) return;
state.lsof_lines.clear();
state.lsof_sel = 0;
state.lsof_top = 0;
state.lsof_lines = run_lsof(selected->pid, run);
if (!state.lsof_lines.empty()) {
state.overlay = tui::OverlayMode::InspectLsof;
state.frame_cache.clear();
std::fputs("\033[5;1H\033[J", stdout);
std::fflush(stdout);
}
}
// =============================================================================
// Local Command Processing Dispatchers
// =============================================================================
static bool already(const IFilterStore &filters, RuleKind kind, int32_t nr, const std::string &text) {
for (const auto &r : filters.rules()) {
if (r.kind != kind) continue;
if (kind == RuleKind::SysId || kind == RuleKind::Pid) {
if (r.nr == nr) return true;
} else if (r.text == text) {
return true;
}
}
return false;
}
static void fill_pick_list(const IView &view, const IFilterStore &filters, tui::UiState &state) {
state.seen_pids.clear();
state.seen_procs.clear();
state.seen_sysids.clear();
state.seen_syscalls.clear();
for (int32_t i = 0; i < view.count(); ++i) {
const UiEvent *e = view.row(i);
if (!e) continue;
if (!already(filters, RuleKind::Pid, e->pid, {}) &&
std::find(state.seen_pids.begin(), state.seen_pids.end(), e->pid) == state.seen_pids.end())
state.seen_pids.push_back(e->pid);
if (!e->comm.empty() && !already(filters, RuleKind::Process, 0, e->comm) &&
std::find(state.seen_procs.begin(), state.seen_procs.end(), e->comm) == state.seen_procs.end())
state.seen_procs.push_back(e->comm);
}
for (int32_t id = 0; id < syscall_count(); ++id) {
if (!already(filters, RuleKind::SysId, id, {}))
state.seen_sysids.push_back(id);
}
for (const auto &name : state.syscall_names) {
if (!already(filters, RuleKind::Syscall, 0, name))
state.seen_syscalls.push_back(name);
}
}
static void handle_overlay_confirmation(IView &view, IFilterStore &filters, tui::UiState &state) {
switch (state.overlay) {
case tui::OverlayMode::SelectOrder:
view.set_desc(state.overlay_sel == 1);
break;
case tui::OverlayMode::SelectSort: {
std::array<Sort, 6> choices = {Sort::Time, Sort::Pid, Sort::Process, Sort::SysId, Sort::Syscall, Sort::Param};
if (state.overlay_sel >= 0 && state.overlay_sel < static_cast<int32_t>(choices.size())) {
view.set_sort(choices[static_cast<size_t>(state.overlay_sel)]);
}
break;
}
case tui::OverlayMode::EditRefreshMs:
state.refresh_ms = tui::clamp_refresh_ms(state.refresh_edit);
break;
case tui::OverlayMode::MainFilterHub:
if (state.overlay_sel == 0) state.overlay = tui::OverlayMode::FilterKind;
else if (state.overlay_sel == 1) state.overlay = tui::OverlayMode::RemoveFilter;
else state.overlay = tui::OverlayMode::ShowFilters;
state.overlay_sel = 0;
return;
case tui::OverlayMode::FilterKind:
fill_pick_list(view, filters, state);
if (state.overlay_sel == 0) state.overlay = tui::OverlayMode::PickPid;
else if (state.overlay_sel == 1) state.overlay = tui::OverlayMode::PickProcess;
else if (state.overlay_sel == 2) state.overlay = tui::OverlayMode::PickSysId;
else state.overlay = tui::OverlayMode::PickSyscall;
state.overlay_sel = 0;
state.overlay_top = 0;
return;
case tui::OverlayMode::PickProcess:
if (state.overlay_sel >= 0 && state.overlay_sel < static_cast<int32_t>(state.seen_procs.size()))
filters.add(FilterRule{RuleKind::Process, 0, state.seen_procs[static_cast<size_t>(state.overlay_sel)]});
break;
case tui::OverlayMode::PickSysId:
if (state.overlay_sel >= 0 && state.overlay_sel < static_cast<int32_t>(state.seen_sysids.size())) {
int32_t id = state.seen_sysids[static_cast<size_t>(state.overlay_sel)];
filters.add(FilterRule{RuleKind::SysId, id, std::to_string(id)});
}
break;
case tui::OverlayMode::PickSyscall:
if (state.overlay_sel >= 0 && state.overlay_sel < static_cast<int32_t>(state.seen_syscalls.size()))
filters.add(FilterRule{RuleKind::Syscall, 0, state.seen_syscalls[static_cast<size_t>(state.overlay_sel)]});
break;
case tui::OverlayMode::PickPid:
if (state.overlay_sel >= 0 && state.overlay_sel < static_cast<int32_t>(state.seen_pids.size())) {
int32_t pid = state.seen_pids[static_cast<size_t>(state.overlay_sel)];
filters.add(FilterRule{RuleKind::Pid, pid, std::to_string(pid)});
}
break;
case tui::OverlayMode::RemoveFilter:
filters.remove_at(state.overlay_sel);
break;
default:
break;
}
clear_overlay_area(view, state);
}
static void handle_active_overlay_input(int key, IView &view, IFilterStore &filters, tui::UiState &state) {
if (key == 0x1b) {
if (state.overlay == tui::OverlayMode::PickProcess ||
state.overlay == tui::OverlayMode::PickSysId ||
state.overlay == tui::OverlayMode::PickSyscall ||
state.overlay == tui::OverlayMode::PickPid) {
state.overlay = tui::OverlayMode::FilterKind;
state.overlay_sel = 0;
return;
}
if (state.overlay == tui::OverlayMode::FilterKind) {
state.overlay = tui::OverlayMode::MainFilterHub;
state.overlay_sel = 0;
return;
}
clear_overlay_area(view, state);
return;
}
// Full-Screen Lsof Scrollable List Pipeline Logic
if (state.overlay == tui::OverlayMode::InspectLsof) {
struct winsize w{};
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
const int32_t visible_rows = (w.ws_row > 5) ? (w.ws_row - 5) : 3;
const int32_t total_items = static_cast<int32_t>(state.lsof_lines.size());
switch (key) {
case static_cast<int>(Key::Up):
if (state.lsof_sel > 0) state.lsof_sel--;
break;
case static_cast<int>(Key::Down):
if (state.lsof_sel < total_items - 1) state.lsof_sel++;
break;
case static_cast<int>(Key::Home):
state.lsof_sel = 0;
break;
case static_cast<int>(Key::End):
state.lsof_sel = total_items > 0 ? total_items - 1 : 0;
break;
case static_cast<int>(Key::PgUp):
state.lsof_sel = (state.lsof_sel - visible_rows > 0) ? state.lsof_sel - visible_rows : 0;
break;
case static_cast<int>(Key::PgDn):
state.lsof_sel = (state.lsof_sel + visible_rows < total_items) ? state.lsof_sel + visible_rows : (total_items > 0 ? total_items - 1 : 0);
break;
default:
break;
}
// Maintain view scroll viewport clamping limits safely
if (state.lsof_sel < state.lsof_top) {
state.lsof_top = state.lsof_sel;
}
if (state.lsof_sel >= state.lsof_top + visible_rows) {
state.lsof_top = state.lsof_sel - visible_rows + 1;
}
return;
}
// Refresh Scale Rate Rate Up/Down 100ms Jump Arithmetic Hooks
if (state.overlay == tui::OverlayMode::EditRefreshMs) {
if (key == static_cast<int>(Key::Up)) {
if (state.refresh_edit <= 9900) {
state.refresh_edit += 100;
}
return;
}
if (key == static_cast<int>(Key::Down)) {
if (state.refresh_edit >= 200) {
state.refresh_edit -= 100;
}
return;
}
}
// Standard Right-Side Popups Interface Controls
int32_t total = 0;
if (state.overlay == tui::OverlayMode::PickProcess) total = static_cast<int32_t>(state.seen_procs.size());
else if (state.overlay == tui::OverlayMode::PickPid) total = static_cast<int32_t>(state.seen_pids.size());
else if (state.overlay == tui::OverlayMode::PickSysId) total = static_cast<int32_t>(state.seen_sysids.size());
else if (state.overlay == tui::OverlayMode::PickSyscall) total = static_cast<int32_t>(state.seen_syscalls.size());
else if (state.overlay == tui::OverlayMode::RemoveFilter || state.overlay == tui::OverlayMode::ShowFilters)
total = static_cast<int32_t>(filters.rules().size());
struct winsize w{};
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
int32_t page = (w.ws_row > 7) ? (w.ws_row - 7) : 4;
switch (key) {
case static_cast<int>(Key::Up):
if (state.overlay_sel > 0) state.overlay_sel--;
break;
case static_cast<int>(Key::Down):
if (total == 0 || state.overlay_sel < total - 1) state.overlay_sel++;
break;
case static_cast<int>(Key::Home):
state.overlay_sel = 0;
break;
case static_cast<int>(Key::End):
state.overlay_sel = total > 0 ? total - 1 : 0;
break;
case static_cast<int>(Key::PgUp):
state.overlay_sel = state.overlay_sel > page ? state.overlay_sel - page : 0;
break;
case static_cast<int>(Key::PgDn):
state.overlay_sel = (total > 0 && state.overlay_sel + page < total)
? state.overlay_sel + page : (total > 0 ? total - 1 : 0);
break;
case '\n':
case '\r':
handle_overlay_confirmation(view, filters, state);
break;
default:
// Maintain raw numeric text entry append arrays capabilities for the refresh utility box
if (state.overlay == tui::OverlayMode::EditRefreshMs) {
if (key >= '0' && key <= '9') {
if (state.refresh_edit >= 10000) state.refresh_edit = 0;
state.refresh_edit = (state.refresh_edit * 10) + (key - '0');
} else if (key == 127 || key == 8) { // 127 represents standard backspace character
state.refresh_edit /= 10;
}
}
break;
}
}
using DashFn = std::function<void(IView &, Capture &, tui::UiState &, LsofRun &)>;
static const std::map<int, DashFn> kDashMap = {
{'f', [](IView &, Capture &, tui::UiState &state, LsofRun &) { state.overlay = tui::OverlayMode::MainFilterHub; state.overlay_sel = 0; }},
{'F', [](IView &, Capture &, tui::UiState &state, LsofRun &) { state.overlay = tui::OverlayMode::MainFilterHub; state.overlay_sel = 0; }},
{'s', [](IView &, Capture &, tui::UiState &state, LsofRun &) { state.overlay = tui::OverlayMode::SelectSort; state.overlay_sel = 0; }},
{'S', [](IView &, Capture &, tui::UiState &state, LsofRun &) { state.overlay = tui::OverlayMode::SelectSort; state.overlay_sel = 0; }},
{'o', [](IView &, Capture &, tui::UiState &state, LsofRun &) { state.overlay = tui::OverlayMode::SelectOrder; state.overlay_sel = 0; }},
{'O', [](IView &, Capture &, tui::UiState &state, LsofRun &) { state.overlay = tui::OverlayMode::SelectOrder; state.overlay_sel = 0; }},
{'r', [](IView &, Capture &, tui::UiState &state, LsofRun &) { state.overlay = tui::OverlayMode::EditRefreshMs; state.refresh_edit = state.refresh_ms; state.overlay_sel = 0; }},
{'R', [](IView &, Capture &, tui::UiState &state, LsofRun &) { state.overlay = tui::OverlayMode::EditRefreshMs; state.refresh_edit = state.refresh_ms; state.overlay_sel = 0; }},
{'l', [](IView &view, Capture &, tui::UiState &state, LsofRun &run) { if (state.has_lsof) populate_lsof_buffer(view, state, run); }},
{'L', [](IView &view, Capture &, tui::UiState &state, LsofRun &run) { if (state.has_lsof) populate_lsof_buffer(view, state, run); }},
{' ', [](IView &view, Capture &, tui::UiState &, LsofRun &) { view.on_key(Key::Pause); }},
{'c', [](IView &, Capture &cap, tui::UiState &state, LsofRun &) { cap.toggle(); state.is_capturing = cap.active(); }},
{'C', [](IView &, Capture &cap, tui::UiState &state, LsofRun &) { cap.toggle(); state.is_capturing = cap.active(); }}
};
static void handle_standard_dashboard_input(int key, IView &view, Capture &cap, tui::UiState &state, LsofRun &run) {
auto it = kDashMap.find(key);
if (it != kDashMap.end()) { it->second(view, cap, state, run); return; }
// Only navigation keys go to the view; anything else is ignored.
switch (static_cast<Key>(key)) {
case Key::Up: case Key::Down: case Key::PgUp: case Key::PgDn:
case Key::Home: case Key::End:
view.on_key(static_cast<Key>(key));
break;
default:
break;
}
}
// Both sources hand the main loop a pollable fd that yields whole 176-byte
// records. Everything after read() runs on the main thread.
class EventSource {
public:
virtual ~EventSource() = default;
virtual int fd() const = 0;
void ingest(EventLoopContext &ctx) {
const int src = fd();
if (src < 0) return;
ssize_t n = ::read(src, buf_.data(), buf_.size());
if (n > 0) {
decode_events(std::span<const uint8_t>(buf_.data(), static_cast<size_t>(n)),
on_raw_kernel_event, &ctx);
if (ctx.cap) ctx.cap->flush();
}
}
private:
// Allocated once, sized for a full ring, reused for every read.
std::vector<uint8_t> buf_ = std::vector<uint8_t>(SM_EVENT_RING_SIZE * SM_EVENT_SIZE);
};
class DeviceSource final : public EventSource {
public:
explicit DeviceSource(Fd &dev) : dev_(dev) {}
int fd() const override { return dev_.get(); }
private:
Fd &dev_;
};
// The generator thread only writes records into a pipe; see mock_generator.hpp.
class SimulatorSource final : public EventSource {
public:
SimulatorSource() { mock_.start(); }
int fd() const override { return mock_.fd(); }
private:
MockEventGenerator mock_;
};
static void usage(std::FILE *out, const char *prog) {
std::fprintf(out,
"SysWatch " SYSWATCH_VERSION " - syscall monitor TUI\n"
"usage: %s [-p PID] [-f FILE] [-h]\n"
" -p PID show only syscalls from process PID\n"
" -f FILE filter rules file (default: ./filters.xml)\n"
" -h show this help\n"
"Reading /dev/syscall_monitor needs root, CAP_PERFMON or CAP_SYS_ADMIN;\n"
"without the device the TUI runs on simulated events.\n", prog);
}
// Runs before the terminal is switched to raw mode, so exiting here is safe.
static int32_t parse_args(int argc, char **argv, std::string &filters_path) {
int32_t fpid = 0;
const char *prog = argc > 0 ? argv[0] : "syswatch";
for (int i = 1; i < argc; i++) {
const std::string_view a = argv[i];
if (a == "-h" || a == "--help") {
usage(stdout, prog);
std::exit(0);
} else if (a == "-p" && i + 1 < argc) {
const std::string_view v = argv[++i];
auto [end, ec] = std::from_chars(v.data(), v.data() + v.size(), fpid);
if (ec != std::errc{} || end != v.data() + v.size() || fpid <= 0) {
std::fprintf(stderr, "%s: -p needs a positive process ID, got '%s'\n", prog, argv[i]);
std::exit(2);
}
} else if (a == "-f" && i + 1 < argc) {
filters_path = argv[++i];
} else {
std::fprintf(stderr, "%s: unknown or incomplete option '%s'\n", prog, argv[i]);
usage(stderr, prog);
std::exit(2);
}
}
return fpid;
}
// open_device returns the descriptor, or the errno. An empty unique_ptr
// used to mean both "failed" and "use the simulator". expected makes the
// failure explicit; the caller still falls back to the simulator.
static std::expected<std::unique_ptr<Fd>, int> open_device(int32_t fpid) {
auto dev = std::make_unique<Fd>(::open("/dev/syscall_monitor", O_RDONLY | O_NONBLOCK));
if (dev->get() < 0) {
int err = errno;
std::cout << tui::ansi::warn_yellow << "Cannot open /dev/syscall_monitor: "
<< std::strerror(err) << tui::ansi::style_reset << "\n";
if (err == EPERM || err == EACCES)
std::cout << "The device needs root, CAP_PERFMON or CAP_SYS_ADMIN "
"(sudo ./build/syswatch).\n";
std::cout << tui::ansi::info_green << "Simulator mode in 2 seconds..."
<< tui::ansi::style_reset << "\n";
::sleep(2);
return std::unexpected(err);
}
sm_s32 self = static_cast<sm_s32>(::getpid());
if (ioctl(dev->get(), SET_EXCLUDE_PID, &self) != 0)
std::cerr << "syswatch: SET_EXCLUDE_PID failed (" << std::strerror(errno)
<< "); the TUI's own syscalls will show up\n";
if (fpid) {
sm_s32 id = fpid;
// Showing every process when one was asked for would be wrong.
if (ioctl(dev->get(), SET_FILTER_PID, &id) != 0)
throw std::runtime_error("SET_FILTER_PID " + std::to_string(fpid) +
" failed: " + std::strerror(errno));
}
return dev;
}
static void load_syscall_names(tui::UiState &state) {
for (const SyscallName &s : syscall_table())
state.syscall_names.emplace_back(s.name);
}
static int64_t now_ms() {
timespec ts{};
clock_gettime(CLOCK_MONOTONIC, &ts);
return static_cast<int64_t>(ts.tv_sec) * 1000 + ts.tv_nsec / 1'000'000;
}
class App {
public:
int run(int argc, char **argv) {
state_.has_lsof = check_lsof_presence();
fpid_ = parse_args(argc, argv, filters_path_);
auto opened = open_device(fpid_);
if (opened) dev_ = std::move(*opened);
filters_ = std::make_unique<FilterStore>(filters_path_);
load_syscall_names(state_);
view_ = std::make_unique<View>(20);
term_ = std::make_unique<Terminal>();
ctx_ = EventLoopContext{filters_.get(), &cap_, view_.get(), &lsof_};
if (dev_) source_ = std::make_unique<DeviceSource>(*dev_);
else source_ = std::make_unique<SimulatorSource>();
sig::install();
tui::render_dashboard(*view_, *filters_, fpid_, state_);
view_->mark_drawn();
int64_t last_draw = now_ms();
while (true) {
pollfd pf[2]{};
nfds_t nfd = 1;
pf[0].fd = STDIN_FILENO;
pf[0].events = POLLIN;
int src = source_->fd();
if (src >= 0) { pf[1].fd = src; pf[1].events = POLLIN; nfd = 2; }
poll(pf, nfd, 10);
if (sig::g_quit) break;
if (sig::g_stop) {
// Ctrl-Z: hand the terminal back, stop for real, and take
// it again (with a full repaint) after SIGCONT.
sig::g_stop = 0;
term_->leave();
sig::set(SIGTSTP, SIG_DFL);
::raise(SIGTSTP);
sig::set(SIGTSTP, sig::on_stop);
term_->enter();
sig::g_winch = 1;
}
if (sig::g_winch) {
sig::g_winch = 0;
state_.frame_cache.clear();
std::fputs("\033[2J", stdout);
tui::render_dashboard(*view_, *filters_, fpid_, state_);
view_->mark_drawn();
last_draw = now_ms();
continue;
}
if (pf[0].revents & POLLIN) {
int key = read_key();
if (key == 'q' || key == 'Q') break;
if (state_.overlay != tui::OverlayMode::None)
handle_active_overlay_input(key, *view_, *filters_, state_);
else
handle_standard_dashboard_input(key, *view_, cap_, state_, lsof_);
tui::render_dashboard(*view_, *filters_, fpid_, state_);
view_->mark_drawn();
last_draw = now_ms();
continue;
}
if (src >= 0 && (pf[1].revents & POLLIN))
source_->ingest(ctx_);
int64_t now = now_ms();
if (view_->dirty() && now - last_draw >= state_.refresh_ms) {
tui::render_dashboard(*view_, *filters_, fpid_, state_);
view_->mark_drawn();
last_draw = now;
}
}
// Stop the simulator thread (if any) while everything it could
// reference is still alive.
source_.reset();
return 0;
}
private:
tui::UiState state_;
int32_t fpid_ = 0;
std::string filters_path_ = "filters.xml";
std::unique_ptr<Fd> dev_;
std::unique_ptr<FilterStore> filters_;
std::unique_ptr<View> view_;
std::unique_ptr<Terminal> term_;
Capture cap_;
LsofRun lsof_;
EventLoopContext ctx_{};
// Declared last so it is destroyed first.
std::unique_ptr<EventSource> source_;
};
int main(int argc, char **argv) {
try {
// App (and with it the Terminal) is destroyed before the handler
// runs, so the terminal is restored before the error is printed.
App app;
return app.run(argc, argv);
} catch (const std::exception &e) {
std::fprintf(stderr, "syswatch: %s\n", e.what());
} catch (...) {
std::fprintf(stderr, "syswatch: unexpected error\n");
}
return 1;
}