This source file includes following definitions.
- OnHotKey
- CreateMemoryWatcher
- DeleteMemoryWatcher
- ThreadMain
- CreateBackgroundThread
- StopBackgroundThread
- IsChromeExe
- DllMain
- __declspec
#include <windows.h>
#include "base/at_exit.h"
#include "tools/memory_watcher/memory_watcher.h"
#include "tools/memory_watcher/hotkey.h"
class MemoryWatcherDumpKey;
static wchar_t* kDumpEvent = L"MemWatcher.DumpEvent";
static base::AtExitManager* g_memory_watcher_exit_manager = NULL;
static MemoryWatcher* g_memory_watcher = NULL;
static MemoryWatcherDumpKey* g_hotkey_handler = NULL;
static HANDLE g_dump_event = INVALID_HANDLE_VALUE;
static HANDLE g_quit_event = INVALID_HANDLE_VALUE;
static HANDLE g_watcher_thread = INVALID_HANDLE_VALUE;
class MemoryWatcherDumpKey : public HotKeyHandler {
public:
MemoryWatcherDumpKey(UINT modifiers, UINT vkey)
: HotKeyHandler(modifiers, vkey) {}
virtual void OnHotKey(UINT, WPARAM, LPARAM) {
SetEvent(g_dump_event);
}
};
void CreateMemoryWatcher() {
g_memory_watcher_exit_manager = new base::AtExitManager();
g_memory_watcher = new MemoryWatcher();
g_hotkey_handler = new MemoryWatcherDumpKey(MOD_ALT|MOD_CONTROL, 0x44);
}
void DeleteMemoryWatcher() {
if (g_hotkey_handler)
delete g_hotkey_handler;
g_hotkey_handler = NULL;
if (g_memory_watcher)
delete g_memory_watcher;
g_memory_watcher = NULL;
}
DWORD WINAPI ThreadMain(LPVOID) {
bool stopping = false;
HANDLE events[2] = { g_dump_event, g_quit_event };
while (!stopping) {
DWORD rv = WaitForMultipleObjects(2, events, FALSE, INFINITE);
switch (rv) {
case WAIT_OBJECT_0:
if (g_memory_watcher) {
g_memory_watcher->DumpLeaks();
}
stopping = true;
break;
case WAIT_OBJECT_0 + 1:
stopping = true;
break;
default:
NOTREACHED();
break;
}
}
return 0;
}
void CreateBackgroundThread() {
g_dump_event = CreateEvent(0, TRUE, FALSE, kDumpEvent);
DCHECK(g_dump_event != NULL);
g_quit_event = CreateEvent(0, TRUE, FALSE, NULL);
DCHECK(g_quit_event != NULL);
g_watcher_thread = CreateThread(0,
0,
ThreadMain,
0,
0,
0);
DCHECK(g_watcher_thread != NULL);
}
void StopBackgroundThread() {
SetEvent(g_quit_event);
DWORD rv = WaitForSingleObject(g_watcher_thread, INFINITE);
DCHECK(rv == WAIT_OBJECT_0);
CloseHandle(g_quit_event);
CloseHandle(g_dump_event);
CloseHandle(g_watcher_thread);
}
bool IsChromeExe() {
return GetModuleHandleA("chrome.exe") != NULL;
}
extern "C" {
BOOL WINAPI DllMain(HINSTANCE dll_instance, DWORD reason,
LPVOID reserved) {
if (!IsChromeExe())
return FALSE;
switch (reason) {
case DLL_PROCESS_ATTACH:
CreateMemoryWatcher();
CreateBackgroundThread();
break;
case DLL_PROCESS_DETACH:
DeleteMemoryWatcher();
StopBackgroundThread();
break;
}
return TRUE;
}
__declspec(dllexport) void __cdecl SetLogName(char* name) {
g_memory_watcher->SetLogName(name);
}
}