Note that there are some explanatory texts on larger screens.

plurals
  1. POOS X: write syscall is not executed when loading binary to memory
    primarykey
    data
    text
    <p>I have a simple hello world program written in assembly. It prints "Hello, world!" and exits. When compiling with <code>nasm</code> and executing the code directly, everything works fine.</p> <p>I also wrote some C code to load a flat binary and execute its code using <code>mmap</code>. When loading the flat binary, the text is not printed out. I'm pretty sure the call is happening, because adding an extra call to <code>exit</code> causes the program to exit prematurely. Here's the code for the assembly program:</p> <pre><code> global start section .text start: ; write is not run mov rax, 0x2000004 mov rdi, 1 mov rsi, msg mov rdx, msg.len syscall ; but exit is... mov rax, 0x2000001 mov rdi, 0 syscall section .data msg: db "Hello, world!", 10 .len: equ $ - msg </code></pre> <p>Compile it with <code>nasm -f macho64 hello.s &amp;&amp; ld -macosx_version_min 10.7.0 hello.o -o hello</code> and generate a flat binary with <code>objcopy -O binary hello.o hello.bin</code>.</p> <p>The code to load and execute the binary looks like this:</p> <pre><code>#include &lt;sys/mman.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; /* allocate executable memory size-bytes long */ void* memexec_alloc(size_t size) { void* ptr = mmap(0, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0); if (ptr == (void *)-1) { printf("mmap error\n"); return NULL; } return ptr; } /* Load contents of file f into mem */ void memload(const char *f, unsigned char *mem) { FILE *file; size_t size; unsigned char *data; file = fopen(f, "r"); fseek(file, 0, SEEK_END); size = ftell(file); rewind(file); data = (unsigned char*) malloc(sizeof(char) * size); fread(data, sizeof(char), size, file); fclose(file); memcpy(mem, data, sizeof(char) * size); free(data); } static const size_t SIZE = 1024; typedef void (*voidfunc)(void); int main(int argc, char **argv) { if (argc != 2) { puts("no file specified!"); return 1; } void *mem = memexec_alloc(SIZE); memload(argv[1], mem); voidfunc func = mem; func(); return 1; } </code></pre> <p>Inspecting the code in a debugger shows that the first <code>syscall</code> <em>is indeed</em> executed, but nothing is printed out, the program then exits with a value of 0 instead of 1. How do I get it to print?</p> <p>(The OS is OS X Mavericks, 64 bit.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload