The capstone for this section. Reversing a buffer in place pulls together everything so far: bytes and memory from the Basics, the loop and comparison from Control Flow, and load/store addressing. It is also the shape of real routines you will meet when reversing and exploiting binaries.
Reverse a byte buffer in place — without a second buffer. Use two pointers that start at opposite ends and walk toward each other, swapping the bytes they point at, until they meet in the middle. Print the result to confirm it worked.
Open one hint at a time before reading the walk-through.
buf + len - 1). lea computes those addresses without reading memory.al, bl), then store each one back at the other pointer's address.inc the left pointer and dec the right. Stop when they meet or cross — cmp the two and jae out of the loop..data, not read-only .rodata. Writing to read-only memory faults.Keep the left pointer in r8 and the right in r9, set with lea to buf and buf + buflen - 1. Each iteration first checks the stop condition: cmp r8, r9 then jae .done leaves the loop once the left pointer has reached or passed the right one.
The swap itself is four moves through 8-bit registers, since we are moving single bytes: load [r8] into al and [r9] into bl, then store bl into [r8] and al into [r9]. With the two bytes exchanged, inc r8 and dec r9 step the pointers inward and jmp .loop goes back for the next pair. Watch the buffer flip in memory — before the loop, and again once the pointers have met:
break _startBreakpoint 1 at 0x401000runBreakpoint 1, 0x0000000000401000 in _start ()x/6xb &buf0x402000: 0x41 0x42 0x43 0x44 0x45 0x46break *0x401029Breakpoint 2 at 0x401029continueBreakpoint 2, 0x0000000000401029 in _start.done ()x/6xb &buf0x402000: 0x46 0x45 0x44 0x43 0x42 0x41Those six bytes are ASCII codes: 0x41–0x46 spell ABCDEF before the loop, and afterward they read 0x46–0x41, which is FEDCBA — reversed. Same addresses, same bytes; nothing was copied anywhere else, each byte was simply swapped with its mirror.
1section .data
2 buf db "ABCDEF"
3 buflen equ $ - buf
4 nl db 10
./revFEDCBAThe buffer came out reversed, and it never used more than the one buffer plus two single-byte temporaries — exactly the in-place algorithm the problem asked for.