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
|
//! x86-64 syscalls by number: their names from `std.os.linux.SYS`, and for
//! the common ones the shape of their arguments, enough to capture the
//! string one points at and to print a call the way strace does.
const std = @import("std");
const linux = std.os.linux;
const event = @import("event.zig");
const Event = event.Event;
pub fn name(nr: u64) ?[]const u8 {
return @tagName(std.enums.fromInt(linux.SYS, nr) orelse return null);
}
/// A letter an argument: i an int (a descriptor, a pid, a signal), d a
/// size, x a pointer or flags, s a NUL-terminated string, b a buffer as long
/// as the next argument says, v a vector of that many buffers (an iovec).
/// Six x for a syscall not listed.
pub fn signature(nr: u64) []const u8 {
return switch (std.enums.fromInt(linux.SYS, nr) orelse return "xxxxxx") {
.getpid, .gettid, .getppid, .getuid, .geteuid, .getgid, .getegid, .sched_yield, .pause, .fork, .vfork => "",
.close, .exit, .exit_group, .dup, .fsync => "i",
.brk, .set_tid_address, .uname, .pipe, .time => "x",
.chdir, .rmdir, .unlink => "s",
.read, .readv, .getdents64 => "ixd",
.writev => "ivd",
.pwritev, .pwritev2 => "ivdd",
.write => "ibd",
.pread64 => "ixdd",
.pwrite64 => "ibdd",
.open => "sxx",
.stat, .lstat, .access, .chmod, .mkdir => "sx",
.execve => "sxx",
.fstat => "ix",
.lseek => "idi",
.mmap => "xdxxid",
.mprotect => "xdx",
.munmap, .set_robust_list, .getcwd => "xd",
.mremap => "xddxx",
.madvise => "xdi",
.rt_sigaction, .rt_sigprocmask => "ixxd",
.ioctl, .fcntl => "ixx",
.dup2, .kill => "ii",
.tgkill => "iii",
.rename => "ss",
.readlink => "sxd",
.arch_prctl, .nanosleep, .sigaltstack => "xx",
.futex => "xiixxi",
.clock_gettime, .clock_getres => "ix",
.clock_nanosleep => "iixx",
.openat, .newfstatat, .faccessat2 => "isxx",
.unlinkat, .faccessat, .mkdirat => "isx",
.readlinkat => "isxd",
.statx => "isxxx",
.prlimit64 => "iixx",
.getrandom => "xdx",
.rseq => "xdxx",
.clone => "xxxxx",
.clone3 => "xd",
.wait4 => "ixxx",
.sched_getaffinity => "idx",
else => "xxxxxx",
};
}
/// What each argument of a syscall is called, in order, for the ones a
/// reader meets most: the names its manual page uses. Empty for a syscall
/// not listed; a viewer then has `signature` and the argument's number.
pub fn names(nr: u64) []const []const u8 {
return switch (std.enums.fromInt(linux.SYS, nr) orelse return &.{}) {
.read, .pread64 => &.{ "fd", "buf", "count", "offset" },
.write, .pwrite64 => &.{ "fd", "buf", "count", "offset" },
.readv, .writev, .pwritev, .pwritev2 => &.{ "fd", "iov", "iovcnt", "offset" },
.open => &.{ "path", "flags", "mode" },
.openat => &.{ "dirfd", "path", "flags", "mode" },
.close, .fsync, .dup => &.{"fd"},
.dup2 => &.{ "oldfd", "newfd" },
.stat, .lstat => &.{ "path", "statbuf" },
.fstat => &.{ "fd", "statbuf" },
.newfstatat => &.{ "dirfd", "path", "statbuf", "flags" },
.statx => &.{ "dirfd", "path", "flags", "mask", "statxbuf" },
.access => &.{ "path", "mode" },
.faccessat, .faccessat2 => &.{ "dirfd", "path", "mode", "flags" },
.lseek => &.{ "fd", "offset", "whence" },
.mmap => &.{ "addr", "length", "prot", "flags", "fd", "offset" },
.mprotect => &.{ "addr", "length", "prot" },
.munmap => &.{ "addr", "length" },
.mremap => &.{ "old_addr", "old_size", "new_size", "flags", "new_addr" },
.madvise => &.{ "addr", "length", "advice" },
.brk => &.{"addr"},
.ioctl => &.{ "fd", "request", "arg" },
.fcntl => &.{ "fd", "cmd", "arg" },
.execve => &.{ "path", "argv", "envp" },
.exit, .exit_group => &.{"status"},
.kill => &.{ "pid", "sig" },
.tgkill => &.{ "tgid", "tid", "sig" },
.wait4 => &.{ "pid", "wstatus", "options", "rusage" },
.rt_sigaction => &.{ "signum", "act", "oldact", "sigsetsize" },
.rt_sigprocmask => &.{ "how", "set", "oldset", "sigsetsize" },
.futex => &.{ "uaddr", "op", "val", "timeout", "uaddr2", "val3" },
.clock_gettime, .clock_getres => &.{ "clockid", "tp" },
.nanosleep => &.{ "req", "rem" },
.getrandom => &.{ "buf", "buflen", "flags" },
.getdents64 => &.{ "fd", "dirp", "count" },
.getcwd => &.{ "buf", "size" },
.chdir, .rmdir, .unlink => &.{"path"},
.unlinkat, .mkdirat => &.{ "dirfd", "path", "flags" },
.mkdir, .chmod => &.{ "path", "mode" },
.rename => &.{ "oldpath", "newpath" },
.readlink => &.{ "path", "buf", "bufsiz" },
.readlinkat => &.{ "dirfd", "path", "buf", "bufsiz" },
.arch_prctl => &.{ "op", "addr" },
.set_tid_address => &.{"tidptr"},
.set_robust_list => &.{ "head", "len" },
.prlimit64 => &.{ "pid", "resource", "new_limit", "old_limit" },
.rseq => &.{ "rseq", "rseq_len", "flags", "sig" },
.clone => &.{ "flags", "stack", "parent_tid", "child_tid", "tls" },
.clone3 => &.{ "cl_args", "size" },
.pipe => &.{"pipefd"},
.uname => &.{"buf"},
.sched_getaffinity => &.{ "pid", "cpusetsize", "mask" },
else => &.{},
};
}
/// A call the way strace prints it, from a `syscall_enter` event and its
/// payload: `openat(-100, "/etc/passwd", 0x80000, 0x0)`.
pub fn formatEnter(w: *std.Io.Writer, ev: *const Event, payload: []const u8) !void {
if (name(ev.aux)) |n| try w.writeAll(n) else try w.print("syscall_{d}", .{ev.aux});
try w.writeAll("(");
// The payload is the first string or buffer, decoded; the registers when there was none to read.
var decoded: ?[]const u8 = if (payload.len == @sizeOf(event.Regs)) null else payload;
for (signature(ev.aux), 0..) |kind, i| {
if (i > 0) try w.writeAll(", ");
switch (kind) {
'i' => try w.print("{d}", .{@as(i32, @bitCast(@as(u32, @truncate(ev.a[i]))))}),
'd' => try w.print("{d}", .{ev.a[i]}),
's', 'b', 'v' => if (decoded) |text| {
// Dots, as strace has them, when the buffer was longer than what was captured.
try w.print("\"{f}\"{s}", .{ std.zig.fmtString(text), if (kind == 'b' and text.len < ev.a[i + 1]) "..." else "" });
decoded = null;
} else try w.print("0x{x}", .{ev.a[i]}),
else => try w.print("0x{x}", .{ev.a[i]}),
}
}
try w.writeAll(")");
}
/// A `syscall_exit` event's result: " = 3", " = 0x7f0000001000", " = -2 ENOENT".
pub fn formatExit(w: *std.Io.Writer, ev: *const Event) !void {
const ret: i64 = @bitCast(ev.a[0]);
if (ret < 0 and ret > -4096) {
try w.print(" = {d}", .{ret});
if (std.enums.fromInt(linux.E, -ret)) |e| try w.print(" E{t}", .{e});
} else if (ret < 0 or ret > 0xffffff) try w.print(" = 0x{x}", .{ev.a[0]}) else try w.print(" = {d}", .{ret});
}
/// A sink that prints each syscall a line and passes every event on.
pub const Printer = struct {
w: *std.Io.Writer,
next: ?event.Sink = null,
/// A call is printed and its result is not.
open: bool = false,
pub fn sink(p: *Printer) event.Sink {
return .{ .ctx = p, .emitFn = emit };
}
fn emit(ctx: *anyopaque, ev: *const Event, payload: []const u8) anyerror!void {
const p: *Printer = @ptrCast(@alignCast(ctx));
switch (ev.kind) {
.syscall_enter => {
// Another thread's call, or one that never returned (exit).
if (p.open) try p.w.writeAll(" ...\n");
try formatEnter(p.w, ev, payload);
p.open = true;
},
.syscall_exit, .exit => if (p.open) {
if (ev.kind == .exit) try p.w.writeAll(" = ?") else try formatExit(p.w, ev);
try p.w.writeAll("\n");
try p.w.flush();
p.open = false;
},
else => {},
}
if (p.next) |next| try next.emit(ev.*, payload);
}
};
test "a call prints the way strace prints it" {
var buf: [256]u8 = undefined;
var w: std.Io.Writer = .fixed(&buf);
var p: Printer = .{ .w = &w };
const at_fdcwd: u64 = @as(u32, @bitCast(@as(i32, -100)));
try p.sink().emit(.{ .kind = .syscall_enter, .aux = @backingInt(linux.SYS.openat), .a = .{ at_fdcwd, 0x1000, 0x80000, 0, 0, 0 } }, "/etc/passwd");
try p.sink().emit(.{ .kind = .syscall_exit, .aux = @backingInt(linux.SYS.openat), .a = .{ @bitCast(@as(i64, -2)), 0, 0, 0, 0, 0 } }, "");
try p.sink().emit(.{ .kind = .syscall_enter, .aux = @backingInt(linux.SYS.write), .a = .{ 1, 0x2000, 3, 0, 0, 0 } }, "hi\n");
try p.sink().emit(.{ .kind = .syscall_exit, .aux = @backingInt(linux.SYS.write), .a = .{ 3, 0, 0, 0, 0, 0 } }, "");
try std.testing.expectEqualStrings(
\\openat(-100, "/etc/passwd", 0x80000, 0x0) = -2 ENOENT
\\write(1, "hi\n", 3) = 3
\\
, w.buffered());
try std.testing.expectEqualStrings("exit_group", name(231).?);
try std.testing.expect(name(100_000) == null);
}
test "an argument has the name its manual page gives it" {
try std.testing.expectEqualStrings("fd", names(@backingInt(linux.SYS.close))[0]);
try std.testing.expectEqualStrings("flags", names(@backingInt(linux.SYS.openat))[2]);
// Every name has an argument to be the name of.
inline for (.{ linux.SYS.read, linux.SYS.mmap, linux.SYS.openat, linux.SYS.futex, linux.SYS.close }) |nr| {
try std.testing.expect(names(@backingInt(nr)).len >= signature(@backingInt(nr)).len);
}
try std.testing.expectEqual(@as(usize, 0), names(100000).len);
}
|