1const std = @import("std");
2const tracer = @import("./mod.zig");
3const alloc = std.heap.c_allocator;
4const log = std.log.scoped(.tracer);
5const root = @import("root");
6const nfs = @import("nfs");
7const nio = @import("nio");
8const time = @import("time");
9const linux = @import("sys-linux");
10
11var pid: linux.pid_t = undefined;
12threadlocal var tid: linux.pid_t = undefined;
13threadlocal var path: [:0]const u8 = undefined;
14threadlocal var file: nfs.File = undefined;
15threadlocal var buffered_writer: nio.BufferedWriter(4096, nfs.File) = undefined;
16
17pub fn init(args: struct {}) !void {
18 _ = args;
19 pid = linux.getpid();
20}
21
22pub fn deinit() void {
23 //
24}
25
26pub fn init_thread(args: struct { nfs.Dir }) !void {
27 const dir = args[0];
28 tid = linux.gettid();
29
30 path = try nio.fmt.allocPrintZ(alloc, "trace.{d}.{d}.chrome.json", .{ pid, tid });
31 file = try dir.createFile(path, .{});
32 buffered_writer = .init(file);
33
34 try buffered_writer.writeAll("[\n");
35}
36
37pub fn deinit_thread() void {
38 defer alloc.free(path);
39 defer file.close();
40
41 buffered_writer.writeAll("]\n") catch {};
42 buffered_writer.flush() catch {};
43}
44
45pub fn trace_begin(src: std.builtin.SourceLocation, comptime ifmt: []const u8, iargs: anytype) void {
46 buffered_writer.print(
47 \\{{"cat":"function", "name":"{s}:{d}:{d} ({s})
48 ++ ifmt ++
49 \\", "ph": "B", "pid": {d}, "tid": {d}, "ts": {d}}},
50 \\
51 ,
52 .{
53 src.file,
54 src.line,
55 src.column,
56 src.fn_name,
57 } ++ iargs ++ .{
58 pid,
59 tid,
60 time.microTimestamp(),
61 },
62 ) catch {};
63}
64
65pub fn trace_end(ctx: tracer.Ctx) void {
66 _ = ctx;
67 buffered_writer.print(
68 \\{{"cat":"function", "ph": "E", "pid": {d}, "tid": {d}, "ts": {d}}},
69 \\
70 ,
71 .{
72 pid,
73 tid,
74 time.microTimestamp(),
75 },
76 ) catch {};
77}
78
79pub const Data = void;