阅读“专业汇编语言书”;它似乎提供了一个错误的代码来读取命令行参数。我纠正了一下,现在它从segfaulting到读取参数计数然后是segfaulting。
这是完整的代码:
.data
output1:
.asciz "There are %d params:\n"
output2:
.asciz "%s\n"
.text
.globl main
main:
movl 4(%esp), %ecx /* Get argument count. */
pushl %ecx
pushl $output1
call printf
addl $4, %esp /* remove output1 */
/* ECX was corrupted by the printf call,
pop it off the stack so that we get it's original
value. */
popl %ecx
/* We don't want to corrupt the stack pointer
as we move ebp to point to the next command-line
argument. */
movl %esp, %ebp
/* Remove argument count from EBP. */
addl $4, %ebp
pr_arg:
pushl (%ebp)
pushl $output2
call printf
addl $8, %esp /* remove output2 and current argument. */
addl $4, %ebp /* Jump to next argument. */
loop pr_arg
/* Done. */
pushl $0
call exit
书中的代码:
.section .data
output1:
.asciz “There are %d parameters:\n”
output2:
.asciz “%s\n”
.section .text
.globl _start
_start:
movl (%esp), %ecx
pushl %ecx
pushl $output1
call printf
addl $4, %esp
popl %ecx
movl %esp, %ebp
addl $4, %ebp
loop1:
pushl %ecx
pushl (%ebp)
pushl $output2
call printf
addl $8, %esp
popl %ecx
addl $4, %ebp
loop loop1
pushl $0
call exit
用GCC(gcc cmd.S
)编译,也许这就是问题所在? __libc_start_main以某种方式修改堆栈?不太确定......
更糟糕的是,尝试调试它以查看堆栈但GDB似乎抛出了许多与printf相关的东西(其中一个是printf.c: File not found
或类似的东西)。
答案 0 :(得分:2)
在@Michael的帮助下,我能够找到问题所在。
使用%ebp作为argv
正如@Michael建议的那样(尽管他使用了%eax
)。另一个问题是我需要将(%ebp)的值与0(空终止符)进行比较,然后在该点结束程序。
代码:
movl 8(%esp), %ebp /* Get argv. */
pr_arg:
cmpl $0, (%ebp)
je endit
pushl %ecx
pushl (%ebp)
pushl $output2
call printf
addl $8, %esp /* remove output2 and current argument. */
addl $4, %ebp
popl %ecx
loop pr_arg
ret