Benjamin
Benjamin

Reputation: 541

Unable to print back entered text in x86 assembly

I have an Assembly program here which is supposed to print a string, allow the user the enter some text, print that exact same text again and then wait for a keypress to terminate the program, using only Win32 native functions.
The problem is that everything seems to work, except printing the user entered string. It just prints a blank new line. Here's the code:

global _main

extern _GetStdHandle@4
extern _WriteFile@20
extern _ReadFile@20
extern _ExitProcess@4

section .text

_main:
    mov ebp, esp
    sub esp, 12

    push -11
    call _GetStdHandle@4
    mov ebx, eax

    push 0
    push dword [ebp - 12]
    lea ecx, [_msg_end - _msg]
    push ecx
    lea edx, [_msg]
    push edx
    push ebx
    call _WriteFile@20

    push -10
    call _GetStdHandle@4
    mov ebx, eax

    push 0
    lea ecx, [ebp - 8]
    push ecx
    push 20
    lea edx, [ebp - 4]
    push edx
    push ebx
    call _ReadFile@20

    push -11
    call _GetStdHandle@4
    mov ebx, eax

    push 0
    push dword [ebp - 12]
    lea ecx, [ebp - 8]
    push ecx
    lea edx, [ebp - 4]
    push edx
    push ebx
    call _WriteFile@20

    push -10
    call _GetStdHandle@4
    mov ebx, eax

    push 0
    lea ecx, [ebp - 8]
    push ecx
    push 1
    lea edx, [ebp - 4]
    push edx
    push ebx
    call _ReadFile@20

    push 0
    call _ExitProcess@4
_msg:
    db "Hello, world!", 10
_msg_end:

EDIT - Here's the working code:

global _main

extern _GetStdHandle@4
extern _ReadFile@20
extern _WriteFile@20
extern _ExitProcess@4

section .bss
_input_buf: resb 20

section .text
_main:
    mov ebp, esp
    sub esp, 8

    push -10
    call _GetStdHandle@4
    mov ebx, eax

    push 0
    lea ecx, [ebp - 4]
    push ecx
    push 20
    lea eax, [_input_buf]
    push eax
    push ebx
    call _ReadFile@20

    push -11
    call _GetStdHandle@4
    mov ebx, eax

    push 0
    lea ecx, [ebp - 8]
    push ecx
    mov edx, [ebp - 4]
    push edx
    lea eax, [_input_buf]
    push eax
    push ebx
    call _WriteFile@20

    push 0
    call _ExitProcess@4

Upvotes: 0

Views: 301

Answers (1)

Jens Björnhager
Jens Björnhager

Reputation: 5648

Two things:

You're only allocating 4 bytes - making space for two characters - as you are reading input into the last allocated dword on the stack:

ebp-12 [undefined]
ebp-8: [input length]
ebp-4: [input buffer]
ebp:

You're giving the length of the input string as a pointer instead of dereferencing it, making it try to output a huge number of bytes, and failing:

lea ecx, [ebp - 8]
push ecx <- address, not value

Upvotes: 1

Related Questions