GCC内联汇编为二进制数组

时间:2018-06-26 11:53:55

标签: c gcc inline-assembly

GCC中是否可以将内联__asm__表示为char[]数组?我想要类似的东西:

void my_func();

char my_code[] = {
    __asm__("callq %0" :: "r" (my_func))
};

以后的my_code将用作运行时补丁,即

void another_function();
mprotect(another_function, getpagesize(), PROT_WRITE | PROT_READ | PROT_EXEC);
memcpy(another_function + offset, my_code, sizeof(my_code));

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您可以只定义一个函数,对其进行编译,然后获取其源机器代码?

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>

void my_func(void) {}

extern void my_code(void);
extern void my_code_end(void);

__attribute__((__used__)) static void _my_code(void) {
        asm volatile(
                ".globl my_code\n"
                "my_code:\n"
                "  callq *%0\n"
                "  nop\n"
                "  ret\n"
                ".globl my_code_end\n"
                "my_code_end:\n"
                :: "r" (my_func)
        );
}

int main() {
        size_t my_code_len = (uintptr_t)my_code_end - (uintptr_t)my_code;
        const unsigned char *arr = (const char*)my_code;
        printf("my_code[%zu]=", my_code_len);
        for (size_t i = 0; i < my_code_len; ++i) {
                printf("%02x", arr[i]);
        }
        printf("\n");
        return 0;
}

示例输出:

my_code[4]=ffd090c3

我们可以从程序集输出中检查它是否正常:

$ objdump -D ./a.out
...
0000000000000727 <my_code>:
 727:   ff d0                   callq  *%rax
 729:   90                      nop
 72a:   c3                      retq   
...