Debug Tutorial Part 5: Handle Leaks

《光学》全套PPT课件(安徽大学) 立即下载
 

Introduction

Welcome to the fifth installment of the debug tutorial series. In this article, we will go over handles in Windows, what they are and how to debug leaks. I hope that you are already familiar with the previous 4 articles, before reading this one. The intent of these articles is not to regurgitate the WinDbg/NTSD help files but rather introduce real problems, what they are and how to solve them using the debuggers.

What is a handle?

To an application, a "handle" is some instance of a device, file, or some other system object or resource. The application will create an instance of the resource by calling a function such as CreateFile or RegOpenKey, and use the handle in subsequent calls to these functions to perform operations on the resource.

In general, you never really care what this handle value is as it really is of no value to your application aside from passing it into functions that perform operations on it. So, what exactly is the handle and what does it represent?

In order to get a clearer picture, let's go over a simple CreateFile call.

If you debug CreateFile, you will notice eventually it gets to NtCreateFile.

kernel32!CreateFileW+0x34a:
77e7b24c ff150810e677 call dword ptr [kernel32!_imp__NtCreateFile (77e61008)]
0:000> kb
ChildEBP RetAddr  Args to Child
0012f728 77e7b4a3 000007c4 80000000 00000000 kernel32!CreateFileW+0x40e
0012f74c 00401ba9 00406760 80000000 00000000 kernel32!CreateFileA+0x2e

NtCreateFile results into a kernel call. How the call is actually performed varies on the system, it could be a sysenter instruction or a software generated interrupt int 2eh. Either case, a call is made into the kernel and the system dispatches the call to the correct driver. When this occurs, an object is created in the kernel which represents the requested resource, in this case a file. If you look at the parameters to NtCreateFile, posted here, you will notice that the first parameter to NtCreateFile is where the handle value will be returned. Let's take a look at what was the first parameter.

eax=0012f730 ebx=00000000 ecx=80100080 edx=00200000 esi=77f58a3e edi=00000000
eip=77e7b24b esp=0012f69c ebp=0012f728 iopl=0         nv up ei ng nz na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=0038  gs=0000             efl=00000282
kernel32!CreateFileW+0x349:
77e7b24b 50               push    eax
0:000>

As we can see, the first parameter was an address, most likely to some local variable in the function. Upon return, we can now check the value it points to. According to the documentation, it's a file handle.

0:000> dd 0012f730
0012f730  000007c4

The returned value is 7c4h, which is NOT a pointer to any memory in your application. It is also not even a pointer in kernel memory. To further investigate, let's find what information we can gather from the handle. There is a debugger command that displays handle information. This command is called !handle. Let's use this command on the value and see what we get.

0:000> !handle 7c4 ff
Handle 7c4
  Type          File
  Attributes    0
  GrantedAccess 0x120089:
         ReadControl,Synch
         Read/List,ReadEA,ReadAttr
  HandleCount   2
  PointerCount  3
  No Object Specific Information available

So, we are told that it is indeed a file type object, we are told the attributes and even granted access to the handle. What we aren't told in this information is the file that this handle points to. To me, that would seem to be the most valuable information that you could gather. There is a reason why we do not see this information, but before I tell you that, we must continue to figure out how the system even found what it did in the first place.

What does the value of a handle represent?

To show you this, I need to hook up the kernel debugger. I have started to debug another process on a Windows 2000 professional machine since I do not have it setup for my Windows XP box. I started Notepad and attempted to get handles in notepad.exe.

