加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何在不创建新进程的情况下运行汇编代码?

发布时间:2020-12-16 10:22:08 所属栏目:百科 来源:网络整理
导读:该文件包含本机程序集代码,我想在当前进程中运行它. 但我不想创建一个真正的文件(.com或.exe),所以我试过: ...using namespace std;typedef void bitcode();void testcode(){ cout"test";};int main(){ bitcode *c=testcode; // bitcode *c stands for the
该文件包含本机程序集代码,我想在当前进程中运行它.
但我不想创建一个真正的文件(.com或.exe),所以我试过:

...
using namespace std;
typedef void bitcode();
void testcode(){
    cout<<"test";
};
int main()
{
    bitcode *c=&testcode; // bitcode *c stands for the file containing the assembly code.
    bitcode *d=reinterpret_cast<bitcode*> (malloc(20));
    memcpy(d,c,20);
    d(); // it doesn't work
    return 0;
};

但是,当我调用d();它时它不起作用.我想知道用C/C++做这个的正确方法是什么.

(我在Windows上,如果你能告诉我如何在Linux上制作它,我会非常感激)

非常感谢!

PS:我不是要求“在没有创建新流程的情况下在另一个流程中运行可执行文件”.

解决方法

在Windows上,这是我之前写的代码.它至少在我的机器上适用于Win7 VS2010.

基本思想是调用VirtualAlloc以使用PAGE_EXECUTE_READWRITE标志分配内存.
并以正确的方式调用它,即保持堆栈平衡.

#include "stdafx.h"
#include "windows.h"


int emitcode[] = 
{0x83ec8b55,0x565340ec,0x0c758b57,0x8b087d8b,0x348d104d,0xcf3c8dce,0x6f0fd9f7,0x6f0fce04,0x0f08ce4c,0x10ce546f,0xce5c6f0f,0x646f0f18,0x6f0f20ce,0x0f28ce6c,0x30ce746f,0xce7c6f0f,0x04e70f38,0x4ce70fcf,0xe70f08cf,0x0f10cf54,0x18cf5ce7,0xcf64e70f,0x6ce70f20,0xe70f28cf,0x0f30cf74,0x38cf7ce7,0x7508c183,0xf8ae0fad,0x5e5f770f,0x5de58b5b,0xccccccc3};

int _tmain(int argc,_TCHAR* argv[])
{
    int *src = new int[64];
    int *dst = new int[64];
    int *dst2 = new int[64];

    for (int i = 0; i < 64; ++i){
        src[i] = i;
    }

    //fastercopy(dst,src,64/2);

    void* address = NULL;
    address= VirtualAlloc(NULL,sizeof(emitcode),MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE);

    memcpy(address,emitcode,sizeof(emitcode));

    //call emit code from assemble
    __asm {
      push        20h  
      mov         eax,dword ptr [src]  
      push        eax  
      mov         ecx,dword ptr [dst]  
      push        ecx
      mov         ecx,dword ptr [address]
      call        ecx
      add         esp,0Ch 
    }

    for (int i = 0; i < 64; ++i){
        printf("%d ",dst[i]);
    }

    //call emit code from function pointer
    typedef void (*FASTCALL)(void* dst,void* src,int len);
    FASTCALL fastcall;
    fastcall = (FASTCALL)address;
    fastcall(dst2,64/2);

    printf("n");
    for (int i = 0; i < 64; ++i){
        printf("%d ",dst2[i]);
    }

    return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读