forked from BOINC/boinc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiagnostics_win.cpp
2115 lines (1791 loc) · 76.4 KB
/
diagnostics_win.cpp
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of BOINC.
// http://boinc.berkeley.edu
// Copyright (C) 2008 University of California
//
// BOINC is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// BOINC is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with BOINC. If not, see <http://www.gnu.org/licenses/>.
// Stuff related to catching SEH exceptions, monitoring threads, and trapping
// debugger messages; used by both core client and by apps.
#if defined(_WIN32) && !defined(__STDWX_H__)
#include "boinc_win.h"
#elif defined(_WIN32) && defined(__STDWX_H__)
#include "stdwx.h"
#endif
#if defined(_MSC_VER) || defined(__MINGW32__)
#define snprintf _snprintf
#define strdate _strdate
#define strtime _strtime
#endif
#ifndef __CYGWIN32__
#include "stackwalker_win.h"
#endif
#include "version.h"
#include "diagnostics.h"
#include "diagnostics_win.h"
#include "error_numbers.h"
#include "str_util.h"
#include "util.h"
// NtQuerySystemInformation
typedef NTSTATUS (WINAPI *tNTQSI)(
ULONG SystemInformationClass,
PVOID SystemInformation,
ULONG SystemInformationLength,
PULONG ReturnLength
);
// IsDebuggerPresent
typedef BOOL (WINAPI *tIDP)();
// CreateToolhelp32Snapshot
typedef HANDLE (WINAPI *tCT32S)(DWORD dwFlags, DWORD dwProcessID);
// Thread32First
typedef BOOL (WINAPI *tT32F)(HANDLE hSnapshot, LPTHREADENTRY32 lpte);
// Thread32Next
typedef BOOL (WINAPI *tT32N)(HANDLE hSnapshot, LPTHREADENTRY32 lpte);
// OpenThread
typedef HANDLE (WINAPI *tOT)(DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwThreadId);
// Look in the registry for the specified value user the BOINC diagnostics
// hive.
BOOL diagnostics_get_registry_value(LPCSTR lpName, LPDWORD lpdwType, LPDWORD lpdwSize, LPBYTE lpData) {
LONG lRetVal;
HKEY hKey;
// Detect platform information
OSVERSIONINFO osvi;
osvi.dwOSVersionInfoSize = sizeof(osvi);
GetVersionEx(&osvi);
if (VER_PLATFORM_WIN32_WINDOWS == osvi.dwPlatformId) {
lRetVal = RegOpenKeyExA(
HKEY_LOCAL_MACHINE,
"SOFTWARE\\Space Sciences Laboratory, U.C. Berkeley\\BOINC Diagnostics",
(DWORD)NULL,
KEY_READ,
&hKey
);
if (lRetVal != ERROR_SUCCESS) return FALSE;
} else {
lRetVal = RegOpenKeyExA(
HKEY_CURRENT_USER,
"SOFTWARE\\Space Sciences Laboratory, U.C. Berkeley\\BOINC Diagnostics",
(DWORD)NULL,
KEY_READ,
&hKey
);
if (lRetVal != ERROR_SUCCESS) return FALSE;
}
lRetVal = RegQueryValueExA(hKey, lpName, NULL, lpdwType, lpData, lpdwSize);
RegCloseKey(hKey);
return (lRetVal == ERROR_SUCCESS);
}
// Provide a structure to store process measurements at the time of a
// crash.
typedef struct _BOINC_PROCESSENTRY {
DWORD process_id;
VM_COUNTERS vm_counters;
IO_COUNTERS io_counters;
} BOINC_PROCESSENTRY, *PBOINC_PROCESSENTRY;
static BOINC_PROCESSENTRY diagnostics_process;
// Provide a set of API's which can be used to display more friendly
// information about each thread. These should also be used to
// dump the callstacks for each executing thread when an unhandled
// SEH exception is thrown.
//
// This structure is used to keep track of stuff nessassary
// to dump backtraces for all threads during an abort or
// crash. This is platform specific in nature since it
// depends on the OS datatypes.
typedef struct _BOINC_THREADLISTENTRY {
DWORD thread_id;
HANDLE thread_handle;
BOOL crash_suspend_exempt;
FLOAT crash_kernel_time;
FLOAT crash_user_time;
FLOAT crash_wait_time;
INT crash_priority;
INT crash_base_priority;
INT crash_state;
INT crash_wait_reason;
PEXCEPTION_POINTERS crash_exception_record;
char crash_message[1024];
} BOINC_THREADLISTENTRY, *PBOINC_THREADLISTENTRY;
static std::vector<PBOINC_THREADLISTENTRY> diagnostics_threads;
static HANDLE hThreadListSync;
// Initialize the thread list entry.
int diagnostics_init_thread_entry(PBOINC_THREADLISTENTRY entry) {
entry->thread_id = 0;
entry->thread_handle = 0;
entry->crash_suspend_exempt = FALSE;
entry->crash_kernel_time = 0.0;
entry->crash_user_time = 0.0;
entry->crash_wait_time = 0.0;
entry->crash_priority = 0;
entry->crash_base_priority = 0;
entry->crash_state = 0;
entry->crash_wait_reason = 0;
entry->crash_exception_record = NULL;
strncpy(entry->crash_message, "", sizeof(entry->crash_message));
return 0;
}
// Initialize the thread list, which means empty it if anything is
// in it.
int diagnostics_init_thread_list() {
int retval = 0;
size_t i;
size_t size;
// Create a Mutex that can be used to syncronize data access
// to the global thread list.
hThreadListSync = CreateMutex(NULL, TRUE, NULL);
if (!hThreadListSync) {
fprintf(
stderr, "diagnostics_init_thread_list(): Creating hThreadListSync failed, GLE %d\n", GetLastError()
);
retval = GetLastError();
} else {
size = diagnostics_threads.size();
for (i=0; i<size; i++) {
delete diagnostics_threads[i];
}
diagnostics_threads.clear();
// Release the Mutex
ReleaseMutex(hThreadListSync);
}
return retval;
}
// Finish the thread list, which means empty it if anything is
// in it.
int diagnostics_finish_thread_list() {
size_t i;
size_t size;
// Wait for the ThreadListSync mutex before writing updates
WaitForSingleObject(hThreadListSync, INFINITE);
size = diagnostics_threads.size();
for (i=0; i<size; i++) {
delete diagnostics_threads[i];
}
diagnostics_threads.clear();
// Release the Mutex
ReleaseMutex(hThreadListSync);
CloseHandle(hThreadListSync);
return 0;
}
// Return a pointer to the thread entry.
//
PBOINC_THREADLISTENTRY diagnostics_find_thread_entry(DWORD dwThreadId) {
PBOINC_THREADLISTENTRY pThread = NULL;
UINT uiIndex = 0;
size_t size = 0;
size = diagnostics_threads.size();
for (uiIndex = 0; uiIndex < size; uiIndex++) {
if (diagnostics_threads[uiIndex]) {
if (dwThreadId == diagnostics_threads[uiIndex]->thread_id) {
pThread = diagnostics_threads[uiIndex];
}
}
}
return pThread;
}
// Enumerate the running threads in the process space and add them to
// the list. This is the most compatible implementation.
int diagnostics_update_thread_list_9X() {
HANDLE hThreadSnap = INVALID_HANDLE_VALUE;
HANDLE hThread = NULL;
HMODULE hKernel32Lib = NULL;
PBOINC_THREADLISTENTRY pThreadEntry = NULL;
tCT32S pCT32S = NULL;
tT32F pT32F = NULL;
tT32N pT32N = NULL;
tOT pOT = NULL;
THREADENTRY32 te32;
// Which version of the data structure are we using.
te32.dwSize = sizeof(te32);
// Dynamically link to the proper function pointers.
hKernel32Lib = GetModuleHandleA("kernel32.dll");
pCT32S = (tCT32S) GetProcAddress( hKernel32Lib, "CreateToolhelp32Snapshot" );
pT32F = (tT32F) GetProcAddress( hKernel32Lib, "Thread32First" );
pT32N = (tT32N) GetProcAddress( hKernel32Lib, "Thread32Next" );
pOT = (tOT) GetProcAddress( hKernel32Lib, "OpenThread" );
if (!pCT32S || !pT32F || !pT32N) {
return ERROR_NOT_SUPPORTED;
}
// Take a snapshot of all running threads
hThreadSnap = pCT32S(TH32CS_SNAPTHREAD, 0);
if( hThreadSnap == INVALID_HANDLE_VALUE ) {
return GetLastError();
}
// Retrieve information about the first thread,
// and exit if unsuccessful
if( !pT32F( hThreadSnap, &te32 ) ) {
CloseHandle( hThreadSnap );
return GetLastError();
}
// Wait for the ThreadListSync mutex before writing updates
WaitForSingleObject(hThreadListSync, INFINITE);
// Now walk the thread list of the system,
// and display information about each thread
// associated with the specified process
do {
if( te32.th32OwnerProcessID == GetCurrentProcessId() ) {
pThreadEntry = diagnostics_find_thread_entry(te32.th32ThreadID);
if (!pThreadEntry) {
pThreadEntry = new BOINC_THREADLISTENTRY;
diagnostics_init_thread_entry(pThreadEntry);
pThreadEntry->thread_id = te32.th32ThreadID;
if (pOT) {
hThread = pOT(
THREAD_ALL_ACCESS,
FALSE,
te32.th32ThreadID
);
pThreadEntry->thread_handle = hThread;
}
diagnostics_threads.push_back(pThreadEntry);
}
}
}
while( pT32N(hThreadSnap, &te32 ) );
// Release the Mutex
ReleaseMutex(hThreadListSync);
CloseHandle(hThreadSnap);
return 0;
}
// Use the native NT API to get all the process and thread information
// about the current process. This isn't a fully documented API but
// enough information exists that we can rely on it for the known
// Windows OS versions. For each new Windows version check the
// _SYSTEM_PROCESS and _SYSTEM_THREAD structures in the DDK to make
// sure it is compatible with the existing stuff.
int diagnostics_get_process_information(PVOID* ppBuffer, PULONG pcbBuffer) {
int retval = 0;
NTSTATUS Status = STATUS_INFO_LENGTH_MISMATCH;
HANDLE hHeap = GetProcessHeap();
HMODULE hNTDllLib = NULL;
tNTQSI pNTQSI = NULL;
hNTDllLib = GetModuleHandleA("ntdll.dll");
pNTQSI = (tNTQSI)GetProcAddress(hNTDllLib, "NtQuerySystemInformation");
do {
*ppBuffer = HeapAlloc(hHeap, HEAP_ZERO_MEMORY, *pcbBuffer);
if (ppBuffer == NULL) {
retval = ERROR_NOT_ENOUGH_MEMORY;
}
Status = pNTQSI(
SystemProcessAndThreadInformation,
*ppBuffer,
*pcbBuffer,
pcbBuffer
);
if (Status == STATUS_INFO_LENGTH_MISMATCH) {
HeapFree(hHeap, (DWORD)NULL, *ppBuffer);
*pcbBuffer *= 2;
} else if (!NT_SUCCESS(Status)) {
HeapFree(hHeap, (DWORD)NULL, *ppBuffer);
retval = Status;
}
} while (Status == STATUS_INFO_LENGTH_MISMATCH);
return retval;
}
// Enumerate the running threads in the process space and add them to
// the list. This only works on NT 4.0 based machines. This also
// includes additional information which can be logged during a crash
// event.
int diagnostics_update_thread_list_NT() {
DWORD dwCurrentProcessId = GetCurrentProcessId();
HANDLE hThread = NULL;
PBOINC_THREADLISTENTRY pThreadEntry = NULL;
ULONG cbBuffer = 32*1024; // 32k initial buffer
PVOID pBuffer = NULL;
PSYSTEM_PROCESSES_NT4 pProcesses = NULL;
PSYSTEM_THREADS pThread = NULL;
UINT uiSystemIndex = 0;
HMODULE hKernel32Lib;
tOT pOT = NULL;
// Dynamically link to the proper function pointers.
hKernel32Lib = GetModuleHandleA("kernel32.dll");
pOT = (tOT) GetProcAddress( hKernel32Lib, "OpenThread" );
// Get a snapshot of the process and thread information.
diagnostics_get_process_information(&pBuffer, &cbBuffer);
// Wait for the ThreadListSync mutex before writing updates
WaitForSingleObject(hThreadListSync, INFINITE);
// Lets start walking the structures to find the good stuff.
pProcesses = (PSYSTEM_PROCESSES_NT4)pBuffer;
do {
// Okay, found the current procceses entry now we just need to
// update the thread data.
if (pProcesses->ProcessId == dwCurrentProcessId) {
// Store the process information we now know about.
diagnostics_process.process_id = pProcesses->ProcessId;
diagnostics_process.vm_counters = pProcesses->VmCounters;
// Enumerate the threads
for(uiSystemIndex = 0; uiSystemIndex < pProcesses->ThreadCount; uiSystemIndex++) {
pThread = &pProcesses->Threads[uiSystemIndex];
pThreadEntry = diagnostics_find_thread_entry(pThread->ClientId.UniqueThread);
if (pThreadEntry) {
pThreadEntry->crash_kernel_time = (FLOAT)pThread->KernelTime.QuadPart;
pThreadEntry->crash_user_time = (FLOAT)pThread->UserTime.QuadPart;
pThreadEntry->crash_wait_time = (FLOAT)pThread->WaitTime;
pThreadEntry->crash_priority = pThread->Priority;
pThreadEntry->crash_base_priority = pThread->BasePriority;
pThreadEntry->crash_state = pThread->State;
pThreadEntry->crash_wait_reason = pThread->WaitReason;
} else {
if (pOT) {
hThread = pOT(
THREAD_ALL_ACCESS,
FALSE,
pThread->ClientId.UniqueThread
);
}
pThreadEntry = new BOINC_THREADLISTENTRY;
diagnostics_init_thread_entry(pThreadEntry);
pThreadEntry->thread_id = pThread->ClientId.UniqueThread;
pThreadEntry->thread_handle = hThread;
pThreadEntry->crash_kernel_time = (FLOAT)pThread->KernelTime.QuadPart;
pThreadEntry->crash_user_time = (FLOAT)pThread->UserTime.QuadPart;
pThreadEntry->crash_wait_time = (FLOAT)pThread->WaitTime;
pThreadEntry->crash_priority = pThread->Priority;
pThreadEntry->crash_base_priority = pThread->BasePriority;
pThreadEntry->crash_state = pThread->State;
pThreadEntry->crash_wait_reason = pThread->WaitReason;
diagnostics_threads.push_back(pThreadEntry);
}
}
}
// Move to the next structure if one exists
if (!pProcesses->NextEntryDelta) {
break;
}
pProcesses = (PSYSTEM_PROCESSES_NT4)(((LPBYTE)pProcesses) + pProcesses->NextEntryDelta);
} while (pProcesses);
// Release resources
if (hThreadListSync) ReleaseMutex(hThreadListSync);
if (pBuffer) HeapFree(GetProcessHeap(), (DWORD)NULL, pBuffer);
return 0;
}
// Enumerate the running threads in the process space and add them to
// the list. This only works on XP or better based machines. This also
// includes additional information which can be logged during a crash
// event.
int diagnostics_update_thread_list_XP() {
DWORD dwCurrentProcessId = GetCurrentProcessId();
HANDLE hThread = NULL;
PBOINC_THREADLISTENTRY pThreadEntry = NULL;
ULONG cbBuffer = 32*1024; // 32k initial buffer
PVOID pBuffer = NULL;
PSYSTEM_PROCESSES pProcesses = NULL;
PSYSTEM_THREADS pThread = NULL;
UINT uiSystemIndex = 0;
HMODULE hKernel32Lib;
tOT pOT = NULL;
// Dynamically link to the proper function pointers.
hKernel32Lib = GetModuleHandleA("kernel32.dll");
pOT = (tOT) GetProcAddress( hKernel32Lib, "OpenThread" );
// Get a snapshot of the process and thread information.
diagnostics_get_process_information(&pBuffer, &cbBuffer);
// Wait for the ThreadListSync mutex before writing updates
WaitForSingleObject(hThreadListSync, INFINITE);
// Lets start walking the structures to find the good stuff.
pProcesses = (PSYSTEM_PROCESSES)pBuffer;
do {
// Okay, found the current procceses entry now we just need to
// update the thread data.
if (pProcesses->ProcessId == dwCurrentProcessId) {
// Store the process information we now know about.
diagnostics_process.process_id = pProcesses->ProcessId;
diagnostics_process.vm_counters = pProcesses->VmCounters;
diagnostics_process.io_counters = pProcesses->IoCounters;
// Enumerate the threads
for(uiSystemIndex = 0; uiSystemIndex < pProcesses->ThreadCount; uiSystemIndex++) {
pThread = &pProcesses->Threads[uiSystemIndex];
pThreadEntry = diagnostics_find_thread_entry(pThread->ClientId.UniqueThread);
if (pThreadEntry) {
pThreadEntry->crash_kernel_time = (FLOAT)pThread->KernelTime.QuadPart;
pThreadEntry->crash_user_time = (FLOAT)pThread->UserTime.QuadPart;
pThreadEntry->crash_wait_time = (FLOAT)pThread->WaitTime;
pThreadEntry->crash_priority = pThread->Priority;
pThreadEntry->crash_base_priority = pThread->BasePriority;
pThreadEntry->crash_state = pThread->State;
pThreadEntry->crash_wait_reason = pThread->WaitReason;
} else {
if (pOT) {
hThread = pOT(
THREAD_ALL_ACCESS,
FALSE,
pThread->ClientId.UniqueThread
);
}
pThreadEntry = new BOINC_THREADLISTENTRY;
diagnostics_init_thread_entry(pThreadEntry);
pThreadEntry->thread_id = pThread->ClientId.UniqueThread;
pThreadEntry->thread_handle = hThread;
pThreadEntry->crash_kernel_time = (FLOAT)pThread->KernelTime.QuadPart;
pThreadEntry->crash_user_time = (FLOAT)pThread->UserTime.QuadPart;
pThreadEntry->crash_wait_time = (FLOAT)pThread->WaitTime;
pThreadEntry->crash_priority = pThread->Priority;
pThreadEntry->crash_base_priority = pThread->BasePriority;
pThreadEntry->crash_state = pThread->State;
pThreadEntry->crash_wait_reason = pThread->WaitReason;
diagnostics_threads.push_back(pThreadEntry);
}
}
}
// Move to the next structure if one exists
if (!pProcesses->NextEntryDelta) {
break;
}
pProcesses = (PSYSTEM_PROCESSES)(((LPBYTE)pProcesses) + pProcesses->NextEntryDelta);
} while (pProcesses);
// Release resources
if (hThreadListSync) ReleaseMutex(hThreadListSync);
if (pBuffer) HeapFree(GetProcessHeap(), (DWORD)NULL, pBuffer);
return 0;
}
// Determine which update thread list function to call based on OS
// version.
int diagnostics_update_thread_list() {
int retval = 0;
// Detect platform information
OSVERSIONINFO osvi;
osvi.dwOSVersionInfoSize = sizeof(osvi);
GetVersionEx(&osvi);
switch(osvi.dwPlatformId) {
case VER_PLATFORM_WIN32_WINDOWS:
// Win95, Win98, WinME
retval = diagnostics_update_thread_list_9X();
break;
case VER_PLATFORM_WIN32_NT:
switch(osvi.dwMajorVersion) {
case 4:
// WinNT 4.0
retval = diagnostics_update_thread_list_NT();
break;
case 5:
// Win2k, WinXP, Win2k3
retval = diagnostics_update_thread_list_XP();
break;
case 6:
if (osvi.dwMinorVersion == 0) {
// WinVista
retval = diagnostics_update_thread_list_XP();
} else {
// In cases where we do not know if the interfaces have
// changed from the ones we know about, just default to
// the most compatible implementation.
retval = diagnostics_update_thread_list_9X();
}
break;
default:
// In cases where we do not know if the interfaces have
// changed from the ones we know about, just default to
// the most compatible implementation.
retval = diagnostics_update_thread_list_9X();
break;
}
break;
}
return retval;
}
// Set the cached exception record for the current thread, let the exception monitor
// thread dump the human readable exception information.
int diagnostics_set_thread_exception_record(PEXCEPTION_POINTERS pExPtrs) {
HANDLE hThread;
PBOINC_THREADLISTENTRY pThreadEntry = NULL;
// Wait for the ThreadListSync mutex before writing updates
WaitForSingleObject(hThreadListSync, INFINITE);
pThreadEntry = diagnostics_find_thread_entry(GetCurrentThreadId());
if (pThreadEntry) {
pThreadEntry->crash_exception_record = pExPtrs;
} else {
DuplicateHandle(
GetCurrentProcess(),
GetCurrentThread(),
GetCurrentProcess(),
&hThread,
0,
FALSE,
DUPLICATE_SAME_ACCESS
);
pThreadEntry = new BOINC_THREADLISTENTRY;
diagnostics_init_thread_entry(pThreadEntry);
pThreadEntry->thread_id = GetCurrentThreadId();
pThreadEntry->thread_handle = hThread;
pThreadEntry->crash_exception_record = pExPtrs;
diagnostics_threads.push_back(pThreadEntry);
}
// Release the Mutex
ReleaseMutex(hThreadListSync);
return 0;
}
// Set the current thread to suspend exempt status. Prevents deadlocks.
int diagnostics_set_thread_exempt_suspend() {
HANDLE hThread;
PBOINC_THREADLISTENTRY pThreadEntry = NULL;
// Wait for the ThreadListSync mutex before writing updates
WaitForSingleObject(hThreadListSync, INFINITE);
pThreadEntry = diagnostics_find_thread_entry(GetCurrentThreadId());
if (pThreadEntry) {
pThreadEntry->crash_suspend_exempt = TRUE;
} else {
DuplicateHandle(
GetCurrentProcess(),
GetCurrentThread(),
GetCurrentProcess(),
&hThread,
0,
FALSE,
DUPLICATE_SAME_ACCESS
);
pThreadEntry = new BOINC_THREADLISTENTRY;
diagnostics_init_thread_entry(pThreadEntry);
pThreadEntry->thread_id = GetCurrentThreadId();
pThreadEntry->thread_handle = hThread;
pThreadEntry->crash_suspend_exempt = TRUE;
diagnostics_threads.push_back(pThreadEntry);
}
// Release the Mutex
ReleaseMutex(hThreadListSync);
return 0;
}
// Checks to see if the specified thread id is flagged for suspend exempt status.
// returns 0 on true, 1 on false. Couldn't use a bool data type since the function
// prototype needs to be compatible with C.
int diagnostics_is_thread_exempt_suspend(long thread_id) {
int retval = 1;
PBOINC_THREADLISTENTRY pThreadEntry = NULL;
// Wait for the ThreadListSync mutex before writing updates
WaitForSingleObject(hThreadListSync, INFINITE);
pThreadEntry = diagnostics_find_thread_entry(thread_id);
if (pThreadEntry) {
if (pThreadEntry->crash_suspend_exempt) {
retval = 0;
}
}
// Release the Mutex
ReleaseMutex(hThreadListSync);
return retval;
}
// Set the current thread's crash message.
int diagnostics_set_thread_crash_message(char* message) {
HANDLE hThread;
PBOINC_THREADLISTENTRY pThreadEntry = NULL;
// Wait for the ThreadListSync mutex before writing updates
WaitForSingleObject(hThreadListSync, INFINITE);
pThreadEntry = diagnostics_find_thread_entry(GetCurrentThreadId());
if (pThreadEntry) {
int buffer_used = snprintf(
pThreadEntry->crash_message,
sizeof(pThreadEntry->crash_message),
"%s",
message
);
if ((sizeof(pThreadEntry->crash_message) == buffer_used) || (-1 == buffer_used)) {
pThreadEntry->crash_message[sizeof(pThreadEntry->crash_message)-1] = '\0';
}
} else {
DuplicateHandle(
GetCurrentProcess(),
GetCurrentThread(),
GetCurrentProcess(),
&hThread,
0,
FALSE,
DUPLICATE_SAME_ACCESS
);
pThreadEntry = new BOINC_THREADLISTENTRY;
diagnostics_init_thread_entry(pThreadEntry);
pThreadEntry->thread_id = GetCurrentThreadId();
pThreadEntry->thread_handle = hThread;
int buffer_used = snprintf(
pThreadEntry->crash_message,
sizeof(pThreadEntry->crash_message),
"%s",
message
);
if ((sizeof(pThreadEntry->crash_message) == buffer_used) || (-1 == buffer_used)) {
pThreadEntry->crash_message[sizeof(pThreadEntry->crash_message)-1] = '\0';
}
diagnostics_threads.push_back(pThreadEntry);
}
// Release the Mutex
ReleaseMutex(hThreadListSync);
return 0;
}
// Translate the thread state into a human readable form.
//
// See: http://support.microsoft.com/?kbid=837372
//
char* diagnostics_format_thread_state(int thread_state) {
switch(thread_state) {
case ThreadStateInitialized: return "Initialized";
case ThreadStateReady: return "Ready";
case ThreadStateRunning: return "Running";
case ThreadStateStandby: return "Standby";
case ThreadStateTerminated: return "Terminated";
case ThreadStateWaiting: return "Waiting";
case ThreadStateTransition: return "Transition";
default: return "Unknown";
}
return "";
}
// Translate the thread wait reason into a human readable form.
//
// See: http://support.microsoft.com/?kbid=837372
//
char* diagnostics_format_thread_wait_reason(int thread_wait_reason) {
switch(thread_wait_reason) {
case ThreadWaitReasonExecutive: return "Executive";
case ThreadWaitReasonFreePage: return "FreePage";
case ThreadWaitReasonPageIn: return "PageIn";
case ThreadWaitReasonPoolAllocation: return "PoolAllocation";
case ThreadWaitReasonDelayExecution: return "ExecutionDelay";
case ThreadWaitReasonSuspended: return "Suspended";
case ThreadWaitReasonUserRequest: return "UserRequest";
case ThreadWaitReasonWrExecutive: return "Executive";
case ThreadWaitReasonWrFreePage: return "FreePage";
case ThreadWaitReasonWrPageIn: return "PageIn";
case ThreadWaitReasonWrPoolAllocation: return "PoolAllocation";
case ThreadWaitReasonWrDelayExecution: return "ExecutionDelay";
case ThreadWaitReasonWrSuspended: return "Suspended";
case ThreadWaitReasonWrUserRequest: return "UserRequest";
case ThreadWaitReasonWrEventPairHigh: return "EventPairHigh";
case ThreadWaitReasonWrEventPairLow: return "EventPairLow";
case ThreadWaitReasonWrLpcReceive: return "LPCReceive";
case ThreadWaitReasonWrLpcReply: return "LPCReply";
case ThreadWaitReasonWrVirtualMemory: return "VirtualMemory";
case ThreadWaitReasonWrPageOut: return "PageOut";
default: return "Unknown";
}
return "";
}
// Translate the process priority class into a human readable form.
//
// See: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/scheduling_priorities.asp
//
char* diagnostics_format_process_priority(int process_priority) {
switch(process_priority) {
case IDLE_PRIORITY_CLASS: return "Idle";
case BELOW_NORMAL_PRIORITY_CLASS: return "Below Normal";
case NORMAL_PRIORITY_CLASS: return "Normal";
case ABOVE_NORMAL_PRIORITY_CLASS: return "Above Normal";
case HIGH_PRIORITY_CLASS: return "High";
case REALTIME_PRIORITY_CLASS: return "Realtime";
default: return "Unknown";
}
return "";
}
// Translate the thread priority class into a human readable form.
//
// See: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/scheduling_priorities.asp
//
char* diagnostics_format_thread_priority(int thread_priority) {
switch(thread_priority) {
case THREAD_PRIORITY_IDLE: return "Idle";
case THREAD_PRIORITY_LOWEST: return "Lowest";
case THREAD_PRIORITY_BELOW_NORMAL: return "Below Normal";
case THREAD_PRIORITY_NORMAL: return "Normal";
case THREAD_PRIORITY_ABOVE_NORMAL: return "Above Normal";
case THREAD_PRIORITY_HIGHEST: return "Highest";
case THREAD_PRIORITY_TIME_CRITICAL: return "Time Critical";
default: return "Unknown";
}
return "";
}
// Provide a mechinism to trap and report messages sent to the debugger's
// viewport. This should only been enabled if a debugger isn't running
// against the current process already.
//
// Documentation about the protocol can be found here:
// http://www.unixwiz.net/techtips/outputdebugstring.html
//
typedef struct _DEBUGGERMESSAGE {
DWORD dwProcessId;
char data[4096 - sizeof(DWORD)];
} DEBUGGERMESSAGE, *PDEBUGGERMESSAGE;
typedef struct _BOINC_MESSAGEMONITORENTRY {
double timestamp;
std::string message;
} BOINC_MESSAGEMONITORENTRY, *PBOINC_MESSAGEMONITORENTRY;
static std::vector<PBOINC_MESSAGEMONITORENTRY> diagnostics_monitor_messages;
static PDEBUGGERMESSAGE pMessageBuffer;
static UINT uiMessageMonitorThreadId;
static HANDLE hMessageMonitorThread;
static HANDLE hMessageMonitorSync;
static HANDLE hMessageSharedMap;
static HANDLE hMessageAckEvent;
static HANDLE hMessageReadyEvent;
static HANDLE hMessageQuitEvent;
static HANDLE hMessageQuitFinishedEvent;
// Initialize the needed structures and startup the message processing thread.
//
int diagnostics_init_message_monitor() {
int retval = 0;
unsigned int i;
DWORD dwType;
DWORD dwSize;
DWORD dwCaptureMessages;
HMODULE hKernel32Lib;
tIDP pIDP = NULL;
SECURITY_ATTRIBUTES sa;
SECURITY_DESCRIPTOR sd;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = &sd;
InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(&sd, TRUE, (PACL)NULL, FALSE);
// Create a mutex that can be used to syncronize data access
// to the global thread list.
hMessageMonitorSync = CreateMutex(NULL, TRUE, NULL);
if (!hMessageMonitorSync) {
fprintf(
stderr, "diagnostics_init_message_monitor(): Creating hMessageMonitorSync failed, GLE %d\n", GetLastError()
);
}
// Clear out any previous messages.
for (i=0; i<diagnostics_monitor_messages.size(); i++) {
delete diagnostics_monitor_messages[i];
}
diagnostics_monitor_messages.clear();
// Check the registry to see if we are aloud to capture debugger messages.
// Apparently many audio and visual payback programs dump serious
// amounts of data to the debugger viewport even on a release build.
// When this feature is enabled it slows down the replay of DVDs and CDs
// such that they become jerky and unpleasent to watch or listen too.
//
// We'll turn it off by default, but keep it around just in case we need
// it.
//
dwCaptureMessages = 0;
dwType = REG_DWORD;
dwSize = sizeof(dwCaptureMessages);
diagnostics_get_registry_value(
"CaptureMessages",
&dwType,
&dwSize,
(LPBYTE)&dwCaptureMessages
);
// If a debugger is present then let it capture the debugger messages
hKernel32Lib = GetModuleHandleA("kernel32.dll");
pIDP = (tIDP) GetProcAddress(hKernel32Lib, "IsDebuggerPresent");
if (pIDP) {
if (!pIDP() && hMessageMonitorSync && dwCaptureMessages) {
hMessageAckEvent = CreateEventA(&sa, FALSE, FALSE, "DBWIN_BUFFER_READY");
if (!hMessageAckEvent) {
fprintf(
stderr, "diagnostics_init_message_monitor(): Creating hMessageAckEvent failed, GLE %d\n", GetLastError()
);
}
hMessageReadyEvent = CreateEventA(&sa, FALSE, FALSE, "DBWIN_DATA_READY");
if (!hMessageReadyEvent) {
fprintf(
stderr, "diagnostics_init_message_monitor(): Creating hMessageReadyEvent failed, GLE %d\n", GetLastError()
);
}
hMessageQuitEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
if (!hMessageQuitEvent) {
fprintf(
stderr, "diagnostics_init_message_monitor(): Creating hMessageQuitEvent failed, GLE %d\n", GetLastError()
);
}
hMessageQuitFinishedEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
if (!hMessageQuitFinishedEvent) {
fprintf(
stderr, "diagnostics_init_message_monitor(): Creating hMessageQuitFinishedEvent failed, GLE %d\n", GetLastError()
);
}
hMessageSharedMap = CreateFileMappingA(
INVALID_HANDLE_VALUE, // use paging file
&sa, // default security
PAGE_READWRITE, // read/write access
0, // max. object size
sizeof(DEBUGGERMESSAGE), // buffer size
"DBWIN_BUFFER" // name of mapping object
);
if (!hMessageSharedMap) {
fprintf(
stderr, "diagnostics_init_message_monitor(): CreateFileMapping hMessageSharedMap failed, GLE %d\n", GetLastError()
);
}
pMessageBuffer = (PDEBUGGERMESSAGE)MapViewOfFile(
hMessageSharedMap,
FILE_MAP_READ | FILE_MAP_WRITE,
0, // file offset high
0, // file offset low
sizeof(DEBUGGERMESSAGE) // # of bytes to map (entire file)
);
if (!pMessageBuffer) {
fprintf(
stderr, "diagnostics_init_message_monitor(): MapViewOfFile pMessageBuffer failed, GLE %d\n", GetLastError()
);
}
hMessageMonitorThread = (HANDLE)_beginthreadex(
NULL,
0,
diagnostics_message_monitor,
0,
0,
&uiMessageMonitorThreadId
);
if (!hMessageMonitorThread) {
fprintf(
stderr, "diagnostics_init_message_monitor(): _beginthreadex, errno %d\n", errno
);
}
} else {
retval = ERROR_NOT_SUPPORTED;
}
}
// Release the Mutex
ReleaseMutex(hMessageMonitorSync);
return retval;
}