#Can you construct a function from non-code data?
1 messages · Page 1 of 1 (latest)
i think you can do it. i've never attempted this myself, but i was able to assign a string to the function pointer with @ptrCast() and then it obviously crashed when trying to call it. But, if it was valid code (compiled binary code, not just source code), then it might work assuming the memory is executable and all that. That will likely be your bigger hurdle to achieving your goal. May I ask why you are trying to do this?
ah ok. i mean obviously it goes without saying you should not be doing this for legitimate purposes lol. only legitimate purpose is for security research. only time i did anything remotely like this was in a college course where we used a buffer overflow to overwrite the return address and execute some shellcode.
but we had to disable all of gcc's checks that normally prevent you from doing this. Executable memory, ASLR, stack canaries, etc. all get in the way of it
const mem = try std.posix.mmap(
null,
1,
std.posix.PROT.WRITE | std.posix.PROT.EXEC,
.{ .TYPE = .PRIVATE, .ANONYMOUS = true },
-1,
0,
);
defer std.posix.munmap(mem);
mem[0..13].* = "\x48\x8b\x06\x48\x8b\x0f\x48\x89\x0e\x48\x89\x07\xc3".*;
const fun: *const fn (*u32, *u32) void = @ptrCast(mem);
var i: u32 = 111;
var j: u32 = 222;
std.debug.print("{} {}\n", .{ i, j });
fun(&i, &j);
std.debug.print("{} {}\n", .{ i, j });
// 111 222
// 222 111
// All 1 tests passed.
Allocate memory with execute permission
Write wathever machine code into that memory