HANDLE and ISHANDLE: Validate Global and Local Handles

This sample consists of two components:
 
>  ISHANDLE.DLL is a dynamic-link library (DLL) that
exports two functions, IsGlobalHandle and IsLocalHandle,
which validate global and local handles.

>  HANDLE.EXE is an application that tests these two
functions by linking into the DLL.

The IsLocalHandle and IsGlobalHandle functions in
ISHANDLE.DLL use a set of functions from TOOLHELP.DLL to
validate the given local or global handle. IsLocalHandle
uses the LocalFirst and LocalNext functions to walk the
local heap until the desired local handle is found.
Similarly, IsGlobalFunction uses the GlobalFirst and
GlobalNext functions to walk the global heap until the
desired global handle is found.

HANDLE demonstrates the IsLocalHandle and IsGlobalHandle
functions by passing good and bad handles to these
functions.

The following code shows how IsLocalHandle walks the local
heap and validates the given local handle, hLocalHandle.


    /* Declare local variables. */
    LOCALENTRY LEntry;

    /* Allocate a buffer to do the local heap walk. */
    bFound = FALSE;
    LEntry.dwSize = sizeof(LOCALENTRY);

    /* Loop through the local heap until hLocalHandle is
found. */
    if (LocalFirst(&LEntry, wHeap))
       {
       do
          {
          if (LEntry.hHandle == hLocalHandle)
             {
             bFound = TRUE;
             break;
             }
          } while (LocalNext(&LEntry));
       }

    if (bFound)
       return hLocalHandle;
    else
       return NULL;

You can adopt this idea to walk the local/global heap and
obtain/store more information on a block of memory from
the LOCALENTRY and GLOBALENTRY structures. For example,
you can build a dynamic list that maintains information
about the heaps, or use the DLL to simulate the
functionality of the TOOLHELP ModuleFindHandle and
TaskFindHandle functions.

HANDLE requires Microsoft(R) Windows(TM) version 3.1 to
build, but has been compiled for 3.1 and 3.0
compatibility. TOOLHELP.DLL was not shipped with Windows
3.0; you must copy this library to the \WINDOWS\SYSTEM
directory to run HANDLE under 3.0.

KEYWORDS: PR-CD2
