title: c generate function and call it
body: <pre><code>#include &lt;stdio.h&gt;
  
  #define uint unsigned int
  #define AddressOfLabel(sectionname,out) __asm{mov [out],offset sectionname};
  
  void* CreateFunction(void* start,void *end) {
      uint __start=(uint)start,__end=(uint)end-1
          ,size,__func_runtime;
      void* func_runtime=malloc(size=(((__end)-(__start)))+1);
      __func_runtime=(uint)func_runtime;
      memcpy((void*)(__func_runtime),start,size);
      ((char*)func_runtime)[size]=0xC3; //ret
      return func_runtime;
  }
  void CallRuntimeFunction(void* address) {
      __asm {
          call address
      }
  }
  
  main() {
      void* _start,*_end;
      AddressOfLabel(__start,_start);
      AddressOfLabel(__end,_end);
      void* func = CreateFunction(_start,_end);
      CallRuntimeFunction(func); //I expected this method to print &quot;Test&quot;
      //but this method raised exception
      return 0;
  __start:
      printf(&quot;Test&quot;);
  __end:
  }
  </code></pre>
  <p><code>CreateFunction</code> - takes two points in memory (function scope), allocate, copy it to the allocated memory and returns it (The <code>void*</code> used like a function to call with Assembly)</p>
  <p><code>CallRuntimeFunction</code> - runs the functions that returns from <code>CreateFunction</code></p>
  <p><code>#define AddressOfLabel(sectionname,out)</code> - Outs the address of label (sectionname) to variable (out)</p>
  <p>When I debugged this code and stepped in the call of <code>CallRuntimeFunction</code> and go to disassembly ,
  I saw alot of <code>???</code> instead of assembly code of between <code>__start</code> and <code>__end</code> labels.</p>
  <p>I tried to copy machine code between two labels and then run it. But I don't have any idea why I can't call function that allocated with <code>malloc</code>.</p>
  <h3>Edit:</h3>
  <p>I changed some code and done part of the work.
  Runtime Function's memory allocate:</p>
  <pre><code>void* func_runtime=VirtualAlloc(0, size=(((__end)-(__start)))+1, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  </code></pre>
  <p>Copy from function scope:</p>
  <pre><code>CopyMemory((void*)(__func_runtime),start,size-1);
  </code></pre>
  <p>But when I ran this program I can that:</p>
  <pre><code>mov         esi,esp  
  push        0E4FD14h  
  call        dword ptr ds:[0E55598h] ; &lt;--- printf ,after that I don't know what is it
  add         esp,4  
  cmp         esi,esp  
  call        000B9DBB  ; &lt;--- here
  mov         dword ptr [ebp-198h],0  
  lea         ecx,[ebp-34h]  
  call        000B9C17  
  mov         eax,dword ptr [ebp-198h]
  jmp         000D01CB  
  ret  
  </code></pre>
  <p>At <code>here</code> it enters to another function and weird stuff.</p>