这是macos 64位的itoa实现。 Itoa需要strdup,这需要strlen,如果需要它们,我也会发布它们。
紧张:
section .text
global _ft_strlen
_ft_strlen:
push rbp
mov rbp, rsp
push rdi
mov rcx, -1
xor al, al
cld
repne scasb
not rcx
lea rax, [rcx - 1]
pop rdi
leave
ret
strdup:
section .text
global _ft_strdup
extern _ft_strlen
extern _malloc
_ft_strdup:
push rbp
mov rbp, rsp
push rdi
call _ft_strlen
inc rax
push rax
mov rdi, rax
call _malloc
test rax, rax
jz .end
pop rcx
pop rsi
mov rdi, rax
rep movsb
.end:
leave
ret
itoa:
default rel
section .data
buffer times 11 db 0
section .text
global _ft_itoa
extern _ft_strdup
_ft_itoa:
push rbp
mov rbp, rsp
xor rcx, rcx ;initialize counter
xor r9, r9 ;set neg flag to 0
mov eax, edi ;move number in RAX for DIV instruction
push rbx ;save RBX
mov ebx, 10
.check_negative:
and edi, 0x80000000
lea rdi, [buffer]
jz .divide ;number is positive, proceed to main loop
not eax ;else
inc eax ;compute absolute value with binary complement
inc r9 ;set neg flag
.divide:
xor edx, edx
div ebx
add edx, 48 ;convert int to char
push rdx
inc rcx
cmp eax, 0
jnz .divide
.check_neg_flag:
cmp r9, 1
jne .buff_string
mov byte[rdi], '-'
.buff_string:
pop rdx
mov byte[rdi + r9], dl
dec rcx
inc r9
cmp rcx, 0
jnz .buff_string
pop rbx ;IF THIS LINE IS SET, IT WORKS FINE
.dup:
mov byte[rdi + r9], 0
call _ft_strdup ;copy buffer string in memory and return pointer
pop rbx ;IF THIS LINE IS SET, SEGFAULT OCCURS
leave
ret
在函数开始时,我将RBX压入堆栈,因为我将在函数中使用它。在函数末尾,我的字符串被抛光,并且我正在调用strdup分配内存空间并将字符串复制到那里。如果我随后弹出RBX来清理堆栈,则会出现功能段错误。但是,如果我在调用strdup之前弹出它,则一切正常。
我在strdup或strlen中都不使用RBX。
为什么会这样?