Koray Tugay
Koray Tugay

Reputation: 23800

How can I print how many bytes has been read to console with Assembly?

Here is my code (buffer.asm)

section .bss
    bufflen equ 2
    buff: resb bufflen

    whatreadlen equ 1
    whatread: resb whatreadlen

section .data

section .text

global main

main:
    nop
    read:
        mov eax,3           ; Specify sys_read
        mov ebx,0           ; Specify standard input
        mov ecx,buff        ; Where to read to...
        mov edx,bufflen     ; How long to read
        int 80h             ; Tell linux to do its magic
        mov esi,eax         ; copy sys_read return value to esi
        mov [whatread],eax  ; Store how many byte reads info to memory at loc whatread

        mov eax,4           ; Specify sys_write
        mov ebx,1           ; Specify standart output
        mov ecx,[whatread]  ; Get the value at loc whatread to ecx
        add ecx,0x30        ; convert digit in EAX to corresponding character digit
        mov edx,1           ; number of bytes to be written
        int 80h             ; Tell linux to do its work

When I call this like:

./buffer > output.txt < all.txt

(Assume all.txt has some text in it like "abcdef")

I am expecting to see a number in the console. However I see nothing. What is it that I am missing?

Upvotes: 1

Views: 288

Answers (1)

tux3
tux3

Reputation: 7330

You're passing a value to sys_write instead of an address, that's not going to work.

Write this instead :

main:
    nop
    read:
        mov eax,3           ; Specify sys_read
        mov ebx,0           ; Specify standard input
        mov ecx,buff        ; Where to read to...
        mov edx,bufflen     ; How long to read
        int 80h             ; Tell linux to do its magic
        mov esi,eax         ; copy sys_read return value to esi
        add eax, 30h        ;; Convert number to ASCII digit
        mov [whatread],eax  ; Store how many byte reads info to memory at loc whatread

        mov eax,4           ; Specify sys_write
        mov ebx,1           ; Specify standart output
        lea ecx,[whatread]  ;; Get the address of whatread in ecx
        mov edx,1           ; number of bytes to be written
        int 80h             ; Tell linux to do its work

Here we're converting our (hopefully single digit) return value from sys_read into an ASCII digit, storing it at whatread, then telling sys_write to write from whatread as if it was a pointer to a string of 1 character (which it is).

And test it with echo aaa | ./buffer > output.txt

Upvotes: 1

Related Questions