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
|
/*
* ExceptionHandler.cpp
* --------------------
* Purpose: Code for handling crashes (unhandled exceptions) in OpenMPT.
* Notes : (currently none)
* Authors: OpenMPT Devs
* The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
*/
#include "stdafx.h"
#include "Mainfrm.h"
#include "Mptrack.h"
#include "AboutDialog.h"
#include "InputHandler.h"
#include "openmpt/sounddevice/SoundDevice.hpp"
#include "Moddoc.h"
#include <shlwapi.h>
#include "ExceptionHandler.h"
#include "../misc/WriteMemoryDump.h"
#include "../common/version.h"
#include "../common/mptFileIO.h"
#include "../soundlib/mod_specifications.h"
#include <atomic>
OPENMPT_NAMESPACE_BEGIN
// Write full memory dump instead of minidump.
bool ExceptionHandler::fullMemDump = false;
bool ExceptionHandler::stopSoundDeviceOnCrash = true;
bool ExceptionHandler::stopSoundDeviceBeforeDump = false;
// Delegate to system-specific crash processing once our own crash handler is
// finished. This is useful to allow attaching a debugger.
bool ExceptionHandler::delegateToWindowsHandler = false;
// Allow debugging the unhandled exception filter. Normally, if a debugger is
// attached, no exceptions are unhandled because the debugger handles them. If
// debugExceptionHandler is true, an additional __try/__catch is inserted around
// InitInstance(), ExitInstance() and the main message loop, which will call our
// filter, which then can be stepped through in a debugger.
bool ExceptionHandler::debugExceptionHandler = false;
bool ExceptionHandler::useAnyCrashHandler = false;
bool ExceptionHandler::useImplicitFallbackSEH = false;
bool ExceptionHandler::useExplicitSEH = false;
bool ExceptionHandler::handleStdTerminate = false;
bool ExceptionHandler::handleMfcExceptions = false;
static thread_local ExceptionHandler::Context *g_Context = nullptr;
static LPTOP_LEVEL_EXCEPTION_FILTER g_OriginalUnhandledExceptionFilter = nullptr;
static std::terminate_handler g_OriginalTerminateHandler = nullptr;
static UINT g_OriginalErrorMode = 0;
ExceptionHandler::Context *ExceptionHandler::SetContext(Context *newContext) noexcept
{
Context *oldContext = g_Context;
g_Context = newContext;
return oldContext;
}
static std::atomic<int> & g_CrashCount()
{
static std::atomic<int> s_CrashCount(0);
return s_CrashCount;
}
static std::atomic<int> & g_TaintCountDriver()
{
static std::atomic<int> s_TaintCountDriver(0);
return s_TaintCountDriver;
}
static std::atomic<int> & g_TaintCountPlugin()
{
static std::atomic<int> s_TaintCountPlugin(0);
return s_TaintCountPlugin;
}
void ExceptionHandler::TaintProcess(ExceptionHandler::TaintReason reason)
{
switch(reason)
{
case ExceptionHandler::TaintReason::Driver:
g_TaintCountDriver().fetch_add(1);
break;
case ExceptionHandler::TaintReason::Plugin:
g_TaintCountPlugin().fetch_add(1);
break;
default:
MPT_ASSERT_NOTREACHED();
break;
}
}
enum DumpMode
{
DumpModeCrash = 0, // crash
DumpModeWarning = 1, // assert
DumpModeDebug = 2, // debug output (e.g. trace log)
};
struct CrashOutputDirectory
{
bool valid;
mpt::PathString path;
CrashOutputDirectory()
: valid(true)
{
const mpt::PathString timestampDir = mpt::PathString::FromCString((CTime::GetCurrentTime()).Format(_T("%Y-%m-%d %H.%M.%S\\")));
// Create a crash directory
path = mpt::GetTempDirectory() + P_("OpenMPT Crash Files\\");
if(!path.IsDirectory())
{
CreateDirectory(path.AsNative().c_str(), nullptr);
}
// Set compressed attribute in order to save disk space.
// Debugging information should clutter the users computer as little as possible.
// Performance is not important here.
// Ignore any errors.
SetFilesystemCompression(path);
// Compression will be inherited by children directories and files automatically.
path += timestampDir;
if(!path.IsDirectory())
{
if(!CreateDirectory(path.AsNative().c_str(), nullptr))
{
valid = false;
}
}
}
};
class DebugReporter
{
private:
int crashCount;
int taintCountDriver;
int taintCountPlugin;
bool stateFrozen;
const DumpMode mode;
const CrashOutputDirectory crashDirectory;
bool writtenMiniDump;
bool writtenTraceLog;
int rescuedFiles;
private:
static bool FreezeState(DumpMode mode);
static bool Cleanup(DumpMode mode);
bool GenerateDump(_EXCEPTION_POINTERS *pExceptionInfo);
bool GenerateTraceLog();
int RescueFiles();
bool HasWrittenDebug() const { return writtenMiniDump || writtenTraceLog; }
static void StopSoundDevice();
public:
DebugReporter(DumpMode mode, _EXCEPTION_POINTERS *pExceptionInfo);
~DebugReporter();
void ReportError(mpt::ustring errorMessage);
};
DebugReporter::DebugReporter(DumpMode mode, _EXCEPTION_POINTERS *pExceptionInfo)
: crashCount(g_CrashCount().fetch_add(1) + 1)
, taintCountDriver(g_TaintCountDriver().load())
, taintCountPlugin(g_TaintCountPlugin().load())
, stateFrozen(FreezeState(mode))
, mode(mode)
, writtenMiniDump(false)
, writtenTraceLog(false)
, rescuedFiles(0)
{
if(mode == DumpModeCrash || mode == DumpModeWarning)
{
writtenMiniDump = GenerateDump(pExceptionInfo);
}
if(mode == DumpModeCrash || mode == DumpModeWarning || mode == DumpModeDebug)
{
writtenTraceLog = GenerateTraceLog();
}
if(mode == DumpModeCrash || mode == DumpModeWarning)
{
rescuedFiles = RescueFiles();
}
}
DebugReporter::~DebugReporter()
{
Cleanup(mode);
}
bool DebugReporter::GenerateDump(_EXCEPTION_POINTERS *pExceptionInfo)
{
return WriteMemoryDump(pExceptionInfo, (crashDirectory.path + P_("crash.dmp")).AsNative().c_str(), ExceptionHandler::fullMemDump);
}
bool DebugReporter::GenerateTraceLog()
{
return mpt::log::Trace::Dump(crashDirectory.path + P_("trace.log"));
}
static void SaveDocumentSafe(CModDoc *pModDoc, const mpt::PathString &filename)
{
__try
{
pModDoc->OnSaveDocument(filename);
} __except(EXCEPTION_EXECUTE_HANDLER)
{
// nothing
}
}
// Rescue modified files...
int DebugReporter::RescueFiles()
{
int numFiles = 0;
auto documents = theApp.GetOpenDocuments();
for(auto modDoc : documents)
{
if(modDoc->IsModified())
{
if(numFiles == 0)
{
// Show the rescue directory in Explorer...
CTrackApp::OpenDirectory(crashDirectory.path);
}
mpt::PathString filename;
filename += crashDirectory.path;
filename += mpt::PathString::FromUnicode(mpt::ufmt::val(++numFiles));
filename += P_("_");
filename += mpt::PathString::FromCString(modDoc->GetTitle()).SanitizeComponent();
filename += P_(".");
filename += mpt::PathString::FromUTF8(modDoc->GetSoundFile().GetModSpecifications().fileExtension);
try
{
SaveDocumentSafe(modDoc, filename);
} catch(...)
{
continue;
}
}
}
return numFiles;
}
void DebugReporter::ReportError(mpt::ustring errorMessage)
{
if(!crashDirectory.valid)
{
errorMessage += UL_("\n\n");
errorMessage += UL_("Could not create the following directory for saving debug information and modified files to:\n");
errorMessage += crashDirectory.path.ToUnicode();
}
if(HasWrittenDebug())
{
errorMessage += UL_("\n\n");
errorMessage += UL_("Debug information has been saved to\n");
errorMessage += crashDirectory.path.ToUnicode();
}
if(rescuedFiles > 0)
{
errorMessage += UL_("\n\n");
if(rescuedFiles == 1)
{
errorMessage += UL_("1 modified file has been rescued, but it cannot be guaranteed that it is still intact.");
} else
{
errorMessage += MPT_UFORMAT("{} modified files have been rescued, but it cannot be guaranteed that they are still intact.")(rescuedFiles);
}
}
errorMessage += UL_("\n\n");
errorMessage += MPT_UFORMAT("OpenMPT {} {} ({} ({}))")
( Build::GetVersionStringExtended()
, mpt::OS::Windows::Name(mpt::OS::Windows::GetProcessArchitecture())
, SourceInfo::Current().GetUrlWithRevision()
, SourceInfo::Current().GetStateString()
);
errorMessage += UL_("\n\n");
errorMessage += MPT_UFORMAT("Session error count: {}\n")(crashCount);
if(taintCountDriver > 0 || taintCountPlugin > 0)
{
errorMessage += UL_("Process is in tainted state!\n");
errorMessage += MPT_UFORMAT("Previously masked driver crashes: {}\n")(taintCountDriver);
errorMessage += MPT_UFORMAT("Previously masked plugin crashes: {}\n")(taintCountPlugin);
}
errorMessage += UL_("\n");
{
mpt::SafeOutputFile sf(crashDirectory.path + P_("error.txt"), std::ios::binary, mpt::FlushMode::Full);
mpt::ofstream& f = sf;
f.imbue(std::locale::classic());
f << mpt::replace(mpt::ToCharset(mpt::Charset::UTF8, errorMessage), std::string("\n"), std::string("\r\n"));
}
if(auto ih = CMainFrame::GetInputHandler(); ih != nullptr)
{
mpt::SafeOutputFile sf(crashDirectory.path + P_("last-commands.txt"), std::ios::binary, mpt::FlushMode::Full);
mpt::ofstream &f = sf;
f.imbue(std::locale::classic());
const auto commandSet = ih->m_activeCommandSet.get();
f << "Last commands:\n";
for(size_t i = 0; i < ih->m_lastCommands.size(); i++)
{
CommandID id = ih->m_lastCommands[(ih->m_lastCommandPos + i) % ih->m_lastCommands.size()];
if(id == kcNull)
continue;
f << mpt::afmt::val(id);
if(commandSet)
f << " (" << mpt::ToCharset(mpt::Charset::UTF8, commandSet->GetCommandText(id)) << ")";
f << "\n";
}
}
{
mpt::SafeOutputFile sf(crashDirectory.path + P_("threads.txt"), std::ios::binary, mpt::FlushMode::Full);
mpt::ofstream& f = sf;
f.imbue(std::locale::classic());
f << MPT_AFORMAT("current : {}")(mpt::afmt::hex0<8>(GetCurrentThreadId())) << "\r\n";
f << MPT_AFORMAT("GUI : {}")(mpt::afmt::hex0<8>(mpt::log::Trace::GetThreadId(mpt::log::Trace::ThreadKindGUI))) << "\r\n";
f << MPT_AFORMAT("Audio : {}")(mpt::afmt::hex0<8>(mpt::log::Trace::GetThreadId(mpt::log::Trace::ThreadKindAudio))) << "\r\n";
f << MPT_AFORMAT("Notify : {}")(mpt::afmt::hex0<8>(mpt::log::Trace::GetThreadId(mpt::log::Trace::ThreadKindNotify))) << "\r\n";
f << MPT_AFORMAT("WatchDir: {}")(mpt::afmt::hex0<8>(mpt::log::Trace::GetThreadId(mpt::log::Trace::ThreadKindWatchdir))) << "\r\n";
}
static constexpr struct { const mpt::uchar * section; const mpt::uchar * key; } configAnonymize[] =
{
{ UL_("Version"), UL_("InstallGUID") },
{ UL_("Recent File List"), nullptr },
};
{
mpt::SafeOutputFile sf(crashDirectory.path + P_("active-settings.txt"), std::ios::binary, mpt::FlushMode::Full);
mpt::ofstream& f = sf;
f.imbue(std::locale::classic());
if(theApp.GetpSettings())
{
SettingsContainer &settings = theApp.GetSettings();
for(const auto &it : settings)
{
bool skipPath = false;
for(const auto &path : configAnonymize)
{
if((path.key == nullptr && path.section == it.first.GetRefSection()) // Omit entire section
|| (path.key != nullptr && it.first == SettingPath(path.section, path.key))) // Omit specific key
{
skipPath = true;
}
}
if(skipPath)
{
continue;
}
f
<< mpt::ToCharset(mpt::Charset::UTF8, it.first.FormatAsString() + U_(" = ") + it.second.GetRefValue().FormatValueAsString())
<< std::endl;
}
}
}
{
const mpt::PathString crashStoredSettingsFilename = crashDirectory.path + P_("stored-mptrack.ini");
CopyFile
( theApp.GetConfigFileName().AsNative().c_str()
, crashStoredSettingsFilename.AsNative().c_str()
, FALSE
);
IniFileSettingsContainer crashStoredSettings{crashStoredSettingsFilename};
for(const auto &path : configAnonymize)
{
if(path.key)
{
crashStoredSettings.Write(SettingPath(path.section, path.key), SettingValue(mpt::ustring()));
} else
{
crashStoredSettings.Remove(path.section);
}
}
crashStoredSettings.Flush();
}
/*
// This is very slow, we instead write active-settings.txt above.
{
IniFileSettingsBackend f(crashDirectory.path + P_("active-mptrack.ini"));
if(theApp.GetpSettings())
{
SettingsContainer & settings = theApp.GetSettings();
for(const auto &it : settings)
{
f.WriteSetting(it.first, it.second.GetRefValue());
}
}
}
*/
{
mpt::SafeOutputFile sf(crashDirectory.path + P_("about-openmpt.txt"), std::ios::binary, mpt::FlushMode::Full);
mpt::ofstream& f = sf;
f.imbue(std::locale::classic());
f << mpt::ToCharset(mpt::Charset::UTF8, CAboutDlg::GetTabText(0));
}
{
mpt::SafeOutputFile sf(crashDirectory.path + P_("about-components.txt"), std::ios::binary, mpt::FlushMode::Full);
mpt::ofstream& f = sf;
f.imbue(std::locale::classic());
f << mpt::ToCharset(mpt::Charset::UTF8, CAboutDlg::GetTabText(1));
}
Reporting::Error(errorMessage, (mode == DumpModeWarning) ? "OpenMPT Warning" : "OpenMPT Crash", CMainFrame::GetMainFrame());
}
// Freezes the state as much as possible in order to avoid further confusion by
// other (possibly still running) threads
bool DebugReporter::FreezeState(DumpMode mode)
{
MPT_TRACE();
// seal the trace log as early as possible
mpt::log::Trace::Seal();
if(mode == DumpModeCrash || mode == DumpModeWarning)
{
if(CMainFrame::GetMainFrame() && CMainFrame::GetMainFrame()->gpSoundDevice && CMainFrame::GetMainFrame()->gpSoundDevice->DebugIsFragileDevice())
{
// For fragile devices, always stop the device. Stop before the dumping if not in realtime context.
if(!CMainFrame::GetMainFrame()->gpSoundDevice->DebugInRealtimeCallback())
{
StopSoundDevice();
}
} else
{
if(ExceptionHandler::stopSoundDeviceOnCrash && ExceptionHandler::stopSoundDeviceBeforeDump)
{
StopSoundDevice();
}
}
}
return true;
}
static void StopSoundDeviceSafe(CMainFrame *pMainFrame)
{
__try
{
if(pMainFrame->gpSoundDevice)
{
pMainFrame->gpSoundDevice->Close();
}
if(pMainFrame->m_NotifyTimer)
{
pMainFrame->KillTimer(pMainFrame->m_NotifyTimer);
pMainFrame->m_NotifyTimer = 0;
}
} __except(EXCEPTION_EXECUTE_HANDLER)
{
// nothing
}
}
void DebugReporter::StopSoundDevice()
{
CMainFrame* pMainFrame = CMainFrame::GetMainFrame();
if(pMainFrame)
{
try
{
StopSoundDeviceSafe(pMainFrame);
} catch(...)
{
// nothing
}
}
}
bool DebugReporter::Cleanup(DumpMode mode)
{
MPT_TRACE();
if(mode == DumpModeCrash || mode == DumpModeWarning)
{
if(CMainFrame::GetMainFrame() && CMainFrame::GetMainFrame()->gpSoundDevice && CMainFrame::GetMainFrame()->gpSoundDevice->DebugIsFragileDevice())
{
// For fragile devices, always stop the device. Stop after the dumping if in realtime context.
if(CMainFrame::GetMainFrame()->gpSoundDevice->DebugInRealtimeCallback())
{
StopSoundDevice();
}
} else
{
if(ExceptionHandler::stopSoundDeviceOnCrash && !ExceptionHandler::stopSoundDeviceBeforeDump)
{
StopSoundDevice();
}
}
}
return true;
}
// Different entry points for different situations in which we want to dump some information
static bool IsCxxException(_EXCEPTION_POINTERS *pExceptionInfo)
{
if (!pExceptionInfo)
return false;
if (!pExceptionInfo->ExceptionRecord)
return false;
if (pExceptionInfo->ExceptionRecord->ExceptionCode != 0xE06D7363u)
return false;
return true;
}
template <typename E>
static const E * GetCxxException(_EXCEPTION_POINTERS *pExceptionInfo)
{
// https://blogs.msdn.microsoft.com/oldnewthing/20100730-00/?p=13273
struct info_a_t
{
DWORD bitmask; // Probably: 1=Const, 2=Volatile
DWORD destructor; // RVA (Relative Virtual Address) of destructor for that exception object
DWORD unknown;
DWORD catchableTypesPtr; // RVA of instance of type "B"
};
struct info_c_t
{
DWORD someBitmask;
DWORD typeInfo; // RVA of std::type_info for that type
DWORD memberDisplacement; // Add to ExceptionInformation[1] in EXCEPTION_RECORD to obtain 'this' pointer.
DWORD virtBaseRelated1; // -1 if no virtual base
DWORD virtBaseRelated2; // ?
DWORD objectSize; // Size of the object in bytes
DWORD probablyCopyCtr; // RVA of copy constructor (?)
};
if(!pExceptionInfo)
return nullptr;
if (!pExceptionInfo->ExceptionRecord)
return nullptr;
if(pExceptionInfo->ExceptionRecord->ExceptionCode != 0xE06D7363u)
return nullptr;
#ifdef _WIN64
if(pExceptionInfo->ExceptionRecord->NumberParameters != 4)
return nullptr;
#else
if(pExceptionInfo->ExceptionRecord->NumberParameters != 3)
return nullptr;
#endif
if(pExceptionInfo->ExceptionRecord->ExceptionInformation[0] != 0x19930520u)
return nullptr;
std::uintptr_t base_address = 0;
#ifdef _WIN64
base_address = pExceptionInfo->ExceptionRecord->ExceptionInformation[3];
#else
base_address = 0;
#endif
std::uintptr_t obj_address = pExceptionInfo->ExceptionRecord->ExceptionInformation[1];
if(!obj_address)
return nullptr;
std::uintptr_t info_a_address = pExceptionInfo->ExceptionRecord->ExceptionInformation[2];
if(!info_a_address)
return nullptr;
const info_a_t * info_a = reinterpret_cast<const info_a_t *>(info_a_address);
std::uintptr_t info_b_offset = info_a->catchableTypesPtr;
if(!info_b_offset)
return nullptr;
const DWORD * info_b = reinterpret_cast<const DWORD *>(base_address + info_b_offset);
for(DWORD type = 1; type <= info_b[0]; ++type)
{
std::uintptr_t info_c_offset = info_b[type];
if(!info_c_offset)
continue;
const info_c_t * info_c = reinterpret_cast<const info_c_t *>(base_address + info_c_offset);
if(!info_c->typeInfo)
continue;
const std::type_info * ti = reinterpret_cast<const std::type_info *>(base_address + info_c->typeInfo);
if(*ti != typeid(E))
continue;
const E * e = reinterpret_cast<const E *>(obj_address + info_c->memberDisplacement);
return e;
}
return nullptr;
}
void ExceptionHandler::UnhandledMFCException(CException * e, const MSG * pMsg)
{
DebugReporter report(DumpModeCrash, nullptr);
mpt::ustring errorMessage;
if(e && dynamic_cast<CSimpleException*>(e))
{
TCHAR tmp[1024 + 1];
MemsetZero(tmp);
if(dynamic_cast<CSimpleException*>(e)->GetErrorMessage(tmp, static_cast<UINT>(std::size(tmp) - 1)) != 0)
{
tmp[1024] = 0;
errorMessage = MPT_UFORMAT("Unhandled MFC exception occurred while processming window message '{}': {}.")
(mpt::ufmt::dec(pMsg ? pMsg->message : 0)
, mpt::ToUnicode(CString(tmp))
);
} else
{
errorMessage = MPT_UFORMAT("Unhandled MFC exception occurred while processming window message '{}': {}.")
(mpt::ufmt::dec(pMsg ? pMsg->message : 0)
, mpt::ToUnicode(CString(tmp))
);
}
}
else
{
errorMessage = MPT_UFORMAT("Unhandled MFC exception occurred while processming window message '{}'.")
( mpt::ufmt::dec(pMsg ? pMsg->message : 0)
);
}
report.ReportError(errorMessage);
}
static void UnhandledExceptionFilterImpl(_EXCEPTION_POINTERS *pExceptionInfo)
{
DebugReporter report(DumpModeCrash, pExceptionInfo);
mpt::ustring errorMessage;
const std::exception * pE = GetCxxException<std::exception>(pExceptionInfo);
if(g_Context)
{
if(!g_Context->description.empty())
{
errorMessage += MPT_UFORMAT("OpenMPT detected a crash in '{}'.\nThis is very likely not an OpenMPT bug. Please report the problem to the respective software author.\n")(g_Context->description);
} else
{
errorMessage += MPT_UFORMAT("OpenMPT detected a crash in unknown foreign code.\nThis is likely not an OpenMPT bug.\n")();
}
}
if(pE)
{
const std::exception & e = *pE;
errorMessage += MPT_UFORMAT("Unhandled C++ exception '{}' occurred at address 0x{}: '{}'.")
( mpt::ToUnicode(mpt::Charset::ASCII, typeid(e).name())
, mpt::ufmt::hex0<mpt::pointer_size*2>(reinterpret_cast<std::uintptr_t>(pExceptionInfo->ExceptionRecord->ExceptionAddress))
, mpt::get_exception_text<mpt::ustring>(e)
);
} else
{
errorMessage += MPT_UFORMAT("Unhandled exception 0x{} at address 0x{} occurred.")
( mpt::ufmt::HEX0<8>(pExceptionInfo->ExceptionRecord->ExceptionCode)
, mpt::ufmt::hex0<mpt::pointer_size*2>(reinterpret_cast<std::uintptr_t>(pExceptionInfo->ExceptionRecord->ExceptionAddress))
);
}
report.ReportError(errorMessage);
}
LONG ExceptionHandler::UnhandledExceptionFilterContinue(_EXCEPTION_POINTERS *pExceptionInfo)
{
UnhandledExceptionFilterImpl(pExceptionInfo);
// Disable the call to std::terminate() as that would re-renter the crash
// handler another time, but with less information available.
#if 0
// MSVC implements calling std::terminate by its own UnhandledExeptionFilter.
// However, we do overwrite it here, thus we have to call std::terminate
// ourselves.
if (IsCxxException(pExceptionInfo))
{
std::terminate();
}
#endif
// Let a potential debugger handle the exception...
return EXCEPTION_CONTINUE_SEARCH;
}
LONG ExceptionHandler::ExceptionFilter(_EXCEPTION_POINTERS *pExceptionInfo)
{
UnhandledExceptionFilterImpl(pExceptionInfo);
// Let a potential debugger handle the exception...
return EXCEPTION_EXECUTE_HANDLER;
}
static void mpt_unexpected_handler();
static void mpt_terminate_handler();
void ExceptionHandler::Register()
{
if(useImplicitFallbackSEH)
{
g_OriginalUnhandledExceptionFilter = ::SetUnhandledExceptionFilter(&UnhandledExceptionFilterContinue);
}
if(handleStdTerminate)
{
g_OriginalTerminateHandler = std::set_terminate(&mpt_terminate_handler);
}
}
void ExceptionHandler::ConfigureSystemHandler()
{
#if (_WIN32_WINNT >= 0x0600)
if(delegateToWindowsHandler)
{
//SetErrorMode(0);
g_OriginalErrorMode = ::GetErrorMode();
} else
{
g_OriginalErrorMode = ::SetErrorMode(::GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
}
#else // _WIN32_WINNT < 0x0600
if(delegateToWindowsHandler)
{
g_OriginalErrorMode = ::SetErrorMode(0);
} else
{
g_OriginalErrorMode = ::SetErrorMode(::SetErrorMode(0) | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
}
#endif // _WIN32_WINNT
}
void ExceptionHandler::UnconfigureSystemHandler()
{
::SetErrorMode(g_OriginalErrorMode);
g_OriginalErrorMode = 0;
}
void ExceptionHandler::Unregister()
{
if(handleStdTerminate)
{
std::set_terminate(g_OriginalTerminateHandler);
g_OriginalTerminateHandler = nullptr;
}
if(useImplicitFallbackSEH)
{
::SetUnhandledExceptionFilter(g_OriginalUnhandledExceptionFilter);
g_OriginalUnhandledExceptionFilter = nullptr;
}
}
static void mpt_terminate_handler()
{
DebugReporter(DumpModeCrash, nullptr).ReportError(U_("A C++ runtime crash occurred: std::terminate() called."));
#if 1
std::abort();
#else
if(g_OriginalTerminateHandler)
{
g_OriginalTerminateHandler();
} else
{
std::abort();
}
#endif
}
#if defined(MPT_ASSERT_HANDLER_NEEDED)
MPT_NOINLINE void AssertHandler(const mpt::source_location &loc, const char *expr, const char *msg)
{
DebugReporter report(msg ? DumpModeWarning : DumpModeCrash, nullptr);
if(IsDebuggerPresent())
{
OutputDebugString(_T("ASSERT("));
OutputDebugString(mpt::ToWin(mpt::Charset::ASCII, expr).c_str());
OutputDebugString(_T(") failed\n"));
DebugBreak();
} else
{
mpt::ustring errorMessage;
if(msg)
{
errorMessage = MPT_UFORMAT("Internal state inconsistency detected at {}({}). This is just a warning that could potentially lead to a crash later on: {} [{}].")
( mpt::ToUnicode(mpt::Charset::ASCII, loc.file_name() ? loc.file_name() : "")
, loc.line()
, mpt::ToUnicode(mpt::Charset::ASCII, msg)
, mpt::ToUnicode(mpt::Charset::ASCII, loc.function_name() ? loc.function_name() : "")
);
} else
{
errorMessage = MPT_UFORMAT("Internal error occurred at {}({}): ASSERT({}) failed in [{}].")
( mpt::ToUnicode(mpt::Charset::ASCII, loc.file_name() ? loc.file_name() : "")
, loc.line()
, mpt::ToUnicode(mpt::Charset::ASCII, expr)
, mpt::ToUnicode(mpt::Charset::ASCII, loc.function_name() ? loc.function_name() : "")
);
}
report.ReportError(errorMessage);
}
}
#endif // MPT_ASSERT_HANDLER_NEEDED
void DebugInjectCrash()
{
DebugReporter(DumpModeCrash, nullptr).ReportError(U_("Injected crash."));
}
void DebugTraceDump()
{
DebugReporter report(DumpModeDebug, nullptr);
}
OPENMPT_NAMESPACE_END
|