在下面的代码中,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 stars', new_line
中new_line
添加了新的字符,
字符代码10.我的初步猜测是new_line
根本不是字符常量。
这可能是什么原因?怎么能修好?我在Mac OS X 10.10上。我有
核心i5 m540 Intel CPU。我使用NASM版本2.11.06。
答案 0 :(得分:4)
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