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.
Related
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
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.
I have C# code that throws ExecutionEngineException only when I debug it. When I just run it from Visual Studio without debugging (press the "Start without debugging") button, this piece of code works OK. But when I debug it from Visual Studio it throws ExecutionEngineException.
Due to this problem I cannot debug my application, as the code I am trying to debug is executed AFTER the problematic piece of code.
Here are some details:
I am using Visual Studio 2012
The main application is a C++/CLI application that calls my C# code
The application runs for some time until it reaches the problematic lines of code in C#
The relevant code is a query against an Entity Framework context.
I am using Entity Framework 5
The DB where my entities are stored is SQL Server LocalDB (the one that comes with VS2012)
Edit
Further investigation shows that the actual problem is an access violation exception that originates in the default constructor of System.Data.DataSet, which also happens if I just write new DataSet().
Edit 2
I created a small application that demonstrates this problem. The source code can be found here.
You are welcome to compile it and try and run the project Application. It should crash in Adder.cs with ExecutionEngineException when creating a new DataSet. Please note that the debugger should be Mixed and not Managed/Native.
Your C++/CLI code is most likely corrupting the garbage collected heap. A very typical way for unmanaged code to misbehave. This doesn't get discovered until later, like when you new an object or the garbage collector runs. So the code that crashes is completely unrelated to the code that caused the corruption and gives you no hint whatsoever where the bug is located.
There is very little joy in debugging this, it typically takes a thorough code review, lots of unit tests on the unmanaged code and days of debugging to find it. The "crashes only in the debug build" scenario is very common as well, it doesn't mean that there is no heap corruption in the release build. You are a bit lucky that it fails like this, heap corruption is way harder to debug when it occurs in the release build. You'll want to invest in a debug allocator to catch the bug in action, like the one you get out of <crtdbg.h>. This problem in general made garbage collectors a favored way to manage memory.
My condolences and good luck with it.
My application is a mix of C# and C++ code. Startup module written in C# loads during initialization phase C++ module through COM (Component Object Model) mechanism. All was functioning correctly until I decided to add to C# part a wcf service. All wcf service calls are routed to C++ code using COM. After adding some new methods I noticed memory leaks in output window. So I added breakpoint to desctructor of C++ class as can be seen from screenshot. From this point on weird things started to happen. After program reaches breakpoint it unexpectedly crashes. First weird thing is that when I run program without breakpoint being set it ends graciously. Second weird thing is that the way program crashes is as if it were running without debugger. After clicking on button "Open in debugger" (or something like this) I get error message: "Program is already opened under debugger." None message in output window that could point me to the source of the error, none suspicious code.
When adding message box to destructor beginning it displays for fraction of second and then whole application closes (without adding user opportunity to read whats displayed in message box). Desperately searching for any clue.
P.S. Problems occurs only when wcf method was called at least once. Doesn't depend if program flow in this particular call was routed to C++ level or not.
When calling C# from C++ sometimes the garbage collector doesn't properly get called before program end. Try forcing garbage collection at the end of your C# code.
Resolved by following code:
public void Dispose()
{
Marshal.Release(internal_interface_ptr);
internal_interface_ptr = IntPtr.Zero;
Marshal.ReleaseComObject(internal_interface);
Marshal.ReleaseComObject(internal_interface);
internal_interface = null;
}
Beside this one other reference was hanging in C++ code. So to make conclusion, main mistake on my part was forgetting to explicitly release COM object in C# code. Even if garbage collector takes task of managing memory this isn't true for modules written in other programming languages. COM destructor was called very lately when particular dynamic linked library was to be unloaded from memory and this caused problems. Hope I explained it sufficient clearly.
I think I have a curly one here... I have an WinForms application that crashes fairly regularly every hour or so when running as an x64 process. I suspect this is due to stack corruption and would like to know if anyone has seen a similar issue or has some advice for diagnosing and detecting the issue.
The program in question has no visible UI. It's just a message window that sits in the background and acts as a sort of 'middleware' between our other client programs and a server.
It dies in different ways on different machines. Sometimes it's an 'APPCRASH' dialog that reports a fault in ntdll.dll. Sometimes it's an 'APPCRASH' that reports our own dll as the culprit. Sometimes it's just a silent death. Sometimes our unhandled exception hook logs the error, sometimes it doesn't.
In the cases where Windows Error Reporting kicks in, I've examined memory dumps from several different crash scenarios and found the same Managed exception in memory each time. This is the same exception I see reported as an unhandled exception in the cases where we it logs before it dies.
I've also been lucky (?) enough to have the application crash while I was actively debugging with Visual Studio - and saw that same exception take down the program.
Now here's the kicker. This particular exception was thrown, caught and swallowed in the first few seconds of the program's life. I have verified this with additional trace logging and I have taken memory dumps of the application a couple of minutes after application startup and verified that exception is still sitting there in the heap somewhere. I've also run a memory profiler over the application and used that to verify that no other .NET object had a reference to it.
The code in question looks a bit like this (vastly simplified, but maintains the key points of flow control)
public class AClass
{
public object FindAThing(string key)
{
object retVal = null;
Collection<Place> places= GetPlaces();
foreach (Place place in places)
{
try
{
retval = place.FindThing(key);
break;
}
catch {} // Guaranteed to only be a 'NotFound' exception
}
return retval;
}
}
public class Place
{
public object FindThing(string key)
{
bool found = InternalContains(key); // <snip> some complex if/else logic
if (code == success)
return InternalFetch(key);
throw new NotFoundException(/*UsefulInfo*/);
}
}
The stack trace I see, both in the event log and when looking at the heap with windbg looks a bit like this.
Company.NotFoundException:
Place.FindThing()
AClass.FindAThing()
Now... to me that reeks of something like stack corruption. The exception is thrown and caught while the application is starting up. But the pointer to it survives on the stack for an hour or more, like a bullet in the brain, and then suddenly breaches a crucial artery, and the application dies in a puddle.
Extra clues:
The code within 'InternalFetch' uses some Marshal.[Alloc/Free]CoTask and pinvoke code. I have run FxCop over it looking for portability issues, and found nothing.
This particular manifestation of the issue is only affecting x64 code built in release mode (with code optimization on). The code I listed for the 'Place.Find' method reflects the optimized .NET code. The unoptimized code returns the found object as the last statement, not 'throw exception'.
We make some COM calls during startup before the above code is run... and in a scenario where the above problem is going to manifest, the very first COM call fails. (Exception is caught and swallowed). I have commented out that particular COM call, and it does not stop the exception sticking around on the heap.
The problem might also affect 32 bit systems, but if it does - then the problem does not manifest in the same spot. I was only sent (typical users!) a few pixels worth of a screen shot of an 'APP CRASH' dialog, but the one thing I could make out was 'StackHash_2264' in the faulting module field.
EDIT:
Breakthrough!
I have narrowed down the problem to a particular call to SetTimer.
The pInvoke looks like this:
[DllImport("user32")]
internal static extern IntPtr SetTimer(IntPtr hwnd, IntPtr nIDEvent, int uElapse, TimerProc CB);
internal delegate void TimerProc(IntPtr hWnd, uint nMsg, IntPtr nIDEvent, int dwTime);
There is a particular class that starts a timer in its constructor. Any timers set before that object is constructed work. Any timers set after that object is constructed work. Any timer set during that constructor causes the application to crash, more often than not. (I have a laptop that crashes maybe 95% of the time, but my desktop only crashes 10% of the time).
Whether the interval is set to 1 hour, or 1 second, seems to make no different. The application dies when the timer is due - usually by throwing some previously handled exception as described above. The callback does not actually get executed. If I set the same timer on the very next line of managed code after the constructor returns - all is fine and happy.
I have had a debugger attached when the bad timer was about to fire, and it caused an access violation in 'DispatchMessage'. The timer callback was never called. I have enabled the MDAs that relate to managed callbacks being garbage collected, and it isn't triggering. I have examined the objects with sos and verified that the callback still existed in memory, and that the address it pointed to was the correct callback function.
If I run '!analyze -v' at this point, it usually (but not always) reports something along the lines of 'ERROR_SXS_CORRUPT_ACTIVATION_STACK'
Replacing the call to SetTimer with Microsoft's 'System.Windows.Forms.Timer' class also stops the crash. I've used a Reflector on the class and can see internally it still calls SetTimer - but does not register a procedure. Instead it has a native window that receives the callback. It's pInvoke definition actually looks wrong... it uses 'ints' for the eventId, where MSDN documentation says it should be a UIntPtr.
Our own code originally also used 'int' for nIDEvent rather than IntPtr - I changed it during the course of this investigation - but the crash continued both before and after this declaration change. So the only real difference that I can see is that we are registering a callback, and the Windows class is not.
So... at this stage I can 'fix' the problem by shuffing one particular call to SetTimer to a slightly different spot. But I am still no closer to actually understanding what is so special about starting the timer within that constructor that causes this error. And I dearly would like to understand the root cause of this issue.
Just briefly thinking about it it sounds like an x64 interop issue (i.e., calling x32 native functions from x64 managed code is fraught with danger). Does the problem go away if you force your application to compile as x32 platform from within project properties?
You can read suggestions on forcing x32 compile during x32/x64 development on Dotnetrocks. Richard Campbell's suggestion is that Visual Studio should default to x32 platform and not AnyCPU.
http://www.dotnetrocks.com/default.aspx?showNum=341 (transcript).
With regard to advanced debugging, I have not had a chance to debug x64 interop code, but i hear that this book is an great resource: Advanced .NET Debugging.
Finally, one thing you might try is force Visual Studio to break when an exception is thrown.
Use something like DebugDiag for x64 or Windbg to write a dump on Kernel32!TerminateProcess and second chance exception on .NET which should give you the actual .excr context frame of the exception that occurred.
This should help you in identifying the call-stack for the process terminate.
IMO it could be mostly because of PInvoke calls. You could use Managed Debugging Assistants to debug these issues.
If MDA is used along with Windbg it would give out messages that would be helpful in debugging
Also I have found tools from the http://clrinterop.codeplex.com/ team are extremely handy when dealing with interop
EDIT
This should give an answer why it is not working in 64 bit Issue with callback method in SetTimer Windows API called from C# code .
This does sound like a corruption issue. I would go through all of your interop calls and ensure that all of the parameters to the DllImport'ed functions are the correct types. For exmaple, using an int in place of an IntPtr will work in 32 bit code but can crash 64 bit.
I would use a site like PInvoke.net to verify all of the signatures.