X86-64 NASM调用外部C函数 [英] X86-64 NASM calling extern c functions

查看:144
本文介绍了X86-64 NASM调用外部C函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对汇编语言很陌生,但是对c有一点了解.我正在玩外部函数调用,如

Im very new to assembly but know a bit of c. Im playing around with extern function calls like

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

但是找不到使用外部函数的任何教程,除了scanf和printf之外.例如strcmp?我该如何呼叫strcmp?

but cant find any tutorials using extern functions except scanf and printf. For example strcmp? How can i call strcmp in my case?

推荐答案

这是我的答案.但是它特定于x86-64.请注意,将参数推入函数时,通常将前6个放在寄存器rdirsirdxrcxr8r9中.其余的将被推入堆栈.对此的规范称为System V ABI(请注意,Windows使用另一种约定,称为"Microsoft x64调用约定").

Here is my answer. It is specific to x86-64 though. Please know that when pushing arguments to a function, you usually place the first 6 in registers rdi, rsi, rdx, rcx, r8, and r9. The rest get pushed to the stack. The specification for this is called the System V ABI (Note that Windows uses a different convention called the "Microsoft x64 Calling Convention").

    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

这篇关于X86-64 NASM调用外部C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