File: windows_crashcatcher.cpp

package info (click to toggle)
openmw 0.49.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 33,992 kB
  • sloc: cpp: 372,479; xml: 2,149; sh: 1,403; python: 797; makefile: 26
file content (263 lines) | stat: -rw-r--r-- 8,561 bytes parent folder | download
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
#include "windows_crashcatcher.hpp"

#include <cassert>
#include <cwchar>
#include <sstream>
#include <thread>

#include "windows_crashmonitor.hpp"
#include "windows_crashshm.hpp"
#include "windowscrashdumppathhelpers.hpp"
#include <SDL_messagebox.h>

#include <components/misc/strings/conversion.hpp>

namespace Crash
{
    namespace
    {
        template <class T, std::size_t N>
        void writePathToShm(T (&buffer)[N], const std::filesystem::path& path)
        {
            memset(buffer, 0, sizeof(buffer));
            const auto str = path.u8string();
            size_t length = str.length();
            if (length >= sizeof(buffer))
                length = sizeof(buffer) - 1;
            strncpy_s(buffer, sizeof(buffer), Misc::StringUtils::u8StringToString(str).c_str(), length);
        }
    }

    HANDLE duplicateHandle(HANDLE handle)
    {
        HANDLE duplicate;
        if (!DuplicateHandle(
                GetCurrentProcess(), handle, GetCurrentProcess(), &duplicate, 0, TRUE, DUPLICATE_SAME_ACCESS))
        {
            throw std::runtime_error("Crash monitor could not duplicate handle");
        }
        return duplicate;
    }

    CrashCatcher* CrashCatcher::sInstance = nullptr;

    CrashCatcher::CrashCatcher(int argc, char** argv, const std::filesystem::path& dumpPath,
        const std::filesystem::path& crashDumpName, const std::filesystem::path& freezeDumpName)
    {
        assert(sInstance == nullptr); // don't allow two instances

        sInstance = this;

        HANDLE shmHandle = nullptr;
        for (int i = 0; i < argc; ++i)
        {
            if (strcmp(argv[i], "--crash-monitor"))
                continue;

            if (i >= argc - 1)
                throw std::runtime_error("Crash monitor is missing the SHM handle argument");

            sscanf(argv[i + 1], "%p", &shmHandle);
            break;
        }

        if (!shmHandle)
        {
            setupIpc();
            startMonitorProcess(dumpPath, crashDumpName, freezeDumpName);
            installHandler();
        }
        else
        {
            CrashMonitor(shmHandle).run();
            exit(0);
        }
    }

    CrashCatcher::~CrashCatcher()
    {
        sInstance = nullptr;

        if (mShm && mSignalMonitorEvent)
        {
            shmLock();
            mShm->mEvent = CrashSHM::Event::Shutdown;
            shmUnlock();

            SetEvent(mSignalMonitorEvent);
        }

        if (mShmHandle)
            CloseHandle(mShmHandle);
    }

    void CrashCatcher::updateDumpPath(const std::filesystem::path& dumpPath)
    {
        shmLock();

        writePathToShm(mShm->mStartup.mDumpDirectoryPath, dumpPath);

        shmUnlock();
    }

    void CrashCatcher::updateDumpNames(
        const std::filesystem::path& crashDumpName, const std::filesystem::path& freezeDumpName)
    {
        shmLock();

        writePathToShm(mShm->mStartup.mCrashDumpFileName, crashDumpName);
        writePathToShm(mShm->mStartup.mFreezeDumpFileName, freezeDumpName);

        shmUnlock();
    }

    void CrashCatcher::setupIpc()
    {
        SECURITY_ATTRIBUTES attributes;
        ZeroMemory(&attributes, sizeof(attributes));
        attributes.bInheritHandle = TRUE;

        mSignalAppEvent = CreateEventW(&attributes, FALSE, FALSE, NULL);
        mSignalMonitorEvent = CreateEventW(&attributes, FALSE, FALSE, NULL);

        mShmHandle = CreateFileMappingW(INVALID_HANDLE_VALUE, &attributes, PAGE_READWRITE, HIWORD(sizeof(CrashSHM)),
            LOWORD(sizeof(CrashSHM)), NULL);
        if (mShmHandle == nullptr)
            throw std::runtime_error("Failed to allocate crash catcher shared memory");

        mShm = reinterpret_cast<CrashSHM*>(MapViewOfFile(mShmHandle, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(CrashSHM)));
        if (mShm == nullptr)
            throw std::runtime_error("Failed to map crash catcher shared memory");

        mShm->mMonitorStatus = CrashSHM::Status::Uninitialised;

        mShmMutex = CreateMutexW(&attributes, FALSE, NULL);
        if (mShmMutex == nullptr)
            throw std::runtime_error("Failed to create crash catcher shared memory mutex");
    }

