Anonymous
Anonymous

Reputation: 147

x86 Assembly reading bytes from file to stack but gdb cant find bytes

I have some assembly code that reads 4 bytes from a file and stores them on the stack and then displays those 4 bytes to stdout, the code works fine but when i use gdb to see what the code is doing, and trying to find thoses 4 bytes on the stack i cant find them..

(gdb) p $esp                                                                  
$1 = (void *) 0xbffff6bc                                                            
(gdb) x/4 $esp                                                                                     
0xbffff6bc: 0 1 0 -1073743777                         

the first 4 bytes of the file are:

cat nummers.txt|od -c
0000000   3  \n   1  \n   2  \n   3  \n
0000010

the code:

%macro write 2
    mov eax,4       ; write syscall
    mov ebx,STDOUT  ; stdout
    mov edx,%2      ; number of bytes
    mov ecx,%1      ; buffer
    int 80h     ; call kernel
%endmacro

section .data   
    filename    db 'nummers.txt' ; just use lenth of string
    filename_len    equ $-filename   ; here we use a constant
    STDOUT      equ 1    ; stdout

section .bss
    buffer      resb 4
section .text
global _start   
    _start:

    ;; read first byte from file to know how many elements there are
    mov eax,5       ; syscall open
    mov ebx,filename    ; filename
    mov ecx,0       ; read-only
    int 80h     ; call kernel

    sub esp,4       ; subtract 4 bytes from stack.
    mov eax,3       ; syscall read
    mov ebx,eax     ; file descriptor
    mov ecx,esp         ; location for storing 4 bytes
    mov edx,4       ; read 4 bytes
    int 80h     ; call the kernel

    mov eax,4
    mov ebx,STDOUT
    mov ecx,esp
    mov edx,4
    int 80h
    call ret        
    ret:    
    mov eax,1
    mov ebx,1
    int 80h

Thanks for any help!!

Upvotes: 0

Views: 2860

Answers (1)

ott--
ott--

Reputation: 5702

Even in this short assembler program you almost hit the top most error count that's possible. The filename is not terminated with a 0 byte. You're not checking the result of the open call. You're trying to read 4 bytes while the filesize is 8. Finally you're reusing esp, hoping that it's value wasn't changed.

Upvotes: 2

Related Questions