title: Shellcode in ARM crashes when called by function which is not 'main()'
body: <p>When I execute the shellcode in the main function, it works fine. However, when I execute it by other function called by main, it will cause Segmentation fault. As far as I know, function call should influence the stack, and the shellcode should be in the heap. Is there something wrong in my code?</p>
  <p>The shellcode is generated by matesploit, and I use qemu-arm to run the program.</p>
  <p>The code is:</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;memory.h&gt;
  
  // msfvenom -p linux/armle/exec CMD=/bin/pwd -f c
  unsigned char buf[] = 
  &quot;\x01\x30\x8f\xe2\x13\xff\x2f\xe1\x78\x46\x0a\x30\x01\x90\x01&quot;
  &quot;\xa9\x92\x1a\x0b\x27\x01\xdf\x2f\x62\x69\x6e\x2f\x70\x77\x64&quot;;
  
  void runShellCode(){
      unsigned char *pShellCode = (unsigned char *)calloc(1, 4096);
      memcpy(pShellCode, buf, sizeof(buf));
      (*(void(*)()) pShellCode)();
  }
  
  int main(int argc, char *argv[])
  {
      // uncomment these lines it will work perfectly fine
      // unsigned char *pShellCode = (unsigned char *)calloc(1, 4096);
      // memcpy(pShellCode, buf, sizeof(buf));
      // (*(void(*)()) pShellCode)();
  
      runShellCode();
      return 0;
  }
  </code></pre>
  <p>The cmd to compile &amp; run:</p>
  <pre><code>arm-linux-gnueabi-gcc test.c -o test_arm -static
  qemu-arm test_arm
  </code></pre>
  <p>The disassembly code of the shellcode(which is uncorrect so I delete it)</p>
  <hr />
  <p>Update the code with mmap() way. However, if the argment of the main() is <code>void</code>, it works fine. While the argument is <code>int argc, char *argv[]</code>, it will cause SEGV.</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;memory.h&gt;
  #include &lt;sys/mman.h&gt;
  
  // msfvenom -p linux/armle/exec CMD=/bin/pwd -f c
  unsigned char buf[] = 
  &quot;\x01\x30\x8f\xe2\x13\xff\x2f\xe1\x78\x46\x0a\x30\x01\x90\x01&quot;
  &quot;\xa9\x92\x1a\x0b\x27\x01\xdf\x2f\x62\x69\x6e\x2f\x70\x77\x64&quot;;
  
  int main(int argc, char *argv[])
  //int main(void)
  {
      unsigned char *pShellCode = (unsigned char *)calloc(1, 4096);
      memcpy(pShellCode, buf, sizeof(buf));
      
      void (*sc) () = NULL;
      sc = mmap (0, 4096, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
      memcpy (sc, pShellCode, 4096);
      __builtin___clear_cache (sc, sc + sizeof(sc));
      sc();
  
      return 0;
  }
  </code></pre>