Different behaviour of eax compared to other registers
-
14-10-2019 - |
Question
I've written a small assembly snippet (Gas, 32 bit) that takes a command-line argument, counts its characters and prints the string if it has a certain length (just for debugging purposes). I'm relatively new to assembly, so I'm pretty sure there is something I miss here because I get different behaviour when I store the string in eax compared to, for instance, ecx, edx or esi.
Here is the snippet. When you replace esi with eax, the loop is entered only twice no matter how long the string is, hence the counter (ebx) is always 1. With esi or other registers, everything seems to work fine.
.section .text
.globl _start
_start:
movl %esp, %ebp
movl 0(%ebp), %eax # get argc
cmpl $2, %eax # ensure argc == 2
jne _exit
movl 8(%ebp), %eax # get argv[1]
movl $0, %ebx # set counter to 0
_begin_loop:
movb (%eax), %al # load a character into %al
cmpb $0, %al # see if \0 is reached
je _end_loop # exit loop if at end of string
incl %ebc # increment counter
incl %eax # advance string
jmp _begin_loop
_end_loop:
cmpl $6, %ebx # print the string if it's six characters long
jne _exit
movl $4, %eax # prepare for output
movl $1, %ebx
movl 8(%ebp), %ecx)
movl $6, %edx
int 0x80
_exit:
movl $1, %eax
movl $0, %ebx
int 0x80
Can anybody give me a hint about what I'm doing wrong/misunderstanding?
Greets
Solution
The al
register is really the lowest 8 bits of the eax
register. So, the instruction movb (%eax), %al
destroys the lowest 8 bits of eax
, that is your pointer.
As a general advice, learn to use a debugger to step through your code and spot where the computer does something different from what you expect.
EDIT: there are some trivial syntax errors in the posted code (such as ebc
instead of ebx
), but I assume some copying error since you say otherwise it works.