c - 运行机器代码时出现模糊的运行时错误

标签 c windows runtime machine-code

我需要帮助弄清楚为什么当我尝试运行机器代码时会在运行时崩溃。代码在“3”和“result = %li”之间崩溃。

注意:假设所有代码都经过错误检查。为了人们阅读本文,我删除了错误检查代码。

机器规范:

Windows 10 Home 64-bit
Intel(R) Core(TM) i7-4712MQ

我正在运行的代码:

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

int main(int argc, char** argv) {

  printf("Loading code\n");

  LPVOID m = VirtualAlloc(NULL, 16, MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE);

  printf("1\n");

  unsigned char code[] = {
    //return x+2;

    0x55,                      //push   %rbp
    0xe5, 0x89, 0x48,          //mov    %rsp,%rbp
    0xc8, 0x89,                //movl    %ecx,%eax
    0x02, 0xc0, 0x83,          //add    $0x2,%eax
    0xc9,                      //leaveq
    0xc3,                      //retq
    0x90                       //nop
  };
  memcpy(m, code, sizeof(code)); 

  printf("2\n");

  PDWORD trash;
  VirtualProtect(m, 16, PAGE_EXECUTE_READ, trash); 

  printf("3\n");

  long int (*addTwo)(long int) = m;
  long int answer = addTwo(2);
  printf("result = %li\n", answer);

  VirtualFree(m, 0, MEM_RELEASE);
  return 0;
}

最佳答案

看来您正在使用堆栈上的内存来存储自动变量:

0x10, 0x4d, 0x89,           //mov    %ecx,0x10(%rbp)
0x10, 0x45, 0x8b,            //mov    0x10(%rbp),%eax

但是你的偏移量是错误的,将0x10添加到%rpb将使结果地址指向之前的堆栈帧;要指向局部变量,您应该从 BP 中减去。此外,您甚至不需要为此使用堆栈,只需执行 movl %ecx, %eax 即可。

关于c - 运行机器代码时出现模糊的运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37357596/

相关文章:

c - 递归 - 数据结构类(class) - 打印所有可能的系列

c - C中的结构和列表

c - 我在此代码中收到错误 "invalid indirection"

java - CMD 正在关闭并且不让看到结果(Java,从 .bat 运行 .jar)

c++ - CreateFile 能否返回 NULL?

java - 在 Windows 上克隆 java 应用程序

C-Linux : list sparse files and print 0-filled disk blocks

windows - 当我在 docker 中运行 `docker run hello-world` 时,连接的主机没有响应

objective-c - 如何通过指针/内存地址取消引用 Objective-C 对象?

grails - 在运行时动态设置Grails DataSource到内存中的H2实例