8

After disassembling a program, I see the following asm code generated :

.text:004D5911 mov     [ebp+var_4], ecx
.text:004D5914 mov     ecx, [ebp+var_4]
.text:004D5917 test    ecx, ecx
.text:004D5919 jnz     short loc_4D591F

I don't get why [ebp+var_4] is copied back to ecx.

Is this an artifact (missed optimization) from the compiler which requires test to take registers as operands?

3
  • 1
    You answered your own question. Yes. Dec 7, 2014 at 6:07
  • 1
    This might also be part of a loop that starts at 4D5914, with the first instruction initializing the loop control variable. Though this seems unlikely, since a) the jnz jumps if cx is not zero, and b) this seems to be an IDA disassembly, and ida would have generated a loc_... label if there was a jump to this address. Dec 7, 2014 at 6:47
  • I've also seen compilers do this for alignment reasons. inside a particular section
    – Fewmitz
    Dec 8, 2014 at 4:04

1 Answer 1

3

This is a common pattern in assembly generated by gcc at least. When it is not asked to optimize the generated code, the translation between C and asm is really straightforward. One statement in C produces a few lines of asm. Next statement: a few more lines of asm, and so on.

In your case:

mov     [ebp+var_4], ecx

is probably the end of a line of C, while:

mov     ecx, [ebp+var_4]

is the beginning of the next one.

These instructions are optimized out as soon as -O1 (or higher) is provided.

1
  • Optimization, as mentioned in this answer, will eliminate this oddity which you have correctly identified as a compiler artifact. Things like these are quite useful for figuring out whether code was "hand written", compiled or, potentially, identifying which compiler was used to build a particular piece of code. Dec 11, 2014 at 2:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.