Im currently trying to get used to assembler and I have written a for loop in c++ and then I have looked at it in disassembly. I was wondering if anyone could explain to me what each step does and/or how to improve the loop manually.
for (int i = 0; i < length; i++){
013A17AE mov dword ptr [i],0
013A17B5 jmp encrypt_chars+30h (13A17C0h)
013A17B7 mov eax,dword ptr [i]
013A17BA add eax,1
013A17BD mov dword ptr [i],eax
013A17C0 mov eax,dword ptr [i]
013A17C3 cmp eax,dword ptr [length]
013A17C6 jge encrypt_chars+6Bh (13A17FBh)
temp_char = OChars [i]; // get next char from original string
013A17C8 mov eax,dword ptr [i]
013A17CB mov cl,byte ptr OChars (13AB138h)[eax]
013A17D1 mov byte ptr [temp_char],cl
Thanks in advance.
First, I’d note that what you’ve posted seems to contain only part of the loop body. Second, it looks like you compiled with all optimization turned off — when/if you turn on optimization, don’t be surprised if the result looks rather different.
That said, let’s look at the code line-by-line:
This is basically just
i=0.This is going to the beginning of the loop. Although it’s common to put the test at the top of a loop in most higher level languages, that’s not always the case in assembly language.
This is
i++in (extremely sub-optimal) assembly language. It’s retrieving the current value ofi, adding one to it, then storing the result back intoi.This is basically
if (i==length) /* skip forward to some code you haven't shown */It’s retrieving the value ofiand comparing it to the value oflength, the jumping somewhere ifiwas greater than or equal tolength.If you were writing this in assembly language by hand, you’d normally use something like
xor eax, eax(orsub eax, eax) to zero a register. In most cases, you’d start from the maximum and count down to zero if possible (avoids a comparison in the loop). You certainly wouldn’t store a value into a variable, then immediately retrieve it back out (in fairness, a compiler probably won’t do that either, if you turn on optimization).Applying that, and moving the “variables” into registers, we’d end up with something on this general order: