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

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.

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).

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.

How is compiler dealing with these Generic Plugin Interface instance methods?

I'm working with some, unfortunately largely undocumented, existing code and I'm having trouble understanding how it calls upon the methods of the plugins it loads.
My aim at the moment is simply to step into one of the methods loaded via the plugin manager, as it's causing an exception. However I had to rebuild the pluginManager from the source to get debug symbols and when I reference this new DLL version the compiler throws up arms.
The code appears to load the plugin into plug.Instance and then access the specific methods like so plug.Instance.ReturnLeaNumber();
This compiler error makes sense, because it doesn't know the details of the plugins. What confuses me is how the compiler ever knew these where valid before run time, when no plugins are initialized. I can step through the code that doesn't work now with the older DLL!
This is an example of where the program loads up a plugin.
plug = GenericServicePlugins.AvailablePlugins.Find(Application.StartupPath + "\\Dlls\\SchoolInterface.dll");
// Compiler doesn't like this next line anymore though
plug.Instance.Initialize(null, null);
If there are any differences between my rebuilt library and the previously working one, I can't tell how as the versions match up with the ones in our source control. Would appreciate some advice on where to start looking!
public interface IGenericPluginMasterInterface
{
String returnName();
void Initialize(ExceptionStringResources.Translate ExceptionStrings);
Object ExecuteFunction(String macAddress, bool log, String functionName, LoginCredentials logonCredentials, WebConfiguration webConfig,
Int64 dataLinkId, DataLinkParam[] dataLinkParams, String dataName,
DataParam[] dataParams, Object[] additionalParams);
}
Rest of Manager code on PasteBin
How does the compiler know about these plug.Instance.Method() methods before runtime?
Edit:
I've not quite worked this out yet, but there was a "PluginsService" file I missed which partly mirrors the "GenericPluginServices".
I think this error could have been caused when I removed parts of this class that related to an now defunct plugin, which I am looking into. However I figured posting this other code snippet would help the question.
PluginService.cs code
GenericPluginService code
Find returns AvailablePlugin, so .Instance is of type IGenericPluginMasterInterface; if so, indeed; that .Instance.ReturnLeaNumber() can't possibly work...
The only way that could work (without introducing some generics etc) is if .Instance actually returned dynamic. With dynamic the name/method resolution is happening at runtime. The compiler treats dynamic very deliberately such as to defer all resolution to runtime, based on either reflection (for simple cases) or IDynamicMetaObjectProvider (for more sohpisticated cases).
However, if the code you have doesn't match what was compiled, then: we can't tell you what it was. IMO, the best option is to get hold of the working dll, and look at it in reflector to see what it is actually doing, and how it is different to the source code that you have.
Actually, strictly speaking it could still do that with the code you've pasted, but only if plug is typed as dynamic, i.e. dynamic plug = ...

Call-site explanation?

scaning the internet , im having trouble understanding in a simple manner - the term call-site (#dlr).
ive been reading here that CallSite is :
one site says
The location in which the method is called.
one book say :
call site . This is the sort of atom of the DLR - the smallest piece
of codewhich can be considered as a single unit. One expression may
contain a lot of call sites, but the behavioris built up in the
natural way, evaluating one call site at a time. For the rest of the
discussion, we'll onlyconsider a single call site at a time. It's
going to be useful to have a small example of a call site to refer
to,so here's a very simple one, where d is of course a variable of
type dynamic
d.Foo(10); The call site is represented in code as a
System.Runtime.CompilerServices.CallSite.
another book says :
the compiler emits code that eventually results in an expression tree
that describes the operation, managed by a call site that the DLR will
bind at runtime. The call site essentially acts as an intermediary
between caller and callee.
sorry , I cant see where those 3 explanations are combining into one simple explanation.
i'll be happy to get a simple explanation :
HOw can I explain my wife -what are call-sites ?
The first explanation has nothing to do with the dlr or the dynamic type: simply speaking, a call site is a location (or site) in the source code where a method is called.
In implementing the dynamic type, it is necessary to store information about the dynamic method calls contained in your code, so they can be invoked at runtime (the dlr needs to look up the method, resolve overloads, etc.). It seems natural that the object representing this information should also be called a ”call site”.
Ok this is how I see it.
For this example call is simply like a method or function that executes some code and returns.
For a static language runtime program (C, or CLR etc) a call site is essentially where a function call takes place. It's the location that the call will return to in a normal (non exceptional) flow. Since this is a static program the call site is simply a memory location, pushed on the stack.
For a dynamic language program (Ruby, Python, etc) , the code you are calling is not worked out until runtime. This means that some form of logic is needed to manage the process of making the correct function call and then cleaning up after the call (if needed). If the dynamic language program is on .NET 4 this is done using dlr (dynamic language runtime) objects of type System.Runtime.CompilerServices.CallSite. So the call will return to a method within the CallSite object and then on to location of the original call.
So the answer is that it depends upon how you doing the call and thus what platform you are using.

Code Access Security - Understanding why SecurityTransparent can call SecurityCritical

I am researching Code Access Security. It's taking some effort to get my head around, so I thought that I would finally make some use of Reflector and start investigating how .NET 4.0 uses security attributes.
Observations
The System.IO.File.Delete method is decorated with the [SecuritySafeCritical] attribute.
The System.IO.File.Delete method delegates to an internal method InternalDelete which is decorated with the [SecurityCritical] attribute.
I have a method in one of my MVC app classes called DeleteFile that is running as SecurityTransparent (which I've verified by checking DeleteFile's MethodInfo.IsSecurityCritical property)
Permissions
From my current understanding that would mean that:
System.IO.File.Delete can call InternalDelete because [SecuritySafeCritical] methods can call [SecurityCritical] so no SecurityException is thrown.
DeleteFile can call System.IO.File.Delete because [SecurityTransparent] can call [SecuritySafeCritical]
So basically, without adjusting any of the out of the box security settings, this code will succesfully delete a dummy file called test.txt
namespace MyTestMvcApp
{
public class FileHelpers()
{
// Has SecurityTransparent
public void DeleteFile()
{
// Will succesfully delete the file
File.Delete("test.txt");
}
}
}
Confusion
Inside the InternalDelete method of System.IO.File.Delete, it uses the CodeAccessPermission.Demand method to check that all callers up the stack have the necessary permissions. What I don't quite understand is this line in the MSDN docs of CodeAccessPermission.Demand:
The permissions of the code that calls this method are not examined; the check begins from the immediate caller of that code and proceeds up the stack.
So my question is, if the DeleteFile method of my application is SecurityTransparent, how come it is allowed to call a SecurityCritical method?
This is probably a broken example perhaps with some missing concepts, but as I said I'm still getting my head around it and any insight people can give the more I'll develop my understanding.
Thanks
You're mixing up two CAS enforcement mechanisms. While they do interact a bit, it's not in quite the same way you seem to be worrying about. For the purposes of full permission demands, as represented by Demand, they're essentially independent.
The CLR applies the transparency verification before executing the code. If this passes, the CLR would then verify any declarative CAS demands applied via attributes. If these pass (or are absent), the CLR would then execute the code, at which time the imperative (inline) demand would run.
The Demand documentation note about "the permissions of the code that calls this method are not examined" apply to the Demand method itself. In other words, if you have a method Foo that calls Demand, the verified call stack starts will Foo's caller, not Foo itself. For example, if you have the call chain A -> B -> C -> Foo -> Demand, only A, B, and C will be verified to check if they have the granted permission.

Categories