Linux系统调用X86 64 echo程序

时间:2017-02-01 15:48:12

标签: linux assembly nasm x86-64

我还在学习集会,所以我的问题可能是微不足道的。 我正在尝试用syscall编写一个echo程序,在其中我得到一个用户输入并在下一行将其作为输出。

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 

1 个答案:

答案 0 :(得分:1)

我假设您要做的只是将输入返回到输出流,所以要做到这一点,您需要做一些事情。

首先,在代码中创建section .bss。这用于初始化数据。您将使用所需的任何名称初始化字符串,并使用label resb sizeInBits执行此操作。为了演示,它将是一个名为echo的32位字符串。

额外注意,';' character用于类似于c ++中的//的注释。

示例代码

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