File: debugging.cpp

package info (click to toggle)
openmw 0.50.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 37,076 kB
  • sloc: cpp: 380,958; xml: 2,192; sh: 1,449; python: 911; makefile: 26; javascript: 5
file content (497 lines) | stat: -rw-r--r-- 15,356 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
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
#include "debugging.hpp"

#include <chrono>
#include <deque>
#include <fstream>
#include <iostream>
#include <memory>

#ifdef _MSC_VER
// TODO: why is this necessary? this has /external:I
#pragma warning(push)
#pragma warning(disable : 4702)
#endif
#include <boost/iostreams/stream.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include <components/crashcatcher/crashcatcher.hpp>
#include <components/files/conversion.hpp>
#include <components/misc/strings/conversion.hpp>
#include <components/misc/strings/lower.hpp>

#ifdef _WIN32
#include <components/crashcatcher/windowscrashcatcher.hpp>
#include <components/files/conversion.hpp>
#include <components/misc/windows.hpp>

#include <Knownfolders.h>

#pragma push_macro("FAR")
#pragma push_macro("NEAR")
#undef FAR
#define FAR
#undef NEAR
#define NEAR
#include <Shlobj.h>
#pragma pop_macro("NEAR")
#pragma pop_macro("FAR")

#endif

#include <SDL_messagebox.h>

namespace Debug
{
#ifdef _WIN32
    bool isRedirected(DWORD nStdHandle)
    {
        DWORD fileType = GetFileType(GetStdHandle(nStdHandle));

        return (fileType == FILE_TYPE_DISK) || (fileType == FILE_TYPE_PIPE);
    }

    bool attachParentConsole()
    {
        if (GetConsoleWindow() != nullptr)
            return true;

        bool inRedirected = isRedirected(STD_INPUT_HANDLE);
        bool outRedirected = isRedirected(STD_OUTPUT_HANDLE);
        bool errRedirected = isRedirected(STD_ERROR_HANDLE);

        // Note: Do not spend three days reinvestigating this PowerShell bug thinking its our bug.
        // https://gitlab.com/OpenMW/openmw/-/merge_requests/408#note_447467393
        // The handles look valid, but GetFinalPathNameByHandleA can't tell what files they go to and writing to them
        // doesn't work.

        if (AttachConsole(ATTACH_PARENT_PROCESS))
        {
            fflush(stdout);
            fflush(stderr);
            std::cout.flush();
            std::cerr.flush();

            // this looks dubious but is really the right way
            if (!inRedirected)
            {
                _wfreopen(L"CON", L"r", stdin);
                freopen("CON", "r", stdin);
                std::cin.clear();
            }
            if (!outRedirected)
            {
                _wfreopen(L"CON", L"w", stdout);
                freopen("CON", "w", stdout);
                std::cout.clear();
            }
            if (!errRedirected)
            {
                _wfreopen(L"CON", L"w", stderr);
                freopen("CON", "w", stderr);
                std::cerr.clear();
            }

            return true;
        }

        return false;
    }
#endif

    static LogListener logListener;
    void setLogListener(LogListener listener)
    {
        logListener = std::move(listener);
    }

    namespace
    {
        class DebugOutputBase : public boost::iostreams::sink
        {
        public:
            virtual std::streamsize write(const char* str, std::streamsize size)
            {
                if (size <= 0)
                    return size;
                std::string_view msg{ str, static_cast<size_t>(size) };

                // Skip debug level marker
                Level level = All;
                if (Log::sWriteLevel)
                {
                    level = getLevelMarker(msg[0]);
                    msg = msg.substr(1);
                }

                char prefix[32];
                std::size_t prefixSize;
                {
                    prefix[0] = '[';
                    const auto now = std::chrono::system_clock::now();
                    const auto time = std::chrono::system_clock::to_time_t(now);
                    tm timeInfo{};
#ifdef _WIN32
                    (void)localtime_s(&timeInfo, &time);
#else
                    (void)localtime_r(&time, &timeInfo);
#endif
                    prefixSize = std::strftime(prefix + 1, sizeof(prefix) - 1, "%T", &timeInfo) + 1;
                    char levelLetter = " EWIVD*"[int(level)];
                    const auto ms
                        = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
                    prefixSize += snprintf(prefix + prefixSize, sizeof(prefix) - prefixSize, ".%03u %c] ",
                        static_cast<unsigned>(ms % 1000), levelLetter);
                }

                while (!msg.empty())
                {
                    if (msg[0] == 0)
                        break;
                    size_t lineSize = 1;
                    while (lineSize < msg.size() && msg[lineSize - 1] != '\n')
                        lineSize++;
                    writeImpl(prefix, prefixSize, level);
                    writeImpl(msg.data(), lineSize, level);
                    if (logListener)
                        logListener(
                            level, std::string_view(prefix, prefixSize), std::string_view(msg.data(), lineSize));
                    msg = msg.substr(lineSize);
                }

                return size;
            }

