Advanced .NET Debugging: Managed Heap and Gar…

2018-06-23 22:37:58来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

原文地址:http://www.informit.com/articles/article.aspx?p=1409801&seqNum=4

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 -stat
total 22812 objects
Statistics:
      MT    Count    TotalSize Class Name
79119954        1           12 System.Security.Permissions.ReflectionPermission
79119834        1           12 System.Security.Permissions.FileDialogPermission
791197b0        1           12 System.Security.PolicyManager
...
...
...
791032a8        2          256 System.Globalization.NumberFormatInfo
79101fe4        6          336 System.Collections.Hashtable
7912d9bc        6          864 System.Collections.Hashtable+bucket[]
7912dd40       10          2084 System.Char[]
00395f68      564         13120    Free
7912d8f8       14         17348 System.Object[]
791379e8        1         80012 System.Runtime.InteropServices.GCHandle[]
79141f50        2         80032 System.Byte[][]
790fd8c4     2108        132148 System.String
7912dae8    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 -gc
Number of GC Heaps: 1
generation 0 starts at 0x56192a54
generation 1 starts at 0x55d91000
generation 2 starts at 0x01c21000
ephemeral segment allocation context: none
 segment    begin allocated     size
003a80e0 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     size
02c20000 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     Size
01c21000 00395f68        12 Free
01c2100c 00395f68        24 Free
01c24c44 00395f68        12 Free
01c24c50 00395f68        12 Free
01c24c5c 00395f68      6336 Free
01e299d0 00395f68        12 Free
0202a6f4 00395f68        12 Free
0222b418 00395f68        12 Free
0242c13c 00395f68        12 Free
0262ce60 00395f68        12 Free
04801000 00395f68        12 Free
0480100c 00395f68        12 Free
04a01d30 00395f68        12 Free
04c02a54 00395f68        12 Free
04e03778 00395f68        12 Free
0500449c 00395f68        12 Free
052051c0 00395f68        12 Free
05801000 00395f68        12 Free
0580100c 00395f68        12 Free
05a01d30 00395f68        12 Free
05c02a54 00395f68        12 Free
05e03778 00395f68        12 Free
0600449c 00395f68        12 Free
062051c0 00395f68        12 Free
06a51000 00395f68        12 Free
06a5100c 00395f68        12 Free
06c51d30 00395f68        12 Free
06e52a54 00395f68        12 Free
07053778 00395f68        12 Free
0725449c 00395f68        12 Free
074551c0 00395f68        12 Free
07a51000 00395f68        12 Free
07a5100c 00395f68        12 Free
07c51d30 00395f68        12 Free
07e52a54 00395f68        12 Free
08053778 00395f68        12 Free
0825449c 00395f68        12 Free
084551c0 00395f68        12 Free
08a51000 00395f68        12 Free
08a5100c 00395f68        12 Free
08c51d30 00395f68        12 Free
08e52a54 00395f68        12 Free
09053778 00395f68        12 Free
0925449c 00395f68        12 Free
094551c0 00395f68        12 Free
09a51000 00395f68        12 Free
09a5100c 00395f68        12 Free
09c51d30 00395f68        12 Free
09e52a54 00395f68        12 Free
0a053778 00395f68        12 Free
0a25449c 00395f68        12 Free
0a4551c0 00395f68        12 Free
0aee1000 00395f68        12 Free
0aee100c 00395f68        12 Free
0b0e1d30 00395f68        12 Free
0b2e2a54 00395f68        12 Free
0b4e3778 00395f68        12 Free
...
...
...
55192a54 00395f68        12 Free
55393778 00395f68        12 Free
5559449c 00395f68        12 Free
557951c0 00395f68        12 Free
55d91000 00395f68        12 Free
55d9100c 00395f68        12 Free
55f91d30 00395f68        12 Free
56192a54 00395f68        12 Free
02c21000 00395f68        16 Free
02c22010 00395f68        16 Free
02c23020 00395f68        16 Free
02c23240 00395f68        16 Free
total 564 objects
Statistics:
      MT    Count    TotalSize Class Name
00395f68      564        13120      Free
Total 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 -stat
total 22233 objects
Statistics:
      MT    Count     TotalSize Class Name
79119954        1            12 System.Security.Permissions.ReflectionPermission
79119834        1            12 System.Security.Permissions.FileDialogPermission
791197b0        1            12 System.Security.PolicyManager
00113038        1            12 Advanced.NET.Debugging.Chapter5.Fragment
791052a8        1            16 System.Security.Permissions.UIPermission
79117480        1            20 System.Security.Permissions.EnvironmentPermission
791037c0        1            20 Microsoft.Win32.SafeHandles.SafeFileMappingHandle
79103764        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.String
00395f68    10006      496172124      Free
7912dae8    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 -gc
Number of GC Heaps: 1
generation 0 starts at 0x55d9100c
generation 1 starts at 0x55d91000
generation 2 starts at 0x01c21000
ephemeral segment allocation context: none
 segment    begin allocated     size
003a80e0 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     size
02c20000 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     50012
55fffb78 00395f68     50012 Free
5600bed4 7912dae8     50012
56018230 00395f68     50012 Free
5602458c 7912dae8     50012
560308e8 00395f68     50012 Free
5603cc44 7912dae8     50012
56048fa0 00395f68     50012 Free
560552fc 7912dae8     50012
56061658 00395f68     50012 Free
5606d9b4 7912dae8     50012
56079d10 00395f68     50012 Free
5608606c 7912dae8     50012
560923c8 00395f68     50012 Free
5609e724 7912dae8     50012
560aaa80 00395f68     50012 Free
560b6ddc 7912dae8     50012
560c3138 00395f68     50012 Free
560cf494 7912dae8     50012
560db7f0 00395f68     50012 Free
560e7b4c 7912dae8     50012
560f3ea8 00395f68     50012 Free
56100204 7912dae8     50012
5610c560 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 5606d9b4
Name: System.Byte[]
MethodTable: 7912dae8
EEClass: 7912dba0
Size: 50012(0xc35c) bytes
Array: Rank 1, Number of elements 50000, Type Byte
Element Type: System.Byte
Fields:
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> !GCHandles
GC Handle Statistics:
Strong Handles: 15
Pinned Handles: 10004
Async Pinned Handles: 0
Ref Count Handles: 0
Weak Long Handles: 0
Weak Short Handles: 1
Other Handles: 0
Statistics:
      MT    Count    TotalSize Class Name
790fd0f0        1           12 System.Object
790feba4        1           28 System.SharedStatics
790fcc48        2           48 System.Reflection.Assembly
790fe17c        1           72 System.ExecutionEngineException
790fe0e0        1           72 System.StackOverflowException
790fe044        1           72 System.OutOfMemoryException
790fed00        1          100 System.AppDomain
790fe704        2          112 System.Threading.Thread
79100a18        4          144 System.Security.PermissionSet
790fe284        2          144 System.Threading.ThreadAbortException
7912d8f8        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.

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.

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:怎样删除windows.old文件

下一篇:C#泛型List的用法