System.AccessViolationException break on thrown - c#

I am trying to resolve a AccessViolationException that is created when returning from native to managed code. Visual studio 2015 / .Net 4.0. I went into the Exception Settings and selected to Break when thrown for AccessViolationException. However that does not appear to occur. I read that there are new behaviors for this exception here.
https://msdn.microsoft.com/en-us/library/system.accessviolationexception(v=vs.110).aspx
Would that prevent the debugger from breaking on the throw?
More details, and maybe you are right the VS simply cannot give me more. The native code returns a struct to the managed code. The struct is defined in managed so that the marshaling can occur. I can step through the native code and the method completes. The debugger ends up on the managed method which was pinvoked. I was hoping the debugger would stop at a point that would allow me to identify the offending memory component

Related

Catching fatal exceptions thrown from unmanaged code

Currently, there is no way (at least I did not find a way) to catch fatal exceptions (such as Stack Overflow, Segfault, ..) with try-catch block.
I already started issue at .net core repository so for more details you can read there (https://github.com/dotnet/core/issues/4228)
What I'm trying to do is to make the application not crash when there is any segfault/stack overflow/any fatal exception in loaded unmanaged code. what happens now is that .NET CLR kills my application if any fatal error occurs.
Example:
In c# managed code loaded external c++ dll via kernel LoadLibrary function.
Assume the dll is intentionally created for robustness testing therefore when a specific function is called it triggers segfault (e.g. trying to get data from outside of array bounds).
When this error happens this gets caught by .net CLR and immediately kills the calling managed c# code(application).
What I would like is just report that this happens instead of dying silently.
I did some research and found out there is the reasoning behind that which is described in the issue above.

VS2013 doesn't seem to attach correctly - a debugger is attached to but not configured to debug this unhandled exception

While coding a console app, I'm using an SAP DLL.
I'm getting the following error when trying to add an SAP object:
A debugger is attached to but not configured to debug this unhandled exception. To debug this exception detach the current debugger.
Code:
SAPbobsCOM.GeneralService oGeneralService = oCmpSrv.GetGeneralService("WEPPAGE");
SAPbobsCOM.GeneralData oGeneralData = (SAPbobsCOM.GeneralData)oGeneralService.GetDataInterface(di.GeneralServiceDataInterfaces.gsGeneralData);
oGeneralData.SetProperty("U_WebId", "1");
try
{
oGeneralService.Add(oGeneralData);
}
catch (Exception e)
{
Logger.WriteLog("Error Add object " + e.Message);
}
Although the code is wrapped with try&catch, the IDE crashes.
After many searches and suggestions around the web, which did not helped, I came across this post and applied the suggested solution and enabled native code debugging under the project properties debug tab.
The result of ticking this option was that instead of letting me debug the unknown error, the exception just "disappeared" and the code runs with no interference.
Questions
Why does the exception disappears and not debugged?
Is it possible to have a different workaround for this problem since enabling the native code debugging is slowing down the app by 10x and not a real solution this problem.
Although the code is wrapped with try&catch, the IDE crashes
No, the WER dialog shows that it is your program that crashed, not the IDE. Not your code, OBServerDLL is a SAP component. And given the nature of the crash, using try/catch is not going to be able to catch this exception, it occurs on a worker thread inside the SAP code.
Do keep in mind that the crash reason is very nasty, exception code c0000005 is the equivalent of an AccessViolationException. The usual reason for it is memory corruption. Never catch an exception like that, your program cannot meaningfully continue operating.
Why does the exception disappears and not debugged?
This is certainly not supposed to happen, very unhealthy. AVEs do tend to be rather random, memory corruption does not guarantee a crash. Keep in mind that when it does occur while you are debugging then you still can't find out anything about the reason, you don't have the source code for the OBServerDLL.
enabling the native code debugging is slowing down the app by 10x
That's quite unlikely, unless the native code is throwing exceptions at a very high rate. Something you can easily see in the Output window. What it does do is slow-down the startup of your debug session. The debugger will try to find PDBs for all the native executables, it isn't going to find anything at the Microsoft Symbol Server for SAP code. Simplest way to avoid that delay is using Tools > Options > Debugging > Symbols, untick the "Microsoft Symbols Servers" option.
This question at the SAP support forums would be somewhat comparable. Also the best place to find help with a problem like this. Albeit that it is likely you need support from a SAP escalation engineer, he'll need a small repro project and a minidump of the crashed process.

try/catch not working inside UnhandledException handler

I've got a weird symptom in an application, where try/catches inside the handler for UnhandledExceptions don't work: (that is a breakpoint inside the catch does not get hit, even if the breakpoint inside the try does).
Obviously searching for 'exception unhandled inside UnhandledException' is not working very well for me.
I've tried doing a mini proof-of-concept, and unfortunately that one works.
So while I'm trying to track down the root of the problem, if anyone here has any ideas where to look I'd be greatful.
(We recently changed from XP to Windows7, and .Net 4.5 from 4.0 - I'm pretty certain that previously this worked).
EDIT: Looks like it's provoked by a call down to a (managed) C++ library which is throwing a System.AccessViolationException. Strangely, if I replace the call with a throw new AccessViolationException, it does do what I want...
You wrote, "We recently changed ... .Net 4.5 from 4.0 - I'm pretty certain that previously this worked." but the following seems worth adding, because pretty sure really means not certain :-)
I read somewhere that AccessViolationException cannot occur in managed code, but may be trapped by the runtime for unmanaged code. Maybe the C++ library calls into unmanaged code?
In .NET 4+ the process will terminate after AccessViolationException. Your exception handler will be ignored. This is among a group of exception types considered unrecoverable: Corrupted State Exceptions. In .NET 4+ you will need to customise the app config to override this behaviour.
Be sure that you try to catch System.AccessViolationException and not native Access Violation error.
When you do throw new AccessViolationException it throws System.AccAccessViolationException.
If library that you calls is native it can throw native Access Violation error, but .NET catch block normally can catch only managed exceptions.
try this:
i think we can't handle Unhandeled exception and have to exit application in finally.
http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx

C# weird exception error

I am calling a function from a native .NET dll like this:
string v = myDLL.GetValueFromString("header");
MessageBox.Show(v);
Upon execution of the program, I get this weird error (on the line which executes this function): "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
What does this error message mean? And is there a way to fix this problem?
This is an AccessViolationException. It is a 'hard' exception, the processor actually crashes trying to execute the machine code. Usually because it is trying to access unmapped memory through a bad pointer value. It is all too common with native code, especially the kind of code that works with C strings.
I'm going to guess that you didn't write this code, you'll need help from the author. Send him a small test program that reproduces the problem. If you want a shot at debugging this yourself then you need the source code for the DLL and switch the debugger to mixed mode so that you can debug both your C# and the native code. Project + Properties, Debug tab, tick the "Enable unmanaged code debugging" option. Set a breakpoint in the native function you are calling.

After calling a COM-dll component, C# exceptions are not caught by the debugger

I'm using a COM dll provided to me by 3rd-party software company (I don't have the source code). I do know for sure they used Java to implement it because their objects contain property names like 'JvmVersion'.
After I instantiated an object introduced by the provided COM dll, all exceptions in my C# program cannot be caught by the VS debugger and every time an exception occurs I get the default Windows Debugger Selection dialog (And that's while executing my program in debug mode under a full VisualStudio debugging environment).
To illustrate:
throw new Exception("exception 1");
m_moo = new moo(); // Component taken from the COM-dll
throw new Exception("exception 2");
Exception 1 will be caught by VS and show the "yellow exception window".
Exception 2 will open a dialog titled "Visual Studio Just-In-Time Debugger" containing the text "An unhandled win32 exception occurred in myfile.vshost.exe[1348]." followed by a list of the existing VS instances on my system to select from.
I guess the instantiation of "moo" object overrides C#'s exception handler or something like that. Am I correct and is there a way to preserve C#'s exception handler?
Well, that's not good. You however haven't proven yet that the CLR's exception handling logic is completely borked. What you describe could also be explained by something detaching the debugger. The Java JVM would certainly be a candidate. Check if a try still works, if it does you still stand a chance to use this COM server.
Debugging is however going to be painful. With some luck, the detach happens only once. Try writing System.Diagnostics.Debugger.Break() after the very first call to the server, click "Debug" on the dialog you'll get.
Also test if a null reference exception still works, that's a hardware exception that's liable to be redirected by a VM calling Windows' SetUnhandledExceptionFilter(). If that can't be caught then you should not use this COM server as-is, it will destabilize your process too much. Running it in a separate process and talking to it with WCF or Remoting is a desperation move that could work out.
Needless to say, this component vendor is violating the COM server contract badly. You shouldn't have to put up with it.
Adding the following line (as the first line) in my main() (in Program.cs file) made exceptions work again:
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
The above line overides the Automatic handler which (I guess) for some reason stopped working after using the COM component.

Categories

Resources