summaryrefslogtreecommitdiffstats
path: root/Source/kwsys/ProcessWin32Kill.cxx
blob: 3afe14a6c29d024af6e8ec04f984c7c0d1b0a193 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
/*=========================================================================

  Program:   KWSys - Kitware System Library
  Module:    $RCSfile$

  Copyright (c) Kitware, Inc., Insight Consortium.  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#define KWSYS_IN_PROCESS_C
#include "kwsysPrivate.h"
#include KWSYS_HEADER(ProcessWin32Kill.h)

/* The following process tree kill implementation is taken from
   http://www.alexfedotov.com/articles/killproc.asp
   It will work only on some versions of windows.  Hopefully
   I will eventually get some time to do a real implementation of this
   for all windows versions.  */

#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <stdarg.h>
#include <tlhelp32.h>

//---------------------------------------------------------------------------
// KillProcess
//
//  Terminates the specified process.
//
//  Parameters:
//        dwProcessId - identifier of the process to terminate
//
//  Returns:
//        TRUE, if successful, FALSE - otherwise.
//
static BOOL
WINAPI
KillProcess(
        IN DWORD dwProcessId
        )
{
        HANDLE hProcess;
        DWORD dwError;

        // first try to obtain handle to the process without the use of any
        // additional privileges
        hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, dwProcessId);
        if (hProcess == NULL)
        {
                if (GetLastError() != ERROR_ACCESS_DENIED)
                        return FALSE;

                OSVERSIONINFO osvi;

                // determine operating system version
                osvi.dwOSVersionInfoSize = sizeof(osvi);
                GetVersionEx(&osvi);

                // we cannot do anything else if this is not Windows NT
                if (osvi.dwPlatformId != VER_PLATFORM_WIN32_NT)
                        return SetLastError(ERROR_ACCESS_DENIED), FALSE;

                // enable SE_DEBUG_NAME privilege and try again

                TOKEN_PRIVILEGES Priv, PrivOld;
                DWORD cbPriv = sizeof(PrivOld);
                HANDLE hToken;

                // obtain the token of the current thread 
                if (!OpenThreadToken(GetCurrentThread(), 
                                                         TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES,
                                                         FALSE, &hToken))
                {
                        if (GetLastError() != ERROR_NO_TOKEN)
                                return FALSE;

                        // revert to the process token
                        if (!OpenProcessToken(GetCurrentProcess(),
                                                                  TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES,
                                                                  &hToken))
                                return FALSE;
                }

                if(!(ANYSIZE_ARRAY > 0))
                  {
                  return 0;
                  }

                Priv.PrivilegeCount = 1;
                Priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
                LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &Priv.Privileges[0].Luid);

                // try to enable the privilege
                if (!AdjustTokenPrivileges(hToken, FALSE, &Priv, sizeof(Priv),
                                                                   &PrivOld, &cbPriv))
                {
                        dwError = GetLastError();
                        CloseHandle(hToken);
                        return SetLastError(dwError), FALSE;
                }

                if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
                {
                        // the SE_DEBUG_NAME privilege is not present in the caller's
                        // token
                        CloseHandle(hToken);
                        return SetLastError(ERROR_ACCESS_DENIED), FALSE;
                }

                // try to open process handle again
                hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, dwProcessId);
                dwError = GetLastError();
                
                // restore the original state of the privilege
                AdjustTokenPrivileges(hToken, FALSE, &PrivOld, sizeof(PrivOld),
                                                          NULL, NULL);
                CloseHandle(hToken);

                if (hProcess == NULL)
                        return SetLastError(FALSE), NULL;
        }

        // terminate the process
        if (!TerminateProcess(hProcess, (UINT)-1))
        {
                dwError = GetLastError();
                CloseHandle(hProcess);
                return SetLastError(dwError), FALSE;
        }

        CloseHandle(hProcess);

        // completed successfully
        return TRUE;
}

typedef LONG    NTSTATUS;
typedef LONG    KPRIORITY;

#define NT_SUCCESS(Status) ((NTSTATUS)(Status) >= 0)

#define STATUS_INFO_LENGTH_MISMATCH      ((NTSTATUS)0xC0000004L)

#define SystemProcessesAndThreadsInformation    5

typedef struct _CLIENT_ID {
    DWORD           UniqueProcess;
    DWORD           UniqueThread;
} CLIENT_ID;

typedef struct _UNICODE_STRING {
    USHORT          Length;
    USHORT          MaximumLength;
    PWSTR           Buffer;
} UNICODE_STRING;

