-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProtected.h
More file actions
535 lines (441 loc) · 13.1 KB
/
Protected.h
File metadata and controls
535 lines (441 loc) · 13.1 KB
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
/*************************************************************************************
cpl - cross-platform library - v. 0.1.0.
Copyright (C) 2016 Janus Lynggaard Thorborg (www.jthorborg.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
See \licenses\ for additional details on licenses associated with this program.
**************************************************************************************
file:Protected.h
Defines a wrapper call that catches system-level exceptions through a platform
independant interface.
*************************************************************************************/
#ifndef CPL_PROTECTED_H
#define CPL_PROTECTED_H
// Avoid PlatformSpecific.h, as that'll pull in JUCE if available.
#include "MacroConstants.h"
#ifdef CPL_WINDOWS
#include <excpt.h>
#endif
#include "LibraryOptions.h"
#include <vector>
#include <signal.h>
#include <thread>
#include <map>
#include <sstream>
#include "Utility.h"
#include <memory>
#include "Exceptions.h"
#define CPL_TRACEGUARD_START \
cpl::CProtected::instance().topLevelTraceGuardedCode([&]() {
#define CPL_TRACEGUARD_STOP(traceGuardName) \
}, traceGuardName)
namespace cpl
{
class CProtected final : Utility::CNoncopyable
{
struct Throwable
{
virtual ~Throwable() {};
virtual void throwImpl() = 0;
};
struct PendingException
{
bool isPending() const noexcept
{
return throwable.get() != nullptr;
}
void throwException()
{
if (!isPending())
CPL_RUNTIME_EXCEPTION_SPECIFIC("not pending", std::logic_error);
auto local = std::move(throwable);
local->throwImpl();
}
void reset(std::unique_ptr<Throwable> newThrowable)
{
throwable = std::move(newThrowable);
}
void reset(Throwable* newThrowable)
{
throwable.reset(newThrowable);
}
private:
std::unique_ptr<Throwable> throwable;
};
template<typename Exception>
struct ThrowableException : std::enable_if<std::is_base_of<std::exception, Exception>::value, Throwable>::type
{
ThrowableException(Exception&& e) : storage(std::move(e)) {}
void throwImpl() override
{
throw storage;
}
Exception storage;
};
#ifndef CPL_MSVC
struct ScopedThreadSignalHandler
{
ScopedThreadSignalHandler()
{
struct sigaction handler {};
handler.sa_sigaction = &CProtected::signalActionHandler;
handler.sa_flags = SA_SIGINFO;
sigemptyset(&handler.sa_mask);
sigaction(SIGILL, &handler, &oldSigIll);
sigaction(SIGSEGV, &handler, &oldSigSegv);
sigaction(SIGFPE, &handler, &oldSigFPE);
sigaction(SIGBUS, &handler, &oldSigBus);
}
~ScopedThreadSignalHandler()
{
sigaction(SIGILL, &oldSigIll, nullptr);
sigaction(SIGSEGV, &oldSigSegv, nullptr);
sigaction(SIGFPE, &oldSigFPE, nullptr);
sigaction(SIGBUS, &oldSigBus, nullptr);
}
struct sigaction
oldSigIll,
oldSigSegv,
oldSigFPE,
oldSigBus;
};
#endif
public:
struct CSystemException;
struct PreembeddedFormatter
{
PreembeddedFormatter(const char * prefixToEmbed)
: prefix(prefixToEmbed)
{
}
std::stringstream & get()
{
if (!hasBeenConstructed)
{
stream.reference() << "Handler: " << prefix << '\n';
hasBeenConstructed = true;
}
return stream.reference();
}
private:
const char * prefix;
bool hasBeenConstructed = false;
Utility::LazyStackPointer<std::stringstream> stream;
};
static std::string formatExceptionMessage(const CSystemException &);
static CProtected & instance();
/// <summary>
/// calls lambda inside 'safe wrappers', catches OS errors and filters them.
/// Throws CSystemException on errors, crashes on unrecoverable errors.
///
/// Does NOT catch software exceptions, but it IS C++ exception safe.
/// Additionally, if you want to catch C++ exceptions across external
/// code, you have to use this function (and Proctected::throwException{T}()).
///
/// Is NOT guaranteed to capture all system hardware exceptions/signals,
/// in general only those that are synchronous.
/// Guaranteed handled exceptions:
/// segmentation violations, bus errors, floating point exceptions, illegal instructions.
///
/// This function is reentrant (with expected behaviour), and safe in multithreaded programs.
///
/// Note that the stack may NOT (until this point) be unwound,
/// so consider your program to be in an UNDEFINED state; write some info to a file and crash gracefully
/// afterwards!
/// </summary>
template <class func>
void runProtectedCode(func && function)
{
auto oldThreadData = std::move(threadData);
threadData.isInStack = true;
auto scopeRelease = [&]()
{
threadData = std::move(oldThreadData);
};
Utility::OnScopeExit<decltype(scopeRelease)> releaser(
scopeRelease
);
#ifdef CPL_MSVC
[&]() {
bool exception_caught = false;
CSystemException::Storage exceptionData;
__try {
function();
}
__except (structuredExceptionHandler(GetExceptionCode(), exceptionData, GetExceptionInformation()))
{
// this is a way of leaving the SEH block before we throw a C++ software exception
exception_caught = true;
}
if (exception_caught)
{
throw CSystemException(exceptionData);
}
} ();
#else
ScopedThreadSignalHandler h;
// set the jump in case a signal gets raised
if (sigsetjmp(threadData.threadJumpBuffer, 1))
{
if (threadData.pendingException.isPending())
threadData.pendingException.throwException();
/*
return from exception handler.
current exception is in CState::currentException
*/
throw CSystemException(threadData.currentExceptionData);
}
// run the potentially bad code
function();
#endif
}
template <class func>
auto topLevelTraceGuardedCode(
func && function,
const char * levelDescription = "Top-level exception/signal handler")
-> decltype(function())
{
PreembeddedFormatter debugOutput(levelDescription);
auto oldThreadData = std::move(threadData);
threadData.isInStack = true;
threadData.traceIntercept = true;
threadData.propagate = true;
threadData.debugTraceBuffer = &debugOutput;
auto scopeRelease = [&]()
{
threadData = std::move(oldThreadData);
};
Utility::OnScopeExit<decltype(scopeRelease)> releaser(
scopeRelease
);
// in this frame we catch signals and SEH exceptions.
#ifdef CPL_MSVC
return internalSEHTraceInterceptor(debugOutput, function);
#else
// async signals will be captured further up
return internalSignalTraceInterceptor(debugOutput, function);
#endif
}
template <class func>
static void runProtectedCodeErrorHandling(func && function)
{
try
{
CProtected::instance().runProtectedCode
(
[&]()
{
function();
}
);
}
catch (CProtected::CSystemException & cs)
{
auto error = CProtected::formatExceptionMessage(cs);
LogException(error);
CrashIfUserDoesntDebug(error);
cs.reraise();
}
catch (std::exception & e)
{
auto error = e.what();
LogException(error);
CrashIfUserDoesntDebug(error);
throw;
}
}
/*
Base exception for all critical exceptions thrown in this program.
Derives from std::exception, but has no meaningful .what()
- See Protected::formatExceptionMessage
*/
struct CSystemException : public std::exception
{
public:
enum class Status
{
nullptr_from_plugin = 1,
access_violation = SIGSEGV,
intdiv_zero,
fdiv_zero,
finvalid,
fdenormal,
finexact,
foverflow,
funderflow,
intsubscript,
intoverflow,
undefined_behaviour
};
struct Storage
{
const void * faultAddr; // the address the exception occured
const void * attemptedAddr; // if exception is a memory violation, this is the attempted address
Status exceptCode; // the exception code
int extraInfoCode; // additional, exception-specific code
int actualCode; // what signal it was
union {
// hack hack union
bool safeToContinue; // exception not critical or can be handled
bool aVInProtectedMemory; // whether an access violation happened in our protected memory
};
static Storage create(Status code, bool resolved = true, const void * faultAddress = nullptr,
const void * attemptedAddress = nullptr, int extraCode = 0, int actualCode = 0)
{
return {faultAddress, attemptedAddress, code, extraCode, actualCode, resolved};
}
static Storage create()
{
return {};
}
} data;
CSystemException()
: data(Storage::create())
{
}
CSystemException(const Storage & eData)
{
data = eData;
}
void reraise() const;
CSystemException(Status code, bool resolved = true, const void * faultAddress = nullptr, const void * attemptedAddress = nullptr, int extraCode = 0, int actualCode = 0)
{
data = Storage::create(code, resolved, faultAddress, attemptedAddress, extraCode, actualCode);
}
const char * what() const noexcept override
{
return "OS specific hardware exception";
}
};
template<typename Exception, typename... Args>
void throwException(Args&&... args)
{
#ifndef CPL_MSVC
if (!threadData.isInStack)
throw Exception(args...);
else
{
threadData.pendingException.reset(new ThrowableException<Exception>(Exception(args...)));
siglongjmp(threadData.threadJumpBuffer, OSCustomRaiseCode);
}
#else
throw Exception(args...);
#endif
}
~CProtected();
protected:
CProtected();
private:
template <class func>
auto internalCxxTraceInterceptor(PreembeddedFormatter & out, func && function)
-> decltype(function())
{
// in this frame, we catch C++ software exceptions
try
{
return function();
}
catch (CProtected::CSystemException & cs)
{
out.get() << "Hardware -> " << CProtected::formatExceptionMessage(cs) << '\n';
out.get() << "what() -> " << cs.what() << '\n';
LogException(out.get().str());
CrashIfUserDoesntDebug(out.get().str());
throw;
}
catch (std::exception & e)
{
out.get() << "Software -> " << e.what() << '\n';
LogException(out.get().str());
CrashIfUserDoesntDebug(out.get().str());
throw;
}
catch (...)
{
out.get() << "Unknown software exception";
LogException(out.get().str());
CrashIfUserDoesntDebug(out.get().str());
throw;
}
}
template <class func>
auto internalSEHTraceInterceptor(PreembeddedFormatter & out, func && function)
-> decltype(function())
{
#ifdef CPL_MSVC
CSystemException::Storage exceptionInformation;
__try
{
return internalCxxTraceInterceptor(out, function);
}
__except (structuredExceptionHandlerTraceInterceptor(
out,
GetExceptionCode(),
exceptionInformation,
GetExceptionInformation())
)
{
std::terminate();
}
#endif
}
template <class func>
auto internalSignalTraceInterceptor(PreembeddedFormatter & out, func && function)
-> decltype(function())
{
#ifndef CPL_MSVC
ScopedThreadSignalHandler h;
// set the jump in case a signal gets raised
if (sigsetjmp(threadData.threadJumpBuffer, 1))
{
/*
return from exception handler.
current exception is in CState::currentException
*/
throw CSystemException(threadData.currentExceptionData);
}
return internalCxxTraceInterceptor(out, function);
#endif
}
struct ThreadData
{
/// <summary>
/// Thread local set on entry and exit of protected code stack frames.
/// </summary>
bool isInStack;
/// <summary>
/// If set, exception will be propagated further in the handler chain
/// </summary>
bool propagate;
/// <summary>
/// If set, logs debug output, presents a message box with debugging abilities
/// </summary>
bool traceIntercept;
/// <summary>
/// A pre-allocated buffer that can be used for scratch space
/// </summary>
PreembeddedFormatter * debugTraceBuffer;
#ifndef CPL_MSVC
sigjmp_buf threadJumpBuffer;
CSystemException::Storage currentExceptionData;
PendingException pendingException;
#endif
unsigned fpuMask;
};
static CPL_THREAD_LOCAL ThreadData threadData;
XWORD structuredExceptionHandler(XWORD _code, CSystemException::Storage & e, void * _systemInformation);
XWORD structuredExceptionHandlerTraceInterceptor(PreembeddedFormatter & outputStream, XWORD _code, CSystemException::Storage & e, void * _systemInformation);
static void signalTraceInterceptor(CSystemException::Storage & e);
static void signalHandler(int some_number);
static void signalActionHandler(int signal, siginfo_t * siginfo, void * extraData);
};
};
#endif