2

I am using a QEMU raspberry pi emulator and trying to set up reading from the STDIN given by the command line. ie "./demo3 < text.txt"

However, my code is extremely short at the moment:

.text
.global main

main:
    bl getchar
    bx lr

but this section alone gives me a segmentation fault, any ideas why?

  • 1
    `bl` of course destroys `lr`, so you need to save and restore it, usually on the stack. – Jester Jan 12 '17 at 14:51
  • So if I use push and pop too and from the stack the segmentation fault seems to stop, but how can I get multiple chars if everytime I use bl getchar I have to restore from the stack? – James Driver Jan 12 '17 at 14:59
  • 1
    @JamesDriver You only need to restore `lr` right before you execute `bx lr`. – fuz Jan 12 '17 at 15:00
  • @fuz if this sets r0 to the result of bl getchar, should using bl printf below the bl getchar print out the character? – James Driver Jan 12 '17 at 15:04
  • @JamesDriver You probably need to load a suitable formatting string (e.g. `"%c"`) and but both a pointer to the formatting string and the result of `getchar` into the right registers. Or you could call `putchar()` instead (after putting its argument into the right register). You also need to check if `getchar` signalized an end-of-file condition. – fuz Jan 12 '17 at 15:07
  • @fuz I used a bcs under the bl getchar to check if the eof has been reached but it is saying that the file I am passing in has an eof immediately despite it containing many characters – James Driver Jan 12 '17 at 15:17
  • @JamesDriver That's not the right way. `getchar` doesn't set any flags. It returns `-1` when the end of file is reached, so you need to compare `r0` with `-1` to check if this is the case. – fuz Jan 12 '17 at 15:37
  • @fuz Thank you for all the help, I am pretty much there now! just need to work out how to pass multiple args to printf(%d,%f) , thanks for all the help! – James Driver Jan 12 '17 at 15:51
  • @JamesDriver Assuming ARMv7. According to Procedure Call Standard - p 15, "The first four registers r0-r3 (a1-a4) are used to pass argument values into a subroutine and to return a result value from a function" Basically, if you place something like fmt: %d %d %d\n" in .data then your func using printf may have push {lr}, ldr r0,=fmt, bl printf, & pop {pc}. Assumes r1, r2, & r3 have existing values. – InfinitelyManic Jan 12 '17 at 17:53

0 Answers0