首页 > 代码库 > Advanced .NET Debugging: Managed Heap and Garbage Collection(转载,托管堆查内存碎片问题解决思路)

Advanced .NET Debugging: Managed Heap and Garbage Collection(转载,托管堆查内存碎片问题解决思路)

Debugging Managed Heap Fragmentation

Earlier in the chapter, we described a phenomenon known as heap fragmentation, in which free and busy blocks are arranged and interleaved on the managed heap in such a way that they can cause problems in applications that surface as OutOfMemory exceptions; in reality, enough memory is free, just not in a contiguous fashion. The CLR heap manager utilizes a technique known as compacting and coalescing to reduce the risk of heap fragmentation. In this section, we will take a look at an example that can cause heap fragmentation to occur and how we can use the debuggers to identify that a heap fragmentation is in fact occurring and the reasons behind it. The example is shown in Listing 5-8.

Listing 5-8. Heap fragmentation example

using System;using System.Text;using System.Runtime.InteropServices;namespace Advanced.NET.Debugging.Chapter5{    class Fragment    {        static void Main(string[] args)        {            Fragment f = new Fragment();            f.Run(args);        }        public void Run(string[] args)        {            if (args.Length < 2)            {               Console.WriteLine("05Fragment.exe <alloc. size> <max mem in MB>");               return;            }            int size = Int32.Parse(args[0]);            int maxmem = Int32.Parse(args[1]);            byte[][] nonPinned = null;            byte[][] pinned = null;            GCHandle[] pinnedHandles = null;            int numAllocs=maxmem*1000000/size;            pinnedHandles = new GCHandle[numAllocs];            pinned = new byte[numAllocs / 2][];            nonPinned = new byte[numAllocs / 2][];            for (int i = 0; i < numAllocs / 2; i++)            {               nonPinned[i] = new byte[size];               pinned[i] = new byte[size];    pinnedHandles[i] =GCHandle.Alloc(pinned[i], GCHandleType.Pinned);            }            Console.WriteLine("Press any key to GC & promo to gen1");            Console.ReadKey();            GC.Collect();            Console.WriteLine("Press any key to GC  & promo to gen2");            Console.ReadKey();            GC.Collect();            Console.WriteLine("Press any key to GC(free non pinned");            Console.ReadKey();            for (int i = 0; i < numAllocs / 2; i++)            {               nonPinned[i] = null;            }            GC.Collect();            Console.WriteLine("Press any key to exit");            Console.ReadKey();        }    }}

The source code and binary for Listing 5-8 can be found in the following folders:

  • Source code: C:\ADND\Chapter5\Fragment
  • Binary: C:\ADNDBin\05Fragment.exe

The application enables the user to specify an allocation size and the maximum amount of memory that the application should consume. For example, if we want the allocation size to be 50,000 bytes and the overall memory consumption limit to be 100MB, we would run the application as following:

C:\ADNDBIN\05Fragment 50000 100

The application proceeds to allocate memory, in chunks of the specified allocation size, until the limit is reached. After the allocations have been made, the application performs a couple of garbage collections to promote the surviving objects to generation 2 and then makes the nonpinned objects rootless, followed by another garbage collection that subsequently releases the nonpinned allocations. Let‘s take a look by running the application under the debugger with an allocation size of 50000 and a max memory threshold of 1GB.

After the Press any key to GC and promo to Gen1 prompt is displayed, the application has finished allocating all the memory and we can take a look at the managed heap using the DumpHeap –stat command:

0:004> !DumpHeap -stattotal 22812 objectsStatistics:      MT    Count    TotalSize Class Name79119954        1           12 System.Security.Permissions.ReflectionPermission79119834        1           12 System.Security.Permissions.FileDialogPermission791197b0        1           12 System.Security.PolicyManager.........791032a8        2          256 System.Globalization.NumberFormatInfo79101fe4        6          336 System.Collections.Hashtable7912d9bc        6          864 System.Collections.Hashtable+bucket[]7912dd40       10          2084 System.Char[]00395f68      564         13120    Free7912d8f8       14         17348 System.Object[]791379e8        1         80012 System.Runtime.InteropServices.GCHandle[]79141f50        2         80032 System.Byte[][]790fd8c4     2108        132148 System.String7912dae8    20002    1000240284 System.Byte[]Total 22812 objects