            virtual ~DebugOutputBase() = default;

        protected:
            static Level getLevelMarker(char marker)
            {
                if (0 <= marker && static_cast<unsigned>(marker) < static_cast<unsigned>(All))
                    return static_cast<Level>(marker);
                return All;
            }

            virtual std::streamsize writeImpl(const char* str, std::streamsize size, Level debugLevel)
            {
                return size;
            }
        };

#if defined _WIN32 && defined _DEBUG
        class DebugOutput : public DebugOutputBase
        {
        public:
            std::streamsize writeImpl(const char* str, std::streamsize size, Level debugLevel)
            {
                // Make a copy for null termination
                std::string tmp(str, static_cast<unsigned int>(size));
                // Write string to Visual Studio Debug output
                OutputDebugString(tmp.c_str());
                return size;
            }

            virtual ~DebugOutput() = default;
        };
#else

        struct Record
        {
            std::string mValue;
            Level mLevel;
        };

        std::deque<Record> globalBuffer;

        Color getColor(Level level)
        {
            switch (level)
            {
                case Error:
                    return Red;
                case Warning:
                    return Yellow;
                case Info:
                    return Reset;
                case Verbose:
                    return DarkGray;
                case Debug:
                    return DarkGray;
                case All:
                    return Reset;
            }
            return Reset;
        }

        bool useColoredOutput()
        {
#if defined(_WIN32)
            if (std::getenv("NO_COLOR") != nullptr)
                return false;

            DWORD mode;
            if (GetConsoleMode(GetStdHandle(STD_ERROR_HANDLE), &mode) && mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)
                return true;

            // some console emulators may not use the Win32 API, so try the Unixy approach
            return std::getenv("TERM") != nullptr && GetFileType(GetStdHandle(STD_ERROR_HANDLE)) == FILE_TYPE_CHAR;
#else
            return std::getenv("TERM") != nullptr && std::getenv("NO_COLOR") == nullptr && isatty(fileno(stderr));
#endif
        }

        class Identity
        {
        public:
            explicit Identity(std::ostream& stream)
                : mStream(stream)
            {
            }

            void write(const char* str, std::streamsize size, Level /*level*/)
            {
                mStream.write(str, size);
                mStream.flush();
            }

        private:
            std::ostream& mStream;
        };

        class Coloured
        {
        public:
            explicit Coloured(std::ostream& stream)
                : mStream(stream)
                // TODO: check which stream is stderr?
                , mUseColor(useColoredOutput())
            {
            }

            void write(const char* str, std::streamsize size, Level level)
            {
                if (mUseColor)
                    mStream << "\033[0;" << getColor(level) << 'm';
                mStream.write(str, size);
                if (mUseColor)
                    mStream << "\033[0;" << Reset << 'm';
                mStream.flush();
            }

        private:
            std::ostream& mStream;
            bool mUseColor;
        };

        class Buffer
        {
        public:
            explicit Buffer(std::size_t capacity, std::deque<Record>& buffer)
                : mCapacity(capacity)
                , mBuffer(buffer)
            {
            }

            void write(const char* str, std::streamsize size, Level debugLevel)
            {
                while (mBuffer.size() >= mCapacity)
                    mBuffer.pop_front();
                mBuffer.push_back(Record{ std::string(str, size), debugLevel });
            }

        private:
            std::size_t mCapacity;
            std::deque<Record>& mBuffer;
        };

        template <class First, class Second>
        class Tee : public DebugOutputBase
        {
        public:
            explicit Tee(First first, Second second)
                : mFirst(first)
                , mSecond(second)
            {
            }

            std::streamsize writeImpl(const char* str, std::streamsize size, Level debugLevel) override
            {
                mFirst.write(str, size, debugLevel);
                mSecond.write(str, size, debugLevel);
                return size;
            }

        private:
            First mFirst;
            Second mSecond;
        };
#endif

        Level toLevel(std::string_view value)
        {
            if (value == "ERROR")
                return Error;
            if (value == "WARNING")
                return Warning;
            if (value == "INFO")
                return Info;
            if (value == "VERBOSE")
                return Verbose;
            if (value == "DEBUG")
                return Debug;

            return Verbose;
        }

        static std::unique_ptr<std::ostream> rawStdout = nullptr;
        static std::unique_ptr<std::ostream> rawStderr = nullptr;
        static std::unique_ptr<std::mutex> rawStderrMutex = nullptr;
        static std::ofstream logfile;

#if defined(_WIN32) && defined(_DEBUG)
        static boost::iostreams::stream_buffer<DebugOutput> sb;
#else
        static boost::iostreams::stream_buffer<Tee<Identity, Coloured>> standardOut;
        static boost::iostreams::stream_buffer<Tee<Identity, Coloured>> standardErr;
        static boost::iostreams::stream_buffer<Tee<Buffer, Coloured>> bufferedOut;
        static boost::iostreams::stream_buffer<Tee<Buffer, Coloured>> bufferedErr;
#endif
    }

