Hi, I've been learning zig for the last 2weeks and I'm writing a little memory library for stringref search etc, but I get an incorrect alignment panic message when running this in my dll. which kinda makes sense since the address would be 0x401003 which isn't aligned to u32. I tried using align(1), readInt, didn't work so I asked AI as a last resort and it didn't do much more, so I'd like to know how I can fix that?
here's my code :
pub const Address = struct {
address: usize,
pub inline fn init(addr: usize) Address {
return .{ .address = addr };
}
pub inline fn absoluteOffset(self: *const Address, off: usize) !Address {
const base = self.address +% off;
if (base == 0)
return MemError.InvalidAddress;
const bytes: *align(1) const [4]u8 = @ptrFromInt(base);
const address = std.mem.readInt(u32, bytes, .little);
return Address.init(address);
}
pub inline fn relativeOffset(self: *const Address, off: usize) !Address {
const base = self.address +% off;
if (base == 0)
return MemError.InvalidAddress;
const displacement = @as(*const i32, @ptrFromInt(base)).*;
return Address.init(base +% 4 +% @as(usize, @intCast(displacement)));
}
pub fn ptr(self: *const Address, comptime T: type) T {
return @ptrFromInt(self.address);
}
pub inline fn get(self: *const Address) usize {
return self.address;
}
};
and the stringref search :
pub fn string(self: Scanner, comptime str: []const u8, comptime utf16: bool, findFirst: bool) !Address {
const textSection = try self.module.section(std.heap.page_allocator, ".text");
const rdataSection = try self.module.section(std.heap.page_allocator, ".rdata");
const scanBytes = textSection.start.?.ptr([*]const u8);
var lastMatch: ?Address = null;
var i: usize = 0;
while (i < textSection.size) : (i += 1) {
if (scanBytes[i] == @intFromEnum(Mnemonic.PUSH)) {
const stringAddress = try Address.init(@intFromPtr(&scanBytes[i])).absoluteOffset(1);
if (rdataSection.isInSection(stringAddress)) {
const stringType = if (utf16) [*:0]const u16 else [*:0]const u8;
const stringBytes = stringAddress.ptr(stringType);
const firstChar: u16 = stringBytes[0];
const isAsciiChar = firstChar <= 0x7F;
if (isAsciiChar) {
if (utf16) {
const lea = std.mem.span(@as([*:0]const u16, @ptrCast(stringBytes)));
if (std.mem.eql(u16, std.unicode.utf8ToUtf16LeStringLiteral(str), lea)) {
const result = Address.init(@intFromPtr(&scanBytes[i]));
if (findFirst) {
return result;
}
lastMatch = result;
}
} else {
const lea = std.mem.span(@as([*:0]const u8, @ptrCast(stringBytes)));
if (std.mem.eql(u8, str, lea)) {
const result = Address.init(@intFromPtr(&scanBytes[i]));
if (findFirst) {
return result;
}
lastMatch = result;
}
}
}
}
}
}
if (lastMatch) |match| {
return match;
}
return MemError.NoResult;
}