Compare commits

..

6 Commits

Author SHA1 Message Date
08bf0f9201 fix: make dependency path strings relative 2022-12-15 03:42:56 -04:00
6467fc25e7 feat: update build.zig
zba-gdbstub now supports being used as a library
2022-12-15 03:33:43 -04:00
732c00efb2 feat: implement Emulator Interface 2022-12-15 02:18:11 -04:00
166baeec1a feat: get to user input in gdb 2022-12-15 01:21:57 -04:00
835878ca40 chore: move structs to separate files 2022-12-14 23:53:16 -04:00
278a5adf25 chore: reorganize code 2022-12-14 22:54:08 -04:00
5 changed files with 97 additions and 156 deletions

View File

@@ -27,7 +27,6 @@ pub fn link(exe: *std.build.LibExeObjStep) void {
pub fn build(b: *std.build.Builder) void { pub fn build(b: *std.build.Builder) void {
const target = b.standardTargetOptions(.{}); const target = b.standardTargetOptions(.{});
_ = target;
const mode = b.standardReleaseOptions(); const mode = b.standardReleaseOptions();
// -- library -- // -- library --
@@ -43,18 +42,18 @@ pub fn build(b: *std.build.Builder) void {
const test_step = b.step("lib-test", "Run Library Tests"); const test_step = b.step("lib-test", "Run Library Tests");
test_step.dependOn(&lib_tests.step); test_step.dependOn(&lib_tests.step);
// // -- Executable -- // -- Executable --
// const exe = b.addExecutable("gdbserver", "src/main.zig"); const exe = b.addExecutable("gdbserver", "src/main.zig");
// link(exe); link(exe);
// exe.setTarget(target); exe.setTarget(target);
// exe.setBuildMode(mode); exe.setBuildMode(mode);
// exe.install(); exe.install();
// const run_cmd = exe.run(); const run_cmd = exe.run();
// run_cmd.step.dependOn(b.getInstallStep()); run_cmd.step.dependOn(b.getInstallStep());
// if (b.args) |args| run_cmd.addArgs(args); if (b.args) |args| run_cmd.addArgs(args);
// const run_step = b.step("run", "Run the app"); const run_step = b.step("run", "Run the app");
// run_step.dependOn(&run_cmd.step); run_step.dependOn(&run_cmd.step);
} }

View File

@@ -1,10 +1,7 @@
const std = @import("std"); const std = @import("std");
const Allocator = std.mem.Allocator;
const Emulator = @import("lib.zig").Emulator;
const target = @import("Server.zig").target; const target = @import("Server.zig").target;
const memory_map = @import("Server.zig").memory_map; const Allocator = std.mem.Allocator;
const Self = @This(); const Self = @This();
const log = std.log.scoped(.Packet); const log = std.log.scoped(.Packet);
@@ -19,6 +16,8 @@ pub fn from(allocator: Allocator, str: []const u8) !Self {
const chksum_str = tokens.next() orelse return error.MissingCheckSum; const chksum_str = tokens.next() orelse return error.MissingCheckSum;
const chksum = std.fmt.parseInt(u8, chksum_str, 16) catch return error.InvalidChecksum; const chksum = std.fmt.parseInt(u8, chksum_str, 16) catch return error.InvalidChecksum;
// log.info("Contents: {s}", .{contents});
if (!Self.verify(contents, chksum)) return error.ChecksumMismatch; if (!Self.verify(contents, chksum)) return error.ChecksumMismatch;
return .{ .contents = try allocator.dupe(u8, contents) }; return .{ .contents = try allocator.dupe(u8, contents) };
@@ -45,29 +44,34 @@ const String = union(enum) {
} }
}; };
pub fn parse(self: *Self, allocator: Allocator, emu: Emulator) !String { pub fn parse(self: *Self, allocator: Allocator) !String {
switch (self.contents[0]) { switch (self.contents[0]) {
// Required // Required
'?' => { '?' => {
const ret = try std.fmt.allocPrint(allocator, "S{x:0>2}", .{@enumToInt(Signal.Int)}); const ret: Signal = .Trap;
return .{ .alloc = ret };
// Deallocated by the caller
return .{ .alloc = try std.fmt.allocPrint(allocator, "T{x:0>2}thread:1;", .{@enumToInt(ret)}) };
}, },
'g' => { 'g' => {
const r = emu.registers(); // TODO: Actually reference GBA Registers
const cpsr = emu.cpsr(); const r = [_]u32{0xDEAD_BEEF} ** 0x10;
const cpsr: u32 = 0xCAFE_B0BA;
const char_len = 2;
const reg_len = @sizeOf(u32) * char_len; // Every byte is represented by 2 characters
const reg_len = @sizeOf(u32) * 2; // Every byte is represented by 2 characters
const ret = try allocator.alloc(u8, r.len * reg_len + reg_len); // r0 -> r15 + CPSR const ret = try allocator.alloc(u8, r.len * reg_len + reg_len); // r0 -> r15 + CPSR
{ {
var i: u32 = 0; var i: usize = 0;
while (i < r.len + 1) : (i += 1) { while (i < r.len + 1) : (i += 1) {
var reg: u32 = if (i < r.len) r[i] else cpsr; const reg: u32 = if (i < r.len) r[i] else cpsr;
if (i == 15) reg -= if (cpsr >> 5 & 1 == 1) 4 else 8; // PC is ahead
// writes the formatted integer to the buffer, returns a slice to the buffer but we ignore that // bufPrintIntToSlice writes to the provided slice, which is all we want from this
// GDB also expects the bytes to be in the opposite order for whatever reason // consequentially, we ignore the slice it returns since it just references the slice
_ = std.fmt.bufPrintIntToSlice(ret[i * 8 ..][0..8], @byteSwap(reg), 16, .lower, .{ .fill = '0', .width = 8 }); // passed as an argument
_ = std.fmt.bufPrintIntToSlice(ret[i * 8 ..][0..8], reg, 16, .lower, .{ .fill = '0', .width = 8 });
} }
} }
@@ -75,23 +79,25 @@ pub fn parse(self: *Self, allocator: Allocator, emu: Emulator) !String {
}, },
'G' => @panic("TODO: Register Write"), 'G' => @panic("TODO: Register Write"),
'm' => { 'm' => {
// TODO: Actually reference GBA Memory
log.err("{s}", .{self.contents});
var tokens = std.mem.tokenize(u8, self.contents[1..], ","); var tokens = std.mem.tokenize(u8, self.contents[1..], ",");
const addr_str = tokens.next() orelse return .{ .static = "E9999" }; // EUNKNOWN const addr_str = tokens.next() orelse return .{ .static = "E9999" }; // EUNKNOWN
const length_str = tokens.next() orelse return .{ .static = "E9999" }; // EUNKNOWN const length_str = tokens.next() orelse return .{ .static = "E9999" }; // EUNKNOWN
const addr = try std.fmt.parseInt(u32, addr_str, 16); const addr = try std.fmt.parseInt(u32, addr_str, 16);
const len = try std.fmt.parseInt(u32, length_str, 16); const len = try std.fmt.parseInt(u32, length_str, 16);
_ = addr;
const ret = try allocator.alloc(u8, len * 2); const ret = try allocator.alloc(u8, len * 2);
{ {
var i: u32 = 0; var i: usize = 0;
while (i < len) : (i += 1) { while (i < len) : (i += 1) {
const value = emu.read(addr + i); const value: u8 = 0;
log.debug("read 0x{X:0>2} from 0x{X:0>8}", .{ value, addr + i });
// writes the formatted integer to the buffer, returns a slice to the buffer but we ignore that _ = std.fmt.bufPrintIntToSlice(ret[i * 2 ..][0..2], value, 16, .lower, .{ .fill = '0', .width = 2 });
_ = std.fmt.bufPrintIntToSlice(ret[i * 2 ..][0..2], emu.read(addr + i), 16, .lower, .{ .fill = '0', .width = 2 });
} }
} }
@@ -99,22 +105,20 @@ pub fn parse(self: *Self, allocator: Allocator, emu: Emulator) !String {
}, },
'M' => @panic("TODO: Memory Write"), 'M' => @panic("TODO: Memory Write"),
'c' => @panic("TODO: Continue"), 'c' => @panic("TODO: Continue"),
's' => { 's' => @panic("TODO: Step"),
// var tokens = std.mem.tokenize(u8, self.contents[1..], " ");
// const addr = if (tokens.next()) |s| try std.fmt.parseInt(u32, s, 16) else null;
emu.step();
const ret = try std.fmt.allocPrint(allocator, "S{x:0>2}", .{@enumToInt(Signal.Trap)});
return .{ .alloc = ret };
},
// Optional // Optional
'D' => { 'H' => {
log.info("Disconnecting...", .{}); log.warn("{s}", .{self.contents});
return .{ .static = "OK" };
switch (self.contents[1]) {
'g', 'c' => return .{ .static = "OK" },
else => {
log.warn("Unimplemented: {s}", .{self.contents});
return .{ .static = "" };
},
}
}, },
'H' => return .{ .static = "" },
'v' => { 'v' => {
if (substr(self.contents[1..], "MustReplyEmpty")) { if (substr(self.contents[1..], "MustReplyEmpty")) {
return .{ .static = "" }; return .{ .static = "" };
@@ -139,14 +143,16 @@ pub fn parse(self: *Self, allocator: Allocator, emu: Emulator) !String {
if (substr(self.contents[1..], "Xfer:features:read")) { if (substr(self.contents[1..], "Xfer:features:read")) {
var tokens = std.mem.tokenize(u8, self.contents[1..], ":,"); var tokens = std.mem.tokenize(u8, self.contents[1..], ":,");
_ = tokens.next(); // Xfer _ = tokens.next(); // qXfer
_ = tokens.next(); // features _ = tokens.next(); // features
_ = tokens.next(); // read _ = tokens.next(); // read
const annex = tokens.next() orelse return .{ .static = "E9999" }; const annex = tokens.next() orelse return .{ .static = "E00" };
const offset_str = tokens.next() orelse return .{ .static = "E99999" }; const offset_str = tokens.next() orelse return .{ .static = "E00" };
const length_str = tokens.next() orelse return .{ .static = "E9999" }; const length_str = tokens.next() orelse return .{ .static = "E00" };
if (std.mem.eql(u8, annex, "target.xml")) { if (std.mem.eql(u8, annex, "target.xml")) {
log.info("Providing ARMv4T target description", .{});
const offset = try std.fmt.parseInt(usize, offset_str, 16); const offset = try std.fmt.parseInt(usize, offset_str, 16);
const length = try std.fmt.parseInt(usize, length_str, 16); const length = try std.fmt.parseInt(usize, length_str, 16);
@@ -162,33 +168,12 @@ pub fn parse(self: *Self, allocator: Allocator, emu: Emulator) !String {
return .{ .alloc = ret }; return .{ .alloc = ret };
} else { } else {
log.err("Unexpected Annex: {s}", .{annex}); log.err("Unexpected Annex: {s}", .{annex});
return .{ .static = "E9999" }; return .{ .static = "E00" };
} }
return .{ .static = "" }; return .{ .static = "" };
} }
if (substr(self.contents[1..], "Xfer:memory-map:read")) {
var tokens = std.mem.tokenize(u8, self.contents[1..], ":,");
_ = tokens.next(); // Xfer
_ = tokens.next(); // memory-map
_ = tokens.next(); // read
const offset_str = tokens.next() orelse return .{ .static = "E9999" };
const length_str = tokens.next() orelse return .{ .static = "E9999" };
const offset = try std.fmt.parseInt(usize, offset_str, 16);
const length = try std.fmt.parseInt(usize, length_str, 16);
// see above
const len = @min(length, (memory_map.len + 1) - offset);
const ret = try allocator.alloc(u8, len);
ret[0] = if (ret.len < length) 'l' else 'm';
std.mem.copy(u8, ret[1..], memory_map[offset..]);
return .{ .alloc = ret };
}
log.warn("Unimplemented: {s}", .{self.contents}); log.warn("Unimplemented: {s}", .{self.contents});
return .{ .static = "" }; return .{ .static = "" };
}, },
@@ -221,7 +206,7 @@ fn verify(input: []const u8, chksum: u8) bool {
} }
const Signal = enum(u32) { const Signal = enum(u32) {
Hup = 1, // Hangup Hup, // Hangup
Int, // Interrupt Int, // Interrupt
Quit, // Quit Quit, // Quit
Ill, // Illegal Instruction Ill, // Illegal Instruction

View File

@@ -4,7 +4,6 @@ const Packet = @import("Packet.zig");
const Socket = network.Socket; const Socket = network.Socket;
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const Emulator = @import("lib.zig").Emulator;
const Self = @This(); const Self = @This();
const log = std.log.scoped(.Server); const log = std.log.scoped(.Server);
@@ -36,32 +35,13 @@ pub const target: []const u8 =
\\</target> \\</target>
; ;
// Game Pak SRAM isn't included
// TODO: Can i be more specific here?
pub const memory_map: []const u8 =
\\ <memory-map version="1.0">
\\ <memory type="rom" start="0x00000000" length="0x00004000"/>
\\ <memory type="ram" start="0x02000000" length="0x00040000"/>
\\ <memory type="ram" start="0x03000000" length="0x00008000"/>
\\ <memory type="ram" start="0x04000000" length="0x00000400"/>
\\ <memory type="ram" start="0x05000000" length="0x00000400"/>
\\ <memory type="ram" start="0x06000000" length="0x00018000"/>
\\ <memory type="ram" start="0x07000000" length="0x00000400"/>
\\ <memory type="rom" start="0x08000000" length="0x02000000"/>
\\ <memory type="rom" start="0x0A000000" length="0x02000000"/>
\\ <memory type="rom" start="0x0C000000" length="0x02000000"/>
\\ </memory-map>
;
// FIXME: Shouldn't this be a Packet Struct? // FIXME: Shouldn't this be a Packet Struct?
pkt_cache: ?[]const u8 = null, pkt_cache: ?[]const u8 = null,
client: Socket, client: Socket,
_socket: Socket, _socket: Socket,
emu: Emulator, pub fn init() !Self {
pub fn init(emulator: Emulator) !Self {
try network.init(); try network.init();
var socket = try Socket.create(.ipv4, .tcp); var socket = try Socket.create(.ipv4, .tcp);
@@ -73,7 +53,7 @@ pub fn init(emulator: Emulator) !Self {
const endpoint = try client.getLocalEndPoint(); const endpoint = try client.getLocalEndPoint();
log.info("client connected from {}", .{endpoint}); log.info("client connected from {}", .{endpoint});
return .{ .emu = emulator, ._socket = socket, .client = client }; return .{ ._socket = socket, .client = client };
} }
pub fn deinit(self: *Self, allocator: Allocator) void { pub fn deinit(self: *Self, allocator: Allocator) void {
@@ -101,50 +81,39 @@ pub fn run(self: *Self, allocator: Allocator) !void {
const len = try self.client.receive(&buf); const len = try self.client.receive(&buf);
if (len == 0) break; if (len == 0) break;
const action = try self.parse(allocator, buf[0..len]); const action = try Self.parse(allocator, buf[0..len]);
try self.send(allocator, action); try self.send(allocator, action);
} }
} }
fn parse(self: *Self, allocator: Allocator, input: []const u8) !Action { fn parse(allocator: Allocator, input: []const u8) !Action {
// log.debug("-> {s}", .{input});
return switch (input[0]) { return switch (input[0]) {
'+' => blk: { '+' => .nothing,
if (input.len == 1) break :blk .nothing;
break :blk switch (input[1]) {
'$' => self.handlePacket(allocator, input[1..]),
else => std.debug.panic("Unknown: {s}", .{input}),
};
},
'-' => .retry, '-' => .retry,
'$' => try self.handlePacket(allocator, input), '$' => blk: {
'\x03' => .nothing, // Packet
else => std.debug.panic("Unknown: {s}", .{input}),
};
}
fn handlePacket(self: *Self, allocator: Allocator, input: []const u8) !Action {
var packet = Packet.from(allocator, input) catch return .nack; var packet = Packet.from(allocator, input) catch return .nack;
defer packet.deinit(allocator); defer packet.deinit(allocator);
var string = packet.parse(allocator, self.emu) catch return .nack; var string = packet.parse(allocator) catch return .nack;
defer string.deinit(allocator); defer string.deinit(allocator);
const reply = string.inner(); const reply = string.inner();
// deallocated by the caller // deallocated by the caller
const response = try std.fmt.allocPrint(allocator, "+${s}#{x:0>2}", .{ reply, Packet.checksum(reply) }); const response = try std.fmt.allocPrint(allocator, "${s}#{x:0>2}", .{ reply, Packet.checksum(reply) });
return .{ .send = response }; break :blk .{ .send = response };
},
else => std.debug.panic("Unknown: {s}", .{input}),
};
} }
fn send(self: *Self, allocator: Allocator, action: Action) !void { fn send(self: *Self, allocator: Allocator, action: Action) !void {
switch (action) { switch (action) {
.send => |pkt| { .send => |pkt| {
_ = try self.client.send("+"); // ACK
_ = try self.client.send(pkt); _ = try self.client.send(pkt);
// log.debug("<- {s}", .{pkt});
self.reset(allocator); self.reset(allocator);
self.pkt_cache = pkt; self.pkt_cache = pkt;
@@ -152,21 +121,14 @@ fn send(self: *Self, allocator: Allocator, action: Action) !void {
.retry => { .retry => {
log.warn("received nack, resending: \"{?s}\"", .{self.pkt_cache}); log.warn("received nack, resending: \"{?s}\"", .{self.pkt_cache});
if (self.pkt_cache) |pkt| { if (self.pkt_cache) |pkt| _ = try self.client.send(pkt); // FIXME: is an ack to a nack necessary?
_ = try self.client.send(pkt);
// log.debug("<- {s}", .{pkt});
}
}, },
.ack => { .ack => {
_ = try self.client.send("+"); _ = try self.client.send("+");
// log.debug("<- +", .{});
self.reset(allocator); self.reset(allocator);
}, },
.nack => { .nack => {
_ = try self.client.send("-"); _ = try self.client.send("-");
// log.debug("<- -", .{});
self.reset(allocator); self.reset(allocator);
}, },
.nothing => self.reset(allocator), .nothing => self.reset(allocator),

View File

@@ -10,10 +10,9 @@ pub const Emulator = struct {
readFn: *const fn (*anyopaque, u32) u8, readFn: *const fn (*anyopaque, u32) u8,
writeFn: *const fn (*anyopaque, u32, u8) void, writeFn: *const fn (*anyopaque, u32, u8) void,
registersFn: *const fn (*anyopaque) *[16]u32, // FIXME: Expensive copy
cpsrFn: *const fn (*anyopaque) u32, registersFn: *const fn (*const anyopaque) [16]u32,
cpsrFn: *const fn (*const anyopaque) u32,
stepFn: *const fn (*anyopaque) void,
pub fn init(ptr: anytype) Self { pub fn init(ptr: anytype) Self {
const Ptr = @TypeOf(ptr); const Ptr = @TypeOf(ptr);
@@ -28,35 +27,35 @@ pub const Emulator = struct {
pub fn readImpl(pointer: *anyopaque, addr: u32) u8 { pub fn readImpl(pointer: *anyopaque, addr: u32) u8 {
const self = @ptrCast(Ptr, @alignCast(alignment, pointer)); const self = @ptrCast(Ptr, @alignCast(alignment, pointer));
return @call(.always_inline, ptr_info.Pointer.child.read, .{ self, addr }); return @call(.{ .modifier = .always_inline }, ptr_info.Pointer.child.read, .{ u8, self, addr });
} }
pub fn writeImpl(pointer: *anyopaque, addr: u32, value: u8) void { pub fn writeImpl(pointer: *anyopaque, addr: u32, value: u8) void {
const self = @ptrCast(Ptr, @alignCast(alignment, pointer)); const self = @ptrCast(Ptr, @alignCast(alignment, pointer));
return @call(.always_inline, ptr_info.Pointer.child.write, .{ self, addr, value }); return @call(.{ .modifier = .always_inline }, ptr_info.Pointer.child.read, .{ u8, self, addr, value });
} }
pub fn registersImpl(pointer: *anyopaque) *[16]u32 { pub fn registersImpl(pointer: *const anyopaque) [16]u32 {
const self = @ptrCast(Ptr, @alignCast(alignment, pointer)); const self = @ptrCast(Ptr, @alignCast(alignment, pointer));
return @call(.always_inline, ptr_info.Pointer.child.registers, .{self}); return self.r;
} }
pub fn cpsrImpl(pointer: *anyopaque) u32 { pub fn cpsrImpl(pointer: *const anyopaque) u32 {
const self = @ptrCast(Ptr, @alignCast(alignment, pointer)); const self = @ptrCast(Ptr, @alignCast(alignment, pointer));
return @call(.always_inline, ptr_info.Pointer.child.cpsr, .{self}); return self.cpsr.raw;
}
pub fn stepImpl(pointer: *anyopaque) void {
const self = @ptrCast(Ptr, @alignCast(alignment, pointer));
return @call(.always_inline, ptr_info.Pointer.child.step, .{self});
} }
}; };
return .{ .ptr = ptr, .readFn = gen.readImpl, .writeFn = gen.writeImpl, .registersFn = gen.registersImpl, .cpsrFn = gen.cpsrImpl, .stepFn = gen.stepImpl }; return .{
.ptr = ptr,
.readFn = gen.readImpl,
.writeFn = gen.writeImpl,
.registersFn = gen.registersImpl,
.cpsrFn = gen.cpsrImpl,
};
} }
pub inline fn read(self: Self, addr: u32) u8 { pub inline fn read(self: Self, addr: u32) u8 {
@@ -67,15 +66,11 @@ pub const Emulator = struct {
self.writeFn(self.ptr, addr, value); self.writeFn(self.ptr, addr, value);
} }
pub inline fn registers(self: Self) *[16]u32 { pub inline fn registers(self: Self) [16]u32 {
return self.registersFn(self.ptr); return self.registersFn(self.ptr);
} }
pub inline fn cpsr(self: Self) u32 { pub inline fn cpsr(self: Self) u32 {
return self.cpsrFn(self.ptr); return self.cpsrFn(self.ptr);
} }
pub inline fn step(self: Self) void {
self.stepFn(self.ptr);
}
}; };