Loading machinecode from file into memory and executing in C -- mprotect failing

Posted by chartreusekitsune on Stack Overflow See other posts from Stack Overflow or by chartreusekitsune
Published on 2010-03-13T09:37:54Z Indexed on 2010/03/13 9:45 UTC
Read the original article Hit count: 321

Filed under:
|
|
|

Hi I'm trying to load raw machine code into memory and run it from within a C program, right now when the program executes it breaks when trying to run mprotect on the memory to make it executable. I'm also not entirely sure that if the memory does get set right it will execute. What I currently have is the following:

#include <memory.h>
#include <sys/mman.h>
#include <stdio.h>

int main ( int argc, char **argv )
{
 FILE *fp;
 int sz = 0;
 char *membuf;
 int output = 0;

 fp = fopen(argv[1],"rb");

 if(fp == NULL)
 {
  printf("Failed to open file, aborting!\n");
  exit(1);
 }

 fseek(fp, 0L, SEEK_END);
 sz = ftell(fp);
 fseek(fp, 0L, SEEK_SET);


 membuf = (char *)malloc(sz*sizeof(char));
 if(membuf == NULL)
 {
  printf("Failed to allocate memory, aborting!\n");
  exit(1);
 }

  memset(membuf, 0x90, sz*sizeof(char));

 if( mprotect(membuf, sz*sizeof(char), PROT_EXEC | PROT_READ | PROT_WRITE) == -1)
 {
  printf("mprotect failed!!! aborting!\n");
  exit(1);
 }



 if((sz*sizeof(char)) != fread(membuf, sz*sizeof(char), 1, fp))
 {
  printf("Read failed, aborting!\n");
  exit(1);
 }
 __asm__
 ( 
  "call %%eax;"
  : "=a" (output)
       : "a" (membuf)
 );
 printf("Output = %x\n", output);

 return 0;
}

© Stack Overflow or respective owner

Related posts about machine-code

Related posts about c