below/HelloSilicon

Help: syscall read has weird behaviours

realhackcraft opened this issue · 2 comments

This is not related to your repo or the book, just thought you might be the best person to ask:

I created an assembly program to read 1 byte from user input and store it in the text section (not best practice, but just to test things out).

Here is my code:

.global _start
.align 4

_start:
   ; Read user input into buffer
    mov x0, 0              ; File descriptor: stdin
    adr x1, input_buffer   ; Buffer to store the input
    mov x2, 1              ; Number of bytes to read
    mov x16, 3             ; System call number for read (sys_read)
    svc 0x80               ; Make the system call

   ; Write the input to stdout
    mov x0, 1              ; File descriptor: stdout
    adr x1, input_buffer   ; Address of the buffer
    mov x2, 1              ; Number of bytes to write
    mov x16, 4             ; System call number for write (sys_write)
    svc 0x80               ; Make the system call

input_buffer:
    .space 1

When I type a single byte in my terminal and press enter, it doesn't print anything and returns with code 0.

I decompiled the binary and found that input_buffer was at 0x0000100003f99. I used lldb to set a breakpoint on this instruction: mov x0, 1 // File descriptor: stdout and found the value at that address were:

0x100003f99: 0x00 0x00 0x00 0x01 0x00 0x00 0x00 0x1c
0x100003fa1: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x1c

Which is not the byte I typed. I typed r (0x72)

I think I didn't use the read syscall properly, but have no idea how. Could you give some guidance?

I solved it. I had to make the label in the .data section to put it in writable memory.

below commented

Excellent that you found the solution! Feel free to add it as an example and send me a PR!