1

I am trying to duplicate the following c codde in assembly language:

long hex_read(char data_buf[]){
  return read(0,data_buf,16);
}

And this is my implementation in assembly language:

    .globl hex_read
hex_read:
    subq $8,%rsp
    
    movq %rdi,%rsi
    movq $0,%rdi
    movq $16,%rdx
    call read

    addq $8,%rsp
    ret

I then tested this assembly code by creating a main assembly function.

    .section .text
hex_read_buf:   .space 16


    .globl main

    
main:
    subq $8,%rsp
    movq $hex_read_buf,%rdi
    call hex_read
    addq $8,%rsp
    ret

But when I test it in gdb, no matter what I input I will get 0 for the returning value of hex_read( stored in %rax), which is weird. Can someone tell me what I am doing wrong here? Thank you so much.

Jester
  • 56,577
  • 4
  • 81
  • 125
M. Chen
  • 203
  • 1
  • 6
  • 2
    Putting `hex_read_buf` into `.section .text` is a bad idea as that is typically read-only. I expected you to get `-1` return with `errno == EFAULT` though. I have just tested, I do get `-1`. Anyway, putting it into `.data` should fix the problem, it does here. – Jester Oct 05 '20 at 17:55
  • @Jester thank you so much! – M. Chen Oct 05 '20 at 18:05
  • (I couldn't find a really good canonical duplicate for `.text` being read-only, like a simple question that segfaults on that, with an answer that identifies that starts by saying that's the problem. Or for system calls returning `-EFAULT` when you pass an unwriteable pointer. If anyone wants to write one here, I can reopen. Or let me know if you anyone finds an existing Q&A.) – Peter Cordes Oct 06 '20 at 03:22

0 Answers0