Go to data segment

I am testing an assembler that I am writing that generates X86 instructions. I would like to do something like this to check if the instructions work or not.

#include<stdio.h>

unsigned char code[2] = {0xc9, 0xc3};

int main() {
  void (*foo)();
  foo = &code;
  foo();
  return 0;
}

However, it appears that OS X is preventing this due to DEP. Is there a way: (a) disable DEP for this program or (b) enter bytes in a different format so that I can go to them.

+5
source share
2 answers

If you just need to check, try this, this is magic ...

const unsigned char code[2] = {0xc9, 0xc3};
^^^^^

const const (! !), , text. . , :

__attribute__((section("text"))
const unsigned char code[2] = {0xc9, 0xc3};

,

    .text
    .globl code
code:
    .byte 0xc9
    .byte 0xc3

: , mprotect. .

:

#include <stdlib.h>
#include <sys/mman.h>
#include <err.h>
#include <stdint.h>

int main(int argc, char *argv[])
{
    unsigned char *p = malloc(4);
    int r;
    // This is x86_64 code
    p[0] = 0x8d;
    p[1] = 0x47;
    p[2] = 0x01;
    p[3] = 0xc3;
    // This is hackish, and in production you should do better.
    // Casting 4095 to uintptr_t is actually necessary on 64-bit.
    r = mprotect((void *) ((uintptr_t) p & ~(uintptr_t) 4095), 4096,
                 PROT_READ | PROT_WRITE | PROT_EXEC);
    if (r)
        err(1, "mprotect");
    // f(x) = x + 1
    int (*f)(int) = (int (*)(int)) p;
    return f(1);
}

mprotect , undefined, ​​ mmap, , , , OS X, OS X malloc mmap (, ).

+6

DEP OSX, , , - malloc() , , malloc'ed. , Linux exec ( , JIT ).

0

All Articles