When you are learning IL you might wonder why some directives even exists. They can do a lot of harm when used incorrectly. I’ll shed some light about one of them. Let’s check .emitbyte
I’m doing a series of blog posts about IL. If you haven’t read the earlier posts – here’s the list:
Ok, let’s get back to our today’s topic – .emitbyte.
What it is and what it does?
Well as the name suggests it allows you to emit a byte into your assembly. So instead of writing nop you could write .emitbyte 0x00. Why would you want to do that? Normally – you wouldn’t but this allows you to convert i.e. a stream of bytes into an assembly by emitting the bytes. It also gives you a bit of a hackish power to prevent (at least a bit of it) others from seeing parts of your code.
If you haven’t learnt by heart the whole IL opcode list – go do it now. Just kidding – don’t do it. But if you check it at least once (wikipedia) – you could see that there’s some blank spots. The first one is at 0x24.
If you ask me why there are holes I would say that maybe for future use but honestly I have no clue. But if there are ones – let’s use them.
So what would happen if we put .emitbyte 0x24 in our codebase? Let’s find out. Well you don’t have to be genius to know that it will end up with a major crash. Nothing special – but what will happen if we keep the .emitbyte, but we will jump over it unconditionally?
This time nothing will happen in the runtime. The application will run as normal. But when we try to analyze our dll with IL dissemblers? Well that’s a different story…
This one is actually handling this case very well. Correctly identifies this as invalid opcode and displays it as such.
Good work dotPeek!
The old king places itself somewhere in the middle between dotPeek and IlSpy/JustDecompile. Doesn’t show the exception nor does not correctly handle this case. Instead we get enigmatic “Invalid method body” message.
I think I would prefer exception in this case. At least I can see that it’s the tools problem not with the code. Here I might wondering what the heck is wrong with the code.
So here’s how the tools handles such odd usage of .emitbyte. So just remember – if your tool doesn’t handle your code correctly it doesn’t mean it’s your fault. Just try another tool.
Let me know if you find this interesting. I have few more similar posts coming soon.