Question

Coming from a Python background, I'm trying to reach myself some Assembly.

So far, I've been getting along quite nicely, but now I'm running into problems. The tutorial I'm following asks me to write some code that greets the user, asks him to input something and then displays this text on the console.

So I basically managed to do this, but the script randomly cuts off parts of the output after a certain length - typing in Fine works out perfectly, but Fine, thanks! gives me back nks!,, Finee, thanks! gives me back Fineeanks!e. This behaviour also always is the same for one string.

This is my code: (Sorry for posting all of the code, but I have no idea where the error could be)

.section .data
hi: .ascii "Hello there!\nHow are you today?\n"
in: .ascii ""
inCp: .ascii "Fine"
nl: .ascii "\n"
inLen: .long 0

.section .text

.globl _start
_start:
  Greet:  # Print the greeting message
    movl $4, %eax # sys_write call
    movl $1, %ebx # stdout
    movl $hi, %ecx # Print greeting
    movl $32, %edx # Print 32 bytes
    int $0x80 # syscall

  Read:   # Read user input
    movl $3, %eax # sys_read call
    movl $0, %ebx # stdin
    movl $in, %ecx # read to "in"
    movl $10000, %edx # read 10000 bytes (at max)
    int $0x80 # syscall

  Length: # Compute length of input
    movl $in, %edi # EDI should point at the beginning of the string
    # Set ecx to highest value/-1
    sub %ecx, %ecx
    not %ecx
    movb $10, %al
    cld # Count from end to beginning
    repne scasb
    # ECX got decreased with every scan, so this gets us the length of the string
    not %ecx
    dec %ecx
    mov %ecx, (inLen)
    jmp Print

  Print:  # Print user input
    movl $4, %eax
    movl $1, %ebx
    movl $in, %ecx
    movl (inLen), %edx
    int $0x80

  Exit: # Exit
    movl $4, %eax
    movl $1, %ebx
    movl $nl, %ecx
    movl $1, %edx
    int $0x80
    movl $1, %eax
    movl $0, %ebx
    int $0x80

I'm using the GNU Assembler on a Debian Linux (32 bit), so this is written in AT&T syntax.

Has anyone got an idea why I'm getting these weird errors?

Was it helpful?

Solution

in: .ascii ""
...
movl $in, %ecx # read to "in"
movl $10000, %edx # read 10000 bytes (at max)

You're reading user input into a variable that has room for no data at all, so you'll be trashing whatever comes after in.

Try reserving some space to hold the user input, for example:

in: .space 256
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top