    void CrashCatcher::shmLock()
    {
        if (WaitForSingleObject(mShmMutex, CrashCatcherTimeout) != WAIT_OBJECT_0)
            throw std::runtime_error("SHM lock timed out");
    }

    void CrashCatcher::shmUnlock()
    {
        ReleaseMutex(mShmMutex);
    }

    void CrashCatcher::waitMonitor()
    {
        if (!waitMonitorNoThrow())
            throw std::runtime_error("Waiting for monitor failed");
    }

    bool CrashCatcher::waitMonitorNoThrow()
    {
        return WaitForSingleObject(mSignalAppEvent, CrashCatcherTimeout) == WAIT_OBJECT_0;
    }

    void CrashCatcher::signalMonitor()
    {
        SetEvent(mSignalMonitorEvent);
    }

    void CrashCatcher::installHandler()
    {
        SetUnhandledExceptionFilter(vectoredExceptionHandler);
    }

    void CrashCatcher::startMonitorProcess(const std::filesystem::path& dumpPath,
        const std::filesystem::path& crashDumpName, const std::filesystem::path& freezeDumpName)
    {
        std::wstring executablePath;
        DWORD copied = 0;
        do
        {
            executablePath.resize(executablePath.size() + MAX_PATH);
            copied = GetModuleFileNameW(nullptr, executablePath.data(), static_cast<DWORD>(executablePath.size()));
        } while (copied >= executablePath.size());
        executablePath.resize(copied);

        writePathToShm(mShm->mStartup.mDumpDirectoryPath, dumpPath);
        writePathToShm(mShm->mStartup.mCrashDumpFileName, crashDumpName);
        writePathToShm(mShm->mStartup.mFreezeDumpFileName, freezeDumpName);

        // note that we don't need to lock the SHM here, the other process has not started yet
        mShm->mEvent = CrashSHM::Event::Startup;
        mShm->mStartup.mShmMutex = duplicateHandle(mShmMutex);
        mShm->mStartup.mAppProcessHandle = duplicateHandle(GetCurrentProcess());
        mShm->mStartup.mAppMainThreadId = GetThreadId(GetCurrentThread());
        mShm->mStartup.mSignalApp = duplicateHandle(mSignalAppEvent);
        mShm->mStartup.mSignalMonitor = duplicateHandle(mSignalMonitorEvent);

        std::wstringstream ss;
        ss << "--crash-monitor " << std::hex << duplicateHandle(mShmHandle);
        std::wstring arguments(ss.str());

        STARTUPINFOW si;
        ZeroMemory(&si, sizeof(si));

        PROCESS_INFORMATION pi;
        ZeroMemory(&pi, sizeof(pi));

        if (!CreateProcessW(executablePath.data(), arguments.data(), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
            throw std::runtime_error("Could not start crash monitor process");

        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);

        waitMonitor();
    }

    LONG CrashCatcher::vectoredExceptionHandler(PEXCEPTION_POINTERS info)
    {
        switch (info->ExceptionRecord->ExceptionCode)
        {
            case EXCEPTION_SINGLE_STEP:
            case EXCEPTION_BREAKPOINT:
            case DBG_PRINTEXCEPTION_C:
                return EXCEPTION_EXECUTE_HANDLER;
        }
        if (!sInstance)
            return EXCEPTION_EXECUTE_HANDLER;

        sInstance->handleVectoredException(info);

        _Exit(1);
    }

    void CrashCatcher::handleVectoredException(PEXCEPTION_POINTERS info)
    {
        shmLock();

        mShm->mEvent = CrashSHM::Event::Crashed;
        mShm->mCrashed.mThreadId = GetCurrentThreadId();
        mShm->mCrashed.mContext = *info->ContextRecord;
        mShm->mCrashed.mExceptionRecord = *info->ExceptionRecord;

        shmUnlock();

        signalMonitor();

        // give monitor a chance to start dumping
        // as we're suspended, this might time out even if it's successful, so mMonitorStatus is the source of truth
        waitMonitorNoThrow();

        shmLock();
        CrashSHM::Status monitorStatus = mShm->mMonitorStatus;
        shmUnlock();

        if (monitorStatus == CrashSHM::Status::DumpedSuccessfully)
        {
            std::string message = "OpenMW has encountered a fatal error.\nCrash dump saved to '"
                + Misc::StringUtils::u8StringToString(getCrashDumpPath(*mShm).u8string())
                + "'.\nPlease report this to https://gitlab.com/OpenMW/openmw/issues !";
            SDL_ShowSimpleMessageBox(0, "Fatal Error", message.c_str(), nullptr);
        }
        else if (monitorStatus == CrashSHM::Status::Dumping)
            SDL_ShowSimpleMessageBox(0, "Fatal Error", "Timed out while creating crash dump", nullptr);
    }

} // namespace Crash