2

通读《专业汇编语言书》;它似乎为读取命令行参数提供了错误的代码。我对其进行了一些纠正,现在它从段错误变为读取参数计数,然后是段错误。

这是完整的代码:

.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或类似的东西)。

4

1 回答 1

2

在@Michael 的帮助下,我能够找到问题所在。

argv正如@Michael 建议的那样使用 %ebp (尽管他使用过%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
于 2013-08-26T17:54:16.750 回答