How do microsoft fakes' shims actually work internally?
Asked Answered
S

1

8

So I am interested in the way that it is implemented. Basically: How can I re-implement the same thing myself? ... which I am not intending to do. Just understand.

The fundamental question is: How is it possible to (?) intercept class instantiation at all? And how can it be replaced in one case with one implementation and in another occurence with it's original or an even different implementation?

How is it even possible to intercept static methods or sealed classes.

This is all about shims/moles not so much about stubs.

Smallclothes answered 13/8, 2014 at 8:46 Comment(3)
Microsoft solved this issue using the darkest eldritch magic.Skerl
It is not clear to me what the question means by "microsoft fakes' shims" - could you clarify please?Choi
@Sander: Microsoft Fakes is a quality tool for unit tests included since VS2012. The main features are shims and stubs.Smallclothes
S
7

This is done by changing the Common Intermediate Language (IL) code that is emitted by the compiler. You can do pre-packaged IL modification using the Fody library. Fody internally uses the mono.cecil library for the low level IL manipulation. The IL generated by the compiler is modified and saved to disk as an assembly.

I have found this reference publication on Moles [pdf file]. Section 4 explains the mechanism of the code instrumentation.

Sinistrorse answered 13/8, 2014 at 8:54 Comment(3)
Are you sure? Shimmed methods are drastically slower than the original object.Skerl
In the PDF mentioned in the answer I found the following core explanation: The instrumentation is done as follows. At the beginning of each method some code is inserted. This code queries a low-level detours library as to whether any detour was attached to this particular method. If so, then the detour delegate is invoked, otherwise, the normal code is executed.Smallclothes
For anyone looking for the Moles paper, it's available in the publication Objects, Models, Components, Patterns, 48th International Conference, TOOLS 2010, Málaga, Spain, June 28 - July 2, 2010. Proceedings, page 253, in a paper titled Moles: Tool-Assisted Environment Isolation with Closures. PDF should be available via a Google search.Galvan

© 2022 - 2024 — McMap. All rights reserved.