    std::ostream& getRawStdout()
    {
        return rawStdout ? *rawStdout : std::cout;
    }

    std::ostream& getRawStderr()
    {
        return rawStderr ? *rawStderr : std::cerr;
    }

    Misc::Locked<std::ostream&> getLockedRawStderr()
    {
        return Misc::Locked<std::ostream&>(*rawStderrMutex, getRawStderr());
    }

    Level getDebugLevel()
    {
        if (const char* env = getenv("OPENMW_DEBUG_LEVEL"))
            return toLevel(env);

        return Verbose;
    }

    Level getRecastMaxLogLevel()
    {
        if (const char* env = getenv("OPENMW_RECAST_MAX_LOG_LEVEL"))
            return toLevel(env);

        return Error;
    }

    void setupLogging(const std::filesystem::path& logDir, std::string_view appName)
    {
        Log::sMinDebugLevel = getDebugLevel();
        Log::sWriteLevel = true;

#if !(defined(_WIN32) && defined(_DEBUG))
        const std::string logName = Misc::StringUtils::lowerCase(appName) + ".log";
        logfile.open(logDir / logName, std::ios::out);

        Identity log(logfile);

        for (const Record& v : globalBuffer)
            log.write(v.mValue.data(), v.mValue.size(), v.mLevel);

        globalBuffer.clear();

        standardOut.open(Tee(log, Coloured(*rawStdout)));
        standardErr.open(Tee(log, Coloured(*rawStderr)));

        std::cout.rdbuf(&standardOut);
        std::cerr.rdbuf(&standardErr);
#endif

#ifdef _WIN32
        if (Crash::CrashCatcher::instance())
        {
            Crash::CrashCatcher::instance()->updateDumpPath(logDir);
        }
#endif
    }

    int wrapApplication(
        int (*innerApplication)(int argc, char* argv[]), int argc, char* argv[], std::string_view appName)
    {
#if defined _WIN32
        (void)attachParentConsole();
#endif
        rawStdout = std::make_unique<std::ostream>(std::cout.rdbuf());
        rawStderr = std::make_unique<std::ostream>(std::cerr.rdbuf());
        rawStderrMutex = std::make_unique<std::mutex>();

#if defined(_WIN32) && defined(_DEBUG)
        // Redirect cout and cerr to VS debug output when running in debug mode
        sb.open(DebugOutput());
        std::cout.rdbuf(&sb);
        std::cerr.rdbuf(&sb);
#else
        constexpr std::size_t bufferCapacity = 1024;

        bufferedOut.open(Tee(Buffer(bufferCapacity, globalBuffer), Coloured(*rawStdout)));
        bufferedErr.open(Tee(Buffer(bufferCapacity, globalBuffer), Coloured(*rawStderr)));

        std::cout.rdbuf(&bufferedOut);
        std::cerr.rdbuf(&bufferedErr);
#endif

        int ret = 0;
        try
        {
            if (const auto env = std::getenv("OPENMW_DISABLE_CRASH_CATCHER");
                env == nullptr || Misc::StringUtils::toNumeric<int>(env, 0) == 0)
            {
#if defined(_WIN32)
                const std::string crashDumpName = Misc::StringUtils::lowerCase(appName) + "-crash.dmp";
                const std::string freezeDumpName = Misc::StringUtils::lowerCase(appName) + "-freeze.dmp";
                std::filesystem::path dumpDirectory = std::filesystem::temp_directory_path();
                PWSTR userProfile = nullptr;
                if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Profile, 0, nullptr, &userProfile)))
                {
                    dumpDirectory = userProfile;
                }
                CoTaskMemFree(userProfile);
                Crash::CrashCatcher crashy(argc, argv, dumpDirectory, crashDumpName, freezeDumpName);
#else
                const std::string crashLogName = Misc::StringUtils::lowerCase(appName) + "-crash.log";
                // install the crash handler as soon as possible.
                crashCatcherInstall(argc, argv, std::filesystem::temp_directory_path() / crashLogName);
#endif
                ret = innerApplication(argc, argv);
            }
            else
                ret = innerApplication(argc, argv);
        }
        catch (const std::exception& e)
        {
#if (defined(__APPLE__) || defined(__linux) || defined(__unix) || defined(__posix))
            if (!isatty(fileno(stdin)))
#endif
                SDL_ShowSimpleMessageBox(0, (std::string(appName) + ": Fatal error").c_str(), e.what(), nullptr);

            Log(Debug::Error) << "Fatal error: " << e.what();

            ret = 1;
        }

        // Restore cout and cerr
        std::cout.rdbuf(rawStdout->rdbuf());
        std::cerr.rdbuf(rawStderr->rdbuf());

        Log::sMinDebugLevel = All;
        Log::sWriteLevel = false;

        return ret;
    }
}