2

I have been working on assembly on Debian mainly just experimenting. first with a simple hello world using printf and this worked with no problem. I then decided to try using system calls to replace the printf and this produced nothing. The code I used was written using AT&T syntax thus.

 .bss                 #bss section of code follows below.

 .data                #data section.
    outStr: .asciz "Hello World\n"             

 .global main

main:
       pushq %rbp
       movq %rsp, %rbp     #refering to the stack pointer and the base pointer.


        movq $1, %rax      # system call number {sys write} #define __NR_write 1
        movq $1, %rdi          # What to do {stdout}
        movq outStr, %rsi      # message 
        movq $13, %rdx         # message length

        syscall                # call linux kernel 

        movq $60, %rax         # Setup the exit sys call #define __NR_exit 60
        movq $0, %rdi          # error code

        syscall               # call linux kernel       


       movq %rbp, %rsp        # move base pointer back to stack pointer
       popq %rbp              # recover base pointer
       ret

using strace I see this which seems to indicate a error. write(1, ox6f57206f6c6c6548, 13 = -1 {bad address} But I do not understand why.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • 4
    I'm on my phone, but I can see that 0x6f57206f6c6c6548 is ASCII for "oW olleH" (Intel is little-endian) so you're passing the syscall a value rather than an address. You need `lea` instead of `mov` for outStr, I think `leaq outStr, %rsi` is the proper syntax but I might be a bit off. (Please confirm whether this works and I can turn it into an answer.) – filbranden Oct 17 '18 at 10:41
  • You are correct works perfectly. Now I spent a lot of time looking all over the web and the code I wrote is how it is shown to be over and over again which means a lot people out there are told incorrectly how to do this. !!!!! –  Oct 17 '18 at 11:13
  • Well done Filipe –  Oct 17 '18 at 11:27
  • I have just seen the problem this also works –  Oct 17 '18 at 11:35
  • movq $outStr, %rsi # message which I miss even so well done –  Oct 17 '18 at 11:36
  • @FilipeBrandenburger: you want `lea outStr(%rip), %rsi`, otherwise you're asking for a 32-bit absolute addressing mode and you might as well have used `mov $outStr, %esi` (which is more efficient and does work in a non-PIE executable). [Difference between movq and movabsq in x86-64](https://stackoverflow.com/q/40315803). – Peter Cordes Oct 17 '18 at 18:12
  • 1
    @m5w: you claim that incorrect is all over the place. That seems unlikely, probably you just forgot the `$` to make it an immediate instead of a dereference, or you were looking at NASM syntax like `mov esi, msg`. – Peter Cordes Oct 17 '18 at 18:14

0 Answers0