The output of the command shows a few interesting fields. Because we are looking specifically for heap fragmentation symptoms, any listed Free blocks should be carefully investigated. In our case, we seem to have 564 free blocks occupying a total size of 13120. Should we be worried about these free blocks causing heap fragmentation? Generally speaking, it is useful to look at the total size of the free blocks in comparison to the overall size of the managed heap. If the size of the free blocks is large in comparison to the overall heap size, heap fragmentation may be an issue and should be investigated further. Another important consideration to be made is that of which generation the possible heap fragmentation is occurring in. In generation 0, fragmentation is typically not a problem because the CLR heap manager can allocate using any free blocks that may be available. In generation 1 and 2 however, the only way for the free blocks to be used is by promoting objects to each respective generation. Because generation 1 is part of the ephemeral segment, which there can only be one of, generation 2 is most commonly the generation of interest when looking at heap fragmentation problems. Let‘s take a look at what our heap looks like by using the eeheap –gc command:

0:004> !eeheap -gcNumber of GC Heaps: 1generation 0 starts at 0x56192a54generation 1 starts at 0x55d91000generation 2 starts at 0x01c21000ephemeral segment allocation context: none segment    begin allocated     size003a80e0 790d8620  790f7d8c 0x0001f76c(128876)01c20000 01c21000  0282db84 0x00c0cb84(12635012)04800000 04801000  05405ee4 0x00c04ee4(12603108)05800000 05801000  06405ee4 0x00c04ee4(12603108)06a50000 06a51000  07655ee4 0x00c04ee4(12603108)07a50000 07a51000  08655ee4 0x00c04ee4(12603108).........4fd90000 4fd91000  50995ee4 0x00c04ee4(12603108)50d90000 50d91000  51995ee4 0x00c04ee4(12603108)51d90000 51d91000  52995ee4 0x00c04ee4(12603108)52d90000 52d91000  53995ee4 0x00c04ee4(12603108)53d90000 53d91000  54995ee4 0x00c04ee4(12603108)54d90000 54d91000  55995ee4 0x00c04ee4(12603108)55d90000 55d91000  5621afd8 0x00489fd8(4759512)Large object heap starts at 0x02c21000 segment    begin allocated     size02c20000 02c21000  02c23250 0x00002250(8784)Total Size  0x3ba38e90(1000574608)––––––––––––––––––––––––––––––GC Heap Size  0x3ba38e90(1000574608)

The last line of the output tells us that the total GC Heap Size is right around 1GB. You may also notice that there is a rather large list of segments. Because we are allocating a rather large amount of memory, the ephemeral segment gets filled up pretty quickly and new generation 2 segments get created. We can verify this by looking at the starting address of generation 2 in the preceding output (0x01c21000) and correlating the start addresses of each segment in the segment list. Let‘s get back to the free blocks we saw earlier. In which generations are they located? We can find out by using the dumpheap –type Free command. An abbreviated output follows:

0:004> !DumpHeap -type Free Address       MT     Size01c21000 00395f68        12 Free01c2100c 00395f68        24 Free01c24c44 00395f68        12 Free01c24c50 00395f68        12 Free01c24c5c 00395f68      6336 Free01e299d0 00395f68        12 Free0202a6f4 00395f68        12 Free0222b418 00395f68        12 Free0242c13c 00395f68        12 Free0262ce60 00395f68        12 Free04801000 00395f68        12 Free0480100c 00395f68        12 Free04a01d30 00395f68        12 Free04c02a54 00395f68        12 Free04e03778 00395f68        12 Free0500449c 00395f68        12 Free052051c0 00395f68        12 Free05801000 00395f68        12 Free0580100c 00395f68        12 Free05a01d30 00395f68        12 Free05c02a54 00395f68        12 Free05e03778 00395f68        12 Free0600449c 00395f68        12 Free062051c0 00395f68        12 Free06a51000 00395f68        12 Free06a5100c 00395f68        12 Free06c51d30 00395f68        12 Free06e52a54 00395f68        12 Free07053778 00395f68        12 Free0725449c 00395f68        12 Free074551c0 00395f68        12 Free07a51000 00395f68        12 Free07a5100c 00395f68        12 Free07c51d30 00395f68        12 Free07e52a54 00395f68        12 Free08053778 00395f68        12 Free0825449c 00395f68        12 Free084551c0 00395f68        12 Free08a51000 00395f68        12 Free08a5100c 00395f68        12 Free08c51d30 00395f68        12 Free08e52a54 00395f68        12 Free09053778 00395f68        12 Free0925449c 00395f68        12 Free094551c0 00395f68        12 Free09a51000 00395f68        12 Free09a5100c 00395f68        12 Free09c51d30 00395f68        12 Free09e52a54 00395f68        12 Free0a053778 00395f68        12 Free0a25449c 00395f68        12 Free0a4551c0 00395f68        12 Free0aee1000 00395f68        12 Free0aee100c 00395f68        12 Free0b0e1d30 00395f68        12 Free0b2e2a54 00395f68        12 Free0b4e3778 00395f68        12 Free.........55192a54 00395f68        12 Free55393778 00395f68        12 Free5559449c 00395f68        12 Free557951c0 00395f68        12 Free55d91000 00395f68        12 Free55d9100c 00395f68        12 Free55f91d30 00395f68        12 Free56192a54 00395f68        12 Free02c21000 00395f68        16 Free02c22010 00395f68        16 Free02c23020 00395f68        16 Free02c23240 00395f68        16 Freetotal 564 objectsStatistics:      MT    Count    TotalSize Class Name00395f68      564        13120      FreeTotal 564 objects

By looking at the address of each of the free blocks and correlating the address to the segments from the eeheap command, we can see that a great majority of the free objects reside in generation 2. With a total free size of 13120 in a heap that is right around 1GB in size, the fragmentation now is only a small fraction of one percent. Nothing to worry about (yet). Let‘s resume the application and keep pressing any key when prompted until you see the Press any key to exit prompt. At that point, break into the debugger and again run the DumpHeap –stat command to get another view of the heap:

0:004> !DumpHeap -stattotal 22233 objectsStatistics:      MT    Count     TotalSize Class Name79119954        1            12 System.Security.Permissions.ReflectionPermission79119834        1            12 System.Security.Permissions.FileDialogPermission791197b0        1            12 System.Security.PolicyManager00113038        1            12 Advanced.NET.Debugging.Chapter5.Fragment791052a8        1            16 System.Security.Permissions.UIPermission79117480        1            20 System.Security.Permissions.EnvironmentPermission791037c0        1            20 Microsoft.Win32.SafeHandles.SafeFileMappingHandle79103764        1            20 Microsoft.Win32.SafeHandles.SafeViewOfFileHandle.........7912d8f8       12         17256 System.Object[]791379e8        1         80012 System.Runtime.InteropServices.GCHandle[]79141f50        2         80032 System.Byte[][]790fd8c4     2101        131812 System.String00395f68    10006      496172124      Free7912dae8    10002      500120284 System.Byte[]Total 22233 objects

This time, we can see that the amount of free space has grown considerably. From the output, there are 10006 instances of free blocks occupying a total of 496172124 bytes of memory. To find out how this total amount correlates to our overall heap size, we once again use the eeheap –gc command:

0:004> !eeheap -gcNumber of GC Heaps: 1generation 0 starts at 0x55d9100cgeneration 1 starts at 0x55d91000generation 2 starts at 0x01c21000ephemeral segment allocation context: none segment    begin allocated     size003a80e0 790d8620  790f7d8c 0x0001f76c(128876)01c20000 01c21000  02821828 0x00c00828(12585000)04800000 04801000  053f9b88 0x00bf8b88(12553096).........54d90000 54d91000  55989b88 0x00bf8b88(12553096)55d90000 55d91000  562190b0 0x004880b0(4751536)Large object heap starts at 0x02c21000 segment    begin allocated     size02c20000 02c21000  02c23240 0x00002240(8768)Total Size  0x3b6725f4(996615668)––––––––––––––––––––––––––––––GC Heap Size  0x3b6725f4(996615668)

The total GC heap size is reported as 996615668 bytes. Overall, we can say that the heap is approximately 50% fragmented. This can easily be verified by looking at the verbose output of the DumpHeap command:

