journal.zig (2408B)
1 const std = @import("std"); 2 const pi = @import("pi"); 3 4 const uart = pi.devices.mini_uart; 5 const interrupts = pi.interrupts; 6 7 const JOURNAL_START: u8 = 0x1; 8 const JOURNAL_START_SENTINEL: u8 = 0x2; 9 const JOURNAL_END_SENTINEL: u8 = 0x2; 10 const JOURNAL_APPEND_LAST_START: u8 = 0x3; 11 const JOURNAL_APPEND_LAST_END: u8 = 0x3; 12 const JOURNAL_APPEND_LAST_REGISTERS: u8 = 0x4; 13 14 pub const LogLevel = enum(u8) { 15 Critical = 0, 16 Error = 1, 17 Warning = 2, 18 Info = 3, 19 Debug = 4, 20 Trace = 5, 21 }; 22 23 pub fn write_slice(level: LogLevel, slice: []const u8) void { 24 uart.write_byte(JOURNAL_START); 25 uart.write_byte(@intFromEnum(level)); 26 27 var slice_len: [4]u8 = undefined; 28 std.mem.writeInt(u32, &slice_len, slice.len, .little); 29 30 uart.write_slice(&slice_len); 31 uart.write_slice(slice); 32 uart.flush(); 33 } 34 35 pub fn start_entry(level: LogLevel) void { 36 uart.write_byte(JOURNAL_START_SENTINEL); 37 uart.write_byte(@intFromEnum(level)); 38 } 39 40 pub fn end_entry() void { 41 uart.write_byte(JOURNAL_END_SENTINEL); 42 uart.flush(); 43 } 44 45 pub fn print(level: LogLevel, comptime fmt: []const u8, args: anytype) void { 46 start_entry(level); 47 uart.print(fmt, args); 48 end_entry(); 49 uart.flush(); 50 } 51 52 pub fn append(comptime fmt: []const u8, args: anytype) void { 53 uart.write_byte(JOURNAL_APPEND_LAST_START); 54 uart.print(fmt, args); 55 uart.write_byte(JOURNAL_APPEND_LAST_END); 56 uart.flush(); 57 } 58 59 fn write_u32(v: u32) void { 60 var slice_len: [4]u8 = undefined; 61 std.mem.writeInt(u32, &slice_len, v, .little); 62 uart.write_slice(&slice_len); 63 } 64 65 pub fn append_registers(regs: *const interrupts.Registers) void { 66 uart.write_byte(JOURNAL_APPEND_LAST_REGISTERS); 67 for (regs.gp) |r| { 68 write_u32(r); 69 } 70 write_u32(regs.sp); 71 write_u32(regs.lr); 72 write_u32(regs.pc); 73 write_u32(@bitCast(regs.psr)); 74 } 75 76 pub fn critical(comptime fmt: []const u8, args: anytype) void { 77 print(.Critical, fmt, args); 78 } 79 pub fn err(comptime fmt: []const u8, args: anytype) void { 80 print(.Error, fmt, args); 81 } 82 pub fn warn(comptime fmt: []const u8, args: anytype) void { 83 print(.Warning, fmt, args); 84 } 85 pub fn info(comptime fmt: []const u8, args: anytype) void { 86 print(.Info, fmt, args); 87 } 88 pub fn trace(comptime fmt: []const u8, args: anytype) void { 89 print(.Trace, fmt, args); 90 } 91 pub fn debug(comptime fmt: []const u8, args: anytype) void { 92 print(.Debug, fmt, args); 93 }