【问题标题】:How to read and write a byte from and to stdin/stdout using Syscall in x86 with NASM assembler?如何在带有 NASM 汇编器的 x86 中使用 Syscall 从 stdin/stdout 读取和写入字节?
【发布时间】:2015-04-15 01:20:17
【问题描述】:

我正在尝试从标准输入读取字符串并使用 x86、NASM 和 Syscall 将其打印出来。读入一个字节将是一个函数,而写出一个字节将是一个函数。我正在从标准输入读取字符串并将每个字符放入一个数组中。这是我最初的想法:

;read_writer.asm
section .data
    arr times 100 db 0   ; array of 100 elements initialzed to 0
    ptr dd 0

section .text
global _start
_start:
    push ebp   ; setup stack
    mov ebp, esp   ; setup stack
    push, 0x10   ; allocate space for potential local variables
    call readin: ;call read in func
    push eax  ;return char from readin will be in eax, push it for writeout 
    call writeout:
    leave 
    mov eax, 1 ;exit
    mov ebx, 0
    int 0x80

readin:
   push ebp
   mov ebp, esp ; setup stack

   mov eax, 3 ;read
   mov ebx, 1 ;stdin
              ; i feel like i am missing code here bit not sure what

   leave  ;reset stack
   ret ;return eax

writeout:
   push ebp
   mov ebp, esp ; setup stack
   push eax   ;push eax since it was pushed earlier
   mov eax, 4 ;write
   mov ebx, 1 ;stdout
              ; i feel like i am missing code here bit not sure what

   leave  ;reset stack
   ret ;return eax

示例输入:

Hello World

样本输出:

Hello World

这些函数应该与 cdecl 一起使用,我认为我做得不对。我也意识到我没有将字符放入 arr。

【问题讨论】:

    标签: io x86 nasm system-calls cdecl


    【解决方案1】:

    首先,您在readinwriteout 中都缺少int 0x80

    而且,如您所见,heresys_readsys_write 都期望在 ecx 中出现 (const) char*。该地址应指向存储要写入的字节/应存储读取的字节的缓冲区。
    edx 的值应设置为要读取/写入的字节数。

    因此,在 readin 示例中,您需要以下内容:

    mov eax, 3    ;read
    mov ebx, 0    ;stdin. NOTE: stdin is 0, not 1
    sub esp,4     ; Allocate some space on the stack
    mov ecx,esp   ; Read characters to the stack
    mov edx,1
    int 0x80
    movzx eax,byte [esp]  ; Place the character in eax, which is used for function return values
    add esp,4
    

    writeout 也是如此。

    【讨论】:

    • 通过在系统调用之前将数组的地址放在ecx中。
    • 这会将每个字符放在不同的索引中吗?
    • 如果你用同一个系统调用读取多个字符,是的。否则,不,不会自动。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 2012-03-08
    相关资源
    最近更新 更多