So i am trying to write basic string to integer function in x86 asm. I know there is a problem in my function str2int but i don't know which state causes error.
#string2integer.s
.data
number: .long 0
.globl str2int
.type str2int, @function
# eax -> Current char to int value
# ebx -> Multiplier value(starting from 1)
# ecx -> counter
# edi -> address value
str2int:
pushl %ebp
movl %esp, %ebp
# address of base char*
movl 8(%ebp), %edi
# calculate the last index of char*
pushl 8(%ebp)
call count_chars
addl $4, %esp
# load last index to register ecx
movl %eax, %ecx
decl %ecx
# set up ebx for base 1
movl $1, %ebx
str2int_lp:
cmpl $0, %ecx
jz str2int_end
movzbl (%edi,%ecx,1), %eax
subl $'0', %eax
#
imull %ebx, %eax
addl %eax, number
# set up registers for next step
decl %ecx
imull $10, %ebx
jmp str2int_lp
str2int_end:
movl number, %eax
movl %ebp, %esp
popl %ebp
ret
and this is my test.c file
#include <stdio.h>
#include <stdlib.h>
extern int str2int(char*);
int main() {
char str[] = "331";
printf("%d\n", str2int(str));
return 0;
}
This is the info registers output from GDB before running the str2int function
eax 0x0 0
ecx 0xffffc1d0 -15920
edx 0xffffc1f0 -15888
ebx 0x56558fd4 1448447956
esp 0xffffc1a0 0xffffc1a0
ebp 0xffffc1b8 0xffffc1b8
esi 0xffffc28c -15732
edi 0xf7ffcb60 -134231200
eip 0x565561e6 0x565561e6 <main+47>
eflags 0x246 [ PF ZF IF ]
cs 0x23 35
ss 0x2b 43
ds 0x2b 43
es 0x2b 43
fs 0x0 0
gs 0x63 99
k0 0x0 0
k1 0x0 0
k2 0x0 0
k3 0x0 0
k4 0x0 0
k5 0x0 0
k6 0x0 0
k7 0x0 0
And after
Program received signal SIGSEGV, Segmentation fault.
0x5655900c in str2int ()
eax 0xffffc1a8 -15960
ecx 0xffffc1d0 -15920
edx 0xffffc1f0 -15888
ebx 0x56558fd4 1448447956
esp 0xffffc18c 0xffffc18c
ebp 0xffffc1b8 0xffffc1b8
esi 0xffffc28c -15732
edi 0xf7ffcb60 -134231200
eip 0x5655900c 0x5655900c
eflags 0x10292 [ AF SF IF RF ]
cs 0x23 35
ss 0x2b 43
ds 0x2b 43
es 0x2b 43
fs 0x0 0
gs 0x63 99
k0 0x0 0
k1 0x0 0
k2 0x0 0
k3 0x0 0
k4 0x0 0
k5 0x0 0
k6 0x0 0
k7 0x0 0
count_chars function:
.globl count_chars
.type count_chars, @function
count_chars:
pushl %ebp
movl %esp, %ebp
pushl %ebx
movl 8(%ebp), %ebx
xorl %ecx, %ecx
count_chars_lp1:
movb (%ebx), %al
cmpb $0, %al
je count_chars_end
incl %ebx
incl %ecx
jmp count_chars_lp1
count_chars_end:
movl %ecx, %eax
popl %ebx
movl %ebp, %esp
popl %ebp
ret
I am still trying to learn gdb. So, if you need me to show anything else, just let me know please.
I’ve already tried to fix it with ChatGPT, but its comments and suggestions don’t make sense. It keeps telling me to compile my code for a 32-bit system, but I’ve already done that.
count_charsfunction is missing. Please provide your full code or a minimal reproducible example.