How to generate a stacktrace of method that is called - c#

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.

Related

Is it normal to see an interface in a clr callstack?

I have an asp.net application, which is crashing. There is an entry for this in the windows event logs which contains this callstack:
Exception type: EntryPointNotFoundException
Exception message: Entry point was not found.
at ***.Interfaces.Portal.Repository.ILookup.get_LookupDataCollection()
at ***.Portal.Repository.Lookup.GetLookUpValue(ILookup lookup, Int32 index)
at ***.Portal.Repository.Lookup.GetLookUpValue(ILookup lookup)
at ***.HttpModules.RuntimeHttpModule.SetPageUrlInfoInContext(PageUrlInfo pinfo)
at ***PortalRuntime.HttpModules.RuntimeHttpModule.BeginRequest(Object sender, EventArgs e)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
This happens only on a customer machine and I was not able to reproduce it locally. As you see on the top there is an interface (ILookup, which is really an interface, not a class).
I built a similar sample (method called via an interface). Visual Studio 2015 is smart enough to show this:
ConsoleApplication2.exe!ConsoleApplication2.Lookup.GetLookupId(ConsoleApplication2.ILookup lookup) Line 37 C#
But there you still see the class which implements the method. I also attached to my sample with windbg and printed the stack when the application sits in a breakpoint in the method which was called via the interface: the interface was not on the stack.
Here is my question:
Is it normal to see an interface in a clr callstack (especially without the class which implements it)? I think I have never seen such a callstack before… Anyone else? (I mean this in general, regardless of the second part of my question)
Here is a very similar question: #Hans Passant in his first comment says “failure to resolve the implementation method for an interface method” and the OP says that “you already answered my question with your first comment”. So is this really the root cause? Does anyone know about a fix for this? Or is it just a special CLR version?
I can explain why you see this a little bit, it will not be helpful at all to resolve your problem. Nor do I know enough about the way the CLR binds interface methods to their implementation, it is crazily micro-optimized.
At issue is that the jitter must generate the code for the method that contains the interface method call. But it cannot yet know the identity of the object reference. That's not know 100% accurate until the code actually executes. So what it does is allocate a stub, a place holder for the target method. And generates a CALL instruction to that stub. The actual name of that stub method is not relevant, it is going to disappear again when the real target method is resolved.
The stub itself generates a call into the CLR to resolve the target method, now knowing the true identity of the object reference and thus which specific implementation method needs to execute. And patches the machine code so the CALL address is replaced. So the next time the method executes you don't pay the price of the method binding and the call runs at maximum possible warp speed.
As noted, the name of the stub does not matter since it is temporary. Giving it the name of the interface method is very helpful to diagnose a MissingMethodException. Good idea.
The real issue is that the assembly that was loaded is not the one you built your code with. Probably an old one that you forgot to redeploy. Or you just plain forgot to rebuild it when you changed the interface because it is not part of the solution. So it doesn't have an implementation of the interface method, the CLR discovers this very late, when the stub executes. So you see the stub method name on the call stack.

Ensure that method return value is not discarded for library

My library has some methods whose return value should never be discarded. Leaking them is a very popular mistake even for me, the author. So I want the compiler to alert programmer when it does so.
Such value may be either stored or used as an argument for another method. It's not strictly to use the stored value but if it's simply discarded it's 100% error.
Is there any easy to setup way to enforce this for my library users?
var x = instance.Method(); // ok
field = instance.Method(); // ok
instance.OtherMethod(instance.Method()); // ok
MyMethod(instance.Method()); // ok, no need to check inside MyMethod
instance.Method(); // callvirt and pop - error!
I thought about making IL analyzer for post-build event but it feels like so overcomplicated...
If you implement Code Analysis / FXCop, the rule CA1806 - Do not ignore method results would cover this case.
See: How to Enable / Disable Code Analysis for Managed Code
Basically, it's as simple as going to the project file, code analysis tab, checking a box and selecting what rules to error / warn on.
Basically tick the checkbox # 1, and then use 2 to get to a window where you can configure a ruleset file (this can either be one you share between libraries or something more global (if you have a build server, make sure its stored somewhere the build can get to, i.e. with the source not on a local machine).
Here's a ruleset with the rule I mean:
The Nicolai's answer enables ruleset for any types but I needed this check for only my library types (I don't want to force my library users to apply rule set on all their code).
Using out everywhere as suggested in the comments makes the library usage to hard.
Therefore I've chosen another approach.
In finalizer I check whether any method was called (it's enough for me to confirm usage). If not - InvalidOperationException. Object creation StackTrace is optionally recorded and appended to the error message.
User may call SetNotLeaked() to disable the check for particular object and all internal objects recursively.
This is not a compile-time check but it will surely be noticed.
This is not a very elegant solution and it breaks some guidelines but it does what I need, doesn't make user to view through unnecessary warnings (RuleSet solution) and doesn't affect code cleanliness (out).
For tests I had to make a base class where I setup Appdomain.UnhandledException handler in SetUp method and check (after GC.Collect) whether any exception was thrown in TearDown because finalizer is called from another thread and NUnit otherwise shows the test as passed.

Intercepting calls to a method in another assembly

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.

Write Out Class Methods to Log File

I have a need to write out a Class's Methods to a log file. This needs to be done so the end user can verify the calculations within the Methods are correct.
So, 2 questions:
Can this be done?
Do you need to see any of my code to accomplish this? C# or VB will work.
You can use Type.GetMethods() to obtain all the methods of a class (http://msdn.microsoft.com/en-us/library/vstudio/td205ybf).
You will obtain an array of System.Reflection.MethodInfo[] containing all the info you can need about a Method (http://msdn.microsoft.com/en-us/library/vstudio/system.reflection.methodinfo)
This needs to be done so the end user can verify the calculations within the Methods are correct.
This seems like an onerous task to me, is there a reason you want end-users having a view on the internals of your code?
If you want the parameters and the results of the methods being logged I recommend using Postsharp in particular the OnMethodBoundaryAspect. But as I said I'm not sure if this is what you're trying to achieve.

How to find out if a method directly or indirectly calls a property?

I'm trying to figure out how to avoid StackOverflowException in one of my classes, where a method indirectly calls a property that ends up calling back the method again. When this first happened, I looked up the stack trace and fixed the code, but then it happened again, in another place of the same method. I strongly suspect there are other indirect calls in that method that will cause the exception again, and so I'd like to be able to find all indirect calls to the property.
Is there some way, using Visual Studio 2010 Graphs functionality to visually assist in finding connections between a method and a property/field?
There isn't a graphical representation, but you can however just right click on the method and hit "Find All References", go through those calls and make sure that none of them are recursive.
Another option is debug, set a breakpoint on the method and check the call stack to identify any possible recursive calls.

Categories