gpt4 book ai didi

c - X86-64 NASM 调用 extern c 函数

转载 作者:太空宇宙 更新时间:2023-11-04 11:50:22 27 4
gpt4 key购买 nike

我对汇编很陌生,但懂一点 C。我正在玩外部函数调用,比如

extern _printf
str db "Hello", 0
push str
call _printf

但除了scanfprintf 外,找不到任何使用extern 函数的教程。如何调用 strcmp

最佳答案

这是我的答案。虽然它特定于 x86-64。请注意,将参数推送到函数时,通常将前 6 个放入寄存器 rdirsirdxrcxr8r9。其余的被插入堆栈。此规范称为 System V ABI(请注意,Windows 使用不同的约定,称为“Microsoft x64 调用约定”)。

    segment .data     ; or use .rodata for read-only data.
str1 db "Hello", 0x0
str2 db "Hellx", 0x0
fmt db "Comparison = %d", 0xa, 0x0

segment .text
global main
extern strcmp, printf
default rel ; RIP-relative addressing for [name] is what you want.

main:
; Create a stack-frame, re-aligning the stack to 16-byte alignment before calls
push rbp
mov rbp, rsp

; Prepare the arguments for strcmp.
lea rdi, [str1]
lea rsi, [str2]

; Call strcmp, return value is in rax.
call strcmp

; Prepare arguments for printf.
lea rdi, [fmt]
mov esi, eax ; int return value from strcmp -> 2nd arg for printf
xor eax, eax ; Indicate no floating point args to printf.

; Call printf
call printf

; Return 0 (EXIT_SUCCESS), and destroy the stack frame.
xor eax, eax
leave ; or just pop rbp because RSP is still pointing at the saved RBP
ret

关于c - X86-64 NASM 调用 extern c 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56240743/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com