assembly - 在 x86_64 程序集中将一个 .data 和一个 .bss 字符串连接在一起
问题描述
我正在编写一个程序,询问您的姓名,然后将其打印出来,如下所示:
<name> is your name?
这是我当前的代码:
section .data
promptText: db "What is your name: ", 0
promptTextLength: equ $ - promptText
secondText: db " is your name?", 0
section .bss
name resb 15
section .text:
global _start
_start:
; Print prompt message
mov rax, 1
mov rdi, 1
mov rsi, promptText
mov rdx, promptTextLength
syscall
; Get name
mov rax, 0
mov rdi, 0
mov rsi, name
mov rdx, 15
syscall
; Somehow concatenate "name" and "secondText"
; Print second message
mov rax, 1
mov rdi, 1
mov rsi, nameAndSecondText
mov rdx, nameAndSecondTextLength
syscall
; Exit 0
mov rax, 60
mov rdi, 0
syscall
因此,几乎添加name
and secondText
,然后将它们打印到终端。
然而,
我不想只调用SYS_WRITE
两次,要打印两个字符串,我需要将它们组合name
成secondText
自己的变量。
谢谢!
PS 抱歉,如果我使用了错误的术语,我已经习惯了更高级别的语言,如 Python、C 等。
解决方案
您不需要字符串的终止 NUL,因为您不使用检查此字符的函数。
删除中的冒号section .text:
。然后就可以用 GDB 调试程序了。
我建议secondText
直接附加到输入的名称。为此,您必须为变量保留更多空间name
。SYS_READ 没有注意到这一点,因此在调用 SYS_READ 之后空格保持空白。
section .data
promptText: db "What is your name: "
promptTextLength: equ $ - promptText
secondText: db " is your name?", 10
secondTextLength: equ $ - secondText
section .bss
name resb 15 + secondTextLength ; Space for input and appended string
section .text
global _start
_start:
; Print prompt message
mov rax, 1 ; SYS_WRITE - http://man7.org/linux/man-pages/man2/write.2.html
mov rdi, 1 ; fd = STDOUT
mov rsi, promptText ; *buf
mov rdx, promptTextLength ; Count of bytes to write
syscall ; Call Linux
; Get name
mov rax, 0 ; SYS_READ - http://man7.org/linux/man-pages/man2/read.2.html
mov rdi, 0 ; fd = STDIN
mov rsi, name ; *buf
mov rdx, 15 ; Max count of bytes to read
syscall ; Call Linux - return EAX = number of bytes read
dec rax ; number of bytes read without ENTER
; Append secondText
mov rsi, secondText ; *source
mov rdi, name ; *dest
add rdi, rax ; Set pointer one byte behind the real name
mov rcx, secondTextLength ; Count of bytes to copy
lea rbx, [rax + rcx] ; Save the total length of the string
rep movsb ; Copy RCX bytes from [RSI] to [RDI]
; Print name (input + second message)
mov rax, 1 ; SYS_WRITE - http://man7.org/linux/man-pages/man2/write.2.html
mov rdi, 1 ; fd = STDOUT
mov rsi, name ; *buf
mov rdx, rbx ; Count of bytes to write (RBX was saved above)
syscall ; Call Linux
; Exit (0)
mov rax, 60 ; SYS_EXIT
mov rdi, 0 ; Exitcode
syscall ; Call Linux / no return
推荐阅读
- sql - 当插入记录时无法访问远程磁盘上的文件时会发生什么?
- c++ - 我可以将智能指针作为函数参数传递给生成顶点数组吗
- python - 通过flask App在heroku服务器中上传mongodb中的图片文件
- rest - REST API URL 设计最佳实践
- android - 如何在片段中添加浮动操作按钮?
- python - 不同形状的 Pandas 堆叠条形图
- batch-file - 自动生成的日期时间日志
- bootstrap-4 - 让文本不包含在 2 列的引导行内
- ndepend - 找不到要分析的程序集。NDepend 只会分析生成 PDB 文件的程序集
- python - 如何更改 matplotlib 中的轴标签?