最近想给一个项目加入反汇编功能,由于我们用的反汇编器是LLVM实现的,所以就学习一下LLVM的MCDisassembler. 以下代码用的是C的接口。
代码:
// gcc -g -Wall -o disas-c disas-c.c -lLLVM
#include <llvm-c/Disassembler.h>
#include <llvm-c/Target.h>
#include <stdio.h>
int main()
{
// instruction bytes, but only one instruction is disassembled
uint8_t instBytes[] = { 0x48, 0x31, 0xc0, 0xcc }; // xor rax, rax; int3
// we need to reserve enough space, otherwise the disasm output will be truncated
char disasm[20];
// Initialize all the essential things
LLVMInitializeX86TargetInfo();
// We don't need LLVMInitializeX86Target();
LLVMInitializeX86TargetMC();
// We don't need LLVMInitializeX86AsmPrinter();
LLVMInitializeX86Disassembler();
LLVMDisasmContextRef disassembler = LLVMCreateDisasm("x86_64", NULL, 0, NULL, NULL);
if (!disassembler) {
fprintf(stderr, "Failed to create a disassembler.\n");
return 1;
}
// use Intel syntax, default is AT&T
if (!LLVMSetDisasmOptions(disassembler, LLVMDisassembler_Option_AsmPrinterVariant)) {
fprintf(stderr, "Failed to set disassembler printer variant.\n");
}
size_t disasm_bytes = LLVMDisasmInstruction(disassembler, instBytes, sizeof(instBytes), /*pc*/ 0, disasm, 20);
printf("%s\n", disasm);
printf("%ld bytes disassembled.\n", disasm_bytes);
// free the Disasm context
LLVMDisasmDispose(disassembler);
}