>>107842351
>>107842381
if i can make some gentle suggestions, though:
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
/** x86_64 machine code for `int times2(int x)` */
static const uint8_t times2_impl[] = {
// lea eax, [rdi+rdi*1]
0x8d, 0x04, 0x3f,
// ret
0xc3,
};
static void *_make_dynamic_times2(const void *const data, size_t size)
{
const int rw = PROT_READ | PROT_WRITE;
const int rx = PROT_READ | PROT_EXEC;
const int flags = MAP_PRIVATE | MAP_ANONYMOUS;
int ret = -1;
void *map = MAP_FAILED;
size = ((size + (getpagesize() - 1)) / getpagesize()) * getpagesize();
map = mmap(NULL, size, rw, flags, -1, 0);
if (map == MAP_FAILED)
{
return NULL;
}
(void)memcpy(map, data, size);
ret = mprotect(map, size, rx);
if (ret != 0)
{
(void)munmap(map, size);
return NULL;
}
return map;
}
int main()
{
int (*times2)(int) = NULL;
int doubled = -1;
times2 = _make_dynamic_times2(times2_impl, sizeof(times2_impl));
if (!times2)
{
return -1;
}
doubled = times2(2);
printf("%d\n", doubled); // want `4`
return (doubled == (2 * 2) ? 0 : -1);
}
apologies for any formatting errors; i am a dirty phoneposter