Compare commits

...

12 Commits

Author SHA1 Message Date
4bca44e5f2 chore: update to lastest zig 2023-01-03 16:54:26 -06:00
1bd9964f58 fix: handle ack+packet strings 2022-12-15 20:25:10 -04:00
460fcec370 feat: implement instruction-granular stepping 2022-12-15 19:35:38 -04:00
21565a9726 feat: gracefully handle disconnects 2022-12-15 06:28:09 -04:00
2bc5bdc310 fix: fix errors in memory-map xml 2022-12-15 06:27:41 -04:00
51082186d7 fix: reverse the endianness of cpu registers 2022-12-15 06:27:21 -04:00
8a58251ef6 feat: implement gdb memory map 2022-12-15 05:06:50 -04:00
400e155502 feat: integrate emulator interface
while I figure out the interface with zba, disable the exe example
since it doesn't have an emu to pass to gdbstub
2022-12-15 04:23:32 -04:00
26aad8d1ae feat: reconfigure zba-gdbstub as a library 2022-12-15 04:23:05 -04:00
f1e1efc5e5 feat: workshop emulator interface 2022-12-15 04:22:42 -04:00
a85874d364 feat: get to user input in gdb 2022-12-15 04:21:16 -04:00
8195012573 chore: reorganize code 2022-12-15 04:21:16 -04:00
6 changed files with 548 additions and 309 deletions

View File

@@ -1,38 +1,60 @@
const std = @import("std");
pub fn build(b: *std.build.Builder) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
fn path(comptime suffix: []const u8) []const u8 {
if (suffix[0] == '/') @compileError("expected a relative path");
return comptime (std.fs.path.dirname(@src().file) orelse ".") ++ std.fs.path.sep_str ++ suffix;
}
// Standard release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
const mode = b.standardReleaseOptions();
const pkgs = struct {
const Pkg = std.build.Pkg;
const exe = b.addExecutable("zba-gdbstub", "src/main.zig");
pub const gdbstub: Pkg = .{
.name = "gdbstub",
.source = .{ .path = path("src/lib.zig") },
.dependencies = &[_]Pkg{network},
};
// https://github.com/MasterQ32/zig-network
exe.addPackagePath("network", "lib/zig-network/network.zig");
pub const network: Pkg = .{
.name = "network",
.source = .{ .path = path("lib/zig-network/network.zig") },
};
};
exe.setTarget(target);
exe.setBuildMode(mode);
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
pub fn link(exe: *std.build.LibExeObjStep) void {
exe.addPackage(pkgs.gdbstub);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
pub fn build(b: *std.build.Builder) void {
const target = b.standardTargetOptions(.{});
_ = target;
const mode = b.standardReleaseOptions();
const exe_tests = b.addTest("src/main.zig");
exe_tests.setTarget(target);
exe_tests.setBuildMode(mode);
// -- library --
const lib = b.addStaticLibrary("gdbstub", "src/lib.zig");
lib.addPackage(pkgs.network);
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&exe_tests.step);
lib.setBuildMode(mode);
lib.install();
const lib_tests = b.addTest("src/lib.zig");
lib_tests.setBuildMode(mode);
const test_step = b.step("lib-test", "Run Library Tests");
test_step.dependOn(&lib_tests.step);
// // -- Executable --
// const exe = b.addExecutable("gdbserver", "src/main.zig");
// link(exe);
// exe.setTarget(target);
// exe.setBuildMode(mode);
// exe.install();
// const run_cmd = exe.run();
// run_cmd.step.dependOn(b.getInstallStep());
// if (b.args) |args| run_cmd.addArgs(args);
// const run_step = b.step("run", "Run the app");
// run_step.dependOn(&run_cmd.step);
}

230
src/Packet.zig Normal file
View File

