Next Generation Emulation banner
81 - 86 of 86 Posts

· Registered
Joined
·
1 Posts
If someone want to test on Linux the code from the first post in this thread, use mmap() instead of malloc(), here the working code (Ubuntu 20.04 64 bit) compiled with -m32 (it's fundamental!!!) flag:

C:
// Include the prototypes of the functions we are using...
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>


/* In the beginning we'll have to define the function pointer.
* I called the function 'dyncode' and gave it an int argument
* as well as an int return value just to show what's possible.
*/

int (*dyncode)(int); // prototype for call of dynamic code

/* The following char array is initialized with some binary code
* which takes the first argument from the stack, increases it,
* and returns to the caller.
* Just very simple code for testing purposes...
*/

unsigned char code[] = {0x8B,0x44,0x24,0x04,  // mov eax, [esp+4]
                        0x40,                 // inc eax
                        0xC3                  // ret
                       };



int main(void)
{
    /* To show you that the code can be dynamically generated
     * although I defined static data above, the code is copied
     * into an allocated memory area and the starting address is
     * assigned to the function pointer 'dyncode'.
     * The strange stuff in front of the malloc is just to cast
     * the address to the same format the function pointer is
     * defined with, otherwise you'd get a compiler warning.
     */

    dyncode = mmap(NULL, sizeof(code), PROT_READ | PROT_WRITE | PROT_EXEC, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
    memcpy(dyncode, code, sizeof(code));

    /* To show that the code works it is called with the argument 41
     * and the return value sould be 42, obviously.
     */

    printf("Return value = %d\n", (*dyncode)(41) ); // call the code and print the return value

    munmap(dyncode, sizeof(code));

    return 0;
}
 
81 - 86 of 86 Posts
This is an older thread, you may not receive a response, and could be reviving an old thread. Please consider creating a new thread.
Top