简体   繁体   中英

Linux system call for X86 64 echo program

I'm still learning assembly so my question may be trivial. I'm trying to write an echo program with syscall, in which I get a user input and give it as output on the next line.

section .text
    global _start

_start:
    mov rax,0
    mov rdx, 13
    syscall

    mov rsi, rax
    mov rdx, 13
    mov rax, 1      
    syscall

    mov    rax, 60
    mov    rdi, 0
    syscall 

I'm assuming all you want to do is return the input to the output stream, so to do that you need to do a few things.

First, create a section .bss in your code. This is for initializing data. You will initialize a string with any name you want and do so with label resb sizeInBits . for demonstration it will be a 32 bit string called echo.

Extra note, the ';' character is used for comments similar to what // is in c++.

Example code

section .data
    text db "Please enter something: " ;This is 24 characters long.

section .bss
    echo resb 32 ;Reserve 32 bits (4 bytes) into string

section .text
    global _start

_start:
    call _printText
    call _getInput
    call _printInput

    mov rax, 60 ;Exit code
    mov rdi, 0 ;Exit with code 0
    syscall

_getInput:
    mov rax, 0 ;Set ID flag to SYS_READ
    mov rdi, 0 ;Set first argument to standard input
    ; SYS_READ works as such
    ;SYS_READ(fileDescriptor, buffer, count)

    ;File descriptors are: 0 -> standard input, 1 -> standard output, 2 -> standard error
    ;The buffer is the location of the string to write
    ;And the count is how long the string is

    mov rsi, echo ;Store the value of echo in rsi
    mov rdx, 32 ;Due to echo being 32 bits, set rdx to 32.
    syscall
    ret ;Return to _start

 _printText:
     mov rax, 1
     mov rdi, 1
     mov rsi, text ;Set rsi to text so that it can display it.
     mov rdx, 24 ;The length of text is 24 characters, and 24 bits.
     syscall
     ret ;Return to _start

_printInput:
    mov rax, 1
    mov rdi, 1
    mov rsi, echo ;Set rsi to the value of echo
    mov rdx, 32 ;Set rdx to 32 because echo reserved 32 bits
    syscall
    ret ;Return to _start

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM