Click here to Skip to main content
Click here to Skip to main content

Finding Undisposed Objects

By , 13 Aug 2009
 
Prize winner in Competition "Best C# article of July 2009"

Introduction

Who likes to see an unkempt room? A street littered with garbage? A smelly toilet?

Who likes to see objects go undisposed in managed code?

Hopefully, no one.

Non-deterministic garbage collection in .NET makes it your responsibility to dispose objects, and bad things can happen if you don't do that. Besides the cost of finalization, your application could run out of resources and crash if it happens to consume them in a way that doesn't trigger garbage collection.

But, this article isn't about why you need to call Dispose - it assumes you've already seen The Light. This article is about ways to find objects that did not get disposed.

Techniques

The simplest way to find undisposed objects is to add some logging to the finalizer of each disposable type. Running the application through typical scenarios and checking the logs should tell you which types are not being disposed. If you know how to use Windbg and SOS, you can also use the !finalizequeue extension command to view all finalizable types. If the list of finalizable types is small, you can go through your code, looking for missing Dispose calls on instances of those types.

Neither approach works well when there is a huge code base, or if there are third party libraries involved. Enter Undisposed, the subject of this article. It's an application I wrote that uses the CLR profiling API to monitor finalizations and object creations at runtime, and shows you all finalized objects, with stack traces for the respective constructors to help you quickly pinpoint the offending section of code. Here's how the result of the analysis looks:

The top panel shows you the number of finalized objects by type, and the bottom panel shows unique stack traces of constructors for the selected type.

How To Use It

Download the application and register Undisposed.dll using:

regsvr32 Undisposed.dll

The DLL requires VC redistributable for VS 2008 SP1, so if registration fails, please install the redistributable from here.

Launch UndisposedViewer.exe:

Enter the path of the application to launch, command line arguments (if any), and a log file location. Click on "Automatically find finalizable types" to search for all finalizable types in the application. You can also enter the type names manually. The list of types in the textbox at the bottom will be the ones that will be monitored for finalization. Hitting Go will launch the target application. Put the application through its paces, and once you exit the application, Undisposed LogViewer will launch automatically, showing you the undisposed objects in that specific run of the application.

How It Works

Undisposed.dll

The key component in this application is Undisposed.dll - a COM component that hooks up with the CLR profiling API. In a throwback to old times, the CLR relies on plain old environment variables to know what profiler to load. The "COR_ENABLE_PROFILING" environment variable tells the CLR that profiling is enabled, and it reads the "COR_PROFILER" environment variable to get the CLSID of the component to be loaded as the profiler.

The CLR Profiling API exposes a ICorProfilerCallback2 interface which must be implemented by the COM component. Once loaded, the CLR calls back into the component using methods on that interface. There are a lot of methods there, but these are the ones Undisposed uses.

  • Initialize - Initializes all trackers
  • Shutdown - Shuts down all trackers
  • FinalizeableObjectQueued - Notifies the finalization tracker, which writes out the details to log
  • ObjectAllocated - Notifies the object tracker, which maps objects with the stack trace obtained by walking the stack
  • SurvivingReferences - Notifies the object tracker about objects that survived a garbage collection
  • MovedReferences - Notifies the object tracker about objects that were moved during a garbage collection

The Initialize callback is also used to get an interface pointer to ICorProfilerInfo. The SetEventMask method on that interface is used to tell the CLR the events that the profiler is interested in. For Undisposed, they are:

hr = m_pCorProfilerInfo->SetEventMask(COR_PRF_MONITOR_CLASS_LOADS 
        | COR_PRF_MONITOR_OBJECT_ALLOCATED 
        | COR_PRF_MONITOR_GC 
        | COR_PRF_ENABLE_OBJECT_ALLOCATED
        | COR_PRF_ENABLE_STACK_SNAPSHOT
        )

The COR_PRF_ENABLE_STACK_SNAPSHOT lets the profiler walk the stack using ICorProfilerInfo2::DoStackSnapshot. This is used to get the constructor stack trace for the object the profiler is tracking.

There are lots of other interesting implementation details, enough to warrant a separate article. At a high level though, this is how the code is organized:

