带浮点的 Windows ASM printf

标签 windows assembly nasm x86-64 calling-convention

我一直在尝试用汇编程序与 Windows 中的标准 C 库进行交互,但遇到了麻烦。由于某种原因,我无法使 printf 接受浮点变量,所以这里出了问题。

这是我可以创建的演示该问题的最短程序。我添加了一些评论来解释我对应该发生的事情的理解。

谢谢

;
; Hello64.asm
; A simple program to print a floating point number in windows
;
; assemble: nasm float64.asm -f win64
; link: golink /console /entry main float64.obj MSVCRT.dll
;

; tell assembler to generate 64-bit code
;
bits 64

; data segment
section .data use64

pi  dq 3.14159

textformat: db "hello, %lf!",0x0a, 0x00     ; friendly greeting

; set up the .text segment for the code
section .text use64

; global main is the entry point
global main
; note that there is no _ before printf here, unlike in OS X
extern printf

main:
mov rcx, textformat 
movq xmm0, qword [pi]
mov rax, 1      ; need to tell printf how many floats
call printf

; note next step - this puts a zero in rax
xor rax,rax
ret ; this returns to the OS based on how Windows calls programs.
; this return causes a delay then the program exits.

最佳答案

您成功地混合了 microsoft 和 sysv 约定。正确的做法是:

mov rcx, textformat 
movq xmm1, qword [pi]
movq rdx, xmm1  ; duplicate into the integer register
sub rsp, 40     ; allocate shadow space and alignment (32+8)
call printf
add rsp, 40     ; restore stack
xor eax, eax
ret

根据MSDN ,当使用可变参数时:

For floating-point values only, both the integer and the floating-point register will contain the float value in case the callee expects the value in the integer registers.

关于带浮点的 Windows ASM printf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35943615/

相关文章:

linux - nasm 文件缓冲区的第二个和第三个元素始终为 0

c++ - 针对 windows 2000 的 visual studio 2012 win32 项目

c - 硬件处理器计数器重置不正确

c# - Windows 的声音管理器类

c - 在 NASM 中打印更大的数字

assembly - 了解 cmpxchg8b/cmpxchg16b 操作

assembly - 为什么在将立即值添加到内存地址处的值时需要消除歧义

c - Visual Studio 13 中的 NASM 设置

windows - Windows 用户的 Git CRLF

windows - 在Windows上混淆物理内存