0:004> !DumpHeap Address       MT      Size.........55ff381c 7912dae8     5001255fffb78 00395f68     50012 Free5600bed4 7912dae8     5001256018230 00395f68     50012 Free5602458c 7912dae8     50012560308e8 00395f68     50012 Free5603cc44 7912dae8     5001256048fa0 00395f68     50012 Free560552fc 7912dae8     5001256061658 00395f68     50012 Free5606d9b4 7912dae8     5001256079d10 00395f68     50012 Free5608606c 7912dae8     50012560923c8 00395f68     50012 Free5609e724 7912dae8     50012560aaa80 00395f68     50012 Free560b6ddc 7912dae8     50012560c3138 00395f68     50012 Free560cf494 7912dae8     50012560db7f0 00395f68     50012 Free560e7b4c 7912dae8     50012560f3ea8 00395f68     50012 Free56100204 7912dae8     500125610c560 00395f68     50012 Free.........

From the output, we can see that a pattern has emerged. We have a block of size 50012 that is allocated and in use followed by a free block of the same size that is considered free. We can use the DumpObj command on the allocated object to find out more details:

0:004> !DumpObj 5606d9b4Name: System.Byte[]MethodTable: 7912dae8EEClass: 7912dba0Size: 50012(0xc35c) bytesArray: Rank 1, Number of elements 50000, Type ByteElement Type: System.ByteFields:None

This object is a byte array, which corresponds to the allocations that our application is creating. How did we end up with such an allocation pattern (allocated, free, allocated, free) to begin with? We know that the garbage collector should perform compacting and coalescing to avoid this scenario. One of the situations that can cause the garbage collector not to compact and coalesce is if there are objects on the heap that are pinned (i.e., nonmoveable). To find out if that is indeed the case in our application, we need to see if there are any pinned handles in the process. We can utilize the GCHandles command to get an overview of handle usage in the process:

0:004> !GCHandlesGC Handle Statistics:Strong Handles: 15Pinned Handles: 10004Async Pinned Handles: 0Ref Count Handles: 0Weak Long Handles: 0Weak Short Handles: 1Other Handles: 0Statistics:      MT    Count    TotalSize Class Name790fd0f0        1           12 System.Object790feba4        1           28 System.SharedStatics790fcc48        2           48 System.Reflection.Assembly790fe17c        1           72 System.ExecutionEngineException790fe0e0        1           72 System.StackOverflowException790fe044        1           72 System.OutOfMemoryException790fed00        1          100 System.AppDomain790fe704        2          112 System.Threading.Thread79100a18        4          144 System.Security.PermissionSet790fe284        2          144 System.Threading.ThreadAbortException7912d8f8        4         8744 System.Object[]7912dae8    10000    500120000 System.Byte[]Total 10020 objects

The output of GCHandles tells us that we have 10004 pinned handles. Further more, in the statistics section, we can see that 10,000 of those handles are used to pin byte arrays. At this point, we are almost there and can do a quick code review that shows that half of the byte array allocations made in the application are explicitly pinned, causing the heap to get fragmented.

Excessive or prolonged pinning is one of the most common reasons behind fragmentation of the managed heap. If pinning is necessary, the developer must ensure that pinning is short lived in order not to interfere too much with the garbage collector.

How Much Is Too Much?

In our preceding example, initially, the heap fragmentation was a fraction of one percent. At that point, we really didn‘t have to pay too much attention to it as it was too small to concern us. Later, we noticed that the fragmentation grew to 50%, which caused an in-depth investigation to figure out the reason for it. Is there a magical percentage of when one should start worrying? There is no hard number, but generally speaking if the heap is between 10% and 30% fragmented, due diligence should be exercised to ensure that it is not a long-running problem.

In the preceding example, we looked at fragmentation as it relates to the managed heap. It is also possible to encounter situations where the virtual memory managed by the Windows virtual memory manager gets fragmented. In those cases, the CLR heap manager may not be able to grow its heap (i.e., allocate new segments) to accommodate allocation requests. The address command can be used to get in-depth information on the systems virtual memory state.

 

Advanced .NET Debugging: Managed Heap and Garbage Collection(转载,托管堆查内存碎片问题解决思路)