Linux系统调用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 

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

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

另外需要注意的是,";"字符用于类似于 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

最新更新