@@ -0,0 +1,230 @@
const std = @import("std");
const Allocator = std.mem.Allocator;
const Emulator = @import("lib.zig").Emulator;
const target = @import("Server.zig").target;
const memory_map = @import("Server.zig").memory_map;
const Self = @This();
const log = std.log.scoped(.Packet);
pub const max_len: usize = 0x1000;
contents: []const u8,
pub fn from(allocator: Allocator, str: []const u8) !Self {
var tokens = std.mem.tokenize(u8, str, "$#");
const contents = tokens.next() orelse return error.InvalidPacket;
const chksum_str = tokens.next() orelse return error.MissingCheckSum;
const chksum = std.fmt.parseInt(u8, chksum_str, 16) catch return error.InvalidChecksum;
if (!Self.verify(contents, chksum)) return error.ChecksumMismatch;
return .{ .contents = try allocator.dupe(u8, contents) };
}
const String = union(enum) {
alloc: []const u8,
static: []const u8,
pub fn inner(self: *const @This()) []const u8 {
return switch (self.*) {
.static => |str| str,
.alloc => |str| str,
};
}
pub fn deinit(self: *@This(), allocator: Allocator) void {
switch (self.*) {
.alloc => |string| allocator.free(string),
.static => {},
}
self.* = undefined;
}
};
pub fn parse(self: *Self, allocator: Allocator, emu: Emulator) !String {
switch (self.contents[0]) {
// Required
'?' => {
const ret = try std.fmt.allocPrint(allocator, "S{x:0>2}", .{@enumToInt(Signal.Int)});
return .{ .alloc = ret };
},
'g' => {
const r = emu.registers();
const cpsr = emu.cpsr();
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
{
var i: u32 = 0;
while (i < r.len + 1) : (i += 1) {
var 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
// GDB also expects the bytes to be in the opposite order for whatever reason
_ = std.fmt.bufPrintIntToSlice(ret[i * 8 ..][0..8], @byteSwap(reg), 16, .lower, .{ .fill = '0', .width = 8 });
}
}
return .{ .alloc = ret };
},
'G' => @panic("TODO: Register Write"),
'm' => {
var tokens = std.mem.tokenize(u8, self.contents[1..], ",");
const addr_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 len = try std.fmt.parseInt(u32, length_str, 16);
const ret = try allocator.alloc(u8, len * 2);
{
var i: u32 = 0;
while (i < len) : (i += 1) {
const value = emu.read(addr + i);
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], emu.read(addr + i), 16, .lower, .{ .fill = '0', .width = 2 });
}
}
return .{ .alloc = ret };
},
'M' => @panic("TODO: Memory Write"),
'c' => @panic("TODO: Continue"),
's' => {
// 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
'D' => {
log.info("Disconnecting...", .{});
return .{ .static = "OK" };
},
'H' => return .{ .static = "" },
'v' => {
if (substr(self.contents[1..], "MustReplyEmpty")) {
return .{ .static = "" };
}
log.warn("Unimplemented: {s}", .{self.contents});
return .{ .static = "" };
},
'q' => {
if (self.contents[1] == 'C' and self.contents.len == 2) return .{ .static = "QC1" };
if (substr(self.contents[1..], "fThreadInfo")) return .{ .static = "m1" };
if (substr(self.contents[1..], "sThreadInfo")) return .{ .static = "l" };
if (substr(self.contents[1..], "Attached")) return .{ .static = "1" }; // Tell GDB we're attached to a process
if (substr(self.contents[1..], "Supported")) {
const format = "PacketSize={x:};qXfer:features:read+;qXfer:memory-map:read+";
// TODO: Anything else?
const ret = try std.fmt.allocPrint(allocator, format, .{Self.max_len});
return .{ .alloc = ret };
}
if (substr(self.contents[1..], "Xfer:features:read")) {
var tokens = std.mem.tokenize(u8, self.contents[1..], ":,");
_ = tokens.next(); // Xfer
_ = tokens.next(); // features
_ = tokens.next(); // read
const annex = tokens.next() orelse return .{ .static = "E9999" };
const offset_str = tokens.next() orelse return .{ .static = "E99999" };
const length_str = tokens.next() orelse return .{ .static = "E9999" };
if (std.mem.eql(u8, annex, "target.xml")) {
const offset = try std.fmt.parseInt(usize, offset_str, 16);
const length = try std.fmt.parseInt(usize, length_str, 16);
// + 2 to account for the "m " in the response
// subtract offset so that the allocated buffer isn't
// larger than it needs to be TODO: Test this?
const len = @min(length, (target.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..], target[offset..]);
return .{ .alloc = ret };
} else {
log.err("Unexpected Annex: {s}", .{annex});
return .{ .static = "E9999" };
}
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});
return .{ .static = "" };
},
else => {
log.warn("Unknown: {s}", .{self.contents});
return .{ .static = "" };
},
}
}
fn substr(haystack: []const u8, needle: []const u8) bool {
return std.mem.indexOf(u8, haystack, needle) != null;
}
pub fn deinit(self: *Self, allocator: Allocator) void {
allocator.free(self.contents);
self.* = undefined;
}
pub fn checksum(input: []const u8) u8 {
var sum: usize = 0;
for (input) |char| sum += char;
return @truncate(u8, sum);
}
fn verify(input: []const u8, chksum: u8) bool {
return Self.checksum(input) == chksum;
}
const Signal = enum(u32) {
Hup = 1, // Hangup
Int, // Interrupt
Quit, // Quit
Ill, // Illegal Instruction
Trap, // Trace/Breakponit trap
Abrt, // Aborted
};

