简体   繁体   中英

Error with address for jmp in inline assembly

What I do is

  1. Get address of ExitProcess
  2. Make space for opcode
  3. Modify opcode in the space
  4. Execute modified opcode by __asm__ ("jmp %%ecx"::"c"(opcode));

Here is my code:

#include <windows.h>
#include <stdio.h>
int main()
{
  char addr[4];
  *(int*)addr = GetProcAddress(GetModuleHandle("kernel32.dll"),"ExitProcess");

  //push 0 == 0x6a 0x00
  //call ExitProcess == 0xe8 0xd8 0x79 0xa2 0x75
  char opcode[400] = {0x6a, 0x00, 0xe8,addr[0], addr[1],addr[2],addr[3]};
  __asm__ ("jmp %%ecx" ::"c"(opcode));


  //never be here
  printf("never get here");
  getchar();
  return 0;
}

I expect program to exit normally, but the program terminates with a segmentation fault .

It seems that it jumps to somewhere, but not to the location I want it to jump.

How can I fix that?

Setting aside the odd thing you are trying to do...

Your problem is the opcode e8 is a relative jump. So you need to account for the address you are storing it at. Something like this maybe:

Update: Per taeyun, account for length of x.

#include <windows.h>
#include <stdio.h>

#pragma pack(1)

struct mfoo {
  unsigned char x[3] = {0x6a, 0x00, 0xe8};
  void *addr;
} foo;

int main()
{
  unsigned char *a = (unsigned char *)GetProcAddress(GetModuleHandle("kernel32.dll"),"ExitProcess");
  foo.addr = (void *)(a - sizeof(foo) - (unsigned char *)foo.x);

  __asm__ ("jmp *%%ecx" ::"c"(&foo));


  //never be here
  printf("never get here");
  getchar();
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM