Search code examples
c++cx86

Why does ptrace(PTRACE_PEEKDATA, ...) return what seems to be a reversed data stream?


This almost certainly stems from my misunderstanding of the x86 binary layout, but I was using ptrace(PTRACE_PEEKDATA, ...) to inspect a running binary, and ran into this:

Here is the text section for main:

0000000000001140 <main>:
    1140:       55                      push   %rbp
    1141:       48 89 e5                mov    %rsp,%rbp
    1144:       48 83 ec 10             sub    $0x10,%rsp
    1148:       c7 45 fc 00 00 00 00    movl   $0x0,-0x4(%rbp)
    114f:       48 8d 3d ae 0e 00 00    lea    0xeae(%rip),%rdi        # 2004 <_IO_stdin_used+0x4>
    1156:       b0 00                   mov    $0x0,%al
    1158:       e8 d3 fe ff ff          call   1030 <printf@plt>
    115d:       31 c0                   xor    %eax,%eax
    115f:       48 83 c4 10             add    $0x10,%rsp
    1163:       5d                      pop    %rbp
    1164:       c3                      ret

I am targeting the address 1158, and expected the call to ptrace to return: 0xe8d3feffff31c048. However, what I am instead finding is the reversal of this, being 0x48c031fffffed3e8.

Why is this reversed? I expected PTRACE_PEEKDATA to dump 8 bytes from the requested address forward? Like I said before this is most definitely a misunderstanding for me with how binary data is stored.

I am running Ubuntu 22.04, x86-64.

Thanks


Solution

  • The data is stored as you expect, both in the program as in the register/memory. However, your debugger or printer is interpreting the 8 bytes in little-endian format for you and "helpfully" reversing the bytes.

    Always use explicit byte-per-byte printing if you want to inspect things at the byte level.