GCC 内联汇编作为二进制数组

GCC inline assembly as binary array

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));

有什么想法吗?

你可以只定义一个函数,编译它,然后得到它的源机器码吗?

#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   
...