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
MethodTable
or inMethodDesc
itself. The location of the slot is determined bymdcHasNonVtableSlot
bit onMethodDesc
. -
The slot is stored in
MethodTable
for methods that require efficient lookup via slot index, e.g. virtual methods or methods on generic types. TheMethodDesc
contains 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 theMethodTable
can be acquired through theType.RuntimeTypeHandle
property. TheTypeHandle
(contained in theObjectInstance
) points to an offset from the beginning of theMethodTable
. This offset is 12 bytes by default.Embedded within the
MethodTable
is a table of slots that point to the respective method descriptors (MethodDesc
), enabling the behavior of the type. TheMethod Slot Table
is 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 methods
The 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
MethodTable
is 40 bytes. - On x64 build, the fixed-size portion of
MethodTable
is 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
MethodDesc
is padded with aPreJitStub
, which is responsible for triggering JIT compilation. -
The
Method Table Slot
entry actually points to the stub instead of the actualMethodDesc
data structure. This is at a negative offset of 5 bytes from the actualMethodDesc
and is part of the 8-byte padding every method inherits. -
MethodDesc
is always 5 bytes after the location pointed by theMethod Table Slot
entry. 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
Flags
field 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. TheFlags
field 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
Invoke
method of the correspondingMethodInfo
. -
For direct normal method call, the
MethodRedirection
instance returned from a call to theRedirectTo
method 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.