typedef struct _VM_COUNTERS {
    SIZE_T          PeakVirtualSize;
    SIZE_T          VirtualSize;
    ULONG           PageFaultCount;
    SIZE_T          PeakWorkingSetSize;
    SIZE_T          WorkingSetSize;
    SIZE_T          QuotaPeakPagedPoolUsage;
    SIZE_T          QuotaPagedPoolUsage;
    SIZE_T          QuotaPeakNonPagedPoolUsage;
    SIZE_T          QuotaNonPagedPoolUsage;
    SIZE_T          PagefileUsage;
    SIZE_T          PeakPagefileUsage;
} VM_COUNTERS;

typedef struct _SYSTEM_THREADS {
    LARGE_INTEGER   KernelTime;
    LARGE_INTEGER   UserTime;
    LARGE_INTEGER   CreateTime;
    ULONG                       WaitTime;
    PVOID                       StartAddress;
    CLIENT_ID       ClientId;
    KPRIORITY       Priority;
    KPRIORITY       BasePriority;
    ULONG                       ContextSwitchCount;
    LONG                        State;
    LONG                        WaitReason;
} SYSTEM_THREADS, * PSYSTEM_THREADS;

// Note that the size of the SYSTEM_PROCESSES structure is different on
// NT 4 and Win2K, but we don't care about it, since we don't access neither
// IoCounters member nor Threads array

typedef struct _SYSTEM_PROCESSES {
    ULONG                       NextEntryDelta;
    ULONG                       ThreadCount;
    ULONG                       Reserved1[6];
    LARGE_INTEGER   CreateTime;
    LARGE_INTEGER   UserTime;
    LARGE_INTEGER   KernelTime;
    UNICODE_STRING  ProcessName;
    KPRIORITY       BasePriority;
    ULONG                       ProcessId;
    ULONG                       InheritedFromProcessId;
    ULONG                       HandleCount;
    ULONG                       Reserved2[2];
    VM_COUNTERS     VmCounters;
#if _WIN32_WINNT >= 0x500
    IO_COUNTERS     IoCounters;
#endif
    SYSTEM_THREADS  Threads[1];
} SYSTEM_PROCESSES, * PSYSTEM_PROCESSES;

//---------------------------------------------------------------------------
// KillProcessTreeNtHelper
//
//  This is a recursive helper function that terminates all the processes
//  started by the specified process and them terminates the process itself
//
//  Parameters:
//        pInfo       - processes information
//        dwProcessId - identifier of the process to terminate
//
//  Returns:
//        Win32 error code.
//
static
BOOL
WINAPI
KillProcessTreeNtHelper(
        IN PSYSTEM_PROCESSES pInfo,
        IN DWORD dwProcessId
        )
{
  if(!pInfo)
    {
    return 0;
    }

    PSYSTEM_PROCESSES p = pInfo;

    // kill all children first
    for (;;)
    {
                if (p->InheritedFromProcessId == dwProcessId)
                        KillProcessTreeNtHelper(pInfo, p->ProcessId);

                if (p->NextEntryDelta == 0)
                        break;

                // find the address of the next process structure
                p = (PSYSTEM_PROCESSES)(((LPBYTE)p) + p->NextEntryDelta);
    }

        // kill the process itself
    if (!KillProcess(dwProcessId))
                return GetLastError();

        return ERROR_SUCCESS;
}

