How to debug an application which suddenly terminates without any feedback? - c#

The application uses Xamarin.Android, which may be a big problem in itself. The problem is that sometimes it just quits (process is being terminated) and there's nothing in the log that can be associated with it. (although I guess that it's related to running out of memory, but I can't yet prove it — according to DDMS, most of the times all is OK, and if Xamarin.Android uses another pool of memory, then I don't know how to measure it)
I've searched the code base for "Environment.Exit" and, of course, didn't found anything.
What are the options for finding the culprit of such thing?

You could try to use the garbage collector by yourself. Just run
Runtime.getRuntime().gc();
The Runtime instance has also a method to read the free memory space. So you could figure out by yourself whether it's a memory problem.
EDIT:
Oh I read that Xamarin uses the C# language. But I'm quite sure that C# has similar methods.

When you say log, are you referring to an application log, or the device log?
When tracking down these sorts of bugs, I've always found aLogCat invaluable.
I open it, clear all the current logs, then use my application up to the point where it crashes. Then I quickly go back to aLogCat, pause it and scroll up to where the error is - it's usually found in the nearest red/orange blocks.
There's a blog post here about how I found attributes left out by the Xamarin linker using this method.

Related

Might GC.Collect() be warranted in this particular case?

Disclaimer: Yes, I know that the general answer to whether or not to use GC.Collect() is a resounding "NO!". This is the first time in several years of programming that I ever consider using it at all.
Well then, here's the situation: We have developed a C# scripting tool based on the Microsoft.CodeAnalysis.CSharp.Scripting libraries (v3.6.0). It's a Winform GUI with editor etc., not unlike others out there. We use it for the validation of integrated circuits, meaning that its primary task is interfacing lab equipment such as power supplies, pattern generators, meters and the like. For the communication to said instruments we predominantly rely on National Instrument's VISA framework, albeit not exclusively. Some devices are controlled directly via DLLs from their respective manufacturers. In general, this system is working beautifully and by now it is successfully used by quite a lot of design engineers who do not know the first thing about the intricacies of .NET and C#.
At this point I should explain that the user can simply write a method (i.e. on "top-level") and then execute it. The Roslyn-part behind this is that the input is fed to CSharpScript.Create() and then compiled. The execution of a method is done via Script.ContinueWith("method name"). Inside of such a method the user can construct an object like, say, new VISA("connection string"), which connects to the device and then communicate with the device via this object. Nothing forces him or her to care about disposing the object (i.e. closing the connection).
Now, the problem is this: recently, very sporadic crashes of the GUI application have occurred with no feedback at all from the system - the form just closes and that's it. By trial-and-error we are currently 99% sure that if all connection objects are explicitely disposed within a method, the crashes do not occur. So, rewriting the method to something like this fixes the problem:
using(var device = new VISA("connection string"))
{
device.Query("IDN?");
}
The reason why I look into the GC's direction at all is that there is no discernible correlation to any actions from the user. The guys might run such methods for an hour without a problem and then, when scrolling in the editor, when no method is currently being executed, the GUI closes without comment. And that's why I'd like to get some input from people more knowledgeable about Roslyn and the GC:
Are there known issues with this scripting library and GC? (I would very much assume that there aren't)
Since the explicit disposal of objects seem to prevent the issue, might this be one of the extremely scarce situations where the use of GC.Collect() might be warranted? (admittedly, I could not yet test whether that also prevents the problem thanks to of home office)
Any ideas what can cause a .NET application to crash without any kind of feedback and how to obtain more information about such a crash? (the scripting engine is a separate DLL, as are the device drivers; the GUI only handles the graphics)
I am fully aware that this is a rather vague description of the problem with very little source code. This is due to the fact that the application comprises of quite a lot of source code and I have no idea what might be relevant here. Also, all namespaces in the above text refer to Microsoft.CodeAnalysis.CSharp.Scripting, except for VISA, which is self-defined. Obviously, I will gladly answer any follow-up questions for getting to the bottom of this.
Thanks in advance.
Short answer: No. It's not only not warranted, it's completely missing the actual issue.
Further explanation: #canton7 instantly hit the nail on the head when writing
I'd argue that your application shouldn't crash even if a finalizer does end up being called
The root issue hid inside a 3rd party DLL in form of an, at the very least, suboptimal implementation of IDisposable. Once I zoomed in on that, it was rather easy to produce a workaround for that.
My original question is so very misguided that I'd like to state the one that I should have asked:
How do I trace a crash of my C# application when my application's logging does not show anything?
This question has been answered comprehensively in a number of posts. In my case, the crash could be seen in the Windows event log.

Random error: Attempted to read or write protected memory

We have a C# .Net application using WCF services. And the application is deployed in our production server under a Windows Service Application. One part of the module is responsible for creating shape files ((*.shp, *.dbf) for a smaller area the workers will be working today and send them down to a PDA.
To write the shape files, we use a third party dll, NetTopologySuite
GisSharpBlog.NetTopologySuite.IO.ShapefileWriter
which is also in C#. (I am not sure whether any dll it reference use unmanaged code.)
The system might work fine for a while say for a week. Then suddenly we get an exception saying
Attempted to read or write protected memory.
This is often an indication that other memory is corrupt.
from the Write method, where we write the geometry collection to shape files.
sfw.Write(FileName, new GeometryCollection(gc.ToArray()));
(GeometryCollection is also from a third party dll, GeoAPI.dll)
This error brings down the whole service and makes it unfunctional. Then we would just restart the service and try to run the same data again, it would work fine for another week till it crash again. It happens only in production and at random times. We were not able to find the cause of the issue.
Many forums suggest that it might be because of memory leaks in some unmanaged code. But we couldn't find which one.
We are also ready to rewrite the part that create new shape files.
Please help me to resolve this issue.
Let me know if more details are required. Thanks in advance.
In my experience, that message was a result of a memory leak. This is what I'd do if I am in your situation especially since you are working on a third-party DLL.
1) Monitor your WCF server and see what is going on with the DLLHost.exe and the aspnet services in the task manager. I have a feeling that your third-party DLL has a memory leak that causes these 2 services to bloat and reach the limit of your servers memory. This is the reason why it works for a while and then suddenly just stopped working.
2) Identify a good schedule on when you can recycle your servers memory and application pool. Since the issue is rampant, you might want to do this every midnight or when no one is actively using it.
3) Write a good error logging code to know exactly what is happening during the time it bogged down. I would put the following information on the error logs: The parameters that you are passing, the user who encountered that problem etc. This is so you will know exactly what is happening.
4) Check the Event Viewer as maybe there is some information in there that can pinpoint the problem.
4) After doing 1, 2, and 3 and I will call your third-party DLL vendor and see what they can do to help you. You might need to provide the information that you collected from 1, 2, 3 and 4 items from above.
Good luck and I hope this will help.
I think you have some unmanaged code in the third libraries that is getting an address protected by the system or used by other applications.
You have an Access Violation (pointer to memory not belonging to your application space, including null/mass - 0x0 - address) in one of your third-party DLLs.
Or else, it's maybe some unmanaged COMObject you're using that causes this error.
The random nature of this error, would suggest to me that it may be a matter of threads. Specifically the Write method of ShapefileWriter might have been called, got delayed in a thread then you call Close. The delayed Write method then tries to write over a closed (and protected) file, which could result in the error you see.
This is purely speculation since there's not much code to make a better guess, but I've experienced this issue using video writing libraries, so it might be the same in your case.
Check to make sure you don't have threads within threads. That is what happened when I encountered this error. See this link for more information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt

