Link to home
Start Free TrialLog in
Avatar of Pavlik
Pavlik

asked on

How to enumerate handles owned by process

I want to find out the way how programs like "handle.exe" from http://www.sysinternals.com enumerate handles owned by some process.
Maybe somebody knows which API i should use for it.
Avatar of jhance
jhance

Their book, Inside Microsoft Windows 2000 discusses this:

http://www.sysinternals.com/insidew2k.shtml
Avatar of jkr
No, this book doesn't - believe me, there is no single line of code in it :o)

You basically have to

void    GetOpenHandleList   (   DWORD   dwPID,  obj_list*   pList)
{

    NTSTATUS                    ntStatus;

    HANDLE                      hObject;
    HANDLE                      hProcess;

    PSYSTEM_HANDLE_INFORMATION  pshi;

    ULONG                       ul  =   0x1000;
    PULONG                      pul =   new ULONG   [   ul];

    hProcess    =   OpenProcess (   PROCESS_DUP_HANDLE, FALSE,  dwPID);

    while   (   STATUS_INFO_LENGTH_MISMATCH ==  ZwQuerySystemInformation    (   SystemHandleInformation,
                                                                                pul,
                                                                                ul  *   sizeof  (   ULONG),
                                                                                0
                                                                            )
            )   delete  []  pul,    pul =   new ULONG   [   ul  *=  2];

    pshi    =   ( PSYSTEM_HANDLE_INFORMATION)   ( pul   +   1);

    for (   ULONG   i   =   0;  i   <   *pul;   i++)
        {
            if  (   pshi    [   i].ProcessId    !=  dwPID)  continue;

            hObject =   NULL;

            ZwDuplicateObject   (   hProcess,
                                    ( HANDLE)   pshi    [   i].Handle,
                                    NtCurrentProcess    (),
                                    &hObject,
                                    0,
                                    0,
                                    DUPLICATE_SAME_ATTRIBUTES
                                );

            if  (   hObject)
                    AppendObjectInformation (   hObject, pList);

        }

    delete  []  pul;
}

ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Pavlik

ASKER

I've tried to find some information about this but i still don't know where can i get functions like ZwQuerySystemInformation(). Is it in the Platform SDK?
>>Is it in the Platform SDK?

No - you'll need the DDK from http://www.microsoft.com/hwdev/ddk/ 

Also note that 'ZwQuerySystemInformation()' is UNDOCUMENTED...
Avatar of Pavlik

ASKER

Thanks jkr.

I can not check all this stuff right now but looks like i have enough information to do it later.