//---------------------------------------------------------------------------
// KillProcessTreeWinHelper
//
//  This is a recursive helper function that terminates all the processes
//  started by the specified process and them terminates the process itself
//
//  Parameters:
//        dwProcessId - identifier of the process to terminate
//
//  Returns:
//        Win32 error code.
//
static
BOOL
WINAPI
KillProcessTreeWinHelper(
        IN DWORD dwProcessId
        )
{
        HINSTANCE hKernel;
        HANDLE (WINAPI * _CreateToolhelp32Snapshot)(DWORD, DWORD);
        BOOL (WINAPI * _Process32First)(HANDLE, PROCESSENTRY32 *);
        BOOL (WINAPI * _Process32Next)(HANDLE, PROCESSENTRY32 *);

        // get handle to KERNEL32.DLL
        hKernel = GetModuleHandle(_T("kernel32.dll"));
        if(!hKernel)
          {
          return 0;
          }

        // locate necessary functions in KERNEL32.DLL
        *(FARPROC *)&_CreateToolhelp32Snapshot =
                GetProcAddress(hKernel, "CreateToolhelp32Snapshot");
        *(FARPROC *)&_Process32First =
                GetProcAddress(hKernel, "Process32First");
        *(FARPROC *)&_Process32Next =
                GetProcAddress(hKernel, "Process32Next");

        if (_CreateToolhelp32Snapshot == NULL ||
                _Process32First == NULL ||
                _Process32Next == NULL)
                return ERROR_PROC_NOT_FOUND;

        HANDLE hSnapshot;
        PROCESSENTRY32 Entry;

        // create a snapshot
        hSnapshot = _CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
        if (hSnapshot == INVALID_HANDLE_VALUE)
                return GetLastError();

        Entry.dwSize = sizeof(Entry);
        if (!_Process32First(hSnapshot, &Entry))
        {
                DWORD dwError = GetLastError();
                CloseHandle(hSnapshot);
                return dwError;
        }

        // kill all children first
        do
        {
                if (Entry.th32ParentProcessID == dwProcessId)
                        KillProcessTreeWinHelper(Entry.th32ProcessID);

                Entry.dwSize = sizeof(Entry);
        }
        while (_Process32Next(hSnapshot, &Entry));

        CloseHandle(hSnapshot);

        // kill the process itself
    if (!KillProcess(dwProcessId))
                return GetLastError();

        return ERROR_SUCCESS;
}

//---------------------------------------------------------------------------
// KillProcessEx
//
//  Terminates the specified process and, optionally, all processes started
//      from the specified process (the so-called process tree).
//
//  Parameters:
//        dwProcessId - identifier of the process to terminate
//        bTree           - specifies whether the entire process tree should be
//                                      terminated
//
//  Returns:
//        TRUE, if successful, FALSE - otherwise.
//
static BOOL
WINAPI
KillProcessEx(
        IN DWORD dwProcessId,
        IN BOOL bTree
        )
{
        if (!bTree)
                return KillProcess(dwProcessId);

        OSVERSIONINFO osvi;
        DWORD dwError;

        // determine operating system version
        osvi.dwOSVersionInfoSize = sizeof(osvi);
        GetVersionEx(&osvi);

        if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT &&
                osvi.dwMajorVersion < 5)
        {
                HINSTANCE hNtDll;
                NTSTATUS (WINAPI * _ZwQuerySystemInformation)(UINT, PVOID, ULONG, PULONG);

                // get handle to NTDLL.DLL
                hNtDll = GetModuleHandle(_T("ntdll.dll"));
                if(!hNtDll)
                  {
                  return 0;
                  }

                // find the address of ZwQuerySystemInformation
                *(FARPROC *)&_ZwQuerySystemInformation =
                        GetProcAddress(hNtDll, "ZwQuerySystemInformation");
                if (_ZwQuerySystemInformation == NULL)
                        return SetLastError(ERROR_PROC_NOT_FOUND), NULL;

                // obtain a handle to the default process heap
                HANDLE hHeap = GetProcessHeap();
    
                NTSTATUS Status;
                ULONG cbBuffer = 0x8000;
                PVOID pBuffer = NULL;

                // it is difficult to say a priory which size of the buffer 
                // will be enough to retrieve all information, so we start
                // with 32K buffer and increase its size until we get the
                // information successfully
                do
                {
                        pBuffer = HeapAlloc(hHeap, 0, cbBuffer);
                        if (pBuffer == NULL)
                                return SetLastError(ERROR_NOT_ENOUGH_MEMORY), FALSE;

                        Status = _ZwQuerySystemInformation(
                                                        SystemProcessesAndThreadsInformation,
                                                        pBuffer, cbBuffer, NULL);

                        if (Status == STATUS_INFO_LENGTH_MISMATCH)
                        {
                                HeapFree(hHeap, 0, pBuffer);
                                cbBuffer *= 2;
                        }
                        else if (!NT_SUCCESS(Status))
                        {
                                HeapFree(hHeap, 0, pBuffer);
                                return SetLastError(Status), NULL;
                        }
                }
                while (Status == STATUS_INFO_LENGTH_MISMATCH);

                // call the helper function
                dwError = KillProcessTreeNtHelper((PSYSTEM_PROCESSES)pBuffer, 
                                                                                  dwProcessId);
                
                HeapFree(hHeap, 0, pBuffer);
        }
        else
        {
                // call the helper function
                dwError = KillProcessTreeWinHelper(dwProcessId);
        }

        SetLastError(dwError);
        return dwError == ERROR_SUCCESS;
}

extern "C" {
int kwsysProcessWin32Kill(int pid)
{
  return KillProcessEx(pid, 1)? 1:0;
}
}