0

can somone please explain me how modulo(best will be step by step) works in assembly. The result of this code is something like:

var = *(_DWORD *)(addrBase + 0x18);
if ( (signed int)var <= 5 || (_DWORD)var == 10 * ((signed int)var / 10) )

cmp     r9d, 5
jle     short loc_62714B
mov     eax, 66666667h
imul    r9d
sar     edx, 2
mov     eax, edx
shr     eax, 1Fh
add     edx, eax
lea     ecx, [rdx+rdx*4]
add     ecx, ecx
cmp     r9d, ecx
jnz     short loc_62718B

And how can i change it to: if ( (signed int)var <= 5 || (_DWORD)var == 30 * ((signed int)var / 30) ) Thanks!

Michael
  • 57,169
  • 9
  • 80
  • 125
Glock
  • 63
  • 4
  • 1
    See [Why does GCC use multiplication by a strange number in implementing integer division?](https://stackoverflow.com/q/41183935/547981). As to how to change ... depends on what you are doing. You can get rid of the optimization and switch to using division. – Jester Jul 13 '21 at 12:54
  • Thanks. Problem is tht this binary is close sourced, so i am looking for HEX change or some sort of explanation to understand the changes with "magic number". – Glock Jul 13 '21 at 13:05
  • It is part of algorithm, which reports every 10 second some system info and i need to change to every 30 seconds :) So the modulo is for sure 10 and i need to change to 30. It is very old (already lost source) app. – Glock Jul 13 '21 at 13:13
  • 1
    For hex change throw out the magic numbers and switch to division. – Jester Jul 13 '21 at 13:13
  • 3
    The first two instructions are doing the `var <= 5` check, replace everything else with `mov ecx, 30; mov eax, r9d; cdq; idiv ecx; test edx, edx; jnz loc_62718B` and pad with `NOP` as needed. Assuming the rest of the code does not depend on register values and I haven't messed anything up, that should about work :) – Jester Jul 13 '21 at 13:21
  • Good. thanks. ! I still tried to calculate magic number somhow like 2^34 /(10,20,30) a put the constants, but always i get some weird value in register. – Glock Jul 13 '21 at 13:40
  • 2
    Look at compiler output for `return x/30` on https://godbolt.org/ and see if it uses the same instructions but with different constants. If so, you can just change them, otherwise you'd have to do it differently. (As Jester says, using `idiv` is simple and slow, but compact in machine code.) – Peter Cordes Jul 13 '21 at 20:29
  • Very good page, thank you. It helps me improve my asm skills. – Glock Jul 14 '21 at 21:14

0 Answers0