首页 > 解决方案 > 从程序集中调用 libc 函数

问题描述

我在程序集中定义了一个调用 libc 函数(swapcontext)的函数。我从我的 C 代码中调用该函数。为了创建可重现的示例,我使用“puts”代替:

富.S:

.globl foo 
foo:
    call puts
    ret

测试.c:

void foo(char *str);

int main() {
    foo("Hello World\n");
    return 0;
}

编译:

gcc test.c foo.S  -o test

这编译得很好。然而,反汇编结果二进制显示链接器没有插入有效的调用指令:

objdump -dR:

0000000000000671 <foo>:
 671:   e8 00 00 00 00          callq  676 <foo+0x5>
            672: R_X86_64_PC32  puts@GLIBC_2.2.5-0x4
 676:   c3                      retq   
 677:   66 0f 1f 84 00 00 00    nopw   0x0(%rax,%rax,1)
 67e:   00 00 

0000000000000530 <puts@plt>:
 530:   ff 25 9a 0a 20 00       jmpq   *0x200a9a(%rip)        # 200fd0 <puts@GLIBC_2.2.5>
 536:   68 00 00 00 00          pushq  $0x0
 53b:   e9 e0 ff ff ff          jmpq   520 <.plt>

执行:

./test1: Symbol `puts' causes overflow in R_X86_64_PC32 relocation
Segmentation fault

任何想法为什么?

标签: cassemblyexternlibc

解决方案


对于您更新的完全独立的问题,它取代了您关于拆卸 a 的问题.o

半相关:函数指针局部变量的意外值提到了链接器在非 PIE 中为您转换对的引用(因为如果静态链接可以让您获得高效的代码),但在 PIE 中没有putsputs@plt

libc 被映射到距离主可执行文件超过 2GiB 的位置,因此 acall rel32无法访问它。

另请参阅Can't call C standard library function on 64-bit Linux from assembly (yasm) code,其中显示了 AT&T 和 NASM 语法,用于通过 PLTcall puts@pltgcc -fno-plt样式从 PIE 可执行文件调用 libc 函数call *puts@gotpcrel(%rip)


推荐阅读