gpt4 book ai didi

macos - 如何在asm中使用malloc

转载 作者:行者123 更新时间:2023-12-05 05:06:41 24 4
gpt4 key购买 nike

我正在尝试使用 malloc 在带有 nasm 的 asm Intel x86_64 中动态分配内存,但我不明白如何使用它。

例如,如果你想分配一个 8 字节的内存区域,我是否应该将 8 压入堆栈,然后调用 malloc,就像这样?

extern _malloc

section .text
global _my_function

_my_function:
push 20
call _malloc
ret

或者我应该将 20 移动到 rdi 寄存器,这通常是函数的第一个参数吗?

extern _malloc

section .text
global _my_function

_my_function:
mov rdi, 20
call _malloc
ret

我都试过了,但都没有用,而且我没有找到任何 nasm 的 malloc 文档。

我正在尝试使用 malloc 来重新编码字符串库中的 strdup 函数,这是我的实际代码:

extern _ft_strlen
extern _ft_strcpy
extern _malloc

section .text
global _ft_strdup

_ft_strdup:
push rsi
push rdi ; rdi = str
call _ft_strlen ; rax = ft_strlen(str)
mov r9, rdi ; save rdi (str) into r9
mov rdi, rax ; rdi = len
inc rdi ; rdi = len + 1
call _malloc ; rax = new_str (allocated)
cmp eax, 0 ; if malloc failed
je _failure ; └──► return NULL
mov rsi, r9 ; rsi = str
mov rdi, rax ; rdi = new_str
call _ft_strcpy ; ft_strcpy(new_str, str)
pop rdi
pop rsi
ret

_failure:
xor rax, rax
pop rdi
pop rsi
ret
section .text
global _ft_strcpy

_ft_strcpy:
push rdi
push rsi
jmp _loop

_loop:
mov r8b, BYTE [rdi] ; Save *dst into r8b
mov r9b, BYTE [rsi] ; Save *src into r8b
cmp r9b, 0 ; if *src == '\0'
je finish ; └──► exit from _loop
mov [rdi], r9 ; *dst = r9 (r9 = *src)
inc rdi ; dst++
inc rsi ; src++
jmp _loop

finish:
mov [rdi], r9 ; *dst = r9 (r9 = *src = '\0')
pop rsi
pop rdi
mov rax, rdi ; rax = initial value of dst
ret ; Return rax (dst pointer)
section .text
global _ft_strlen

_ft_strlen:
push rdi
xor rax, rax ; rax = 0
jmp _loop

_loop:
cmp [rdi], byte 0 ; if *str == '\0'
je finish ; └──► exit from _loop
inc rax ; rax++ (len)
inc rdi ; str++
jmp _loop

finish:
pop rdi
ret ; Return rax (len)

当我调用 ft_strdup 时,我从清理中得到一个SEGV on unknown address 0x000000000000错误。

我这样调用函数:

int main(int ac, char **av)
{
char new_str = ft_strdup(av[1]);
return (0);
}

最佳答案

解决方案- jester

Intel x86_64 和 nasm 的 Malloc 使用

  • 分配给 malloc 的字节进入 rdi 寄存器。
  • 返回指向 rax 寄存器中内存区域的指针。
mov rdi, 20
call _malloc

根据 standard calling convention您不能在调用 _ft_strlen 后依赖 rdi 的值,调用 _mallocr9 也是如此。这是因为两个寄存器都是 caller-saved .

保留r9的值

push r9
call _malloc
pop r9

汇编编程技巧

关于macos - 如何在asm中使用malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59697603/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com