NASM Assembly OS X打印整数分段故障问题

时间:2015-02-01 21:52:54

标签: macos assembly printing nasm x86-64

我刚刚开始学习OS X上的x86程序集,我正在努力解决一个我认为与栈有关的问题。

我编写的程序非常简单 - 将两个数字加在一起然后打印结果。我一直试图避免使用任何C函数,但实际上我在调用printf时遇到了类似的问题。

我的汇编程序是:

    %define SYSCALL_WRITE 0x2000004
    %define SYSCALL_EXIT 0x2000001
    %define SYSCALL_READ 0x2000003

    section .data ;this is where constants go

    digits db   '0123456789'

    section .text          ;delcaring our .text segment

    global _main        ;telling where program execution should start

    _main:                 ;this is where code starts getting executed
            xor rax, rax   ;clears the registers - not sure why this is needed? check!
            xor rcx, rcx
            xor rdx, rdx
            xor r8, r8
            mov rax, 100
            mov rbx, 72
            add rax, rbx
            mov r8, 0
            jmp _numtostr

    _exit:
            mov rax, SYSCALL_EXIT
            mov rdi, 0
            syscall


    _numtostr:
            cmp rax, 0
            jne _convert
            jmp _print


    _convert:
            inc r8
            mov rcx, 10
            div rcx ; divide what is in the rax by 10
            push rdx ; put the remainder on the stack
            ;push rax
            ;lea rsi, [rel digits] ;load the effective address of digits
            ;add rsi, rdx ; add the computed value to get the correct digit of digits
            ;mov rdx, 1 ;number of words to output
            ;mov rdi, 1     ;stdout
            ;mov rax, SYSCALL_WRITE
            ;syscall
            ;pop rax
            jmp _numtostr


    _print:
            cmp r8, 0
            jne _output
            jmp _exit

    _output:
            pop rdx
            lea rsi, [rel digits] ;load the effective address of digits
            add rsi, rdx ; add the computed value to get the correct digit of digits
            mov rdx, 1 ;number of words to output
            mov rdi, 1     ;stdout
            mov rax, SYSCALL_WRITE
            syscall
            dec r8
            jmp _print

我希望我的主要内容过于复杂,但我感到困惑的是,在_convert部分我将剩余结果推送到堆栈然后在_output部分我突然出现其余的退出堆栈。但是,这不起作用,我收到segmentation fault: 11错误。

如果我取消注释程序工作的_convert部分中的代码 - 我将271172输出到命令行,这就是我所期望的。这就是让我觉得我从推送或拉出堆栈的方式存在问题,因为看起来有意义的是,当这段代码被注释掉时,我应该得到172(我想要的答案) )。

我已经读过OS X存在某种堆栈对齐问题,我想知道这是否与我遇到的情况有关?

非常感谢任何帮助。

0 个答案:

没有答案