Alex Rivera | Logout

What's the purpose of the CIL nop opcode?

Asked 2008-10-24T19:14:03.313
83

I'm going through MSIL and noticing there are a lot of nop instructions in the MSIL.

The MSDN article says they take no action and are used to fill space if the opcode is patched. They're used a lot more in debug builds than release builds.

I know that these kinds of statements are used in assembly languages to align later instructions, but why are MSIL nops needed in MSIL?

(Editor's note: the accepted answer is about machine-code NOPs, not MSIL/CIL NOPs which the question originally asked about.)

Edit
Report

5 Answers

109

NOPs serve several purposes:

  • They allow the debugger to place a breakpoint on a line even if it is combined with others in the generated code.
  • It allows the loader to patch a jump with a different-sized target offset.
  • It allows a block of code to be aligned at a particular boundary, which can be good for caching.
  • It allows for incremental linking to overwrite chunks of code with a call to a new section without having to worry about the overall function changing size.
answered 2008-10-24T19:41:12.837
5

In one processor I worked for recently (for four years) NOP was used to make sure the previous operation finished before the next operation was started. For instance:

load value to register (takes 8 cycles) nop 8 add 1 to register

This made sure register had the correct value before the add operation.

Another use was to fill in execution units, such as the interrupt vectors which had to be a certain size (32 bytes) because address for vector0 was, say 0, for vector 1 0x20 and so on, so the compiler put NOPs in there if needed.

answered 2009-05-28T13:03:36.383
3

One classic use for them is so that your debugger can always associate a source-code line with an IL instruction.

answered 2008-10-24T19:17:58.797
3

I've also seen NOPs in code that modifies itself to obfuscate what it does as a placeholder (veeery old copy protection).

answered 2008-10-24T20:03:31.873
3

As ddaa said, nops let you account for variance in the stack, so that when you overwrite the return address it jumps to the nop sled (a lot of nops in a row) and then hits the executable code correctly, rather than jumping to some byte in the instruction that isn't the beginning.

answered 2008-10-25T02:24:50.277

Your Answer