Intercepting calls to a method in another assembly - c#

Is there a way to do the following, possibly by reflection? Reflection isn't required. Any method is acceptable.
I have two assemblies, VenderAssembly (I do not have the source code) and MyAssembly. I would like to invoke MyAssembly.MyMethod whenever VenderAssembly.VendorMethod is invoked where MyAssembly is not the assembly responsible for invoking VenderMethod.
I do not need access to the argument values being passed to VendorMethod. I just need to trigger MyMethod each and every time VendorMethod is invoked.

You can't call a method 'dynamically' when another one is called.
You can't register on methods, you can only register on events. So unless your VendorMethod() calls an event VendorMethodCalled, which you can subscribe to, it is not possible.

Ziad Elmalki has written a description of how to replace a method implementation at runtime and published code.
It appears that the crucial part of the technique is to ask the JIT to compile a method with the same signature as the one to be replaced, and then overwrite the method table of the type (managed version of a vtbl) to refer to the new method.
The replacement will be unconditional, if you want to test whether the call is coming from outside the assembly, you'd need to do a stack walk (.NET makes this fairly easy).
Of course, this will fail to replace methods which are small enough for the JIT to choose to inline them.

Related

Is there any way to auto run some code in DLL?

I have some DLL from third party that I need to license. It has some method that I must call from my own DLL. My DLL is referenced in couple of projects and I don't want to make changes to every hoster. Is there any method that I can use within my DLL which will call some method in my DLL? Like add some static class or constructor but without explicit call to that class from hosters? I am not sure if I am explaining it clearly. Please ask questions if needed.
ThirdPartyType license = new ThirdPartyType();
license.Load("license.xml");
This is a piece of licensing code that I want to place in my DLL and call it within the same DLL.
At the low level, the runtime supports "module initializers". However, C# does not provide any way of implementing them, so the closest you can manage is a static constructor ("type initializer") or just a regular constructor.
However, it is probably a bad idea to hook your licencing into either a module initializer or a type initializer, as you don't know when they will run, and it could impact code that wasn't going to access your lib. It is somewhat frowned upon to take someone's app down because your licensing code decided it was unhappy - especially if your library wasn't actively being invoked at the time.
As such: I suggest the most appropriate place to do this is in either a constructor, or a post-construction Initialize(...) method (with the tool refusing to work unless supplied with valid details).

Why it is possible to assign partial methods to delegates in spite of other constraints?

