且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C ++中将汇编转换为机器代码

更新时间:2023-02-10 23:29:31

想要:



您要在运行时生成机器码吗?然后使用一些 JIT编辑库,例如 libjit LLVM GNU闪电 asmjit asmjit 是一个发出x86机器码的库,大概是你需要的。没有绝对需要使用包含汇编代码的字符串



还是要翻译一些汇编语法语法甚至x86)到对象代码或机器代码?然后你***运行一个真正的汇编程序作为外部程序。生成的对象代码将包含 relocation 指令,您需要处理这些指令(例如 dlopen(3) dlsym )。请参见



详细信息显然是操作系统, a href =https://en.wikipedia.org/wiki/Application_binary_interface =nofollow> ABI 和处理器专用。


I seek for any lib or function to convert a string of assembly code to machine code, like the following:

char asmString[] = {"mov eax,13H"};
byte[] output; // array of byte
output = asm2mach(asmString); // {0xB8, 0x13, 0x00, 0x00, 0x00}

The motivation is to inject machine code to call asm function in the program. This injection mainly has 3 steps: VirtualAllocEx, WriteProcessMemory and CreateRemoteThread. Here are the code:

bool injectAsm(const char* exeName,const byte* code, int size) 
{ 
    LPVOID allocAddr = NULL;
    HANDLE ThreadProcess = NULL;
    HANDLE hProcess = OpenProcessEasy(exeName);

    allocAddr = VirtualAllocEx(hProcess, NULL, size, MEM_COMMIT, PAGE_READWRITE);
    if(allocAddr){
        if(WriteProcessMemory(hProcess, allocAddr, code, size, NULL)) {
            ThreadProcess = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)allocAddr, NULL, 0, NULL);
            WaitForSingleObject(ThreadProcess, INFINITE);
            VirtualFreeEx(hProcess,allocAddr, 0, MEM_RELEASE);
            CloseHandle(ThreadProcess);
            return true;
        }
    }
    if(allocAddr){
        VirtualFreeEx(hProcess, allocAddr, 0, MEM_RELEASE);
    }
    return false;
}

int main()
{
    byte code[] = {0xB8, 0x10, 0xED, 0x4A, 0x00, 0xFF, 0xD0, 0xC3, 0x90};
    injectAsm("game.exe",code,sizeof(code));
    system("pause");
    return 0;
} 

You should define what you really want:

Do you want to generate machine code at runtime? Then use some JIT compilation library like libjit, LLVM, GNU lightning, or asmjit. asmjit is a library emitting x86 machine code, probably what you need. There is no absolute need to use a string containing assembler code.

Or do you want to translate some assembler syntax (and there are several assembler syntaxes even for x86) to object code or machine code? Then you'll better run a real assembler as an external program. The produced object code will contain relocation directives, and you'll need something to handle these (e.g. a linker).

Alternative, you should consider generating some (e.g.) C code at runtime, then forking a compilation, and dynamically loading and using the resulting function at runtime (e.g. with dlopen(3) and dlsym). See this

Details are obviously operating system, ABI, and processor specific.