Linux AMD64 call C libary functions from copied assembly -


how call memcpy'ed assembly function c library functions?

i'm making example test code how 1 can allocate , change memory protection on linux, amd64 run arbitrarily generated code c. done compile small gas assembly function along side main program (written in c) , copy assembly binary blob onto piece executable memory in run-time , jump it. part works ok.

but if call c library puts() copied assembly blob results in segfault due bad function address?! how fix it?

the assembly code blob:

       .text        .global      _print_hello_size        .global      _print_hello        .type        _print_hello,@function _print_hello:        push %rbp        mov %rsp, %rbp        # puts("hello world\n")        mov $_message, %rdi        call puts    # <-- segfault        pop %rbp        ret procend: # mark end address of _print_hello code        .section .rodata _message:        .asciz  "hello, world\n" _print_hello_size:        .long procend - _print_hello 

then in c main() (pseudo code):

// import assembler function , size extern "c" void _print_hello(void); extern "c" const long _print_hello_size; int main() {     // use special function allocates read-write-executable memory     void * memexec = mallocexecutablememory(1024);     // copy binary asm blob, memexec aligned @ least 16-bytes     memcpy(memexec, (void*)_print_hello, _print_hello_size);      void (*jmpfunc)(void) = (void (*)(void))memexec;      jmpfunc(); // works, jumps copied assembly func     return 0; } 

later if possible not compile asm blob, encode example program in in unsigned char execblob[] = { 0xcc,0xcc,0xc3,..} , copy executable region. bit code exploration how start generating asm c.

maybe do

push %rbp mov %rsp, %rbp # puts("hello world\n") mov $_message, %rdi mov $puts, %eax call %eax pop %rbp ret 

and forcing call become absolute one. question whether assembler won't optimize out own purposes.


Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -