使用x86_64 GNU汇编(非NASM)通过系统调用写文件的问题解决
x86_64 GNU汇编文件写入问题解决过程
前置说明
- 本文不使用NASM语法,同类问题多采用NASM语法,但本人不熟悉该语法。
问题场景
尝试用x86_64 GNU汇编通过open、write系统调用写入txt文件,未达到预期效果。使用的编译命令如下:
sudo as -o db.o db.S sudo ld -s -o db db.o ./db
调试与解决过程
核心关注函数为write_to_txt_file,调试步骤如下:
- 通过gdb调试发现,write流程中第一个系统调用后
%rax返回值为-22; - 使用strace工具分析,调整后错误码变为-2,程序无法定位同目录下的目标txt文件;
- 对比
strace cat database.txt和strace tee database.txt的输出,排查参数差异; - 将filename移至数据声明顶部后,再次用strace分析;
- 问题已解决,以下是可用的实现代码:
write_to_txt_file: #%rdi must hold an address to a character array, like mov $buf, %rdi #%rsi must hold %rdi's length, like mov $tlen, %rsi push %rdi push %rsi #open file: mov $0x2, %rax mov $filename, %rdi mov $0x61, %rdx mov $0x441, %rsi syscall mov %rax, %r8 #write to file: mov $0x1, %rax mov %r8, %rdi pop %r13 #contents of %rdi which were pushed onto the stack get popped into %r12 pop %r12 #^^same but with length mov %r12, %rsi mov %r13, %rdx syscall ret
内容的提问来源于stack exchange,提问作者JBatswani
相关产品推荐
相关产品推荐