I know the title might not be totally clear, but I didn't want to make it too long.
One thing boggles me when thinking about restrictions placed on partial methods. It seems to me that the rules are inconsistent. As you probably know:
Partial methods must always have a return type of void, and they
cannot have any parameters marked with the out modifier. These
restrictions are in place because at run time, the method may not
exist and so you can’t initialize a variable to what the method might
return because the method might not exist. Similarly, you can’t have
an out parameter because the method would have to initialize it and
the method might not exist. [1]
It sounds sensible to me. But at the same time:
If there is no implementing partial method declaration, then you
cannot have any code that attempts to create a delegate that refers
to the partial method. Again, the reason is that the method doesn’t
exist at run time. [1]
At first, all these rules seem to follow the same compiler logic. There is a difference, though. As stated in the second quotation, compiler issues an error only when there is no method implementation of the partial method. Why can't it also check for the implementation at compile-time in other scenarios? This would allow much more flexibility when using partial methods and the logic behind all rules would be identical.
I am afraid that the only answer I can get is "Because that's how it was implemented", but maybe there is something more to it?
[1] CLR via C#, Fourth Edition
The whole point of partial methods is to facilitate extensibility in generated code scenarios without runtime performance impact. The code generator emits a partial method signature, and then emits code that calls this partial method.
Now, at compile time, if the method isn't implemented, these call sites get entirely removed, and the remaining code has to be valid. The quotes are confusing in this regard, because they're talking about "runtime existence" of the method. That's nonsense: everything is resolved at compile time.
This is the reason for the difference: the rules you quoted first impose restrictions on the method signature, whereas the delegate rule imposes a restriction on method usage.
The rules about the signature make sure you can call the method in a manner the code will remain valid if the method call is removed. And the intended use case for partial methods is for them to be absent 99% of the time. If you require them to be implemented then that's not the feature you should be using in the first place. Use an abstract method or something alike.
Building a delegate to a method is like taking the pointer to the method, and you can't do that if the method doesn't exist (well, I suppose you could argue the compiler could just replace the delegate with null at this point, but you can't write, say, new Action(null)), yet there is no reason to disallow it if the method does exist, for the implementer's convenience. But the code generator shouldn't emit code that creates delegates to the method.
Keep in mind that the reason for partial methods is so they can be used in designer-generated code, i.e. the designer can generate calls to the methods and leave their (optional) implementation to a human developer (who will later compile the code). If, as you suggest, the calls gave compile-time errors when the method is not implemented, then there are cases where the generated code would not compile until the developer either changed the generated code (usually a bad idea) or until he implemented all the methods.
C# already has interfaces and abstract methods to force method implementation, partial methods try to do something else.

Event / detect when your DLL gets loaded?

Imagine there is a MainLibrary.dll that's dynamically loading other helper DLLs. This is a design change for us and for this to work, we need to bootstrap the process by registering the AssemblyResolve callback.
This is simple to do when there is a single point of entry (eg: Main()) but in our case, MainLibrary.dll has multiple entry points. We'd want to avoid introducing an explicit Init() call since that would break the existing client-library API ("You must now call Init() before calling DoSomeWork()").
So is there a way for a library to know when it's been loaded or about to be used? That way we can latch onto that to perform our registration there, maintaining the client-library interface as before this dynamic loading change.
There is no built-in way for assembly to know when it is loaded (unlike in native code where DllMain get called on load).
You will need to reorganize your code to know when to load other binaries if they can't be loaded with default load rules.
Cheap way is to provide (maybe even automatically generated) layer of interface/objects wrapper implementations that will simply enforce loading of dependencies before calling into your actual API.

How to generate a stacktrace of method that is called

I call a method of another c# assembly, which returns true or false.
Now I want to find out if the method itself calls another method to generate the return value or simply returns true or false because it's hardcoded.
I already solved the problem by looking into the IL code, but but i'm wondering if there is an more generic way to do this by stacktrace?
The stack will show you the calls that lead to the current line, but not a complete history. In other words, you can only see whether a method was called while it is being called. After it returns from a method, the information about what happened inside is lost.
So if you own this method that may or may not be called, or any other methods it would trigger (via event subscription for example), you would be able to place StackFrame.GetFrame in one of them and see where it was coming from. Otherwise, I think the only way to do it would be to duplicate the logic inside the method to work out whether it would have been called.
Use a decompiler like DotPeek or JustDecompile.
http://www.jetbrains.com/decompiler/
http://www.telerik.com/products/decompiler.aspx
Don't waste time on IL (unless you really have lots of time)
Sorry that is not possible because other assembly can be just a .dll which u might have referenced in your project.
If you have ample of time you may try unethical way of breaking the .dll which will let you explore all the source code.

Injecting advice to a recursive method in Spring.Net?

I'm trying to use Spring.NET's support for AOP to do dependency injection/inversion of control/aspect-oriented programming (sorry for the slew of buzzwords - maybe I'll post a separate question asking someone to clarify the difference :) ).
Specifically, I want to have intercept a recursive method call, so that every time that the method is invoked, the AOP advice/interceptor will be called.
Spring.Net doesn't appear to intercept anything other than the very first method call. I think that Spring.Net is maintaining exactly 1 chain of interceptors per instance, and not call any more interceptors until that first method invocation has finished.
Does anybody have any info about getting the interceptor (the advice) to be triggered for EVERY method invocation, including recursive calls?
I can provide code/example output, if that's helpful.
Thanks!
See http://forum.springframework.net/showthread.php?t=5331
If you are using proxy-based AOP then this will not work for recursive method calls. The first call against the target will be intercepted by the proxy and your advice will run. Then the method on the target will be invoked, and subsequent calls will stay within the target class, ignorant of the proxy. The only way to make this work is to actually modify your bytecode so that class itself contains the behavior.
I actually haven't worked with Spring.NET (only Spring with Java) so I'm unfortunately ignorant about what kinds of bytecode weaving options exist in the .NET universe.
I know this isn't Spring.NET per se, but have a look at PostSharp. It gives you compile time weaving that doesn't rely on dynamic proxies, and would handle the recursive method call. The configuration is slightly different though...

Categories