title: C : running a compiled function from ram
body: <p>I'm working on a project that i need to load a simple <code>exe</code> file to a buffer and then call the entry point of the <code>exe</code> file from within the ram .</p>
  
  <p>i know that i can't load and run a very complicated exe file with a lot of dependencies from buffer but i think its possible to call an independent function of the <code>exe (PE)</code> file (like an empty main).</p>
  
  <p>to do so,i have to find the entry point address of exe file (its offset) and then cast that address (which is now loaded in a buffer) to a pointer-to-function and then call that, it probably would call the function loaded in ram but i don't know how to find the address .</p>
  
  <p>this is what I've done so far :</p>
  
  <pre><code>int main(){
  
      void (* function)();
      unsigned char* buffer;
      FILE* fp;
      size_t size;
      char* path = "address of the file";
      fp = fopen(path, "rb");
      fseek(fp, 0, SEEK_END); 
      size = ftell(fp);         /*calc the size needed*/
      fseek(fp, 0, SEEK_SET); 
      buffer = (unsigned char *) malloc(size);
      fclose(fp);
  
      /*problem : i have to sum the buffer address with that offset here*/
      function = (void (*)())(buffer);
  
      function();
  
      return 0;
  }
  </code></pre>
  
  <p>i think it's pretty much clear from the code what im trying to do .</p>
  
  <p>here is a link that tries to do the same thing for <code>meterpreter</code> (the idea is the same):</p>
  
  <p><a href="https://github.com/rsmudge/metasploit-loader/blob/master/src/main.c" rel="nofollow noreferrer">https://github.com/rsmudge/metasploit-loader/blob/master/src/main.c</a></p>
  
  <p>i'd appreciate any help .</p>
  
  <p>Thanks</p>