Note that there are some explanatory texts on larger screens.

plurals
  1. POLoading MachineCode From File Into Memory and Executing in C -- mprotect Failing
    text
    copied!<p>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. I am currently running this on Ubuntu Linux x86 (Maybe the problem is Ubuntu's over-protection?)</p> <p>What I currently have is the following:</p> <pre><code>#include &lt;memory.h&gt; #include &lt;sys/mman.h&gt; #include &lt;stdio.h&gt; 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) { perror("mprotect"); printf("mprotect failed!!! aborting!\n"); exit(1); } if(!(fread(membuf, sz*sizeof(char), 1, fp))) { perror("fread"); printf("Read failed, aborting!\n"); exit(1); } __asm__ ( "call %%eax;" : "=a" (output) : "a" (membuf) ); printf("Output = %x\n", output); return 0; } </code></pre> <p>I do get the compiler warning:</p> <pre><code>/tmp/ccVnhHak.s: Assembler messages: /tmp/ccVnhHak.s:107: Warning: indirect call without `*' </code></pre> <p>I've not gotten the program to reach this code yet so I am unable to see if my assembler code is doing what it should.</p>
 

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