Skip to content

Commit 06e5df4

Browse files
committed
Aligned memory block
1 parent 0d48901 commit 06e5df4

File tree

1 file changed

+25
-7
lines changed

1 file changed

+25
-7
lines changed

src/lib.zig

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,24 @@ pub fn new() !*TCCState {
3232
return tcc_new() orelse error.TCCNewError;
3333
}
3434

35+
pub const DynMem = struct {
36+
allocator: std.mem.Allocator,
37+
mem: []align(std.mem.page_size) u8,
38+
39+
pub fn alloc(allocator: std.mem.Allocator, size: usize) !DynMem {
40+
const mem = try allocator.alignedAlloc(u8, std.mem.page_size, size);
41+
return .{
42+
.allocator = std.testing.allocator,
43+
.mem = mem,
44+
};
45+
}
46+
47+
pub fn free(self: DynMem) void {
48+
std.posix.mprotect(self.mem, std.posix.PROT.READ | std.posix.PROT.WRITE) catch {};
49+
self.allocator.free(self.mem);
50+
}
51+
};
52+
3553
pub const TCCState = opaque {
3654
/// set CONFIG_TCCDIR at runtime
3755
pub fn set_lib_path(self: *TCCState, path: [:0]const u8) void {
@@ -158,15 +176,15 @@ pub const TCCState = opaque {
158176
tcc_list_symbols(self, ctx, symbol_cb);
159177
}
160178

161-
pub fn relocateAlloc(self: *TCCState, allocator: std.mem.Allocator) ![]u8 {
179+
pub fn relocateAlloc(self: *TCCState, allocator: std.mem.Allocator) !DynMem {
162180
const bytes = try self.relocationSize();
163-
const ptr = try allocator.alloc(u8, @intCast(bytes));
164-
errdefer allocator.free(ptr);
165-
try self.relocate(.{ .addr = @ptrCast(@alignCast(ptr.ptr)) });
166-
return ptr;
181+
const mem = try DynMem.alloc(allocator, @intCast(bytes));
182+
errdefer mem.free();
183+
try self.relocate(.{ .addr = @ptrCast(@alignCast(mem.mem.ptr)) });
184+
return mem;
167185
}
168186

169-
pub fn compileStringOnceAlloc(self: *TCCState, allocator: std.mem.Allocator, buf: []const u8) ![]u8 {
187+
pub fn compileStringOnceAlloc(self: *TCCState, allocator: std.mem.Allocator, buf: []const u8) !DynMem {
170188
const zbytes = try allocator.dupeZ(u8, buf);
171189
defer allocator.free(zbytes);
172190
try self.compile_string(zbytes);
@@ -239,7 +257,7 @@ test "tcc - compileStringOnceAlloc" {
239257
\\ return 234;
240258
\\}
241259
);
242-
defer allocator.free(mem);
260+
defer mem.free();
243261

244262
const Fn = *const fn () callconv(.c) c_int;
245263

0 commit comments

Comments
 (0)