-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDbgViewMini.cpp
562 lines (477 loc) · 13.1 KB
/
DbgViewMini.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
/*
* DbgViewMini is based on code from Task Explorer and System Informer:
* https://github.com/DavidXanatos/TaskExplorer/blob/master/TaskExplorer/API/Windows/Monitors/WinDbgMonitor.cpp
* https://github.com/processhacker/plugins-extra/blob/master/DbgViewPlugin/log.c
*
* Original license:
*
* System Informer Plugins -
* qt port of Debug View Plugin
*
* Copyright (C) 2015-2017 dmex
* Copyright (C) 2020-2022 David Xanatos
*
* This file is part of Task Explorer and contains System Informer code.
*
*/
#include <Windows.h>
#include <Sddl.h>
#include <tlhelp32.h>
#include <stdio.h>
#include <expected>
#include <optional>
#include <string>
#include <string_view>
#include <unordered_map>
using namespace std::string_view_literals;
#define DBG_VIEW_MINI_VERSION "1.0.4"
#define PAGE_SIZE 0x1000
#define DBWIN_BUFFER_READY L"DBWIN_BUFFER_READY"
#define DBWIN_DATA_READY L"DBWIN_DATA_READY"
#define DBWIN_BUFFER L"DBWIN_BUFFER"
// The Win32 OutputDebugString buffer.
typedef struct _DBWIN_PAGE_BUFFER
{
ULONG ProcessId; /** The ID of the process. */
CHAR Buffer[PAGE_SIZE - sizeof(ULONG)]; /** The buffer containing the debug message. */
} DBWIN_PAGE_BUFFER, * PDBWIN_PAGE_BUFFER;
class ERR
{
public:
ERR(PCSTR name, DWORD code) : name(name), code(code) {}
PCSTR name;
DWORD code;
};
struct SWinDbgMonitor
{
SWinDbgMonitor(const char* pattern = nullptr) : Pattern(pattern)
{
LocalCaptureEnabled = FALSE;
LocalBufferReadyEvent = NULL;
LocalDataReadyEvent = NULL;
LocalDataBufferHandle = NULL;
LocalDebugBuffer = NULL;
GlobalCaptureEnabled = FALSE;
GlobalBufferReadyEvent = NULL;
GlobalDataReadyEvent = NULL;
GlobalDataBufferHandle = NULL;
GlobalDebugBuffer = NULL;
DbgCreateSecurityAttributes();
}
~SWinDbgMonitor()
{
DbgCleanupSecurityAttributes();
}
SECURITY_ATTRIBUTES SecurityAttributes;
BOOLEAN LocalCaptureEnabled;
HANDLE LocalBufferReadyEvent;
HANDLE LocalDataReadyEvent;
HANDLE LocalDataBufferHandle;
PDBWIN_PAGE_BUFFER LocalDebugBuffer;
BOOLEAN GlobalCaptureEnabled;
HANDLE GlobalBufferReadyEvent;
HANDLE GlobalDataReadyEvent;
HANDLE GlobalDataBufferHandle;
PDBWIN_PAGE_BUFFER GlobalDebugBuffer;
const char* Pattern;
BOOL DbgCreateSecurityAttributes()
{
SecurityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
SecurityAttributes.bInheritHandle = FALSE;
return ConvertStringSecurityDescriptorToSecurityDescriptor(
L"D:(A;;GRGWGX;;;WD)(A;;GA;;;SY)(A;;GA;;;BA)(A;;GRGWGX;;;AN)(A;;GRGWGX;;;RC)(A;;GRGWGX;;;S-1-15-2-1)S:(ML;;NW;;;LW)",
SDDL_REVISION, &SecurityAttributes.lpSecurityDescriptor, NULL);
}
void DbgCleanupSecurityAttributes()
{
if (SecurityAttributes.lpSecurityDescriptor)
{
LocalFree(SecurityAttributes.lpSecurityDescriptor);
SecurityAttributes.lpSecurityDescriptor = NULL;
}
}
std::expected<void, ERR> Init(bool bGlobal)
{
BOOLEAN& CaptureEnabled = bGlobal ? GlobalCaptureEnabled : LocalCaptureEnabled;
HANDLE& BufferReadyEvent = bGlobal ? GlobalBufferReadyEvent : LocalBufferReadyEvent;
HANDLE& DataReadyEvent = bGlobal ? GlobalDataReadyEvent : LocalDataReadyEvent;
HANDLE& DataBufferHandle = bGlobal ? GlobalDataBufferHandle : LocalDataBufferHandle;
PDBWIN_PAGE_BUFFER& DebugBuffer = bGlobal ? GlobalDebugBuffer : LocalDebugBuffer;
SIZE_T viewSize;
LARGE_INTEGER maximumSize;
maximumSize.QuadPart = PAGE_SIZE;
viewSize = sizeof(DBWIN_PAGE_BUFFER);
if (!(BufferReadyEvent = CreateEvent(&SecurityAttributes, FALSE, FALSE, bGlobal ? L"Global\\" DBWIN_BUFFER_READY : L"Local\\" DBWIN_BUFFER_READY)) ||
GetLastError() == ERROR_ALREADY_EXISTS)
{
return std::unexpected(ERR("DBWIN_BUFFER_READY", GetLastError()));
}
if (!(DataReadyEvent = CreateEvent(&SecurityAttributes, FALSE, FALSE, bGlobal ? L"Global\\" DBWIN_DATA_READY : L"Local\\" DBWIN_DATA_READY)) ||
GetLastError() == ERROR_ALREADY_EXISTS)
{
return std::unexpected(ERR("DBWIN_DATA_READY", GetLastError()));
}
if (!(DataBufferHandle = CreateFileMapping(
INVALID_HANDLE_VALUE,
&SecurityAttributes,
PAGE_READWRITE,
maximumSize.HighPart,
maximumSize.LowPart,
bGlobal ? L"Global\\" DBWIN_BUFFER : L"Local\\" DBWIN_BUFFER
)) || GetLastError() == ERROR_ALREADY_EXISTS)
{
return std::unexpected(ERR("CreateFileMapping", GetLastError()));
}
if (!(DebugBuffer = (PDBWIN_PAGE_BUFFER)MapViewOfFile(
DataBufferHandle,
FILE_MAP_READ,
0,
0,
viewSize
)))
{
return std::unexpected(ERR("MapViewOfFile", GetLastError()));
}
CaptureEnabled = TRUE;
return {};
}
void UnInit(bool bGlobal)
{
BOOLEAN& CaptureEnabled = bGlobal ? GlobalCaptureEnabled : LocalCaptureEnabled;
HANDLE& BufferReadyEvent = bGlobal ? GlobalBufferReadyEvent : LocalBufferReadyEvent;
HANDLE& DataReadyEvent = bGlobal ? GlobalDataReadyEvent : LocalDataReadyEvent;
HANDLE& DataBufferHandle = bGlobal ? GlobalDataBufferHandle : LocalDataBufferHandle;
PDBWIN_PAGE_BUFFER& DebugBuffer = bGlobal ? GlobalDebugBuffer : LocalDebugBuffer;
CaptureEnabled = FALSE;
if (DebugBuffer)
{
UnmapViewOfFile(DebugBuffer);
DebugBuffer = NULL;
}
if (DataBufferHandle)
{
CloseHandle(DataBufferHandle);
DataBufferHandle = NULL;
}
if (BufferReadyEvent)
{
CloseHandle(BufferReadyEvent);
BufferReadyEvent = NULL;
}
if (DataReadyEvent)
{
CloseHandle(DataReadyEvent);
DataReadyEvent = NULL;
}
}
};
// https://github.com/tidwall/match.c
//
// match returns true if str matches pattern. This is a very
// simple wildcard match where '*' matches on any number characters
// and '?' matches on any one character.
//
// pattern:
// { term }
// term:
// '*' matches any sequence of non-Separator characters
// '?' matches any single non-Separator character
// c matches character c (c != '*', '?')
// '\\' c matches character c
bool match(const char* pat, size_t plen, const char* str, size_t slen)
{
while (plen > 0)
{
if (pat[0] == '\\')
{
if (plen == 1) return false;
pat++; plen--;
}
else if (pat[0] == '*')
{
if (plen == 1) return true;
if (pat[1] == '*')
{
pat++; plen--;
continue;
}
if (match(pat + 1, plen - 1, str, slen)) return true;
if (slen == 0) return false;
str++; slen--;
continue;
}
if (slen == 0) return false;
if (pat[0] != '?' && str[0] != pat[0]) return false;
pat++; plen--;
str++; slen--;
}
return slen == 0 && plen == 0;
}
std::unordered_map<DWORD, std::wstring> GetProcessNames()
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE)
{
return {};
}
std::unordered_map<DWORD, std::wstring> result;
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(hSnapshot, &pe32))
{
do
{
result.try_emplace(pe32.th32ProcessID, pe32.szExeFile);
} while (Process32Next(hSnapshot, &pe32));
}
CloseHandle(hSnapshot);
return result;
}
size_t StrRemoveNewlines(const char* src, char* dst)
{
char* start = dst;
char* lastNewlineSequence = nullptr;
while (*src)
{
if (*src == '\r' || *src == '\n')
{
if (!lastNewlineSequence)
{
lastNewlineSequence = dst;
}
*dst++ = ' ';
if (src[0] == '\r' && src[1] == '\n')
{
src += 2;
}
else
{
src++;
}
}
else
{
*dst++ = *src++;
lastNewlineSequence = nullptr;
}
}
char* end = lastNewlineSequence ? lastNewlineSequence : dst;
*end = '\0';
return end - start;
}
std::wstring StrA2W(std::string_view str, UINT codePage = CP_ACP)
{
std::wstring result;
int strLen = static_cast<int>(str.size());
if (strLen > 0)
{
int sizeNeeded = MultiByteToWideChar(codePage, 0, str.data(), strLen, nullptr, 0);
if (sizeNeeded > 0)
{
result.resize(sizeNeeded);
MultiByteToWideChar(codePage, 0, str.data(), strLen, result.data(), sizeNeeded);
}
}
return result;
}
std::string StrW2A(std::wstring_view str, UINT codePage = CP_ACP)
{
std::string result;
int strLen = static_cast<int>(str.size());
if (strLen > 0)
{
int sizeNeeded = WideCharToMultiByte(codePage, 0, str.data(), strLen, nullptr, 0, nullptr, nullptr);
if (sizeNeeded > 0)
{
result.resize(sizeNeeded);
WideCharToMultiByte(codePage, 0, str.data(), strLen, result.data(), sizeNeeded, nullptr, nullptr);
}
}
return result;
}
DWORD DbgEventsThread(bool bGlobal, SWinDbgMonitor* m)
{
HANDLE& BufferReadyEvent = bGlobal ? m->GlobalBufferReadyEvent : m->LocalBufferReadyEvent;
HANDLE& DataReadyEvent = bGlobal ? m->GlobalDataReadyEvent : m->LocalDataReadyEvent;
PDBWIN_PAGE_BUFFER debugMessageBuffer = bGlobal ? m->GlobalDebugBuffer : m->LocalDebugBuffer;
const char* pattern = m->Pattern;
size_t patternLen = pattern ? strlen(pattern) : 0;
std::unordered_map<DWORD, std::wstring> processNames;
DWORD processNamesTickCount = 0;
while (TRUE)
{
SetEvent(BufferReadyEvent);
DWORD status = WaitForSingleObject(DataReadyEvent, INFINITE);
if (status != WAIT_OBJECT_0)
break;
char bufferWithoutNewlines[sizeof(debugMessageBuffer->Buffer)];
size_t bufferWithoutNewlinesLen = StrRemoveNewlines(debugMessageBuffer->Buffer, bufferWithoutNewlines);
if (pattern && !match(pattern, patternLen, bufferWithoutNewlines, bufferWithoutNewlinesLen))
continue;
SYSTEMTIME st;
GetLocalTime(&st);
if (GetTickCount() - processNamesTickCount > 1000 * 60)
{
processNames.clear();
}
std::wstring_view processName;
if (auto it = processNames.find(debugMessageBuffer->ProcessId); it != processNames.end())
{
processName = it->second;
}
else
{
processNames = GetProcessNames();
processNamesTickCount = GetTickCount();
if (auto it = processNames.find(debugMessageBuffer->ProcessId); it != processNames.end())
{
processName = it->second;
}
else
{
processName = L"<unknown>"sv;
}
}
// Convert manually to UTF-8. Using wprintf doesn't work for some characters such as emojis.
// https://stackoverflow.com/q/77247757
auto processNameUtf8 = StrW2A(processName, CP_UTF8);
auto bufferWithoutNewlinesUtf8 = StrW2A(StrA2W(bufferWithoutNewlines), CP_UTF8);
printf("%02d:%02d:%02d.%03d %d %s %s\n",
st.wHour, st.wMinute, st.wSecond, st.wMilliseconds,
debugMessageBuffer->ProcessId,
processNameUtf8.c_str(),
bufferWithoutNewlinesUtf8.c_str());
}
return 0;
}
DWORD WINAPI DbgEventsLocalThread(PVOID Parameter)
{
return DbgEventsThread(false, (SWinDbgMonitor*)Parameter);
}
DWORD WINAPI DbgEventsGlobalThread(PVOID Parameter)
{
return DbgEventsThread(true, (SWinDbgMonitor*)Parameter);
}
void PrintBanner()
{
printf("DbgViewMini v%s\n", DBG_VIEW_MINI_VERSION);
}
int main(int argc, char* argv[])
{
SetConsoleOutputCP(CP_UTF8);
bool local = false;
bool global = false;
const char* pattern = nullptr;
for (int i = 1; i < argc; i++)
{
if (strcmp(argv[i], "-l") == 0 || strcmp(argv[i], "--local") == 0)
{
local = true;
}
else if (strcmp(argv[i], "-g") == 0 || strcmp(argv[i], "--global") == 0)
{
global = true;
}
else if (strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--pattern") == 0)
{
if (i + 1 < argc)
{
pattern = argv[i + 1];
i++;
}
else
{
PrintBanner();
printf("Missing pattern\n");
return 1;
}
}
else if (strcmp(argv[i], "-n") == 0 || strcmp(argv[i], "--no-buffering") == 0)
{
setvbuf(stdout, nullptr, _IONBF, 0);
setvbuf(stderr, nullptr, _IONBF, 0);
}
else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0)
{
PrintBanner();
printf("Usage: DbgViewMini.exe [-l|--local] [-g|--global] [-p|--pattern <pattern>] [-n|--no-buffering]\n");
return 0;
}
else
{
PrintBanner();
printf("Unknown option: %s\n", argv[i]);
return 1;
}
}
if (!local && !global)
{
local = true;
global = true;
}
PrintBanner();
printf("Listening for OutputDebugString messages...\n");
static SWinDbgMonitor monitor(pattern);
if (local)
{
std::optional<ERR> error;
if (auto status = monitor.Init(false); !status.has_value())
{
error = status.error();
}
else if (HANDLE threadHandle = CreateThread(nullptr, 0, DbgEventsLocalThread, &monitor, 0, nullptr); !threadHandle)
{
error = ERR("CreateThread", GetLastError());
}
else
{
CloseHandle(threadHandle);
}
if (error)
{
monitor.UnInit(false);
printf("Local capture error: %s (%u)\n", error->name, error->code);
printf("Another DbgViewMini instance (or a similar application) might be running.\n");
}
}
if (global)
{
std::optional<ERR> error;
if (auto status = monitor.Init(true); !status.has_value())
{
error = status.error();
}
else if (HANDLE threadHandle = CreateThread(nullptr, 0, DbgEventsGlobalThread, &monitor, 0, nullptr); !threadHandle)
{
error = ERR("CreateThread", GetLastError());
}
else
{
CloseHandle(threadHandle);
}
if (error)
{
monitor.UnInit(true);
if (error->code != ERROR_ACCESS_DENIED || !local)
{
printf("Global capture error: %s (%u)\n", error->name, error->code);
}
}
}
if (!monitor.LocalCaptureEnabled && !monitor.GlobalCaptureEnabled)
{
return 1;
}
// Continue logging in the newly created threads.
ExitThread(0);
/*
getchar();
printf("Shutting down...\n");
if (monitor->LocalCaptureEnabled)
monitor->UnInit(false);
if (monitor->GlobalCaptureEnabled)
monitor->UnInit(true);
delete monitor;
return 0;
*/
}