gpt4 book ai didi

macos - 为什么下面的汇编代码不打印出换行符(0xa)?

转载 作者:行者123 更新时间:2023-12-02 04:25:17 27 4
gpt4 key购买 nike

在下面的代码中,NASM 按预期运行所有内容,除了在末尾打印新行字符。可能是什么原因?

%define sys_write       0x2000004           ; system call number for write
%define sys_read 0x2000003 ; system call number for read
%define sys_exit 0x2000001 ; system call number for exit
%define std_out 0x1 ; file descriptor number for standard output
%define std_in 0x2 ; file descriptor number for standard input
%define new_line 0xa ; a new line character
%define current_address $ ; address of current location

; a macro to implement the write system call and write
; a string into standard output using two parameters
%macro write_string 2
mov rax, sys_write ; system call to write
mov rdi, std_out ; standard output
mov rsi, %1 ; a string to write
mov rdx, %2 ; length of the string
syscall ; kernel call interruption
%endmacro

; a macro to implement the exit system call
%macro exit 0
mov rax, sys_exit ; system call to exit
syscall
%endmacro

section .data

message: db 'Displaying 9 stars', new_line ; a message
.length: equ current_address - message ; length of the message
asterisks: times 9 db '*' ; a string of 9 asterisks

global start

section .text

start: ; linker entry point

write_string message, message.length ; print a message to standard output
write_string asterisks, 9 ; print 9 asterisks
write_string new_line, 1 ; print a line feed(new line)

exit ; end the program

组装后:

user$ nasm -f macho64 9stars.asm
user$ ld 9stars.o -o 9stars
ld: warning: -macosx_version_min not specified, assuming 10.10
user$ ./9stars

预期输出应该是:

Displaying 9 stars
*********
user$

但当前输出是:

Displaying 9 stars
*********user$

看起来 write_string new_line, 1 没有将 new_line 视为字符常量尽管在 db 'Displaying 9 star', new_line 中,new_line 添加了一个换行符,字符代码 10。我最初的猜测是 new_line 根本不是字符常量。这可能是什么原因?如何解决这个问题?我使用的是 Mac OS X 10.10。我有英特尔酷睿 i5 m540 CPU。我使用 NASM 版本 2.11.06。

最佳答案

write_string 需要字符串的地址,但 new_line 只是字符值 0xa 。尝试将其解释为字符串的地址将产生不可预测的结果。如果您想要一个仅包含可以打印的单个 0xa 的字符串,那么您需要执行如下操作:

    section .data

message: db 'Displaying 9 stars', new_line ; a message
.length: equ current_address - message ; length of the message
asterisks: times 9 db '*' ; a string of 9 asterisks
newline: db new_line ; <<< a single LF

global start

section .text

start: ; linker entry point

write_string message, message.length ; print a message to standard output
write_string asterisks, 9 ; print 9 asterisks
write_string newline, 1 ; <<< print LF

关于macos - 为什么下面的汇编代码不打印出换行符(0xa)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27535437/

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