代码之家  ›  专栏  ›  技术社区  ›  ivaigult

gcc内联程序集作为二进制数组

  •  0
  • ivaigult  · 技术社区  · 6 年前

    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 回复  |  直到 6 年前
        1
  •  2
  •   KamilCuk    6 年前

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

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