The Controller forwards calls from the CLR to the appropriate tracker objects. ObjectTracker maintains the list of live objects of all monitored types, along with the stack trace of their constructors. It also does the book keeping after a garbage collection is done. FinalizerRunLogger writes out the object type and the stack trace when it gets notified that an object of one of the monitored types is about to be finalized. TypeTracker, not shown above, maintains a map from the internal data structures to the type names.

UndisposedViewer.exe

The main application merely launches the target application after setting up the environment variables to load Undisposed.dll. It also writes its current state to a config file that is then read by the COM component. This is needed to pass things like the list of types to monitor.

UndisposedLogViewer.exe

The log viewer is launched after the target application exits. There is not much logic in there, it simply reads the log file generated by Undisposed.dll and shows the data grouped by type and stack trace.

Conclusion

The inspiration for writing this application came from this post in the Lounge. Hopefully, it will prove useful to you as well. Feedback and suggestions are welcome.

History

  • 20-07-2009 - Initial version
  • 13-08-2009 - Updated source code and binaries

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)

About the Author

S. Senthil Kumar
Software Developer Atmel R&D India Pvt. Ltd.
India India
Member
I'm a 27 yrs old developer working with Atmel R&D India Pvt. Ltd., Chennai. I'm currently working in C# and C++, but I've done some Java programming as well. I was a Microsoft MVP in Visual C# from 2007 to 2009.
 
