Reputation: 313
I'm trying to understand some disassembled code, but I can't understand what's going on here. Can you explain what it does?
sub ecx, edi
sar edx, 1
mov eax, 2AAAAAABh
imul ecx
mov eax, edx
shr eax, 31
add eax, edx
test eax, eax
jle ...
ecx
, edx
and edi
contains some kind of input values for this code.
I can only assume that the pair of last two lines may work as something like if(eax <= 0) goto ...
, but I'm not sure.
Upvotes: 3
Views: 1183
Reputation: 112
the code is a form of an optimized division, the constant used in the code is a Wagstaff prime,
Upvotes: 1
Reputation: 14409
2AAAAAAB
is a "magic number". The sequence
MOV EAX, 2AAAAAABh
IMUL dividend
MOV EAX, dividend
SHR EAX, 31
ADD EDX, EAX
is this signed division without using IDIV
:
EDX = dividend/6
The instruction sar edx, 1
is useless, since EDX
will be overwritten by imul ecx
. In C the posted sequence can written as
if ((ECX-EDI)/6 > 0) { ... } else ("jle") { ... }
.
Upvotes: 4
Reputation: 8623
I think it is checking for overflow of a calculation for unknown purposes.
sub ecx,edi ; ecx = ??? no idea where these come from or what they mean
sar edx,1 ; edx changed but value is lost, as are flags, no idea why this is done
mov eax,2AAAAAABh ; eax = 715827883, no idea why this number is important
imul ecx ; edx:eax = (original ecx-edi) * 715827883
mov eax,edx ; eax = high-dword of product
shr eax,31 ; eax = high-bit of high-dword of product
add eax,edx ; eax = high-dword of product + high-bit of high-dword of product
; assuming 0 <= ecx < ~10, eax will be zero if the result did not carry into edx
; assuming ~-10 < ecx < 0, eax will be zero if the result did not carry into edx
; therefore, |ecx|<~10, eax = overflow-from-multiplication
test eax,eax
jle ... ; taken if eax=0 or SF=OF
I'm not sure what the significance of the "sign flag = overflow flag" part means. It may not be possible to occur for small values of ecx.
Upvotes: 0