Reverse Engineering for Beginners

(avery) #1

APPENDIX A. X86 APPENDIX A. X86


lea edi, string
mov ecx, 0FFFFFFFFh ; scan 232 − 1 bytes, i.e., almost "infinitely"
xor eax, eax ; 0 is the terminator
repne scasb
add edi, 0FFFFFFFFh ; correct it

; now EDI points to the last character of the ASCIIZ string.

; lets determine string length'
; current ECX = -1-strlen

not ecx
dec ecx

; now ECX contain string length

If we use a different AX/EAX/RAX value, the function acts like the memchr() standard C function, i.e., it finds a specific
byte.

SHLshift value left


SHRshift value right:


7 6 5 4 3 2 1 0

CF 7 6 5 4 3 2 1 0 0

7 6 5 4 3 2 1 0

0 7 6 5 4 3 2 1 0 CF

These instructions are frequently used for multiplication and division by 2 n. Another very frequent application is
processing bit fields:19 on page 289.

SHRDop1, op2, op3: shift value in op2 right by op3 bits, taking bits from op1.


Example:24 on page 379.

STOSB/STOSW/STOSD/STOSQstore byte/ 16-bit word/ 32-bit word/ 64-bit word from AX/EAX/RAX into the address which
is in DI/EDI/RDI.


Together with the REP prefix, it is to be repeated in a loop, the counter is in the CX/ECX/RCX register: it works like
memset() in C. If the block size is known to the compiler on compile stage, memset() is often inlined into a short code
fragment using REP MOVSx, sometimes even as several instructions.

memset(EDI, 0xAA, 15) equivalent is:

; store 15 0xAA bytes to EDI
CLD ; set direction to "forward"
MOV EAX, 0AAAAAAAAh
MOV ECX, 3
REP STOSD ; write 12 bytes
STOSW ; write 2 more bytes
STOSB ; write remaining byte

( Supposedly, it works faster than storing 15 bytes using just one REP STOSB).

SUBsubtract values. A frequently occurring pattern isSUB reg,reg, which implies zeroing ofreg.


TESTsame as AND but without saving the result, see also:19 on page 289


XCHGexchange the values in the operands


XORop1, op2:XOR^4 values.op1 =op 1 ⊕op 2. A frequently occurring pattern isXOR reg,reg, which implies zeroing of
reg.


XORis widely used when one needs just to flip specific bit(s).

Indeed, theXORoperation applied with 1 effectively inverts a bit:

(^4) eXclusive OR

Free download pdf