@@ -32,6 +32,24 @@ pub fn new() !*TCCState {
32
32
return tcc_new () orelse error .TCCNewError ;
33
33
}
34
34
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
+
35
53
pub const TCCState = opaque {
36
54
/// set CONFIG_TCCDIR at runtime
37
55
pub fn set_lib_path (self : * TCCState , path : [:0 ]const u8 ) void {
@@ -158,15 +176,15 @@ pub const TCCState = opaque {
158
176
tcc_list_symbols (self , ctx , symbol_cb );
159
177
}
160
178
161
- pub fn relocateAlloc (self : * TCCState , allocator : std.mem.Allocator ) ! [] u8 {
179
+ pub fn relocateAlloc (self : * TCCState , allocator : std.mem.Allocator ) ! DynMem {
162
180
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 ;
167
185
}
168
186
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 {
170
188
const zbytes = try allocator .dupeZ (u8 , buf );
171
189
defer allocator .free (zbytes );
172
190
try self .compile_string (zbytes );
@@ -239,7 +257,7 @@ test "tcc - compileStringOnceAlloc" {
239
257
\\ return 234;
240
258
\\}
241
259
);
242
- defer allocator .free (mem );
260
+ defer mem .free ();
243
261
244
262
const Fn = * const fn () callconv (.c ) c_int ;
245
263
0 commit comments