macos - 为什么我的 x86 链表函数会抛出段错误?

标签 macos assembly return stack x86-64

我整天都在写代码,试图在 x86 汇编中获取链表。什么都不起作用,这非常令人沮丧。我正在尝试制作一个包含元素 1、2 和 3 的元素。GDB 告诉我它在 ret 中出现段错误。声明于end ,但没有提供更多信息。谁能帮我这个?我正在 Mac 上使用 Clang 进行组装。

这是我的代码:

    .global _main
    .text

/*
r12: result
r14: number of elements left in list
r15: stack offset for accessing arguments
*/

make_list:
    # # # # #
    push rbp
    mov rbp, rsp
    # # # # #
    mov rdi, [rbp + r15]
    mov qword ptr [rax], rdi  # assign first_node.head
    lea r13, [rax + 8]  # store address of first_node.tail
    # # # # #
    mov rdi, 16
    sub rsp, 8
    call _malloc
    add rsp, 8
    # # # # #
    add r15, 8
    sub r14, 1
    # # # # #
    mov rdi, [rbp + r15]
    mov qword ptr [r13], rdi  # assign second_node.head
    # # # # #
    cmp r14, 0
    je end
    # # # # #
    mov rdi, 16
    sub rsp, 8
    call _malloc
    add rsp, 8
    # # # # #
    jmp make_list  # assign second_node.tail to an argument
    # # # # #
    end:
        mov qword ptr [r13 + 8], 0  # second_node.tail = NULL
        mov rsp, rbp
        pop rbp
        ret
    # # # # #

_main:
    # # # # #
    mov rdi, 16
    sub rsp, 8
    call _malloc
    add rsp, 8
    lea r12, [rax]
    # # # # #
    mov r14, 3
    mov r15, 16
    # # # # #
    push 3
    push 2
    push 1
    # # # # #
    call make_list
    add rsp, 24
    # # # # #
    mov rdi, 0
    mov rax, 0x2000001
    syscall
    # # # # #

最佳答案

jmp make_list 指令不正确。您不想跳转到函数的开头,在那里您再次使用 rbp,而是在完成所有设置后跳转到函数中途的某个位置。

ret 之前未弹出的多个 push rbp 指令会导致指令指针在其中获取无效值,从而导致设置错误。

关于macos - 为什么我的 x86 链表函数会抛出段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64490054/

相关文章:

r - "Permission denied"播放WAV文件时

Linux Assembly x86_64 使用命令行参数创建文件

javascript - return func() 或 return func without () 形式 func(),代码会发生什么情况?

c++ - 如何使用 MSVC++ for x86-32 获得有效的 asm 来归零一个微小的结构?

javascript - 如何在javascript中1秒后递增变量

function - PowerShell 将其他值添加到函数的返回值中

ios - 避免静态库中的符号引用

macos - 单击按钮时应用程序崩溃

macos - 找不到 Doxygen(缺少 : DOXYGEN_EXECUTABLE) in Mac OS X

gcc - .s(小写)和 .S(大写)汇编文件之间的预期含义是否存在差异?