【问题标题】:My strdup in ASM我在 ASM 中的 strdup
【发布时间】:2018-01-10 16:17:56
【问题描述】:

大家好,我学校的每个人我都必须在 ASM [intel] [NASM] 中执行我自己的 strdup 函数。

我有一个奇怪的问题......

如果我在我的代码中call _malloc

我的代码段错误出现此错误:

Program received signal SIGSEGV, Segmentation fault.
0x00007fff849612da in stack_not_16_byte_aligned_error () from /usr/lib/system/libdyld.dylib

我不明白为什么,因为在 .text 部分我说extern _malloc

有人知道我为什么会犯这个错误? :)

这是我的代码:

section .text
     global _ft_strdup
     extern _strlen
     extern _malloc
     ;  extern _ft_memcpy

_ft_strdup:
     call _strlen           ;rax = len of str
     mov r8, rdi            ;r8 = str = src
     inc rax                ;rax++
     ;  mov r9, rax         ;len of dest with '\0'
     mov rdi, rax           ;to send the len for malloc
     call _malloc           ;rax = ptr of dest
     ;  cmp rax, 0          ;malloc failled
     ;  jle _error_malloc
     ;  mov rdi, rax        ;malloc param 1 of ft_memcpy
     ;  mov rsi, r8         ;str in param 2 of ft_memcpy
     ;  mov rdx, r9         ;len of str with '\0' param 3 of ft_memcpy
     ;  call _ft_memcpy     ;call ft_memcpy
     ret
_error_malloc:
     xor rax, rax           ;return NULL
     ret

所有以ft_开头的函数都与libc Thx all 相同

【问题讨论】:

  • 至于关于您的问题的可能提示,您不知道stack_not_16_byte_aligned_error 可能意味着什么吗?也许您应该开始研究如何设置堆栈帧?
  • Fuz 的回答是正确的。作为一个实验,您可以尝试将堆栈对齐到 16 字节边界,只需将任何值压入堆栈并在最后将其弹出即可。例如,作为_ft_strdup 中的第一条指令放置push rbp,然后在每个ret 之前放置pop rbp
  • Fuz 和 Michael Petch,我没有段错误了,看起来我一直在检查 thx :)

标签: macos assembly nasm x86-64 glibc


【解决方案1】:

此错误消息表明您调用 malloc 时堆栈对齐不充分。 amd64 的 SysV-ABI 要求堆栈在函数调用时与 16 字节对齐。

在您自己的代码中,您可以通过确保始终将偶数个四字压入堆栈来确保这一点,并记住在进入时,由于返回地址已经在堆栈上,堆栈未对齐 8 个字节.

没有看到您的源代码,很难提供更具体的帮助。

【讨论】:

    猜你喜欢
    • 2021-07-11
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    • 2017-02-03
    • 2010-09-20
    • 2018-05-14
    相关资源
    最近更新 更多