You can read My Blog here. I've also done some open source software - please visit my website to know more.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5membergndnet21 Jul '12 - 2:51 
awesome
GeneralMy vote of 5membergndnet19 Jul '12 - 21:42 
5
GeneralMy vote of 5memberthatraja3 Dec '10 - 22:57 
Very good one dude. Really awesome.
QuestionWhy log file?memberVitaly Tomilov3 May '10 - 8:29 
No matter in which language, what always worked for is the following simple approach...   For eaxmple, for C++/C# it would be like this:   You declare a class/template that increments a global counter for its type when constructed, and then decrements it when destructed.  ...
AnswerRe: Why log file?memberS. Senthil Kumar3 May '10 - 9:23 
Vitaly Tomilov wrote: I never needed any logging for such trivial task...   1. The counter will only tell you whether an object has been disposed or not - you won't know who created it. 2. Your approach requires the ability to modify and recompile source code. It won't work for types in...
GeneralRe: Why log file?memberVitaly Tomilov3 May '10 - 9:27 
Very well, agreed. Professional System Library on www.prosyslib.org
Question[My vote of 1] What is the motivation for doing this?memberwishay14 Apr '10 - 11:57 
The "How To Use It" section could really use a lot more detail. You say that "Undisposed LogViewer will [...] show you the undisposed objects in that specific run of the application."   I don't think that's what it does, because none of the objects in your Leaky example are even...
AnswerRe: [My vote of 1] What is the motivation for doing this?memberS. Senthil Kumar14 Apr '10 - 17:35 
wishay wrote:I might just not be thinking straight, but I don't see how this information can be used to find IDisposable objects that don't get disposed.   According to the .NET framework guidelines, every type that provides a finalizer must implement IDisposable and override Dispose to...
GeneralRe: [My vote of 1] What is the motivation for doing this?memberwishay14 Apr '10 - 21:56 
This does help, thank you!   It wasn't clear to me from the article that the detector assumes the Microsoft policy being implemented. I personally feel that some of the best IDisposable advice is given in IDisposable: What Your Mother Never Told You About Resource Deallocation, and that...
QuestionFound lots of objects. Now what?memberPaul Meems25 Aug '09 - 1:13 
Thanks for this great article. I used it on a big application we have and got over 1000 undisposed objects in our custom code and over 800 objects in System. code. How do I interpreter the log file? How can I see what object is not disposed, so I can fix it?   Thanks, Paul
AnswerRe: Found lots of objects. Now what?memberS. Senthil Kumar25 Aug '09 - 1:18 
For each object, you will now know the type of the object and the full stack trace of its constructor (click on the object type row in the log viewer). Armed with this information, you can hopefully look at the source code and figure out why it's not being disposed.   Regards Senthil...
Generalvery good - my vote of 4!memberPratik.Patel23 Aug '09 - 17:42 
This is very good. I am not big fan of C++ but I would definitely love to run your program to see if I can see undisposed objects of my application or not. Thanks for posting this article.   Regards, Pratik   People say dont re-invent the wheel, I say I've got a better wheel!
Questionhow to test it?memberelvis_pan21 Aug '09 - 22:59 
i write the follow code for test finding undisposed object.build and link it to exe file.   static void Main(string[] args) { FileStream fs = new FileStream("D:\\videotest\\mtv.wmv", FileMode.Open); byte[] bs = new byte[100]; ...
AnswerRe: how to test it?memberS. Senthil Kumar22 Aug '09 - 1:13 
elvis_pan wrote:where is the error? I use the UndisposedViewer.exe in the wrong way?   Try adding a GC.Collect before you return from Main. The application relies on FinalizeableObjectQueued notifications from the profiling API - in your case, the program starts and terminates so rapidly...
GeneralCLR Profilermemberzubairy21 Aug '09 - 18:20 
we already have CLR profiler for dotnet applications, can you tell me what is the main difference between Microsoft CLR profiler and this application.   Good Luck
GeneralRe: CLR ProfilermemberS. Senthil Kumar22 Aug '09 - 7:28 
zubairy wrote:can you tell me what is the main difference between Microsoft CLR profiler and this application.   CLR Profiler lets you look at objects on the heap and track allocations, but AFAIK, it doesn't show you finalized objects (and their stack traces).   Regards Senthil...
QuestionStill cannot find log filememberhat_master18 Aug '09 - 10:53 
I've tried both the Code Project file and the Codeplex file and I still receive an error that the log file cannot be found. Thoughts?   Thanks
AnswerRe: Still cannot find log filememberS. Senthil Kumar18 Aug '09 - 17:25 
Can you check if a log file is actually generated in the location you specified? If there isn't one, did you register Undisposed.dll using regsvr32 Undisposed.dll?   Regards Senthil _____________________________ My Home Page |My Blog | My Articles | My Flickr | WinMacro
QuestionWhat is Leaky.exe?memberBOWLINGBALL18 Aug '09 - 2:14 
Solution also has Leaky.exe - what does it do?
AnswerRe: What is Leaky.exe?memberS. Senthil Kumar18 Aug '09 - 2:38 
It is a test project that creates managed objects and doesn't dispose all of them i.e. leaks some of them.   Regards Senthil _____________________________ My Home Page |My Blog | My Articles | My Flickr | WinMacro
QuestionError: Could not find file : andmemberliquidfirexyz12 Aug '09 - 8:56 
I launch the program and press go, then as soon as I close the application I was watching I get the error :   "Could not find file : and "   Any ideas?
AnswerRe: Error: Could not find file : andmemberS. Senthil Kumar12 Aug '09 - 21:01 
This is a bug - the application isn't handling log file paths with space properly.   I've fixed it though, and the updated version should be available in CodeProject shortly. If you're in a hurry, you can download the updated version from...
GeneralInteresting, but it doesn't workmemberjirka.stejskal@gmail.com12 Aug '09 - 1:13 
I'm working in mixed environment and the amin app is pure and simple C++. .NET is used for UI stuff, XML handling and some database access layers. When I hit "Automatically find ...", I got a crash (UE).
GeneralRe: Interesting, but it doesn't workmemberS. Senthil Kumar12 Aug '09 - 1:26 
jirka.stejskal@gmail.com wrote:d ...", I got a crash (UE).   I haven't tried the automatic type finder on mixed mode assemblies. I'll check that out, thanks.   Does it work if you give it fully qualified type names instead?   Regards Senthil _____________________________...
GeneralRe: Interesting, but it doesn't workmemberjirka.stejskal@gmail.com12 Aug '09 - 2:55 
I tried to give it one type. It launched program - very slowly (side note - our program is BIG and there is a lot of COM). It usually loads in about 30s, now it took about 3-4 minutes. When I finished it, it reported "Couldn't find ...". Lukks like you do not suport space inside the Log file path.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 13 Aug 2009
Article Copyright 2009 by S. Senthil Kumar
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid