MethodRedirect is a MethodInfo extension written in C# that can be used to redirect a method call to another using reflection.
This implementation uses marshalling to modify the address of the corresponding Method Descriptor without the need to use unsafe block.
This project was inspired by one of the answers given for this question on StackOverflow about replacing the content of a C# method. The answer did not provide sufficient explanation on how it actually works and neither shows an example of its usage. The following are development notes and references used to implement this project and hopefully explain how it works too.
-
Each MethodDesc has a slot, which contains the entry point of the method. The slot and entry point must exist for all methods, even the ones that never run like abstract methods.
-
The slot is either in
MethodTableor inMethodDescitself. The location of the slot is determined bymdcHasNonVtableSlotbit onMethodDesc. -
The slot is stored in
MethodTablefor methods that require efficient lookup via slot index, e.g. virtual methods or methods on generic types. TheMethodDesccontains the slot index to allow fast lookup of the entry point in this case. -
Each class and interface will be represented in memory by a
MethodTable(MT) data structure. A pointer to theMethodTablecan be acquired through theType.RuntimeTypeHandleproperty. TheTypeHandle(contained in theObjectInstance) points to an offset from the beginning of theMethodTable. This offset is 12 bytes by default.Embedded within the
MethodTableis a table of slots that point to the respective method descriptors (MethodDesc), enabling the behavior of the type. TheMethod Slot Tableis created based on the linearized list of implementation methods laid out in the following order:1. Inherited virtuals 2. Introduced virtuals 3. Instance methods 4. Static methodsThe first four methods of any type will always be
ToString(),Equals(),GetHashCode(), andFinalize()in this order. On x86, each method's address is represented on 4 bytes. On x64 build, each method's address is represented on 8 bytes.- On x86 build, the fixed-size portion of
MethodTableis 40 bytes. - On x64 build, the fixed-size portion of
MethodTableis 64 bytes.
The object constructor (.ctor) is automatically generated by the C# compiler for all objects having no constructor explicitly defined.
The class constructor (.cctor) is generated by the C# compiler when at least one static variable is defined.
-
Method Descriptor (
MethodDesc) is an encapsulation of method implementation as the CLR knows it. -
Each
MethodDescis padded with aPreJitStub, which is responsible for triggering JIT compilation. -
The
Method Table Slotentry actually points to the stub instead of the actualMethodDescdata structure. This is at a negative offset of 5 bytes from the actualMethodDescand is part of the 8-byte padding every method inherits. -
MethodDescis always 5 bytes after the location pointed by theMethod Table Slotentry. After the compilation is complete, the 5 bytes containing the call instruction will be overwritten with an unconditional jump to the JIT-compiled code. -
The
Flagsfield in the method descriptor is encoded to contain the information about the type of the method, such as static, instance, interface method, or COM implementation. TheFlagsfield is represented on 3-bit [0-7] and can be one of the MethodClassification enumeration value.
- On x86 build, the fixed-size portion of
-
Calling a redirected static method using a direct function call may return a cached result. An alternative approach is to call the static function using the
Invokemethod of the correspondingMethodInfo. -
For direct normal method call, the
MethodRedirectioninstance returned from a call to theRedirectTomethod can be used to revert the method redirection to the original address. However, it is not actually possible to revert a redirected method call that is made within another already compiled (JITted) method since the address of the redirected method call will remain unchanged in the compiled method. See the unit tests of Scenario5 for more details on this behavior. -
Using lambda expression (see Scenario6's unit tests), the method redirection works when the origin method is declared as
virtual.
- .NET Framework Internals: How the CLR Creates Runtime Objects
- Method Descriptor
- Dynamically replace the contents of a C# method?
- The VTABLE
- CLR implementation of virtual method calls to interface members
- Exploiting C++ VTABLES: Instance Replacement
- "Stubs" in the .NET Runtime
- Custom memory allocation in C#
- CLR runtime details-Method Descriptor
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.



