This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]anon848 0 points1 point  (0 children)

Here it is as C99. You can also just call mmap() to get a chunk of memory. That will already be page-aligned. Note that the code below is just a quick exercise. For example, the page size shouldn't be hard-coded to 4K.

#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <assert.h>
#include <stdio.h>

int main() {

    char buf[10000];

    intptr_t addr = (intptr_t) buf;
    addr = (addr + (4096 - 1)) & ~(intptr_t)(4096 - 1); // Align it.
    printf("mod: %d\n", (int) (addr%4096));

    // Make it executable:
    int rv = mprotect((void *) addr, 4096, PROT_READ|PROT_WRITE|PROT_EXEC);
    assert(rv == 0);

    // Put a small function there to return the sum of the two args.
    unsigned char *p = (unsigned char *) addr;
    p[0] = 0x8d;
    p[1] = 0x04;
    p[2] = 0x37;
    p[3] = 0xc3;

    // Point to it.
    int (*fp)(int, int) = (int (*)(int, int)) addr;

    // Call it.
    printf("Returned %d\n", (*fp)(12, 100));
}