简体   繁体   中英

How to use .net cil jmp opcode

I'm trying to get the jmp opcode to work in Cil

jmp  void ILTest.Program::MyFunc2(int32)

ilasm is fine with it, but when I run the program I always get "common language runtime detects an invalid program" exception.

I know this is unverifiable code so I have tried to give permissions

SecurityPermission perm = new SecurityPermission(SecurityPermissionFlag.Execution | SecurityPermissionFlag.SkipVerification | SecurityPermissionFlag.UnmanagedCode);

but it does not seem to have any effect.

Has anyone got a program using 'jmp' working?

jmp can only jump to a method with the same arguments as the current method. Make sure you're already in a method taking an int32 as a parameter, and that you've nothing pushed on the stack: it must be empty. Also ensure you're not in a try/catch/filter/finally block.

If you can't meet those criteria, use a call instead.

One thing to keep in mind is that all assemblies and dynamicmethods have their own sets of metadata tokens, that are used to reference other methods, fields, and types. So when replacing IL code of an existing assembly you can only use tokens that have already been used in that assembly (in other classes and methods). Most likely you cannot allocate new tokens after assembly has already been built. (at least it's my hunch)

Also I think there are two ways of "jumping" from one assembly to another. One is using DynamicMethod.Invoke, another is prebuilding a dummy method, and parsing destination method token from it's IL code. In my project I ended up needing both, so good luck. :)

Also when replacing an existing method's IL code you need to have big enough "max stack" value, and somehow make sure that there's enough local variables for your new code.

Unfortunately .net runtime exceptions are really generic, and never tell you what went wrong. So, be prepared for having lots of small test cases, for testing your solutions on various methods.

Here's also some useful links:

http://www.codeproject.com/Articles/14058/Parsing-the-IL-of-a-Method-Body

http://blogs.msdn.com/b/haibo_luo/archive/2006/11/07/turn-methodinfo-to-dynamicmethod.aspx

http://www.codeproject.com/script/Content/ViewAssociatedFile.aspx?rzp=%2Fkb%2Fdotnet%2Fdotnetinternals_injection%2Frbcoree.zip&zep=rbcoree%2Frbcoree.cpp&obid=26060&obtid=2&ovid=1

https://www.google.fi/search?num=100&es_sm=93&q=CORINFO_METHOD_INFO&oq=CORINFO_METHOD_INFO&gs_l=serp.3...0.0.0.4517435.0.0.0.0.0.0.0.0..0.0....0...1c..64.serp..0.0.0.cdFZu2hO9Yo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM