Stackoverflow in InitializeComponent - c#

I have lots of controls (at least hundreds) added to my form, and quite a few of them are custom controls, and the code inside InitializeComponent is huge. Still, I simply cannot see how can there be any recursion and why does the stack overflow happen.
It only happens if I run the Debug version from inside VS (2008, it uses .net framework 3.5 and Winforms). If I just double click on the executable, the application runs.
Can someone tell me how is that possible, and what can I do to find out why?
Thanks.

Possibly the code of your InitializeComponent method contains a lot of local variable / big local variables (e.g struct with a lot of fields) - that use almost all the stack space available, and when running under the debugger within VS there is a little bit less space in the stack, hence the error.
If this is the problem, it might be fixed converting local variables to class fields, and/or splitting the InitInstance method in various methods with their own local variables - that will share the same stack space.

your best bet is to find out exactly where the exception is happening - control Alt E brings up the Exceptions dialog - click under Thrown for common language runtime exceptions and debugging will stop as soon as your error is thrown - from there you can view the call stack and trace the calls to see where you went wrong. (If the shortcut doesn't work, you can click debug/exceptions in visual studio for the same thing)
(Just to be clear - the Exceptions window brings up a dialog with a list down the left, C++ exceptions, Common Language Runtime Exceptions, etc... you want to click the first checkbox in line with the Common Language Runtime Exceptions so that your code breaks as soon as you hit your issue Then for further investiagtion, debug/windows/callstack - or control/alt C - which will quickly let you see if you do have recursion or some other issue.)

Related

Tools for tracing a C# crash when debugger exits with no call stack?

I have a large, complex C# GUI application which is crashing in a completely reproducible way, but I cannot easily diagnose the cause of the crash because rather than breaking the debugger with a call stack in the usual way, the debugging session completely exits.
The only hint is that there's a message at the end of the output window: STATUS_STACK_BUFFER_OVERRUN.
I am painstakingly trying to put breakpoints in at random places before the crash happens, trying to gradually get my breakpoints closer to where the problem happens, but this approach is not getting me anywhere quickly.
I'm wondering if there are any existing tools which work sort of like an instrumenting profiler, basically observing and logging all of the function enters and exits, so that when the program crashes with a corrupted stack, it's still possible to examine this external data to determine where execution was last happening?
I don't expect that this is a feature that most performance-oriented profilers have, since they are more concerned with how many times a function was called and for how long, but perhaps there's a tool which will tell me exactly what the last known running piece of code was?
I'm open to other suggestions if there's a way to solve/diagnose this within Visual Studio or using other techniques.
You can use a conditional breakpoint to trigger when the stack depth exceeds a certain value:
(new StackTrace()).GetFrames().Length > 60
The trick here is knowing where to put the breakpoint, as it has to be set somewhere in the recursive cycle. But if you know what triggers the error you might have enough intuition to choose some strategic places to put the check. You can also use a process of elimination: if the breakpoint isn't triggered, you know that code is not involved in the cycle.
Also note that the conditional breakpoint is costly and will significantly slow down the application being debugged. If you're not opposed to littering your code with debugging statements, you can call Debugger.Break() instead of setting breakpoints:
if (Debugger.IsAttached && (new StackTrace()).GetFrames().Length > 60)
Debugger.Break();
STATUS_STACK_BUFFER_OVERRUN means that someone blew passed the end or beginning of their stack variables, most likely in unmanaged or interop code.
If you attach the debugger in native mode or mixed mode, go to the Exceptions window and add a Win32 exception with the code 0xc0000409 (stack overflow). If you trigger the error, it should break in the debugger.
You can use my Runtime Flow tool to log all function calls in your application. After a crash you can see what was the last function enter.

Visual Studio 2015+ C#/.NET Debugger: How to break only on unhandld exceptions?

So, I have found a lot of resources and StackOverflow questions on this exact topic, but it seems to only apply to pretty old versions of Visual Studi0 -- like 2012.
My issue is that I want the Debugger to ONLY break when an exception is UN-HANDLED. The official MSDN says that the Debugger breaks on what is called a "first-chance" exception, meaning that it is intended functionality to break even if the exception is going to be handled.
I find it incredibly annoying to have the Debugger break on an InvalidCastException that I have wrapped inside a try-catch. Is there any way that I can force the Debugger to ignore first-chance exceptions that will be handled? A common answer is to just disable breaking on that particular CLR Exception type, but that's honestly a ridiculous solution. I don't want to suppress the Exception everywhere. I just don't want to be notified that an Exception was thrown when I already guarded against it.
I can imagine your frustration, but there has to be something odd with your VisualStudio settings. I can assure you that on my setups, VS never catches exceptions that are handled, and that is/was true across all VS versions ranging from VS2008 upto VS2015.
"FirstChance exception" line you see in the output window is an information that an exception has been just thrown, at exactly that moment, before any handlers were triggered or stacks unwound.
But that does not imply any breaking in VisualStudio. Only a one-liner is written to the debug output, and program continues - stack is unwound, and nearest matching catch is executed, and program runs forward.
Now, the VS/Debugger/CLR can break on exceptions being throw, but it has to be turned on. You can get there by Debug->Windows->Exceptions, or press CTRL+D+E. When you click that, a new panel should appear, with a list of exceptions and one or two options for each of them:
break when thrown
break on unhandled
but that may vary depending on your VS version. For example, in VS Community 2015, there's only "Break when thrown", and "unhandled" is not visible, but still is active for all of them. You just can't turn off breaking on "unhandled".
Anyways, the important thing is that by default, all "unhandled" are selected, and none or almost none of "when thrown" is. In VS2015Community, I see following "when thrown" set by default:
some C++ "Platform::xxxx" exceptions
System.Reflection.MissingMetadata [<-C#]
System.Reflection.MissingRuntimeArtifact [<-C#]
System.Windows.Markup.XamlParseException [<-C#]
Javascript exception: Access Denied, code 0x80070005
some ManagedDebuggingAssistants: LoaderLock, ContextSwitch, ...
a few Win32 exceptions
and that's all. Maybe total of 10..20 very specific types, I didn't count. In "Common Language Runtime" group only three are checked by default, those listed above. No InvalidCastExceptions.
If your VS is triggering at the moment it is thrown, then it means that you, or someone that had access to your VS, has configured it differently. Most probably, in that "ExceptionSettings" panel, you have "InvalidCastException" marked as "break when thrown". Go there, see the state of the checkbox at "InvalidCastExceptions" and uncheck it, and retry.
If this helps for the case of InvalidCastExceptions, and if this problem happens for some other exceptions as well, then you can repeat it for any other type that you dont want to break-on-thrown. And yes, it means that at some point of time you (or someone else) have clicked there and checked them to break on them.
If you have many of them checked to break-on-thrown, then instead of clicking on each one, you can click on the subtree root and check/uncheck whole groups. (btw. maybe you had accidentaly clicked and checked a whole group a week or month ago?)
Also, there's a very useful "Restore Defaults" underrightclick and even a button called "Restore the list to default settings", both of which simply reset everything to the default settings (like in the list I wrote above: some C++, some reflection, some win32, and so on).
Finally, whatever exceptions you deselect for break-on-thrown in ExceptionSettings panel, VisualStudio will still break on any unhandled exceptions. (unless you see there another set of checkboxes, labelled as "unhandled" - there was such thing in i.e. VS2010Pro, but in VS2015Community I dont see it.. maybe it's a Pro thing)
As of Visual Studio 2015, you can go to Debug -> Windows -> Exception Settings. You define which exceptions to automatically break for on a case-by-case basis. There is also a link to this window when VS breaks for an exception - click on "Exception Settings" at the bottom of the window.
On my home computer, I only see one column, "Thrown", so to your point, there is no way to throw only unhandled exception. At work, though, I have a second column called "User Unhandled", which allows me to do exactly what you're talking about. Leaving "user unhandled" checked and unchecking "thrown" causes it to break only on unhandled exceptions, not on ones that are caught. I think this may be a feature of Visual Studio Professional edition - at home I use Community Edition.
If you use the higher VS version like the VS2015, it has no the option to enable/disable the Unhandled Exception like the Old VS version, but it has his own feature:
So if we just want to capture the unhandled exception, we could disable the checkbox.
Is there any way that I can force the Debugger to ignore first-chance exceptions that will be handled?
I don't want to suppress the Exception everywhere. I just don't want to be notified that an Exception was thrown when I already guarded against it.
But if you still want to get the first change exception messages that will be handled, it has no good workaround for this issue, since at this point the debugger does not know if the exception will be caught (handled) by the application, and if you enable the checkbox, it will capture the first-chance exception(When an exception is first thrown in the application, this is classified as a “first chance” exception).
Reference:
https://blogs.msdn.microsoft.com/visualstudioalm/2015/02/23/the-new-exception-settings-window-in-visual-studio-2015/
https://blogs.msdn.microsoft.com/visualstudioalm/2015/01/07/understanding-exceptions-while-debugging-with-visual-studio/#unhandled.
Remember that you can define your own build configuration next to Release or Debug which can follow the #if <name> and #endif marks in your code. There you can for example decide if you want to focus on exception or not depending on configuration.

How to get information on a Buffer Overflow Exception in a mixed application?

In all WPF application I develop there is a global exception handler subscribed to AppDomain.CurrentDomain.UnhandledException which logs everything it can find and then shows a dialog box telling the user to contact the author, where the log file is etc. This works extremely well and both clients and me are very happy with it because it allows fixing problems fast.
However during development of a mixed WPF / C# / CLI / C++ application there are sometimes application crashes that do not make it to the aforementioned exception handler. Instead, a standard windows dialog box saying "XXX hast stopped working" pops up. In the details it shows eg
Problem Event Name: BEX
Application Name: XXX.exe
Fault Module Name: clr.dll
...
This mostly happens when calling back a managed function from within umanaged code, and when that function updates the screen. I didn't took me long to figure out the root cause of problem, but only because I can reproduce the crash at my machine and hook up the debugger: in all occasions the native thread was still at the point of calling the function pointer to the managed delegate that calls directly into C#/WPF code.
The real problem would be when this happens on a client machine: given that usually clients are not the best error reporters out there it migh take very, very long to figure out what is wrong when all they can provide me are the details above.
The question: what can I do to get more information for crashes like these? Is there a way to get an exception like this call a custom error handler anyway? Or get a process dump? When loading the symbols for msvcr100_clr0004.dll and clr.dll (loaded on the thread where the break occurrs), the call stack is like this:
msvcr100_clr0400.dll!__crt_debugger_hook()
clr.dll!___report_gsfailure() + 0xeb bytes
clr.dll!_DoJITFailFast#0() + 0x8 bytes
clr.dll!CrawlFrame::CheckGSCookies() + 0x2c3b72 bytes
Can I somehow hook some native C++ code into __crt_debugger_hook() (eg for writing a minidump)? Which leads me to an additional question: how does CheckGSCookies behave on a machine with no debugger installed, would it still call the same code?
update some clarification on the code: native C++ calls a CLI delegate (to which a native function pointer is acquired using GetFunctionPointerForDelegate which in turn calls a C# System.Action. This Action updates a string (bound to a WPF label) and raises a propertychanged event. This somehow invokes a buffer overflow (when updating very fast) in an unnamed thread that was not created directly in my code.
update looking into SetUnhandledExceptionFilter, which didn't do anything at first, I found this nifty article explaining how to catch any exception. It works, and I was able to write a minidump in an exception filter installed by using that procedure. The dump gives basically the same information as hooking the debugger: the real problem seems to be that the Status string is being overwritten (by being called from the native thread) while at the same time being read from the ui thread. All nice ans such, but it does require dll hooking which is not my favorite method to solve things. Another way would still be nice.
The .NET 4 version of the CLR has protection against buffer overflow attacks. The basic scheme is that the code writes a "cookie" at the end of an array or stack frame, then checks later if that cookie still has the original value. If it has changed, the runtime assumes that malware has compromised the program state and immediately aborts the program. This kind of abort does not go through the usual unhandled exception mechanism, that would be too exploitable.
The odds that your program is really being attacked are small of course. Much more likely is that your native code has a pointer bug and scribbles junk into a CLR structure or stack frame. Debugging that isn't easy, the damage is usually done well before the crash. One approach is to comment out code until the crash disappears.

C# Exceptions only caught when debugging? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Exception handling problem in release mode
I suspect there is a perfectly simple explanation for this, but I can't seem to find it.
When my WinForms C# 4.0 application loads itself in the Program.cs file, the entire Main() function has inside it a try/catch statement.
I have written a little exception wrapper which behaves quite similarly to the vanilla .net "uncaught exception" box, except it provides a bit more information, allows the exception tree to be saved (serialised), and it allows the user to submit the error report directly to me.
Now, it works fine while debugging (F5). If I trigger an exception anywhere in the program which is in the main thread, if there is not try/catch then the exception fires its way all the way back to Main() and shows the custom window.
(All other exceptions I have accounted for and are handled appropriately).
When I run the program simply by running the .exe file, the vanilla .net exception box comes up, not the one I have coded.
Is there any reason you can think of why this would happen?
The strangest thing is that it behaves quite differently when running in debug mode vs running on its own.
I am building as debug - not release.
Edit (22-March-11):
I'm just adding a little addendum here, in case some of you can't find the answer hidden in the comments for the accepted answer below:
Forget that I said I was building as debug instead of release. That is of no relevance - I just added it for extra info. What is important is that when I'm debugging in VS the exceptions are caught as expected, but when executing my EXE outside VS they aren't.
As Cody said, Application.Run() has its own handler for exceptions which is why they never get to my main catch, however I mentioned that I am not even using Application.Run() anywhere in my code... instead my GUI is first launched with Form.ShowDialog().
I have done some experimentation, and can confirm that Form.ShowDialog() behaves the same was as Application.Run() in that exceptions are handled within the method itself.
This is the expected behavior.
The difference you see is a result of the application being run with the debugger attached. When you launch it from within Visual Studio, the debugger is automatically attached (unless, of course, you choose to "Start Without Debugging"). That disables the built-in exception handler, which is the one responsible for showing you the "vanilla" .NET exception dialog. Launching it from outside VS doesn't attach the debugger, leaving the built-in exception handling enabled. (Note that this has nothing to do with compiling your program in "Debug" mode versus "Release" mode.)
See the accepted answer to this related question for more information. I do not believe the difference between VB.NET and C# is relevant in this case.
As that answer mentions, there is a way to disable the built-in exception handler. But before choosing to do so, I recommend reconsidering your approach. Rather than wrapping your entire Main method in a try-catch block, which sounds like a bit of a code smell to me, you might consider handling the built-in AppDomain.UnhandledException event. Jeff Atwood posted a great article here on Code Project about how to replace the standard .NET exception handling with your own more user-friendly method. The solution he proposes has become only that much more elegant as later versions of the .NET FW have improved how the AppDomain.UnhandledException event is handled.

Third-party dll crashes program with no exception thrown

I am using Visual Studio 2010, and coding in C#. I have a third-party dll that I am using in my project. When I attempt to use a specific method, at seemingly random occasions, the program simply crashes, with no exception thrown. The session simply ends. Is there any way I can trace what is going on?
The way the stack for a thread is laid out in Windows goes like this (roughly; this is not an exact description of everything that goes on, just enough to give you the gist. And the way the CLR handles stack pages is somewhat different than how unmanaged code handles it also.)
At the top of the stack there are all the committed pages that you are using. Then there is a "guard page" - if you hit that page then the guard page becomes a new page of stack, and the following page becomes the new guard page. However, the last page of stack is special. If you hit it once, you get a stack overflow exception. If you hit it twice then the process is terminated immediately. By "immediately" I mean "immediately" - no exception, go straight to jail, do not pass go, do not collect $200. The operating system reasons that at this point the process is deeply diseased and possibly it has become actively hostile to the user. The stack has overflowed and the code that is overflowing the stack might be trying to write arbitrarily much garbage into memory. (*)
Since the process is potentially a hazard to itself and others, the operating system takes it down without allowing any more code to run.
My suspicion is that something in your unmanaged code is hitting the final stack page twice. Almost every time I see a process suddenly disappear with no exception or other explanation its because the "don't mess with me" stack page was hit.
(*) Back in the early 1990s I worked on database drivers for a little operating system called NetWare. It did not have these sorts of protections that more modern operating systems now have routinely. I needed to be able to "switch stacks" dynamically while running at kernel protection level; I knew when my driver had accidentally blown the stack because it would eventually write into screen memory and I could then debug the problem by looking at what garbage had been written directly to the screen. Ah, those were the days.
Have you checked the Windows Event Log? You can access that in the Admin Tools menu > Event Viewer. Check in the Application and System logs particularly.
Try to force the debugger to catch even handled exceptions - especially the bad ones like Access Violation and Stack Overflow. You can do this in Debug -> Exceptions.
It is possible that the third-party DLL catches all exceptions and then calls exit() or some similar beauty which quits the whole program.
If your third-party dll is managed, using Runtime Flow (developed by me) you can see what happens inside of it before the crash - a stack overflow, a forceful exit or an exception will be clearly identifiable.

Categories