I’m trying to use the Writer interface to store the trace logs of the CPU execution of my emulator to a file, but it’s not working. For some reason, I’m seeing the output in the stdout and then at some point I get this error:
thread 33427 panic: Flush failed: error.WriteFailed
/home/labatata/Downloads/zig-x86_64-linux-0.15.2/lib/std/posix.zig:1551:22: 0x126ba76 in pwritev (ness)
.BADF => return error.NotOpenForWriting, // Can be a race condition.
^
/home/labatata/Downloads/zig-x86_64-linux-0.15.2/lib/std/fs/File.zig:1762:25: 0x126410a in drain (ness)
return error.WriteFailed;
^
/home/labatata/Downloads/zig-x86_64-linux-0.15.2/lib/std/Io/Writer.zig:316:28: 0x11ccdba in defaultFlush (ness)
while (w.end != 0) _ = try drainFn(w, &.{""}, 1);
^
/home/labatata/Downloads/zig-x86_64-linux-0.15.2/lib/std/Io/Writer.zig:310:5: 0x11e71ba in flush (ness)
return w.vtable.flush(w);
^
/home/labatata/Code/Zig/8bit-emulator/src/system.zig:182:51: 0x125d97a in dump_trace (ness)
writer.flush() catch |err| std.debug.panic("Flush failed: {any}\n", .{err});
^
/home/labatata/Code/Zig/8bit-emulator/src/system.zig:173:32: 0x1256003 in is_frame_complete (ness)
self.dump_trace();
^
/home/labatata/Code/Zig/8bit-emulator/src/system.zig:139:39: 0x124b67c in run_frame (ness)
while (!self.is_frame_complete()) {
^
/home/labatata/Code/Zig/8bit-emulator/src/main.zig:105:25: 0x124a695 in main (ness)
system.run_frame();
^
/home/labatata/Downloads/zig-x86_64-linux-0.15.2/lib/std/start.zig:627:37: 0x124bd95 in main (ness)
const result = root.main() catch |err| {
Here’s how I’m setting up the code
var trace_file: ?std.fs.File = null;
var trace_file_writer: ?std.Io.Writer = null;
var trace_file_buffer: [4096]u8 = undefined;
if (settings.trace_cpu) {
trace_file = try std.fs.cwd().createFile("cpu.trace", .{});
const w = trace_file.?.writer(&trace_file_buffer);
trace_file_writer = w.interface;
}
Then I keep tracing while the frame isn’t complete
pub fn run_frame(self: *Self) void {
while (!self.is_frame_complete()) {
if (self.settings.trace_cpu) {
trace(&self.trace_file_writer.?, self.cpu) catch @panic("Failed to trace CPU");
}
self.tick();
}
}
When it’s complete, I dump to the file
pub fn is_frame_complete(self: *Self) bool {
if (self.ppu.frame_complete) {
self.ppu.frame_complete = false;
if (self.settings.trace_cpu) {
self.dump_trace();
}
return true;
}
return false;
}
fn dump_trace(self: *const Self) void {
var writer = self.trace_file_writer.?;
writer.flush() catch |err| std.debug.panic("Flush failed: {any}\n", .{err});
}
Here’s the file that implements the trace function.
What I’m doing wrong here?