Find out where a multi-threading C# program is stuck

I have written a C# program having some thousand lines and several threads. Execution works fine for several hours/days until the application, which is running on a Windows server, starts to slow everything (other programs/web server) down as it suddenly begins to use up about 50-80% of the CPU.
I assume that it is stuck in some while-loop, but I do not know where exactly. It would already be a help to know which thread uses up the largest share of the system resources. As there is not any exception thrown, I do not see any direct possibility to find out.
The code has already been inspected but I did not find any significant/obvious programming mistakes.
Does anybody know a good way to let Visual Studio monitor the current CPU-load in order to show where it is used up?
Oh, how I love Managed Stack Explorer. http://mse.codeplex.com/ for most versions of .NET and https://github.com/vadimskipin/MSE for 4.0
Point it at your running application, and it snapshots the stacks of each thread. After looking at a few snapshots, you'll work out where the problem is. Oh, the nastiness of the problem I was facing when I first learnt of this. Oh the joy when it let me find what I'd been hunting for days in just a few minutes.
You can use Perfview (http://www.microsoft.com/en-us/download/details.aspx?id=28567) to capture and the analyse ETL traces when this happens.

Windows Application doesn't crash when debugging, but crashes otherwise

I have a windows application that calls an external .dll. After a while, there were fatal errors being brought to my attention that had to do with user marshaling. There was a source online that with that particular error I was to change my target to x86 rather than AnyCPU. I did so, and now whenever I let the app run, it will exit debug mode and crash the application. But if I set a break point immediately after the .dll call, and step over each line until I receive control of the application again, it doesn't crash. Is there anything specific that could be causing this? Has does one debug this issue?
Thanks!
Stepping code solving an issue is often a symptom of timing problems in the original code. If an external resource loads asynchronously, it will not show up on the stack of the current thread in the debugger, but will be able to be called. Stepping over code induces a delay in the flow.
Thank you all for you suggestions! Fortunately, I ended up getting it to work (with minimal understanding as to why it works) but changing the build target to specifically x86 machines rather than "AnyCPU." This was suggested by a website and can no longer find :\ Hope this helps others than run into a similar issue!
I consider the most common cause of this sort of thing to be uninitialized variables. They pick up whatever was in memory and the presence of a debugger can easily change what's in the unused part of the stack--the memory that's going to become local variables when the next routine is called. Check the DLLs code.
Note that your "fix" makes me even more suspect that this is the real answer.
(Then there's also the really crazy case of a problem with the debugger. Long ago I hit a case where the debugger had no problem loading an invalid value into a segment register if you were single stepping.)

How to debug random crashes?

we have a dotnet 2.0 desktop winforms app and it seems to randomly crash. no stack trace, vent log, or anything. it just dissapears.
There are a few theories:
machine simply runs out of resources. some people have said you will always get a window handle exception or a gdi exception but others say it might simply cause crashes.
we are using wrappers around non managed code for 2 modules. exceptions inside either of these modules could cause this behavior.
again, this is not reproducible so i wanted to see if there were any suggestions on how to debug better or anything i can put on the machine to "catch" the crash before it happens to help us understand whats going on.
Your best bet is to purchase John Robbins' book "Debugging Microsoft .NET 2.0 Applications". Your question can go WAY deeper than we have room to type here.
Sounds for me like you need to log at first - maybe you can attach with PostSharp a logger to your methods (see Log4PostSharp) . This will certainly slow you down a lot and produce tons of messages. But you should be able to narrow the problematic code down ... Attach there more logs - remove others. Maybe you can stress-test this parts, later. If the suspect parts are small enough you might even do a code review there.
I know, your question was about debugging - but this could be an approach, too.
You could use Process Monitor from SysInternals (now a part of Microsoft) filtered down to just what you want to monitor. This would give you a good place to start. Just start with a tight focus or make sure you have plenty of space for the log file.
I agree with Boydski. But I also offer this suggestion. Take a close look at the threads if you're doing multi-threading. I had an error like this once that took a long long time to figure out and actually ended up with John Robbins on the phone helping out with it. It turned out to be improper exception handling with threads.
Run your app, with pdb files, and attach WinDbg, make run.
Whem crash occur WinDbg stop app.
Execute this command to generate dump file :
.dump /ma c:\myapp.dmp
An auxiliary tool of analysis is ADPlus
Or try this :
Capturing user dumps using Performance alert
How to use ADPlus to troubleshoot "hangs" and "crashes"
Debugging on the Windows Platform
Do you have a try/catch block around the line 'Application.Run' call that starts the GUI thread? If not do add one and put some logging in for any exceptions thrown there.
You can also wrie up the Application.ThreadException event and log that in case that gives you some more hints.
you should use a global exception handler:
http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx
I my past I have this kind of behaviour primarily in relation to COM objects not being released and/or threading issues. Dive into the suggestions that you have gotten here already, but I would also suggest to look into whether you properly release the non-managed objects, so that they do not leak memory.

Categories