Tip: In Windows XP/2003, more information is available to the system as well as displayed in the debugger. For example, !handle on a thread will display the thread entry function. Windows 2000 will not do this. This can be very useful if you want to find the matching thread to a handle, especially if the thread handle was leaked and the thread is no longer around. There is also the command dt which was shown earlier in these tutorials. Windows 2000 may have problems displaying structures that are always displayed on Windows 2003/XP (Referring to system structures like NT's _EPROCESS). This is either due to the way DBGs and PDBs are handled when debugging Windows 2000, or the information is simply missing. These and many other benefits make debugging on Windows XP/2003 more desirable than Windows 2000.

So, I selected a file in Notepad and set break points on CreateFile. After I selected a file, the breakpoint hit and I simply set another breakpoint on the return address. Now, I dump EAX to get the handle information of the file I selected.

0:000> !handle eax ff
Handle 120
  Type          File
  Attributes    0
  GrantedAccess 0x120089:
         ReadControl,Synch
         Read/List,ReadEA,ReadAttr
  HandleCount   2
  PointerCount  3

This doesn't really tell me much aside from really, it's a file. Now, I'm going to let you in on the first secret. These handles are process specific. This value, "120h", is only known from within this process space. If this handle value was sent to another process, it would either not exist or most likely be a handle to a different object. These handles are not like window handles, their scope is within a process.

Handles are also representations of kernel mode objects. This means that every process has a handle table located in kernel mode and each entry points to a kernel memory location. This is secret number two. This is why I hooked up the kernel debugger. Now, let's break into the kernel and we will attempt to find this handle.

The first thing I do in the kernel debugger is "!process 0 0" to list all processes. Once all processes are listed, I will then use the !handle command. The syntax is a little different though. I will need to specify the process in order to list the correct handle.

kd> !process 0 0
**** NT ACTIVE PROCESS DUMP ****
...
PROCESS fcc77200  SessionId: 0  Cid: 0338    Peb: 7ffdf000  ParentCid: 02c8
    DirBase: 079de000  ObjectTable: fccc30c8  TableSize:  74.
    Image: notepad.exe
kd> !handle 120 ff fcc77200  
processor number 0
PROCESS fcc77200  SessionId: 0  Cid: 0338    Peb: 7ffdf000  ParentCid: 02c8
    DirBase: 079de000  ObjectTable: fccc30c8  TableSize:  74.
    Image: notepad.exe

Handle Table at e1e5f000 with 74 Entries in use
0120: Object: fcd32448  GrantedAccess: 00120089
Object: fcd32448  Type: (fced7c40) File
    ObjectHeader: fcd32430
        HandleCount: 1  PointerCount: 1
        Directory Object: 00000000  Name: /TripItinerary.txt {HarddiskVolume1}

The first bold number is the process object. It's basically a structure in memory that contains information and locations of data specific to that process. Since handles are process specific, we need to tell the !handle command what process to look in. The "ff" I use simply sets all the bit fields to give me all the information it possibly can. The help will tell you what each bit represents if you want to be picky about the displayed information. I always just use "ff" so I don't need to bother with setting exact flags and I know I should get all available information.

The second bold address is the handle table for that process. This memory location specifies all entries to the handles used by that process. Notice that it currently has 74 handles open. The last bold is the object's memory location itself. This is where all the data is being pulled from. Notice that the "Name" property gives us the actual location and file name. How come we couldn't see this in the user mode debugger?

Displaying Handle Information In User Mode

Obviously, this table is located in the kernel so it cannot be seen directly from user mode. NT does provide APIs that can be used to query these handles from the kernel. If you have read my article #3, the QuickView: System Explorer utility I wrote actually does this and will display the handle information for processes that it can access. The API that does this is called NtQueryObject.

The downfall of this API is that certain objects may hang when you attempt to query them. This is because those objects, for example, are opened with SYNC access and some of them really mean business. There are pipes opened on the system that if you attempt to query them will hang indefinitely. In order to prevent this, the debugger as well as the application I wrote attempt to prevent this by not querying objects that have the potential to cause deadlock. In my application though, I not only check for the SYNC flag to be set, I found some common access masks that would not hang and allow those to be queried.

There is another utility called HANDLE.EXE that can be downloaded from SysInternals that DOES display all information. So, how does it do that without deadlocking? They have their own kernel driver, and since all memory in system space is accessible by any driver also running in system space, it's quite simple. As shown, the kernel object's memory location can be found and simply read directly without having to acquire a system lock which deadlocks the NtQueryObject call. I have been thinking to add a driver to future versions of QuickView to get around the deadlocking issue and display more detailed information.

Multiple Handles

You have seen the above example on my Windows 2000 machine. I have opened /TripItinerary.txt file. So, what happens if I open it again with another instance of Notepad? Let's try this and see what happens.

Inside the user mode debugger:

0:000> !handle eax ff
Handle 58
  Type          File
  Attributes    0
  GrantedAccess 0x120089:
         ReadControl,Synch
         Read/List,ReadEA,ReadAttr
  HandleCount   2
  PointerCount  3

In the kernel debugger, I found the process and list the handle:

kd> !handle 58 ff fcd8ace0  
processor number 0
PROCESS fcd8ace0  SessionId: 0  Cid: 0258    Peb: 7ffdf000  ParentCid: 0198
    DirBase: 04b19000  ObjectTable: fccc9648  TableSize:  22.
    Image: notepad.exe

Handle Table at e1e89000 with 22 Entries in use
0058: Object: fcce7028  GrantedAccess: 00120089
Object: fcce7028  Type: (fced7c40) File
    ObjectHeader: fcce7010
        HandleCount: 1  PointerCount: 1
        Directory Object: 00000000  Name: /TripItinerary.txt {HarddiskVolume1}

I can also list the handle in the original Notepad process:

kd> !handle 120 ff fcc77200  
processor number 0
PROCESS fcc77200  SessionId: 0  Cid: 0338    Peb: 7ffdf000  ParentCid: 02c8
    DirBase: 079de000  ObjectTable: fccc30c8  TableSize:  74.
    Image: notepad.exe

Handle Table at e1e5f000 with 74 Entries in use
0120: Object: fcd32448  GrantedAccess: 00120089
Object: fcd32448  Type: (fced7c40) File
    ObjectHeader: fcd32430
        HandleCount: 1  PointerCount: 1
        Directory Object: 00000000  Name: /TripItinerary.txt {HarddiskVolume1}

In this case, not only did they get their own handle, but they got their own memory location in the kernel. This isn't always the case with all objects. Sometimes the kernel object can be shared across processes. If the same process opens the file, generally they get two handles but one kernel object as well. You can experiment by using the utility I wrote or SysInternals handle application to display handle information and sort them by kernel object or handle #. This can help to get you acquainted with handles.

Why did the user mode debugger show a HandleCount of 2 and a PointerCount of 3?

If you noticed, there was a "HandleCount" 2 and "PointerCount" 3 when we used the user mode debugger to show handle information. This is because it did not adjust itself when displaying the information. In order for the debugger to get the handle information, it must duplicate the handle using DuplicateHandle. The duplication increases the HandleCount by 1 and the PointerCount by 2. If the debugger would decrement by 1 and by 2, it could display the correct information but it chooses not to. Let's check this out and see.

What I have first done is looked at the handle ObjectHeader: "fcd32430" in the kernel.

kd> !handle 120 ff fcc77200  
processor number 0
PROCESS fcc77200  SessionId: 0  Cid: 0338    Peb: 7ffdf000  ParentCid: 02c8
    DirBase: 079de000  ObjectTable: fccc30c8  TableSize:  74.
    Image: notepad.exe

Handle Table at e1e5f000 with 74 Entries in use
0120: Object: fcd32448  GrantedAccess: 00120089
Object: fcd32448  Type: (fced7c40) File
    ObjectHeader: fcd32430
        HandleCount: 1  PointerCount: 1
        Directory Object: 00000000  Name: /TripItinerary.txt {HarddiskVolume1}

kd> dd fcd32430
fcd32430  00000001 00000001 fced7c40 00000800
fcd32440  fcce5fc8 00000000 00700005 fceccbd0
fcd32450  fcecc248 e1e730d8 e1e73250 fcc790b4
fcd32460  00000000 00000000 00000000 00010000
fcd32470  00010100 00040042 00380024 e1bf2568
fcd32480  00000000 00000000 00000000 00000000
fcd32490  00000000 00040001 00000000 fcd3249c
fcd324a0  fcd3249c 00040000 00000001 fcd324ac
kd> ba r1 fcd32430  
kd> ba r1 fcd32434
kd> g

As we can see, the handle count is 1 and the pointer count is 1. I then set "ba r1" break points on the handle count address and the pointer count address. "BA" means Break if address is accessed. "r" means if it's accessed through read or write. The 1 on "r1" simply means 1 byte.

Once I have done this and hit "g" to let the kernel continue, I will now simply type "!handle 120 ff" in the user mode debugger. This will cause the user mode debugger to access this object to find the information. Let's see when these pointers are incremented.

kd> kb
ChildEBP RetAddr  Args to Child              
fb66ebf0 8049ff0d 00000120 00000000 00000000 nt!ObReferenceObjectByHandle+0x1af
fb66ed40 80461691 00000074 00000120 ffffffff nt!NtDuplicateObject+0x12d
fb66ed40 77f83f85 00000074 00000120 ffffffff nt!KiSystemService+0xc4
0006ef28 00000000 00000000 00000000 00000000 ntdll!NtDuplicateObject+0xb

As we can see, our first call calls ObReferenceObjectByHandle. This adds a reference to the pointer. Let's see what our handle count says now.

kd> !handle 120 ff fcc77200  
processor number 0
PROCESS fcc77200  SessionId: 0  Cid: 0338    Peb: 7ffdf000  ParentCid: 02c8
    DirBase: 079de000  ObjectTable: fccc30c8  TableSize:  74.
    Image: notepad.exe

Handle Table at e1e5f000 with 74 Entries in use
0120: Object: fcd32448  GrantedAccess: 00120089
Object: fcd32448  Type: (fced7c40) File
    ObjectHeader: fcd32430
        HandleCount: 1  PointerCount: 2
        Directory Object: 00000000  Name: /TripItinerary.txt {HarddiskVolume1}

As we can see, our pointer count has incremented to 2. Let's see what happens next.

kd> kb
ChildEBP RetAddr  Args to Child              
fb66ebec 8049fffb 00000002 fcc77800 fcd32448 nt!ObpIncrementHandleCount+0x236
fb66ed40 80461691 00000074 00000120 ffffffff nt!NtDuplicateObject+0x3c3
fb66ed40 77f83f85 00000074 00000120 ffffffff nt!KiSystemService+0xc4
0006eed0 77e846ed 00000074 00000120 ffffffff ntdll!NtDuplicateObject+0xb
0006ef28 69b22188 00000074 00000120 ffffffff KERNEL32!DuplicateHandle+0xd4
0006f454 69b2252e 00000074 00000120 000000ff ntsdexts!GetHandleInfo+0x29
0006f4d0 0100d562 00000074 00000050 01001dec ntsdexts!handle+0x10f
0006f52c 0100e497 00233848 0006f54c 0006f553 ntsd!CallExtension+0x77
0006f65c 0100c2bb 01089c81 010241d8 01089138 ntsd!fnBangCmd+0x377
0006f868 0100be0f 80000003 00000001 0006fc2c ntsd!ProcessCommands+0x2ac
0006fab4 01008406 00000000 00000000 ffffffff ntsd!ProcessStateChange+0x687
0006fc2c 01008a14 0006fc4c 00000000 00000000 ntsd!DebugEventHandler+0x6a5
0006fca8 010076dc 00000000 00000000 7ffdf000 ntsd!NtsdExecution+0x13b
0006ff70 010226bf 00000002 002337b0 00232978 ntsd!main+0x3d7
0006ffc0 77e87903 00000000 00000000 7ffdf000 ntsd!mainCRTStartup+0xff
0006fff0 00000000 010225c0 00000000 000000c8 KERNEL32!BaseProcessStart+0x3d
kd> !handle 120 ff fcc77200  
processor number 0
PROCESS fcc77200  SessionId: 0  Cid: 0338    Peb: 7ffdf000  ParentCid: 02c8
    DirBase: 079de000  ObjectTable: fccc30c8  TableSize:  74.
    Image: notepad.exe

Handle Table at e1e5f000 with 74 Entries in use
0120: Object: fcd32448  GrantedAccess: 00120089
Object: fcd32448  Type: (fced7c40) File
    ObjectHeader: fcd32430
        HandleCount: 2  PointerCount: 2
        Directory Object: 00000000  Name: /TripItinerary.txt {HarddiskVolume1}

As we can see, this now calls ObpIncrementHandleCount and our handle count is now also 2. Notice that both calls are within NtDuplicateObject which was called from the usermode API DuplicateHandle. So, duplicate object will increment the reference pointer count to this kernel memory and increment the number of handles that are pointing to this kernel object. This is an instance where two processes are referencing the same kernel object. So, where does the third pointer reference come in?

kd> kb
ChildEBP RetAddr  Args to Child              
fb66ec68 804baed8 00000100 00000000 00000000 nt!ObReferenceObjectByHandle+0x1af
fb66ed48 80461691 00000100 00000002 0006ef4c nt!NtQueryObject+0xc1
fb66ed48 77f8c4e1 00000100 00000002 0006ef4c nt!KiSystemService+0xc4
0006ef24 69b22203 00000100 00000002 0006ef4c ntdll!NtQueryObject+0xb
0006f454 69b2252e 00000000 00000120 000000ff ntsdexts!GetHandleInfo+0xa4
0006f4d0 0100d562 00000074 00000050 01001dec ntsdexts!handle+0x10f
0006f52c 0100e497 00233848 0006f54c 0006f553 ntsd!CallExtension+0x77
0006f65c 0100c2bb 01089c81 010241d8 01089138 ntsd!fnBangCmd+0x377
0006f868 0100be0f 80000003 00000001 0006fc2c ntsd!ProcessCommands+0x2ac
0006fab4 01008406 00000000 00000000 ffffffff ntsd!ProcessStateChange+0x687
0006fc2c 01008a14 0006fc4c 00000000 00000000 ntsd!DebugEventHandler+0x6a5
0006fca8 010076dc 00000000 00000000 7ffdf000 ntsd!NtsdExecution+0x13b
0006ff70 010226bf 00000002 002337b0 00232978 ntsd!main+0x3d7
0006ffc0 77e87903 00000000 00000000 7ffdf000 ntsd!mainCRTStartup+0xff
0006fff0 00000000 010225c0 00000000 000000c8 KERNEL32!BaseProcessStart+0x3d
kd> !handle 120 ff fcc77200  
processor number 0
PROCESS fcc77200  SessionId: 0  Cid: 0338    Peb: 7ffdf000  ParentCid: 02c8
    DirBase: 079de000  ObjectTable: fccc30c8  TableSize:  74.
    Image: notepad.exe

Handle Table at e1e5f000 with 74 Entries in use
0120: Object: fcd32448  GrantedAccess: 00120089
Object: fcd32448  Type: (fced7c40) File
    ObjectHeader: fcd32430
        HandleCount: 2  PointerCount: 3
        Directory Object: 00000000  Name: /TripItinerary.txt {HarddiskVolume1}

There it is, as I mentioned before, the debugger will need to call NtQueryObject in order to ask the system to tell it information about an object. The NtQueryObject API before attempting to read the memory will reference it by again calling ObReferenceObjectByHandle. This causes the pointer count to increase to 3. However, NtQueryObject does not need to create another handle instance or duplicate any handles. Once it's able to get a pointer reference to the object, it simply queries the information and releases the reference count.

Another process could possibly release its handle or pointer count during this operation and could even display only the debugger's references to the object. The returned information to the debugger will be 1 extra handle reference (the one it created), and 2 extra pointer references (the one it created when duplicating the handle and the one created by NtQueryObject to read the object information). The debugger, as mentioned before, could always subtract this to display only relevant information, since after the NtQueryObect call, one pointer reference goes away and it will also close its duplicated handle. That will let the object dereference to its original state (or new state if another process also now references it).

BTW, the DuplicateHandle API takes a process handle from which to duplicate the handle. So, you must be able to call OpenProcess with duplicate privileges in order to duplicate handles in other processes, just in case you were wondering. DuplicateHandle.

Debugging Handle Leaks

So, now that we have been acquainted with handles, how do we find leaks? Aside from the usual applications such as "Bounds Checker", we can find them ourselves. The first thing to do is check the application at a good time to get a baseline for handles. Task Manager has an option to display a "handles" column. This is a good place to start. Next, you should then perform operations with the application and of course, see if the handles grow or shrink. When the handles grow, you should not immediately think there's a handle leak. You must know to determine expected behavior from unexpected.

For example, if you had a server application and you were checking network connections. You notice that as you connect a lot of clients to the application, the number of network connections on the server grew. This would be expected, obviously so it would need to be determined if it's more than expected. Also, when all the clients disconnected, it would then be expected that all the network connections were cleaned up. So, if you know your handle count grows on purpose but selecting another option should then decrease the handle count, that should be tested.

Step One: Determine A Leak

If you've been monitoring the application, determine if the handle count is expected or not. See if it's growing steadily over time, fast or slow. Once you have determined this is truly a leak or are unsure at this point, it may be time to move onto the next step which would be to identify the handles being leaked. If possible, it would also be great to attempt to determine the pattern for the leak. An example would be every time a certain menu item is selected or a file is opened. This would help to narrow down reproduction steps and limit the area of the source that appears to be the location causing the problem.

Step Two: Determine The Type And Object Information

The best ways to do this would be to use a tool such as "Handle" from SysInternals and/or the debugger. I created a simple program that leaked handles very fast. I ran the application and looked in Task Manager. I found that over 65,000 handles were leaked. So, the first thing I want to do is determine what type of handle leaked. This way, I can limit down what APIs I want to look at in my application to find the leak.

0:001> !handle 0 0
65545 Handles
Type            Count
Event           3
Section         1
File            1
Port            1
Directory       3
WindowStation   2
Semaphore       2
Key             65530
Desktop         1
KeyedEvent      1

As we can see in this exaggerated example, the handle that appears to be leaking is a "Key", which is a registry handle. Some place in this application is opening the registry. The first thing now to do is attempt to identify the location and if there are more opens on a particular key than others. If we can get the key information, we would then be able to sort out which key was opened the most if there is one, and then we can limit our search in the application.

!handle 0 ff Key
Handle 2de0
  Type          Key
  Attributes    0
  GrantedAccess 0xf003f:
         Delete,ReadControl,WriteDac,WriteOwner
         QueryValue,SetValue,CreateSubKey,EnumSubKey,Notify,CreateLink
  HandleCount   2
  PointerCount  3
  Name          /REGISTRY/USER/S-1-5-21-789336058-706699826-1202660629-1003/Software
  Object Specific Information
    Key last write time:  01:10:03. 5/9/2004
    Key name Software

With the "Key", we get lucky. The debugger shows us the key being opened and HKCU/Software appears to be being opened the most. We have identified it is a key object, which means points of creation would be RegOpenKey and RegOpenKeyEx. We have also now identified the actual key being opened, HKCU/Software. Step 3:

Step Three: Browse Source and Debug Application

We now have the type, the APIs, and luckily enough even the exact resource being opened. So now, we can do things like look through the source for locations opening this key or even setting break points in the application on RegOpenKey/RegOpenKeyEx to get stack traces. We could then keep track of the allocated handles and determine which ones were getting closed. Bounds checker could also be used as a tool in aiding this process.

Another technique which can be done but may be overkill in most cases would be to use the memory leak trick stated in the "Heap" tutorial. Wrapper functions can be written around the APIs creating the handles and you could add the handle to a linked list. Upon free, you could search the linked list and remove the handle. This operation would allow the handle itself to still be returned so you do not have to have a wrapper for all functions. The only downfall is that it would be slower since you would need to traverse the list on a close.

//This method could return the actual key, but would require 
//a search of the linked list on a close.

DWORD MyOpenKey(..., phKey)
{
    dwResult = RegOpenKey(... phKey);

    pTemp = Allocate();
    pTemp->pNext = gpHead;
    gpHead = pTemp;
    gpHead->hKey = phKey;
  
    return dwResult;
}

//This method would allow faster look up in the close but 
//would also require a wrapper for all functions.

PMYKEY MyOpenKey(...)
{
    hKey = RegOpenKey(...);

    pTemp = Allocate();
    pTemp->pNext = gpHead;
    gpHead = pTemp;
    gpHead->hKey = hKey;
  
    return gpHead;
}

Also, remember that the above are examples, almost pseudo code. Critical sections would be used when needed and implementations can vary. The purpose of a global list is so a debugger extension (tutorial part 4) could be written to traverse the linked list and debug symbols could be used to find the location of this global to walk the list. This may be overkill for most problems and the implementation would probably only benefit if it was pre-built into all the builds without necessary implementation all the time (such as #define MyOpenKey RegOpenKey for retail builds).

Smaller Leaks

Not all handle leaks will appear like the above. For example, you may notice an operation is causing one or two handle leaks every time it's called. You could then break into the application, get a handle count for all values, then perform the leak and get the next snapshot. Once that occurs, you could then cause the problem again, but this time set break points on locations that would create the objects that you have seen increasing.

Other Tips

Here are some other tips when dealing with handles.

Invalid thread wait for exit looping

I have noticed many applications use a Sleep()/GetExitCodeThread() loop combination to wait for a thread to exit. For an example:

   do {
     Sleep(10);
     bReturn = GetExitCodeThread(hThread, &ExitCode);
   } while(bReturn && ExitCode == STILL_ACTIVE) ;

MSDN states, the problem with this is that the thread could return STILL_ACTIVE (value 259) as its return value. While that may be true, that's not the reason I would worry about this loop. A problem that I found was that some applications were using MFC's CThread libraries and attempting to do this loop. The problem is that AfxBeginThread() sends the thread handle to the created thread. The created thread uses AfxEndThread() to exit, which then closes the handle. If you have not duplicated this handle, that handle is now invalid.

In general, this may not be a problem as the loop would still exit when it got the failure to use the handle. The problem occurs when another object was now created using the old thread handle! Remember, these handles are re-used by the system once they are freed. That means that another object could be assigned to the handle in the time it takes to call the function again. This object could be anything and the call may fail with invalid object. It could also be another, newly created thread which would now not let this loop exit!

So the first rules are, even outside of the Afx* functions, if you're going to close the handle elsewhere, be sure to duplicate it. Secondly, you don't need to loop since the thread handle becomes signaled when the thread exits.

  WaitForSingleObject(hThread, INFINTE);
  GetExitCodeThread(hThread, &ExitCode);
  CloseHandle(hThread);

So, the above could have been better solved by the series of code modeled above.

.DMP files missing handle information?

If you have a .DMP file and you use !handle sometimes, you may receive an error. This is because if you have a .DMP file, you can't call NtQueryObject to get the handle information anymore. In that case, the debugger needed to have queried all objects and saved the information into the .DMP while creating it. Some .dump flags do not do this. What I have found is that almost all NTSD/CDB/WinDbg versions never save handle information when using .dump /f x.dmp (full dump). They have a separate option, /mh though that does. .dump /mh x2.dmp but it's not a full dump, it's a "mini dump". What I have done in the past is create two dumps using both options.

This is not necessary if you have a newer debugger downloaded from Microsoft's site though. There is a new option, /ma that creates a full dump with handle information. .dump /ma x3.dmp and that is all you need. This is the flag I would recommend to create all user mode dumps since you never know if you may need to look at handle information.

Conclusion

Handles are yet another part of Windows which we must learn to work with and "handle" them correctly. When checking applications you write for memory leaks and other problems, always be sure to check the handle count! Hopefully, this article helped you learn what handles are and how to investigate them

YOLO26算法婴幼儿面部情绪识别目标检测+训练好的模型+2681张数据集+pyqt可视化界面.zip 附训练好的 YOLO 权重与 PyQt 可视化检测界面,页面底部含可视化效果预览,毕设/课设开箱即用。 【数据集概况】 · 检测类别(中文):[哭泣(crying), 开心(happy)] · 总计:2681 张 · 测试集:186 张 · 验证集:0 张 · 训练集:2495 张 【训练曲线与评估图】 【模型训练配置】 参数 | 值 模型 | yolo26n 训练轮数 | 100 epochs 输入尺寸 | 640x640 批次大小 | 24 优化器 | auto 初始学习率 | 0.01 训练设备 【关键指标汇总】 训练了 100 个 epoch,最终轮指标: 指标 | 数值 mAP50 | **0.8069** mAP50-95 | 0.5664 Precision | 0.8700 Recall | 0.7726 train/box_loss | 0.7524 train/cls_loss | 0.4490 val/box_loss | 1.1351 val/cls_loss | 0.7588 【训练过程分析】 训练伊始,模型对 box_loss 和 cls_loss 的下降表现出惊人的效率,前 20 轮迅速将训练损失降至低位,显示了训练集的强大适应性。然而,在第 20 轮之后,loss 下降速度明显放缓,整体趋于平稳。到了 60 轮左右,box_loss 值逐渐接近 0.75,而 cls_loss 则稳定在 0.44 左右。从训练集的 box_loss 从 0.7524 降至 0.7325,能看出来 model 正在逐步优化每个实例的边界框准确性,这一过程在前 40 轮尤为显著。相比之下,cls_loss 从 0.4490 降至 0.4389,尽管变化不大,但整体上表现出了模型对类别的清晰度提升... 使用场景:毕业设计、课程设计、深度学习入门、工业场景落地验证。 立即下载

相关推荐

依赖专家资源的传统机构与依赖数据算法的现代平台,在转化效率上谁更胜一筹?.docx

依赖专家资源的传统机构与依赖数据算法的现代平台,在转化效率上谁更胜一筹?

输入流写入持久化卷

输入流写入持久化卷 有一个简单的需求:有一个输入流InputStream,要将其写入持久化卷;写了几版,总是报coverity有内存泄露;写下解决过程 第一版: private static void writeUserImportFile(InputStream is) throws IOException{ BufferedInputStream in=null; BufferedOutputStream out=null; File targetfil

Anakin6174的博客 1910

PostgreSQL 数据库辅助类(要求 Npgsql 7.0 及以上) .NET Framework 4.7.2+ 或 .NET 6+;C# 7.3+

类别 :方法 数据源: Initialize、Close、DataSource、ConfigureBuilder、CommandTimeout、OnSqlExecuted 参数: CreateParameter(含类型版)、CreateJsonbParameter、CreateArrayParameter、ParamsFrom 执行: ExecuteNonQuery、ExecuteScalar<T>、ExecuteDataTable、ExecuteDataSet、ExecuteList<T>、ExecuteModel<T>、ExecuteDictionaryList、ExecuteColumn<T>、ExecuteReader(均有异步版) 封装: Exists、Count、ExecutePagedDataTable/List、Insert、Update、Delete、Upsert、TableExists、ColumnExists、GetTableNames、GetServerVersion、TestConnection 数据库对象: ExecuteFunctionTable/Scalar、CallProcedure 批量: ExecuteBatch(NpgsqlBatch)、BulkInsert(二进制 COPY)、CopyOut、ToDataTable 事务: ExecuteInTransaction(Async)、OpenTransaction(Async) 其他: Notify、ListenAsync、PgRetry(只读、显式调用)

c++定位内存泄露

//测试代码 #include "DebugTracer.h" //主要的思路是: // 1.重载new,在重载的new中保存new出来的地址,new的文件名(__FILE___),new的行数(__LINE__) //2.将该new的信息存放在一个容器中,delete时,删除一个,程序结束,还在容器中的指针,就是已经泄露的指针 int main() { int*p = new int; ...

m0_38126105的博客 614

知识管理四款团队知识库选型对比:Confluence、OmniBox、语雀、Sward适用场景与部署方案分析

内容概要:本文对2026年主流的四款团队知识库工具Confluence、小黑OmniBox、语雀和Sward进行了横向评测,指出这四款产品并非直接竞争关系,而是分别对应不同组织状态下的解决方案。评测围绕部署方式、权限协作、检索与AI能力三大核心维度展开,强调选型不应仅看功能列表,而应关注资料来源、使用场景与团队特征。Confluence适合已有Atlassian体系的中大型企业,强在权限控制与流程治理;小黑OmniBox聚焦多源资料整合与AI问答,适用于资料分散的团队;语雀以“书本式”结构降低中文团队使用门槛;Sward则主打开源私有化部署,满足内网合规需求。文章最后提供四类典型团队的选型路径,并澄清了“AI万能”“私有化即安全”等常见误区。; 适合人群:企业IT负责人、技术管理者、知识管理相关从业者,尤其是面临知识库选型决策的团队领导者。; 使用场景及目标:①帮助团队根据自身规模、技术栈、数据主权要求和协作习惯选择合适知识库工具;②厘清AI与知识库的关系,避免选型误区;③指导已有系统如何与新工具(如OmniBox)叠加使用,提升知识利用率。; 阅读建议:此评测基于公开资料与产品文档,未进行压力测试或大规模实测,建议结合实际业务场景试用验证,并优先考虑现有系统兼容性与迁移成本。

基于深度学习分类的时相关MIMO信道的递归CSI量化(Matlab代码实现)

内容概要:本文系统阐述了基于深度学习分类的时相关MIMO信道递归CSI量化方法,并提供了完整的Matlab代码实现。该方法针对大规模MIMO系统中因信道状态信息(CSI)反馈开销过大而导致的系统效率下降问题,提出一种结合深度学习与递归结构的量化方案,利用分类网络对时域相关的CSI进行高效压缩,通过递归机制捕捉信道动态的时间连续性特征,显著提升了量化精度与频谱利用率。文中详细介绍了算法设计原理、神经网络架构选型、训练策略设计、损失函数构建及仿真验证流程,展示了在不同信道模型与时变条件下相较于传统量化方法的性能优势。; 适合人群:具备通信工程、信号处理或无线通信领域基础知识,熟悉MIMO系统原理与深度学习基本模型(如RNN、CNN)的研究生、科研人员及工程师,尤其适合从事智能通信、信道建模、CSI反馈优化等相关方向的研究者。; 使用场景及目标:①应用于大规模MIMO和5G/6G系统中的CSI反馈压缩与传输优化;②为时变无线信道环境下的高效信道量化提供基于深度学习的智能化解决方案;③支持科研复现实验,促进先进信号处理技术在通信系统中的融合与创新; 阅读建议:建议读者结合提供的Matlab代码逐模块调试运行,深入理解深度学习模型在信道量化任务中的输入输出设计、网络训练流程与性能评估方式,可尝试在不同信道参数(如多普勒频移、SNR)下进行仿真实验以验证算法鲁棒性与泛化能力。

IAR7.1-IAR8.3编译错误

IAR7.10.1编译错误 1、Error[Pe020]: identifier “xxx” is undefined (1)把xxx的定义,放在了使用它的语句下面,引起的错误。 良好的编程习惯是,如果变量的定义和使用处于同一文件,就要先定义后使用,且定义语句要放在使用的前面。所以最好将定义放在头文件里,再引用头文件即可。 (2)没有引用相关头文件 (3)真的没有定义 (4)定义在其他c文件时,要用extern定义 2、Error[Pe247]: variable “cx20921” has already

qq_34414144的博客 1万+

konica C368(柯尼卡美能达bizhub C368系列打印机驱动)

1、查看本机 IP,确保电脑和复印机在同一个局域网。 2、安装时 右键以管理员运行 ,旧驱动先卸载干净避免冲突。 3、端口默认:9100(RAW),也可用 LPR。 安装方法: 1. 解压后进入文件夹,64 位运行 `Setup64.exe`,32 位运行 `Setup.exe`。 2. 同意协议 → 选择【安装(网络搜索)】,程序自动扫描局域网内 C368P。 3. 在列表选中对应 IP 的机器,下一步;如果扫不到,切换到【手动设置】,填入复印机 IP。 4. 勾选驱动类型(PCL6),点击安装,等待完成。 5. 安装结束,打印测试页验证。

java 嵌入式开发面试题,[转]国外嵌入式面试题

Embedded System Interview Questions:1.Can structures be passed to the functions by value?2.Why cannot arrays be passed by values to functions?3.Advantages and disadvantages of using macro and inline f...

weixin_39582708的博客 360

EI复现梯级水光互补系统最大化可消纳电量期望短期优化调度模型(Python代码实现)

内容概要:本文提出了一种针对梯级水光互补系统的短期优化调度模型,旨在最大化可消纳电量期望,通过构建精确的数学优化模型并结合Python编程实现,对水电与光伏发电出力进行协同调度,提升新能源的利用效率与系统运行的稳定性;研究中引入Copula理论对光伏出力的不确定性与风光之间的时空相关性进行建模,提高了功率预测的概率精度与场景生成的科学性,从而增强调度方案在实际复杂环境下的鲁棒性与实用性。; 适合人群:具备电力系统运行与优化基础、掌握Python编程技能,从事新能源调度、多能互补系统建模、可再生能源集成研究的科研人员、工程技术人员及研究生。; 使用场景及目标:①应用于梯级水电站与大型光伏电站的联合运行调度分析;②支撑高比例可再生能源接入背景下的电力系统短期优化决策;③为考虑风光出力不确定性与相关性的多能源互补系统提供从概率预测到优化调度的完整技术路径与代码实现参考。; 阅读建议:建议读者结合文中Copula光伏预测模块与优化调度框架,使用实际气象与运行数据进行代码复现与参数调优,深入理解不确定性建模与优化求解的耦合机制,并可进一步拓展至含储能、负荷响应等多元灵活性资源的综合调度场景研究。

无GPS室内飞行:基于PX4与MID360的FAST-LIO定点悬停实战解析

本文详细解析了基于PX4飞控与大疆MID360激光雷达的无GPS室内飞行技术,重点介绍了FAST-LIO算法在定点悬停中的应用。通过硬件配置、软件环境搭建、坐标系转换等实战经验,帮助开发者解决室内定位难题,实现精准悬停与稳定飞行。

weixin_29056781的博客 265

长期运行程序的文件描述符泄漏问题

摘自https://oroboro.com/file-handle-leaks-server/ So you’ve created a socket server that opens sockets over TCP/IP. After running it for a few hours under heavy load the operating system kills yo

3025

Anaconda安装教程傻瓜教程

网上好多教程找的我心好累,为了方便新手安装,我这边整理了大致详细的教程,参考了好几个大佬的教程,废话不多说,直接开始~ **前言:**有人纠结先安装python还是安装anaconda,这边的建议是装anaconda,就不需要单独装python了。 其次,有小伙伴的Anaconda的安装分两种情况: 情况一:电脑现在没有装python或者现在装的可以卸载掉(装Anaconda时先卸python); 情况二:电脑目前装了python,但想保留它;

zlc2351951436的博客 5万+

理解和解决IE的内存泄漏模式

http://msdn.microsoft.com/zh-cn/library/bb250448%28v=VS.85%29.aspx。这篇文章是在解决IE内存泄漏问题方面极为重要的一篇文章,可惜一直没有译文。MSDN的英文并不难懂,所以原文附上,并加上一些个人的解读。 Unde

博客只是岁月的记录 1012

onnxruntime-gpu版本选择与CUDA环境配置实战指南

本文是onnxruntime-gpu版本选择与CUDA环境配置的实战指南。针对AI模型部署中常见的GPU无法调用问题,核心在于确保onnxruntime-gpu版本与系统CUDA Toolkit版本严格匹配。文章详细讲解了如何精准确定CUDA版本、查找官方对应关系、执行正确安装命令,并通过完整测试脚本验证GPU是否成功启用,最后提供了常见问题排查与生产环境调优建议。

weixin_29164091的博客 530

万物皆可GAN ---普通GAN, pix2pix, CycleGAN和pix2pixHD的比较以及演变过程

普通GAN, pix2pix, CycleGAN和pix2pixHD的原理、比较以及演变过程

m0_61985580的博客 3729

Check failed: proto SerializeToOstream(&output)

问题描述:这个问题我是在生成均值文件的时候提示的,我看网友们很多是在训练过程提示的。 Check failed: proto.SerializeToOstream(&output) 解决方法:我删掉了桌面的一些东西,竟然可以用了。感人,根本不知道是怎么解决的。(如果在训练过程中出现问题,网友们说是存储空间不够了,但是绝大多数都是linux系统出现的问题),我的系统是windows

一个做图像文本的深度学习人 3122

C语言练习题:据说一个人的标准体重应该是其身高(单位:厘米)减去100、再乘以0.9所得到的公斤数。已知市斤的数值是公斤数值的两倍。现给定某人身高,请你计算其标准体重应该是多少?

题目内容: 据说一个人的标准体重应该是其身高(单位:厘米)减去100、再乘以0.9所得到的公斤数。已知市斤的数值是公斤数值的两倍。现给定某人身高,请你计算其标准体重应该是多少?(顺便也悄悄给自己算一下吧……) 输入格式: 输入第一行给出一个正整数H(100 < H ≤ 300),为某人身高。 输出格式: 在一行中输出对应的标准体重,单位为市斤,保留小数点后1位。 输入样例: 169 输出样例: 124.2 代码如下: #include<stdio.h> int main() { i

weixin_44877226的博客 2万+
上一篇: Get File Version in your code
下一篇: Heap Memory Management
iiprogram
博客等级 码龄25年 1068粉丝 1515原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址