179
src/Server.zig Normal file
View File

@@ -0,0 +1,179 @@
const std = @import("std");
const network = @import("network");
const Packet = @import("Packet.zig");
const Socket = network.Socket;
const Allocator = std.mem.Allocator;
const Emulator = @import("lib.zig").Emulator;
const Self = @This();
const log = std.log.scoped(.Server);
const port: u16 = 2424;
pub const target: []const u8 =
\\<target version="1.0">
\\ <architecture>armv4t</architecture>
\\ <feature name="org.gnu.gdb.arm.core">
\\ <reg name="r0" bitsize="32" type="uint32"/>
\\ <reg name="r1" bitsize="32" type="uint32"/>
\\ <reg name="r2" bitsize="32" type="uint32"/>
\\ <reg name="r3" bitsize="32" type="uint32"/>
\\ <reg name="r4" bitsize="32" type="uint32"/>
\\ <reg name="r5" bitsize="32" type="uint32"/>
\\ <reg name="r6" bitsize="32" type="uint32"/>
\\ <reg name="r7" bitsize="32" type="uint32"/>
\\ <reg name="r8" bitsize="32" type="uint32"/>
\\ <reg name="r9" bitsize="32" type="uint32"/>
\\ <reg name="r10" bitsize="32" type="uint32"/>
\\ <reg name="r11" bitsize="32" type="uint32"/>
\\ <reg name="r12" bitsize="32" type="uint32"/>
\\ <reg name="sp" bitsize="32" type="data_ptr"/>
\\ <reg name="lr" bitsize="32"/>
\\ <reg name="pc" bitsize="32" type="code_ptr"/>
\\
\\ <reg name="cpsr" bitsize="32" regnum="25"/>
\\ </feature>
\\</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?
pkt_cache: ?[]const u8 = null,
client: Socket,
_socket: Socket,
emu: Emulator,
pub fn init(emulator: Emulator) !Self {
try network.init();
var socket = try Socket.create(.ipv4, .tcp);
try socket.bindToPort(port);
try socket.listen();
var client = try socket.accept(); // TODO: This blocks, is this OK?
const endpoint = try client.getLocalEndPoint();
log.info("client connected from {}", .{endpoint});
return .{ .emu = emulator, ._socket = socket, .client = client };
}
pub fn deinit(self: *Self, allocator: Allocator) void {
self.reset(allocator);
self.client.close();
self._socket.close();
network.deinit();
self.* = undefined;
}
const Action = union(enum) {
nothing,
send: []const u8,
retry,
ack,
nack,
};
pub fn run(self: *Self, allocator: Allocator) !void {
var buf: [Packet.max_len]u8 = undefined;
while (true) {
const len = try self.client.receive(&buf);
if (len == 0) break;
const action = try self.parse(allocator, buf[0..len]);
try self.send(allocator, action);
}
}
fn parse(self: *Self, allocator: Allocator, input: []const u8) !Action {
// log.debug("-> {s}", .{input});
return switch (input[0]) {
'+' => blk: {
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,
'$' => try self.handlePacket(allocator, input),
'\x03' => .nothing,
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;
defer packet.deinit(allocator);
var string = packet.parse(allocator, self.emu) catch return .nack;
defer string.deinit(allocator);
const reply = string.inner();
// deallocated by the caller
const response = try std.fmt.allocPrint(allocator, "+${s}#{x:0>2}", .{ reply, Packet.checksum(reply) });
return .{ .send = response };
}
fn send(self: *Self, allocator: Allocator, action: Action) !void {
switch (action) {
.send => |pkt| {
_ = try self.client.send(pkt);
// log.debug("<- {s}", .{pkt});
self.reset(allocator);
self.pkt_cache = pkt;
},
.retry => {
log.warn("received nack, resending: \"{?s}\"", .{self.pkt_cache});
if (self.pkt_cache) |pkt| {
_ = try self.client.send(pkt);
// log.debug("<- {s}", .{pkt});
}
},
.ack => {
_ = try self.client.send("+");
// log.debug("<- +", .{});
self.reset(allocator);
},
.nack => {
_ = try self.client.send("-");
// log.debug("<- -", .{});
self.reset(allocator);
},
.nothing => self.reset(allocator),
}
}
fn reset(self: *Self, allocator: Allocator) void {
if (self.pkt_cache) |pkt| allocator.free(pkt);
self.pkt_cache = null;
}

81
src/lib.zig Normal file
View File

@@ -0,0 +1,81 @@
/// Re-export of the server interface
pub const Server = @import("Server.zig");
/// Interface for interacting between GDB and a GBA emu
pub const Emulator = struct {
const Self = @This();
ptr: *anyopaque,
readFn: *const fn (*anyopaque, u32) u8,
writeFn: *const fn (*anyopaque, u32, u8) void,
registersFn: *const fn (*anyopaque) *[16]u32,
cpsrFn: *const fn (*anyopaque) u32,
stepFn: *const fn (*anyopaque) void,
pub fn init(ptr: anytype) Self {
const Ptr = @TypeOf(ptr);
const ptr_info = @typeInfo(Ptr);
if (ptr_info != .Pointer) @compileError("ptr must be a pointer");
if (ptr_info.Pointer.size != .One) @compileError("ptr must be a single-item pointer");
const alignment = ptr_info.Pointer.alignment;
const gen = struct {
pub fn readImpl(pointer: *anyopaque, addr: u32) u8 {
const self = @ptrCast(Ptr, @alignCast(alignment, pointer));
return @call(.always_inline, ptr_info.Pointer.child.read, .{ self, addr });
}
pub fn writeImpl(pointer: *anyopaque, addr: u32, value: u8) void {
const self = @ptrCast(Ptr, @alignCast(alignment, pointer));
return @call(.always_inline, ptr_info.Pointer.child.write, .{ self, addr, value });
}
pub fn registersImpl(pointer: *anyopaque) *[16]u32 {
const self = @ptrCast(Ptr, @alignCast(alignment, pointer));
return @call(.always_inline, ptr_info.Pointer.child.registers, .{self});
}
pub fn cpsrImpl(pointer: *anyopaque) u32 {
const self = @ptrCast(Ptr, @alignCast(alignment, pointer));
return @call(.always_inline, ptr_info.Pointer.child.cpsr, .{self});
}
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 };
}
pub inline fn read(self: Self, addr: u32) u8 {
return self.readFn(self.ptr, addr);
}
pub inline fn write(self: Self, addr: u32, value: u8) void {
self.writeFn(self.ptr, addr, value);
}
pub inline fn registers(self: Self) *[16]u32 {
return self.registersFn(self.ptr);
}
pub inline fn cpsr(self: Self) u32 {
return self.cpsrFn(self.ptr);
}
pub inline fn step(self: Self) void {
self.stepFn(self.ptr);
}
};

View File

@@ -1,291 +1,18 @@
const std = @import("std");
const network = @import("network");
const Allocator = std.mem.Allocator;
const Socket = network.Socket;
const port: u16 = 2424;
const target: []const u8 =
\\<target version="1.0">
\\ <architecture>armv4t</architecture>
\\ <feature name="org.gnu.gdb.arm.core">
\\ <reg name="r0" bitsize="32" type="uint32"/>
\\ <reg name="r1" bitsize="32" type="uint32"/>
\\ <reg name="r2" bitsize="32" type="uint32"/>
\\ <reg name="r3" bitsize="32" type="uint32"/>
\\ <reg name="r4" bitsize="32" type="uint32"/>
\\ <reg name="r5" bitsize="32" type="uint32"/>
\\ <reg name="r6" bitsize="32" type="uint32"/>
\\ <reg name="r7" bitsize="32" type="uint32"/>
\\ <reg name="r8" bitsize="32" type="uint32"/>
\\ <reg name="r9" bitsize="32" type="uint32"/>
\\ <reg name="r10" bitsize="32" type="uint32"/>
\\ <reg name="r11" bitsize="32" type="uint32"/>
\\ <reg name="r12" bitsize="32" type="uint32"/>
\\ <reg name="sp" bitsize="32" type="data_ptr"/>
\\ <reg name="lr" bitsize="32"/>
\\ <reg name="pc" bitsize="32" type="code_ptr"/>
\\
\\ <reg name="cpsr" bitsize="32" regnum="25"/>
\\ </feature>
\\</target>
;
const Server = @import("gdbstub").Server;
pub fn main() !void {
const log = std.log.scoped(.Server);
const log = std.log.scoped(.Main);
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer std.debug.assert(!gpa.deinit());
const allocator = gpa.allocator();
try network.init();
defer network.deinit();
var server = try Server.init();
defer server.deinit(allocator);
var socket = try Socket.create(.ipv4, .tcp);
defer socket.close();
try socket.bindToPort(port);
try socket.listen();
var client = try socket.accept();
defer client.close();
const endpoint = try client.getLocalEndPoint();
log.info("client connected from {}", .{endpoint});
try gdbStubServer(allocator, client);
try server.run(allocator);
log.info("Client disconnected", .{});
}
fn gdbStubServer(allocator: Allocator, client: Socket) !void {
var buf: [Packet.size]u8 = undefined;
var previous: ?[]const u8 = null;
defer if (previous) |packet| allocator.free(packet);
while (true) {
const len = try client.receive(&buf);
if (len == 0) break;
switch (try parse(allocator, client, previous, buf[0..len])) {
.send => |response| {
if (previous) |packet| allocator.free(packet);
previous = response;
},
.recv_ack => {
if (previous) |packet| allocator.free(packet);
previous = null;
},
.recv_nack => {},
}
}
}
const Action = union(enum) {
send: []const u8,
recv_nack,
recv_ack,
};
fn parse(allocator: Allocator, client: Socket, previous: ?[]const u8, input: []const u8) !Action {
const log = std.log.scoped(.GdbStubParser);
return switch (input[0]) {
'+' => .recv_ack,
'-' => blk: {
if (previous) |packet| {
log.warn("received nack, resending: \"{s}\"", .{packet});
_ = try client.send(packet);
} else {
log.err("received nack, but we don't recall sending anything", .{});
}
break :blk .recv_nack;
},
'$' => blk: {
// Packet
var packet = try Packet.from(allocator, input);
defer packet.deinit(allocator);
var string = try packet.parse(allocator);
defer string.deinit(allocator);
const reply = string.inner();
_ = try client.send("+"); // Acknowledge
// deallocated by the caller
const response = try std.fmt.allocPrint(allocator, "${s}#{x:0>2}", .{ reply, Packet.checksum(reply) });
_ = try client.send(response);
break :blk .{ .send = response };
},
else => std.debug.panic("Unknown: {s}", .{input}),
};
}
const Packet = struct {
const Self = @This();
const log = std.log.scoped(.Packet);
const size: usize = 0x1000;
contents: []const u8,
pub fn from(allocator: Allocator, str: []const u8) !Self {
var tokens = std.mem.tokenize(u8, str, "$#");
const contents = tokens.next() orelse return error.InvalidPacket;
const chksum_str = tokens.next() orelse return error.MissingCheckSum;
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;
return .{ .contents = try allocator.dupe(u8, contents) };
}
const String = union(enum) {
alloc: []const u8,
static: []const u8,
pub fn inner(self: *const @This()) []const u8 {
return switch (self.*) {
.static => |str| str,
.alloc => |str| str,
};
}
pub fn deinit(self: *@This(), allocator: Allocator) void {
switch (self.*) {
.alloc => |string| allocator.free(string),
.static => {},
}
self.* = undefined;
}
};
pub fn parse(self: *Self, allocator: Allocator) !String {
switch (self.contents[0]) {
// Required
'?' => {
const ret: Signal = .Trap;
// Deallocated by the caller
return .{ .alloc = try std.fmt.allocPrint(allocator, "T{x:0>2}thread:1;", .{@enumToInt(ret)}) };
},
'g', 'G' => @panic("TODO: Register Access"),
'm', 'M' => @panic("TODO: Memory Access"),
'c' => @panic("TODO: Continue"),
's' => @panic("TODO: Step"),
// Optional
'H' => {
log.warn("{s}", .{self.contents});
switch (self.contents[1]) {
'g', 'c' => return .{ .static = "OK" },
else => {
log.warn("Unimplemented: {s}", .{self.contents});
return .{ .static = "" };
},
}
},
'v' => {
if (substr(self.contents[1..], "MustReplyEmpty")) {
return .{ .static = "" };
}
log.warn("Unimplemented: {s}", .{self.contents});
return .{ .static = "" };
},
'q' => {
if (self.contents[1] == 'C' and self.contents.len == 2) return .{ .static = "QC1" };
if (substr(self.contents[1..], "fThreadInfo")) return .{ .static = "m1" };
if (substr(self.contents[1..], "sThreadInfo")) return .{ .static = "l" };
if (substr(self.contents[1..], "Attached")) return .{ .static = "1" }; // Tell GDB we're attached to a process
if (substr(self.contents[1..], "Supported")) {
const format = "PacketSize={x:};qXfer:features:read+;qXfer:memory-map:read+";
// TODO: Anything else?
const ret = try std.fmt.allocPrint(allocator, format, .{Packet.size});
return .{ .alloc = ret };
}
if (substr(self.contents[1..], "Xfer:features:read")) {
var tokens = std.mem.tokenize(u8, self.contents[1..], ":,");
_ = tokens.next(); // qXfer
_ = tokens.next(); // features
_ = tokens.next(); // read
const annex = tokens.next() orelse return .{ .static = "E00" };
const offset_str = tokens.next() orelse return .{ .static = "E00" };
const length_str = tokens.next() orelse return .{ .static = "E00" };
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 length = try std.fmt.parseInt(usize, length_str, 16);
// + 2 to account for the "m " in the response
// subtract offset so that the allocated buffer isn't
// larger than it needs to be TODO: Test this?
const len = @min(length, (target.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..], target[offset..]);
return .{ .alloc = ret };
} else {
log.err("Unexpected Annex: {s}", .{annex});
return .{ .static = "E00" };
}
return .{ .static = "" };
}
log.warn("Unimplemented: {s}", .{self.contents});
return .{ .static = "" };
},
else => {
log.warn("Unknown: {s}", .{self.contents});
return .{ .static = "" };
},
}
}
fn substr(haystack: []const u8, needle: []const u8) bool {
return std.mem.indexOf(u8, haystack, needle) != null;
}
fn deinit(self: *Self, allocator: Allocator) void {
allocator.free(self.contents);
self.* = undefined;
}
pub fn checksum(input: []const u8) u8 {
var sum: usize = 0;
for (input) |char| sum += char;
return @truncate(u8, sum);
}
fn verify(input: []const u8, chksum: u8) bool {
return Self.checksum(input) == chksum;
}
};
const Signal = enum(u32) {
Hup, // Hangup
Int, // Interrupt
Quit, // Quit
Ill, // Illegal Instruction
Trap, // Trace/Breakponit trap
Abrt, // Aborted
};