Advanced .NET Debugging: Managed Heap and Garbage Collection
- Windows Memory Architecture Overview
- Garbage Collector Internals
- Debugging Managed Heap Corruptions
- Debugging Managed Heap Fragmentation
- Debugging Out of Memory Exceptions
- Summary
Manual memory management is a very common source of errors in applications today. As a matter of fact, several online studies indicate that the most common errors are related to manual memory management. Examples of such problems include
- Dangling pointers
- Double free
- Memory leaks
Automatic memory management serves to remove the tedious and error-prone process of managing memory manually. Even though automatic memory management has gained more attention with the advent of Java and the .NET platform, the concept and implementation have been around for some time. Invented by John McCarthy in 1959 to solve the problems of manual memory management in LISP, other languages have implemented their own automatic memory management schemes as well. The implementation of an automatic memory management component has become almost universally known as a garbage collector (GC). The .NET platform also works on the basis of automatic memory management and implements its own highly performing and reliable GC. Although using a GC makes life a lot simpler for developers and enables them to focus on more of the business logic, having a solid understanding of how the GC operates is key to avoiding a set of problems that can occur when working in a garbage collected environment. In this chapter, we take a look at the internals of the CLR heap manager and the GC and some common pitfalls that can wreak havoc in your application. We utilize the debuggers and a set of other tools to illustrate how we can get to the bottom of the problems.
Windows Memory Architecture Overview
Before we delve into the details of the CLR heap manager and GC, it is useful to review the overall memory architecture of Windows. Figure 5-1 shows a high-level overview of the various pieces commonly involved in a process.
Figure 5-1 High-level overview of Windows memory architecture
As you can see from Figure 5-1, processes that run in user mode typically use one or more heap managers. The most common heap managers are the Windows heap manager, which is used extensively in most user mode applications, and the CLR heap manager, which is used exclusively by .NET applications. The Windows heap manager is responsible for satisfying most memory allocation/deallocation requests by allocating memory, in larger chunks known as segments, from the Windows virtual memory manager and maintaining bookkeeping data (such as look aside and free lists) that enable it to efficiently break up the larger chunks into smaller-sized allocations requested by the process. The CLR heap manager takes on similar responsibilities by being the one-stop shop for all memory allocations in a managed process. Similar to the Windows heap manager, it also uses the Windows virtual memory manager to allocate larger chunks of memory, also known as segments, and satisfies any memory allocation/deallocation requests from those segments. They key difference between the two heap managers is how the bookkeeping data is structured to maintain the integrity of the heap. Figure 5-2 shows a high-level overview of the CLR heap manager.
Figure 5-2 High-level overview of the CLR heap manager
From Figure 5-2, you can see how the CLR heap manager uses carefully managed larger chunks (segments) to satisfy the memory requests. Also interesting to note from Figure 5-2 is the mode in which the CLR heap manager can operate.
There are two modes of operation: workstation and server. As far as the CLR heap manager is concerned, the primary difference is that rather than having just one heap, there is now one heap per processor, where the size of the heap segments is typically larger than that of the workstation heap (although this is an implementation detail that should not be relied upon). From the GC's perspective, there are other fundamental differences between workstation and server primarily in the area of GC threading models, where the server flavor of the GC has a dedicated thread for all GC activity versus the workstation GC, which runs the GC process on the thread that performed the memory allocation.
Each managed process starts out with two heaps with their own respective segments that are initialized when the CLR is loaded. The first heap is known as the small object heap and has one initial segment of size 16MB on workstations (the server version is bigger). The small object heap is used to hold objects that are less than 85,000 bytes in size. The second heap is known as the large object heap (LOH) and has one initial segment of size 16MB. The LOH is used to hold objects greater than or equal to 85,000 bytes in size. We will see the reason behind dividing the heaps based on object size limits later when we discuss the garbage collector internals. It is important to note that when a segment is created, not all of the memory in that segment is committed; rather, the CLR heap manager reserves the memory space and commits on demand. Whenever a segment is exhausted on the small object heap, the CLR heap manager triggers a GC and expands the heap if space is low. On the large object heap, however, the heap manager creates a new segment that is used to serve up memory. Conversely, as memory is freed by the garbage collector, memory in any given segment can be decommitted as needed, and when a segment is fully decommitted, it might be freed altogether.
As briefly mentioned in Chapter 2, "CLR Fundamentals," each object that resides on the managed heap carries with it some additional metadata. More specifically, each object is prefixed by an additional 8 bytes. Figure 5-3 shows an example of a small object heap segment.
Figure 5-3 Example of a small object heap segment
In Figure 5-3, we can see that the first 4 bytes of any object located on the managed heap is the sync block index followed by an additional 4 bytes that indicate the method table pointer.
Allocating Memory
Now that we understand how the CLR heap manager, at a high level, structures the memory available to applications, we can take a look at how allocation requests are satisfied. We already know that the CLR heap manager consists of one or more segments and that memory allocations are allotted from one of the segments and returned to the caller. How is this memory allocation performed? Figure 5-4 illustrates the process that the CLR heap manager goes through when a memory allocation request arrives.
Figure 5-4 Memory allocation process in the CLR heap manager
In the most optimal case, when a GC is not needed for the allocation to succeed, an allocation request is satisfied very efficiently. The two primary tasks performed in that scenario are those of simply advancing a pointer and clearing the memory region. The act of advancing the allocation pointer implies that new allocations are simply tacked on after the last allocated object in the segment. When another allocation request is satisfied, the allocation pointer is again advanced, and so forth. Please note that this allocation scheme is quite different than the Windows heap manager in the sense that the Windows heap manager does not guarantee locality of objects on the heap in the same fashion. An allocation request on the Windows heap manager can be satisfied from any given free block anywhere in the segment. The other scenario to consider is what happens when a GC is required due to breaching a memory threshold. In this case, a GC is performed and the allocation attempt is tried again. The last interesting aspect from Figure 5-4 is that of checking to see if the allocated object is finalizable. Although not, strictly speaking, a function of the managed heap, it is important to call out as it is part of the allocation process. If an object is finalizable, a record of it is stored in the GC to properly manage the lifetime of the object. We will discuss finalizable objects in more detail later in the chapter.
Before we move on and discuss the garbage collector internals, let's take a look at a very simple application that performs a memory allocation. The source code behind the application is shown in Listing 5-1.
Listing 5-1. Simple memory allocation
using System; using System.Text; using System.Runtime.Remoting; namespace Advanced.NET.Debugging.Chapter5 { class Name { private string first; private string last; public string First { get { return first; } } public string Last { get { return last; } } public Name(string f, string l) { first = f; last = l; } } class SimpleAlloc { static void Main(string[] args) { Name name = null; Console.WriteLine("Press any key to allocate memory"); Console.ReadKey(); name = new Name("Mario", "Hewardt"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } } }
The source code and binary for Listing 5-1 can be found in the following folders:
- Source code: C:\ADND\Chapter5\SimpleAlloc
- Binary: C:\ADNDBin\05SimpleAlloc.exe
The source code in Listing 5-1 is painfully simple, but the more interesting question is, how do we find that particular memory allocation on the managed heap using the debuggers? Fortunately, the SOS debugger extension has a few handy commands that enable us to gain some insight into the contents of the managed heap. The command we will use in this particular example is the DumpHeap command. By default, the DumpHeap command lists all the objects that are stored on the managed heap together with their associated address, method table, and size. Let's run our 05SimpleAlloc.exe application under the debugger and break execution when the Press any key to allocate memory prompt is shown. When execution breaks into the debugger, run the DumpHeap command. A partial listing of the output of the command is shown in the following:
0:004> !DumpHeap Address MT Size 790d8620 790fd0f0 12 790d862c 790fd8c4 28 790d8648 790fd8c4 32 790d8668 790fd8c4 32 790d8688 790fd8c4 28 790d86a4 790fd8c4 24 790d86bc 790fd8c4 24 ... ... ... total 2379 objects Statistics: MT Count TotalSize Class Name 79119954 1 12 System.Security.Permissions.ReflectionPermission 79119834 1 12 System.Security.Permissions.FileDialogPermission 791032a8 1 128 System.Globalization.NumberFormatInfo 79100e38 3 132 System.Security.FrameSecurityDescriptor 791028f4 2 136 System.Globalization.CultureInfo 791050b8 4 144 System.Security.Util.TokenBasedSet 790fe284 2 144 System.Threading.ThreadAbortException 79102290 13 156 System.Int32 790f97c4 3 156 System.Security.Policy.PolicyLevel 790ff734 9 180 System.RuntimeType 790ffb6c 3 192 System.IO.UnmanagedMemoryStream 7912d7c0 11 200 System.Int32[] 790fd0f0 17 204 System.Object 79119364 8 256 System.Collections.ArrayList+SyncArrayList 79101fe4 6 336 System.Collections.Hashtable 79100a18 10 360 System.Security.PermissionSet 79112d68 18 504 System.Collections.ArrayList+ArrayListEnumeratorSimple 79104368 21 504 System.Collections.ArrayList 7912d9bc 6 864 System.Collections.Hashtable+bucket[] 7912dae8 8 1700 System.Byte[] 7912dd40 14 2296 System.Char[] 7912d8f8 23 17604 System.Object[] 790fd8c4 2100 132680 System.String Total 2379 objects
The output of the DumpHeap command is divided into two sections. The first section contains the entire list of objects located on the managed heap. The DumpObject command can be used on any of the listed objects to get further information about the object. The second section contains a statistical view of the managed heap activity by grouping related objects and displaying the method table, count, total size, and the object's type name. For example, the item
79100a18 10 360 System.Security.PermissionSet
indicates that the object in question is a PermissionSet with a method descriptor of 0x79100a18 and that there are 10 instances on the managed heap with a total size of 360 bytes. The statistical view can be very useful when trying to understand an excessively large managed heap and which objects may be causing the heap to grow.
The DumpHeap command produces quite a lot of output and it can be difficult to find a particular allocation in the midst of all of the output. Fortunately, the DumpHeap command has a variety of switches that makes life easier. For example, the –type and –mt switches enable you to search the managed heap for a given type name or a method table address. If we run the DumpHeap command with the –type switch looking for the allocation our application makes, we get the following:
0:003> !DumpHeap -type Advanced.NET.Debugging.Chapter5.Name Address MT Size total 0 objects Statistics: MT Count TotalSize Class Name Total 0 objects
The output clearly indicates that there are no allocations on the managed heap of the given type. Of course, this makes perfect sense because our sample application has not performed its allocation. Resume execution of the application until you see the Press any key to exit prompt. Again, break execution and run the DumpHeap command again with the –type switch:
0:004> !DumpHeap –type Advanced.NET.Debugging.Chapter5.Name Address MT Size 01ca6c7c 002030cc 16 total 1 objects Statistics: MT Count TotalSize Class Name 002030cc 1 16 Advanced.NET.Debugging.Chapter5.Name Total 1 objects
This time, we can see that we have an instance of our type on the managed heap. The output follows the same structure as the default DumpHeap output by first showing the instance specific data (address, method table, and size) followed by the statistical view, which shows the managed heap only having one instance of our type.
The DumpHeap command has several other useful switches depending on the debugging scenario at hand. Table 5-1 details the switches available.
Table 5-1. DumpHeap Switches
Switch |
Description |
-stat |
Limits output to managed heap statistics |
-strings |
Limits output to strings stored on the managed heap |
-short |
Limits output to just the address of the objects on the managed heap |
-min |
Filters based on the minimum object size specified |
-max |
Filters based on the maximum object size specified |
-thinlock |
Outputs objects with associated thinlocks |
-startAtLowerBound |
Begin walking the heap at a lower bound |
-mt |
Limit output to the specified method table |
-type |
Limit output to the specified type name (substring match) |
This concludes our high-level discussion of the Windows memory architecture and how the CLR heap manager fits in. We've looked at how the CLR heap manager organizes memory to provide an efficient memory management scheme as well as the process that the CLR heap manager goes through when a memory allocation request arrives at its doorstep. The next big question is how the GC itself functions, its relationship to the CLR heap manager, and how memory is freed after it has been considered discarded.