-
Notifications
You must be signed in to change notification settings - Fork 6
/
common.hpp
798 lines (632 loc) · 20.5 KB
/
common.hpp
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
/******************************************************************************\
* This is a part of the Microsoft Source Code Samples.
* Copyright (C) 1994-1998 Microsoft Corporation.
* All rights reserved.
* This source code is only intended as a supplement to
* Microsoft Development Tools and/or WinHelp documentation.
* See these sources for detailed information regarding the
* Microsoft samples programs.
\******************************************************************************/
/*++
Module Name:
common.c
Abstract:
This module contains common apis used by tlist & kill.
--*/
#include <windows.h>
#include <winperf.h> // for Windows NT
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tlhelp32.h> // for Windows 95
#define TITLE_SIZE 64
#define PROCESS_SIZE MAX_PATH
#include <tchar.h>
#ifndef min
#define min(a,b) ((a)<(b)?(a):(b))
#endif
//
// task list structure
//
typedef struct _TASK_LIST {
DWORD dwProcessId;
DWORD dwInheritedFromProcessId;
BOOL flags;
HANDLE hwnd;
TCHAR ProcessName[PROCESS_SIZE];
TCHAR WindowTitle[TITLE_SIZE];
} TASK_LIST, *PTASK_LIST;
typedef struct _TASK_LIST_ENUM {
PTASK_LIST tlist;
DWORD numtasks;
} TASK_LIST_ENUM, *PTASK_LIST_ENUM;
//
// Function pointer types for accessing platform-specific functions
//
typedef DWORD (*LPGetTaskList)(PTASK_LIST, DWORD);
typedef BOOL (*LPEnableDebugPriv)(VOID);
//
// Function prototypes
//
DWORD
GetTaskList95(
PTASK_LIST pTask,
DWORD dwNumTasks
);
DWORD
GetTaskListNT(
PTASK_LIST pTask,
DWORD dwNumTasks
);
BOOL
EnableDebugPriv95(
VOID
);
BOOL
EnableDebugPrivNT(
VOID
);
BOOL
KillProcess(
PTASK_LIST tlist,
BOOL fForce
);
VOID
GetWindowTitles(
PTASK_LIST_ENUM te
);
BOOL
MatchPattern(
LPTSTR String,
LPTSTR Pattern
);
//
// manafest constants
//
#define INITIAL_SIZE 51200
#define EXTEND_SIZE 25600
#define REGKEY_PERF _T("software\\microsoft\\windows nt\\currentversion\\perflib")
#define REGSUBKEY_COUNTERS _T("Counters")
#define PROCESS_COUNTER _T("process")
#define PROCESSID_COUNTER _T("id process")
#define UNKNOWN_TASK _T("unknown")
//
// Function pointer types for accessing Toolhelp32 functions dynamically.
// By dynamically accessing these functions, we can do so only on Windows
// 95 and still run on Windows NT, which does not have these functions.
//
typedef BOOL (WINAPI *PROCESSWALK)(HANDLE hSnapshot, LPPROCESSENTRY32 lppe);
typedef HANDLE (WINAPI *CREATESNAPSHOT)(DWORD dwFlags, DWORD th32ProcessID);
//
// prototypes
//
BOOL CALLBACK
EnumWindowsProc(
HWND hwnd,
DWORD lParam
);
DWORD
GetTaskList95(
PTASK_LIST pTask,
DWORD dwNumTasks
)
/*++
Routine Description:
Provides an API for getting a list of tasks running at the time of the
API call. This function uses Toolhelp32to get the task list and is
therefore straight WIN32 calls that anyone can call.
Arguments:
dwNumTasks - maximum number of tasks that the pTask array can hold
Return Value:
Number of tasks placed into the pTask array.
--*/
{
CREATESNAPSHOT pCreateToolhelp32Snapshot = NULL;
PROCESSWALK pProcess32First = NULL;
PROCESSWALK pProcess32Next = NULL;
HANDLE hKernel = NULL;
HANDLE hProcessSnap = NULL;
PROCESSENTRY32 pe32 = {0};
DWORD dwTaskCount = 0;
// Guarantee to the code later on that we'll enum at least one task.
if (dwNumTasks == 0)
return 0;
// Obtain a module handle to KERNEL so that we can get the addresses of
// the 32-bit Toolhelp functions we need.
hKernel = GetModuleHandle(_T("KERNEL32.DLL"));
if (hKernel)
{
pCreateToolhelp32Snapshot =
(CREATESNAPSHOT)GetProcAddress((HMODULE) hKernel, "CreateToolhelp32Snapshot");
pProcess32First = (PROCESSWALK)GetProcAddress((HMODULE)hKernel,
"Process32First");
pProcess32Next = (PROCESSWALK)GetProcAddress((HMODULE)hKernel,
"Process32Next");
}
// make sure we got addresses of all needed Toolhelp functions.
if (!(pProcess32First && pProcess32Next && pCreateToolhelp32Snapshot))
return 0;
// Take a snapshot of all processes currently in the system.
hProcessSnap = pCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == (HANDLE)-1)
return 0;
// Walk the snapshot of processes and for each process, get information
// to display.
dwTaskCount = 0;
pe32.dwSize = sizeof(PROCESSENTRY32); // must be filled out before use
if (pProcess32First(hProcessSnap, &pe32))
{
do
{
LPTSTR pCurChar;
// strip path and leave executabe filename splitpath
for (pCurChar = (pe32.szExeFile + lstrlen (pe32.szExeFile));
*pCurChar != '\\' && pCurChar != pe32.szExeFile;
--pCurChar)
lstrcpy(pTask -> ProcessName, pCurChar);
pTask -> flags = 0;
pTask -> dwProcessId = pe32.th32ProcessID;
++dwTaskCount; // keep track of how many tasks we've got so far
++pTask; // get to next task info block.
}
while (dwTaskCount < dwNumTasks && pProcess32Next(hProcessSnap, &pe32));
}
else
dwTaskCount = 0; // Couldn't walk the list of processes.
// Don't forget to clean up the snapshot object...
CloseHandle (hProcessSnap);
return dwTaskCount;
}
DWORD
GetTaskListNT(
PTASK_LIST pTask,
DWORD dwNumTasks
)
/*++
Routine Description:
Provides an API for getting a list of tasks running at the time of the
API call. This function uses the registry performance data to get the
task list and is therefore straight WIN32 calls that anyone can call.
Arguments:
dwNumTasks - maximum number of tasks that the pTask array can hold
Return Value:
Number of tasks placed into the pTask array.
--*/
{
DWORD rc;
HKEY hKeyNames;
DWORD dwType;
DWORD dwSize;
LPTSTR buf = NULL;
TCHAR szSubKey[1024];
LANGID lid;
LPTSTR p;
LPTSTR p2;
PPERF_DATA_BLOCK pPerf;
PPERF_OBJECT_TYPE pObj;
PPERF_INSTANCE_DEFINITION pInst;
PPERF_COUNTER_BLOCK pCounter;
PPERF_COUNTER_DEFINITION pCounterDef;
DWORD i;
DWORD dwProcessIdTitle;
DWORD dwProcessIdCounter;
TCHAR szProcessName[MAX_PATH];
DWORD dwLimit = dwNumTasks - 1;
//
// Look for the list of counters. Always use the neutral
// English version, regardless of the local language. We
// are looking for some particular keys, and we are always
// going to do our looking in English. We are not going
// to show the user the counter names, so there is no need
// to go find the corresponding name in the local language.
//
lid = MAKELANGID( LANG_ENGLISH, SUBLANG_NEUTRAL );
_stprintf( szSubKey, _T("%s\\%03x"), REGKEY_PERF, lid );
rc = RegOpenKeyEx( HKEY_LOCAL_MACHINE,
szSubKey,
0,
KEY_READ,
&hKeyNames
);
if (rc != ERROR_SUCCESS) {
goto exit;
}
//
// get the buffer size for the counter names
//
rc = RegQueryValueEx( hKeyNames,
REGSUBKEY_COUNTERS,
NULL,
&dwType,
NULL,
&dwSize
);
if (rc != ERROR_SUCCESS) {
goto exit;
}
//
// allocate the counter names buffer
//
buf = (LPTSTR) malloc( dwSize );
if (buf == NULL) {
goto exit;
}
memset( buf, 0, dwSize );
//
// read the counter names from the registry
//
rc = RegQueryValueEx( hKeyNames,
REGSUBKEY_COUNTERS,
NULL,
&dwType,
(LPBYTE)buf,
&dwSize
);
if (rc != ERROR_SUCCESS) {
goto exit;
}
//
// now loop thru the counter names looking for the following counters:
//
// 1. "Process" process name
// 2. "ID Process" process id
//
// the buffer contains multiple null terminated strings and then
// finally null terminated at the end. the strings are in pairs of
// counter number and counter name.
//
p = buf;
while (*p) {
if (p > buf) {
for( p2=p-2; _istdigit(*p2); p2--) ;
}
if (_tcsicmp(p, PROCESS_COUNTER) == 0) {
//
// look backwards for the counter number
//
for( p2=p-2; _istdigit(*p2); p2--) ;
_tcscpy( szSubKey, p2+1 );
}
else
if (_tcsicmp(p, PROCESSID_COUNTER) == 0) {
//
// look backwards for the counter number
//
for( p2=p-2; _istdigit(*p2); p2--) ;
dwProcessIdTitle = _ttol( p2+1 );
}
//
// next string
//
p += (_tcslen(p) + 1);
}
//
// free the counter names buffer
//
free( buf );
//
// allocate the initial buffer for the performance data
//
dwSize = INITIAL_SIZE;
buf = (LPTSTR)malloc( dwSize );
if (buf == NULL) {
goto exit;
}
memset( buf, 0, dwSize );
while (TRUE) {
rc = RegQueryValueEx( HKEY_PERFORMANCE_DATA,
szSubKey,
NULL,
&dwType,
(LPBYTE)buf,
&dwSize
);
pPerf = (PPERF_DATA_BLOCK) buf;
//
// check for success and valid perf data block signature
//
if ((rc == ERROR_SUCCESS) &&
(dwSize > 0) &&
(pPerf)->Signature[0] == (WCHAR)'P' &&
(pPerf)->Signature[1] == (WCHAR)'E' &&
(pPerf)->Signature[2] == (WCHAR)'R' &&
(pPerf)->Signature[3] == (WCHAR)'F' ) {
break;
}
//
// if buffer is not big enough, reallocate and try again
//
if (rc == ERROR_MORE_DATA) {
dwSize += EXTEND_SIZE;
buf = (LPTSTR)realloc( buf, dwSize );
memset( buf, 0, dwSize );
}
else {
goto exit;
}
}
//
// set the perf_object_type pointer
//
pObj = (PPERF_OBJECT_TYPE) ((PBYTE)pPerf + pPerf->HeaderLength);
//
// loop thru the performance counter definition records looking
// for the process id counter and then save its offset
//
pCounterDef = (PPERF_COUNTER_DEFINITION) ((PBYTE)pObj + pObj->HeaderLength);
for (i=0; i<(DWORD)pObj->NumCounters; i++) {
if (pCounterDef->CounterNameTitleIndex == dwProcessIdTitle) {
dwProcessIdCounter = pCounterDef->CounterOffset;
break;
}
pCounterDef++;
}
dwNumTasks = min( dwLimit, (DWORD)pObj->NumInstances );
pInst = (PPERF_INSTANCE_DEFINITION) ((PBYTE)pObj + pObj->DefinitionLength);
//
// loop thru the performance instance data extracting each process name
// and process id
//
for (i=0; i<dwNumTasks; i++) {
//
// pointer to the process name
//
p = (LPTSTR) ((PBYTE)pInst + pInst->NameOffset);
//
// convert it to ascii
//
#ifndef _UNICODE
rc = WideCharToMultiByte( CP_ACP,
0,
(LPCWSTR)p,
-1,
szProcessName,
sizeof(szProcessName),
NULL,
NULL
);
#else
rc = _tcslen(_tcscpy(szProcessName,p));
#endif
if (!rc) {
//
// if we cant convert the string then use a default value
//
_tcscpy( pTask->ProcessName, UNKNOWN_TASK );
}
if (_tcslen(szProcessName)+4 <= sizeof(pTask->ProcessName)) {
_tcscpy( pTask->ProcessName, szProcessName );
_tcscat( pTask->ProcessName, _T(".exe") );
}
//
// get the process id
//
pCounter = (PPERF_COUNTER_BLOCK) ((PBYTE)pInst + pInst->ByteLength);
pTask->flags = 0;
pTask->dwProcessId = *((LPDWORD) ((PBYTE)pCounter + dwProcessIdCounter));
if (pTask->dwProcessId == 0) {
pTask->dwProcessId = (DWORD)-2;
}
//
// next process
//
pTask++;
pInst = (PPERF_INSTANCE_DEFINITION) ((PBYTE)pCounter + pCounter->ByteLength);
}
exit:
if (buf) {
free( buf );
}
RegCloseKey( hKeyNames );
RegCloseKey( HKEY_PERFORMANCE_DATA );
return dwNumTasks;
}
BOOL
EnableDebugPriv95(
VOID
)
/*++
Routine Description:
Changes the process's privilege so that kill works properly.
Arguments:
Return Value:
TRUE - success
FALSE - failure
Comments:
Always returns TRUE
--*/
{
return TRUE;
}
BOOL
EnableDebugPrivNT(
VOID
)
/*++
Routine Description:
Changes the process's privilege so that kill works properly.
Arguments:
Return Value:
TRUE - success
FALSE - failure
--*/
{
HANDLE hToken;
LUID DebugValue;
TOKEN_PRIVILEGES tkp;
//
// Retrieve a handle of the access token
//
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
&hToken)) {
printf("OpenProcessToken failed with %lu\n", GetLastError());
return FALSE;
}
//
// Enable the SE_DEBUG_NAME privilege
//
if (!LookupPrivilegeValue((LPTSTR) NULL,
SE_DEBUG_NAME,
&DebugValue)) {
printf("LookupPrivilegeValue failed with %lu\n", GetLastError());
return FALSE;
}
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Luid = DebugValue;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken,
FALSE,
&tkp,
sizeof(TOKEN_PRIVILEGES),
(PTOKEN_PRIVILEGES) NULL,
(PDWORD) NULL);
//
// The return value of AdjustTokenPrivileges can't be tested
//
if (GetLastError() != ERROR_SUCCESS) {
printf("AdjustTokenPrivileges failed with %lu\n", GetLastError());
return FALSE;
}
return TRUE;
}
BOOL
KillProcess(
PTASK_LIST tlist,
BOOL fForce
)
{
HANDLE hProcess;
if (fForce || !tlist->hwnd) {
hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, tlist->dwProcessId );
if (hProcess) {
hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, tlist->dwProcessId );
if (hProcess == NULL) {
return FALSE;
}
if (!TerminateProcess( hProcess, 1 )) {
CloseHandle( hProcess );
return FALSE;
}
CloseHandle( hProcess );
return TRUE;
}
}
//
// kill the process
//
PostMessage( (HWND)tlist->hwnd, WM_CLOSE, 0, 0 );
return TRUE;
}
VOID
GetWindowTitles(
PTASK_LIST_ENUM te
)
{
//
// enumerate all windows
//
EnumWindows( (WNDENUMPROC)EnumWindowsProc, (LPARAM) te );
}
BOOL CALLBACK
EnumWindowsProc(
HWND hwnd,
DWORD lParam
)
/*++
Routine Description:
Callback function for window enumeration.
Arguments:
hwnd - window handle
lParam - ** not used **
Return Value:
TRUE - continues the enumeration
--*/
{
DWORD pid = 0;
DWORD i;
TCHAR buf[TITLE_SIZE];
PTASK_LIST_ENUM te = (PTASK_LIST_ENUM)lParam;
PTASK_LIST tlist = te->tlist;
DWORD numTasks = te->numtasks;
//
// get the processid for this window
//
if (!GetWindowThreadProcessId( hwnd, &pid )) {
return TRUE;
}
//
// look for the task in the task list for this window
//
for (i=0; i<numTasks; i++) {
if (tlist[i].dwProcessId == pid) {
tlist[i].hwnd = hwnd;
//
// we found the task so lets try to get the
// window text
//
if (GetWindowText( (HWND)tlist[i].hwnd, buf, sizeof(buf) )) {
//
// got it, so lets save it
//
_tcscpy( tlist[i].WindowTitle, buf );
}
break;
}
}
//
// continue the enumeration
//
return TRUE;
}
BOOL
MatchPattern(
LPTSTR String,
LPTSTR Pattern
)
{
TCHAR c, p, l;
for (; ;) {
switch (p = *Pattern++) {
case 0: // end of pattern
return *String ? FALSE : TRUE; // if end of string TRUE
case _T('*'):
while (*String) { // match zero or more char
if (MatchPattern (String++, Pattern))
return TRUE;
}
return MatchPattern (String, Pattern);
case _T('?'):
if (*String++ == 0) // match any one char
return FALSE; // not end of string
break;
case _T('['):
if ( (c = *String++) == 0) // match char set
return FALSE; // syntax
c = _totupper(c);
l = 0;
while ((p = *Pattern++)) {
if (p == ']') // if end of char set, then
return FALSE; // no match found
if (p == '-') { // check a range of chars?
p = *Pattern; // get high limit of range
if (p == 0 || p == ']')
return FALSE; // syntax
if (c >= l && c <= p)
break; // if in range, move on
}
l = p;
if (c == p) // if char matches this element
break; // move on
}
while (p && p != ']') // got a match in char set
p = *Pattern++; // skip to end of set
break;
default:
c = *String++;
if (_totupper(c) != p) // check for exact char
return FALSE; // not a match
break;
}
}
}