File: exceptionhandler.cpp

package info (click to toggle)
warzone2100 4.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 660,348 kB
  • sloc: cpp: 675,711; ansic: 387,204; javascript: 75,107; python: 16,628; php: 4,294; sh: 3,941; makefile: 2,330; lisp: 1,492; cs: 489; xml: 404; perl: 224; ruby: 156; java: 89
file content (842 lines) | stat: -rw-r--r-- 23,157 bytes parent folder | download | duplicates (2)
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
/*
	This file is part of Warzone 2100.
	Copyright (C) 2007-2020  Warzone 2100 Project

	Warzone 2100 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 2 of the License, or
	(at your option) any later version.

	Warzone 2100 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 Warzone 2100; if not, write to the Free Software
	Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/

#define _WITH_DPRINTF  // Required for FreeBSD < 12 (?) for dprintf(); Must be before any include of stdio.h

#include "lib/framework/frame.h"
#include "lib/framework/string_ext.h"
#include "exceptionhandler.h"
#include "dumpinfo.h"
#include <LaunchInfo.h>

#if defined(WZ_OS_WIN)
#include <tchar.h>
#if defined( _MSC_VER )
	// Silence warning when using MSVC + the Windows 7 SDK (required for XP compatibility)
	//	warning C4091: 'typedef ': ignored on left of 'tagGPFIDL_FLAGS' when no variable is declared
	#pragma warning( push )
	#pragma warning( disable : 4091 )
#endif
#include <shlobj.h>
#if defined( _MSC_VER )
	#pragma warning( pop )
#endif
#include <shlwapi.h>

#include "exchndl.h"

#elif defined(WZ_OS_UNIX) && !defined(WZ_OS_MAC)

// C99 headers:
# include <stdint.h>
# include <signal.h>
# include <string.h>
# include <errno.h>

// POSIX headers:
# include <unistd.h>
# include <fcntl.h>
# include <time.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <sys/wait.h>
#ifdef HAVE_SYS_UCONTEXT_H
# include <sys/ucontext.h>
#endif
# include <sys/utsname.h>
#ifdef WZ_OS_LINUX
# include <sys/prctl.h>
#ifndef PR_SET_PTRACER
# define PR_SET_PTRACER 0x59616d61  // prctl will ignore unknown options
#endif
#endif

// GNU extension for backtrace():
# if defined(__GLIBC__)
#  include <execinfo.h>
#  define MAX_BACKTRACE 20
# endif

# define MAX_PID_STRING 16
# define MAX_DATE_STRING 256


#ifdef SA_SIGINFO
typedef void(*SigActionHandler)(int, siginfo_t *, void *);
#else
typedef void(*SigActionHandler)(int);
#endif


#ifdef WZ_OS_MAC
static struct sigaction oldAction[32];
#elif defined(_NSIG)
static struct sigaction oldAction[_NSIG];
#else
static struct sigaction oldAction[NSIG];
#endif


static struct utsname sysInfo;
static bool gdbIsAvailable = false, programIsAvailable = false, sysInfoValid = false;
static char
executionDate[MAX_DATE_STRING] = {'\0'},
                                 programPID[MAX_PID_STRING] = {'\0'},
                                         programPath[PATH_MAX] = {'\0'},
                                                 gdbPath[PATH_MAX] = {'\0'},
                                                         WritePath[PATH_MAX] = {'\0'};


/**
 * Signal number to string mapper.
 * Also takes into account the signal code with details about the signal.
 *
 * \param signum Signal number
 * \param sigcode Signal code
 * \return String with the description of the signal. "Unknown signal" when no description is available.
 */
#ifdef SA_SIGINFO
static const char *wz_strsignal(int signum, int sigcode)
{
	switch (signum)
	{
	case SIGABRT:
		return "SIGABRT: Process abort signal";
	case SIGALRM:
		return "SIGALRM: Alarm clock";
	case SIGBUS:
		switch (sigcode)
		{
#ifdef BUS_ADRALN
		case BUS_ADRALN:
			return "SIGBUS: Access to an undefined portion of a memory object: Invalid address alignment";
#endif /* BUS_ADRALN */
#ifdef BUS_ADRERR
		case BUS_ADRERR:
			return "SIGBUS: Access to an undefined portion of a memory object: Nonexistent physical address";
#endif /* BUS_ADRERR */
#ifdef BUS_OBJERR
		case BUS_OBJERR:
			return "SIGBUS: Access to an undefined portion of a memory object: Object-specific hardware error";
#endif /* BUS_OBJERR */
		default:
			return "SIGBUS: Access to an undefined portion of a memory object";
		}
	case SIGFPE:
		switch (sigcode)
		{
#ifdef FPE_INTDIV
		case FPE_INTDIV:
			return "SIGFPE: Erroneous arithmetic operation: Integer divide by zero";
#endif /* FPE_INTDIV */
#ifdef FPE_INTOVF
		case FPE_INTOVF:
			return "SIGFPE: Erroneous arithmetic operation: Integer overflow";
#endif /* FPE_INTOVF */
#ifdef FPE_FLTDIV
		case FPE_FLTDIV:
			return "SIGFPE: Erroneous arithmetic operation: Floating-point divide by zero";
#endif /* FPE_FLTDIV */
#ifdef FPE_FLTOVF
		case FPE_FLTOVF:
			return "SIGFPE: Erroneous arithmetic operation: Floating-point overflow";
#endif /* FPE_FLTOVF */
#ifdef FPE_FLTUND
		case FPE_FLTUND:
			return "SIGFPE: Erroneous arithmetic operation: Floating-point underflow";
#endif /* FPE_FLTUND */
#ifdef FPE_FLTRES
		case FPE_FLTRES:
			return "SIGFPE: Erroneous arithmetic operation: Floating-point inexact result";
#endif /* FPE_FLTRES */
#ifdef FPE_FLTINV
		case FPE_FLTINV:
			return "SIGFPE: Erroneous arithmetic operation: Invalid floating-point operation";
#endif /* FPE_FLTINV */
#ifdef FPE_FLTSUB
		case FPE_FLTSUB:
			return "SIGFPE: Erroneous arithmetic operation: Subscript out of range";
#endif /* FPE_FLTSUB */
		default:
			return "SIGFPE: Erroneous arithmetic operation";
		};
	case SIGHUP:
		return "SIGHUP: Hangup";
	case SIGILL:
		switch (sigcode)
		{
#ifdef ILL_ILLOPC
		case ILL_ILLOPC:
			return "SIGILL: Illegal instruction: Illegal opcode";
#endif /* ILL_ILLOPC */
#ifdef ILL_ILLOPN
		case ILL_ILLOPN:
			return "SIGILL: Illegal instruction: Illegal operand";
#endif /* ILL_ILLOPN */
#ifdef ILL_ILLADR
		case ILL_ILLADR:
			return "SIGILL: Illegal instruction: Illegal addressing mode";
#endif /* ILL_ILLADR */
#ifdef ILL_ILLTRP
		case ILL_ILLTRP:
			return "SIGILL: Illegal instruction: Illegal trap";
#endif /* ILL_ILLTRP */
#ifdef ILL_PRVOPC
		case ILL_PRVOPC:
			return "SIGILL: Illegal instruction: Privileged opcode";
#endif /* ILL_PRVOPC */
#ifdef ILL_PRVREG
		case ILL_PRVREG:
			return "SIGILL: Illegal instruction: Privileged register";
#endif /* ILL_PRVREG */
#ifdef ILL_COPROC
		case ILL_COPROC:
			return "SIGILL: Illegal instruction: Coprocessor error";
#endif /* ILL_COPROC */
#ifdef ILL_BADSTK
		case ILL_BADSTK:
			return "SIGILL: Illegal instruction: Internal stack error";
#endif /* ILL_BADSTK */
		default:
			return "SIGILL: Illegal instruction";
		}
	case SIGINT:
		return "SIGINT: Terminal interrupt signal";
	case SIGKILL:
		return "SIGKILL: Kill";
	case SIGPIPE:
		return "SIGPIPE: Write on a pipe with no one to read it";
	case SIGQUIT:
		return "SIGQUIT: Terminal quit signal";
	case SIGSEGV:
		switch (sigcode)
		{
#ifdef SEGV_MAPERR
		case SEGV_MAPERR:
			return "SIGSEGV: Invalid memory reference: Address not mapped to object";
#endif /* SEGV_MAPERR */
#ifdef SEGV_ACCERR
		case SEGV_ACCERR:
			return "SIGSEGV: Invalid memory reference: Invalid permissions for mapped object";
#endif /* SEGV_ACCERR */
		default:
			return "SIGSEGV: Invalid memory reference";
		}
	case SIGTERM:
		return "SIGTERM: Termination signal";
	case SIGUSR1:
		return "SIGUSR1: User-defined signal 1";
	case SIGUSR2:
		return "SIGUSR2: User-defined signal 2";
#if _XOPEN_UNIX
	case SIGPROF:
		return "SIGPROF: Profiling timer expired";
	case SIGSYS:
		return "SIGSYS: Bad system call";
	case SIGTRAP:
		switch (sigcode)
		{
#ifdef TRAP_BRKPT
		case TRAP_BRKPT:
			return "SIGTRAP: Trace/breakpoint trap: Process breakpoint";
#endif /* TRAP_BRKPT */
#ifdef TRAP_TRACE
		case TRAP_TRACE:
			return "SIGTRAP: Trace/breakpoint trap: Process trace trap";
#endif /* TRAP_TRACE */
		default:
			return "SIGTRAP: Trace/breakpoint trap";
		}
#endif // _XOPEN_UNIX
#if _XOPEN_UNIX
# ifdef SIGVTALRM
	case SIGVTALRM:
		return "SIGVTALRM: Virtual timer expired";
# endif /* SIGVTALRM */
# ifdef SIGXCPU
	case SIGXCPU:
		return "SIGXCPU: CPU time limit exceeded";
# endif /* SIGXCPU */
# ifdef SIGXFSZ
	case SIGXFSZ:
		return "SIGXFSZ: File size limit exceeded";
# endif /* SIGXFSZ */
#endif // _XOPEN_UNIX
	default:
		return "Unknown signal";
	}
}
#endif // SA_SIGINFO


/**
 * Set signal handlers for fatal signals on POSIX systems
 *
 * \param signalHandler Pointer to the signal handler function
 */
static void setFatalSignalHandler(SigActionHandler signalHandler)
{
	struct sigaction new_handler;

	sigemptyset(&new_handler.sa_mask);
#ifdef SA_SIGINFO
	new_handler.sa_flags = SA_SIGINFO;
	new_handler.sa_sigaction = signalHandler;
#else
	new_handler.sa_handler = signalHandler;
#endif

	sigaction(SIGABRT, nullptr, &oldAction[SIGABRT]);
	if (oldAction[SIGABRT].sa_handler != SIG_IGN)
	{
		sigaction(SIGABRT, &new_handler, nullptr);
	}

	sigaction(SIGBUS, nullptr, &oldAction[SIGBUS]);
	if (oldAction[SIGBUS].sa_handler != SIG_IGN)
	{
		sigaction(SIGBUS, &new_handler, nullptr);
	}

	sigaction(SIGFPE, nullptr, &oldAction[SIGFPE]);
	if (oldAction[SIGFPE].sa_handler != SIG_IGN)
	{
		sigaction(SIGFPE, &new_handler, nullptr);
	}

	sigaction(SIGILL, nullptr, &oldAction[SIGILL]);
	if (oldAction[SIGILL].sa_handler != SIG_IGN)
	{
		sigaction(SIGILL, &new_handler, nullptr);
	}

	sigaction(SIGQUIT, nullptr, &oldAction[SIGQUIT]);
	if (oldAction[SIGQUIT].sa_handler != SIG_IGN)
	{
		sigaction(SIGQUIT, &new_handler, nullptr);
	}

	sigaction(SIGSEGV, nullptr, &oldAction[SIGSEGV]);
	if (oldAction[SIGSEGV].sa_handler != SIG_IGN)
	{
		sigaction(SIGSEGV, &new_handler, nullptr);
	}

#if _XOPEN_UNIX
	sigaction(SIGSYS, nullptr, &oldAction[SIGSYS]);
	if (oldAction[SIGSYS].sa_handler != SIG_IGN)
	{
		sigaction(SIGSYS, &new_handler, nullptr);
	}

	sigaction(SIGXCPU, nullptr, &oldAction[SIGXCPU]);
	if (oldAction[SIGXCPU].sa_handler != SIG_IGN)
	{
		sigaction(SIGXCPU, &new_handler, nullptr);
	}

	sigaction(SIGXFSZ, nullptr, &oldAction[SIGXFSZ]);
	if (oldAction[SIGXFSZ].sa_handler != SIG_IGN)
	{
		sigaction(SIGXFSZ, &new_handler, nullptr);
	}

	// ignore SIGTRAP
	new_handler.sa_handler = SIG_IGN;
	sigaction(SIGTRAP, &new_handler, &oldAction[SIGTRAP]);
#endif // _XOPEN_UNIX
}

static ssize_t writeAll(int const fd, const char* const str)
{
	size_t const to_write = strlen(str);
	size_t written = 0;
	while (written < to_write)
	{
		ssize_t ret = write(fd, str + written, to_write - written);
		if (ret == -1)
		{
			switch (errno)
			{
				case EAGAIN:
#if defined(EWOULDBLOCK) && EAGAIN != EWOULDBLOCK
				case EWOULDBLOCK:
#endif
				case EINTR:
					continue;
				default:
					return -1;
			}
		}
		written += ret;
	}

	return written;
}

/**
 * Spawn a new GDB process and attach it to the current process.
 *
 * @param dumpFile          a POSIX file descriptor to write GDB's output to,
 *                          it will also be used to write failure messages to.
 * @param[out] gdbWritePipe a POSIX file descriptor linked to GDB's stdin.
 *
 * @return 0 if we failed to spawn a new process, a non-zero process ID if we
 *           successfully spawned a new process.
 *
 * @post If the function returned a non-zero process ID a new process has
 *       successfully been spawned. This doesn't mean that 'gdb' was
 *       successfully started though. If 'gdb' failed to start the read end of
 *       the pipe will be closed, also the spawned process will give 1 as its
 *       return code.
 *
 * @post If the function returned a non-zero process ID *gdbWritePipe will
 *       contain a valid POSIX file descriptor representing GDB's stdin. If the
 *       function was unsuccessful and returned zero *gdbWritePipe's value will
 *       be unchanged.
 */
static pid_t execGdb(int const dumpFile, int *gdbWritePipe)
{
	int gdbPipe[2];
	pid_t pid;
	char *gdbArgv[] = { gdbPath, programPath, programPID, nullptr };
	char *gdbEnv[] = { nullptr };
	/* Check if the "bare minimum" is available: GDB and an absolute path
	 * to our program's binary.
	 */
	if (!programIsAvailable
	    || !gdbIsAvailable)
	{
		writeAll(dumpFile, "No extended backtrace dumped:\n");

		if (!programIsAvailable)
		{
			writeAll(dumpFile, "- Program path not available\n");
		}
		if (!gdbIsAvailable)
		{
			writeAll(dumpFile, "- GDB not available\n");
		}

		return 0;
	}

	// Create a pipe to use for communication with 'gdb'
	if (pipe(gdbPipe) == -1)
	{
		writeAll(dumpFile, "Pipe failed\n");

		printf("Pipe failed\n");

		return 0;
	}

	// Fork a new child process
	pid = fork();
	if (pid == -1)
	{
		writeAll(dumpFile, "Fork failed\n");

		printf("Fork failed\n");

		// Clean up our pipe
		close(gdbPipe[0]);
		close(gdbPipe[1]);

		return 0;
	}

	// Check to see if we're the parent
	if (pid != 0)
	{
#ifdef WZ_OS_LINUX
		// Allow tracing the process, some hardened kernel configurations disallow this.
		prctl(PR_SET_PTRACER, pid, 0, 0, 0);
#endif

		// Return the write end of the pipe
		*gdbWritePipe = gdbPipe[1];

		return pid;
	}

	close(gdbPipe[1]); // No output to pipe

	dup2(gdbPipe[0], STDIN_FILENO); // STDIN from pipe
	dup2(dumpFile, STDOUT_FILENO); // STDOUT to dumpFile

	writeAll(dumpFile, "GDB extended backtrace:\n");

	/* If execve() is successful it effectively prevents further
	 * execution of this function.
	 */
	execve(gdbPath, (char **)gdbArgv, (char **)gdbEnv);

	// If we get here it means that execve failed!
	writeAll(dumpFile, "execcv(\"gdb\") failed\n");

	// Terminate the child, indicating failure
	_exit(1);
}

/**
 * Dumps a backtrace of the stack to the given output stream.
 *
 * @param dumpFile a POSIX file descriptor to write the resulting backtrace to.
 *
 * @return false if any failure occurred, preventing a full "extended"
 *               backtrace.
 */
#ifdef SA_SIGINFO
static bool gdbExtendedBacktrace(int const dumpFile, const ucontext_t *sigcontext)
#else
static bool gdbExtendedBacktrace(int const dumpFile)
#endif
{
	/*
	 * Pointer to the stackframe of the function containing faulting
	 * instruction (assuming
	 * -fomit-frame-pointer has *not* been used).
	 *
	 * The frame pointer register (x86: %ebp, x64: %rbp) point's to the
	 * local variables of the current function (which are preceded by the
	 * previous frame pointer and the return address).  Hence the
	 * additions to the frame-pointer register's content.
	 */
	void const *const frame =
#if   defined(SA_SIGINFO) && defined(REG_RBP)
	    sigcontext ? (void *)(sigcontext->uc_mcontext.gregs[REG_RBP] + sizeof(greg_t) + sizeof(void (*)(void))) : nullptr;
#elif defined(SA_SIGINFO) && defined(REG_EBP)
	    sigcontext ? (void *)(sigcontext->uc_mcontext.gregs[REG_EBP] + sizeof(greg_t) + sizeof(void (*)(void))) : NULL;
#else
	    NULL;
#endif

	/*
	 * Faulting instruction.
	 */
	void (*instruction)(void) =
#if   defined(SA_SIGINFO) && defined(REG_RIP)
	    sigcontext ? (void (*)(void))sigcontext->uc_mcontext.gregs[REG_RIP] : nullptr;
#elif defined(SA_SIGINFO) && defined(REG_EIP)
	    sigcontext ? (void (*)(void))sigcontext->uc_mcontext.gregs[REG_EIP] : NULL;
#else
	    NULL;
#endif

	// Spawn a GDB instance and retrieve a pipe to its stdin
	int gdbPipe;
	int status;
	pid_t wpid;
	// Retrieve a full stack backtrace
	static const char gdbCommands[] = "thread apply all backtrace full\n"

	                                  // Move to the stack frame where we triggered the crash
	                                  "frame 4\n"

	                                  // Show the assembly code associated with that stack frame
	                                  "disassemble /m\n"

	                                  // Show the content of all registers
	                                  "info registers\n"
	                                  "quit\n";
	const pid_t pid = execGdb(dumpFile, &gdbPipe);
	if (pid == 0)
	{
		return false;
	}

	// Disassemble the faulting instruction (if we know it)
	if (instruction)
	{
		dprintf(gdbPipe, "x/i %p\n", (void *)instruction);
	}

	// We have an intelligent guess for the *correct* frame, disassemble *that* one.
	if (frame)
	{
		dprintf(gdbPipe, "frame %p\n"
		        "disassemble /m\n", frame);
	}

	writeAll(gdbPipe, gdbCommands);

	/* Flush our end of the pipe to make sure that GDB has all commands
	 * directly available to it.
	 */
	fsync(gdbPipe);

	// Wait for our child to terminate
	wpid = waitpid(pid, &status, 0);

	// Clean up our end of the pipe
	close(gdbPipe);

	// waitpid(): on error, -1 is returned
	if (wpid == -1)
	{
		writeAll(dumpFile, "GDB failed\n");
		printf("GDB failed\n");

		return false;
	}

	/* waitpid(): on success, returns the process ID of the child whose
	 * state has changed
	 *
	 * We only have one child, from our fork() call above, thus these PIDs
	 * should match.
	 */
	assert(pid == wpid);

	/* Check whether our child (which presumably was GDB, but doesn't
	 * necessarily have to be) didn't terminate normally or had a non-zero
	 * return code.
	 */
	if (!WIFEXITED(status)
	    || WEXITSTATUS(status) != 0)
	{
		writeAll(dumpFile, "GDB failed\n");
		printf("GDB failed\n");

		return false;
	}

	return true;
}


/**
 * Exception (signal) handling on POSIX systems.
 * Dumps info about the system incl. backtrace (when GLibC or GDB is present) to /tmp/warzone2100.gdmp
 *
 * \param signum Signal number
 * \param siginfo Signal info
 * \param sigcontext Signal context
 */
#ifdef SA_SIGINFO
static void posixExceptionHandler(int signum, siginfo_t *siginfo, void *sigcontext)
#else
static void posixExceptionHandler(int signum)
#endif
{
	static sig_atomic_t allreadyRunning = 0;
	// XXXXXX will be converted into random characters by mkstemp(3)
	static const char gdmpFile[] = "warzone2100.gdmp-XXXXXX";
	char gdmpPath[PATH_MAX] = {'\0'};
	char dumpFilename[PATH_MAX];
	int dumpFile;
	const char *signal;
# if defined(__GLIBC__)
	void *btBuffer[MAX_BACKTRACE] = {nullptr};
	uint32_t btSize = backtrace(btBuffer, MAX_BACKTRACE);
# endif

	if (allreadyRunning)
	{
		raise(signum);
	}
	allreadyRunning = 1;
	// we use our write directory (which is the only directory that wz should have access to)
	// and stuff it into our logs directory (same as on windows)
	ssprintf(gdmpPath, "%slogs/%s", WritePath, gdmpFile);
	sstrcpy(dumpFilename, gdmpPath);

	dumpFile = mkstemp(dumpFilename);

	if (dumpFile == -1)
	{
		printf("Failed to create dump file '%s'", dumpFilename);
		return;
	}

	// Dump a generic info header
	dbgDumpHeader(dumpFile);

#ifdef SA_SIGINFO
	writeAll(dumpFile, "Dump caused by signal: ");

	signal = wz_strsignal(siginfo->si_signo, siginfo->si_code);
	writeAll(dumpFile, signal);
	writeAll(dumpFile, "\n\n");
#endif

	dbgDumpLog(dumpFile); // dump out the last several log calls

# if defined(__GLIBC__)
	// Dump raw backtrace in case GDB is not available or fails
	writeAll(dumpFile, "GLIBC raw backtrace:\n");
	backtrace_symbols_fd(btBuffer, btSize, dumpFile);
	writeAll(dumpFile, "\n");
# else
	writeAll(dumpFile, "GLIBC not available, no raw backtrace dumped\n\n");
# endif


	// Make sure everything is written before letting GDB write to it
	fsync(dumpFile);

	// Use 'gdb' to provide an "extended" backtrace
#ifdef SA_SIGINFO
	gdbExtendedBacktrace(dumpFile, (ucontext_t *)sigcontext);
#else
	gdbExtendedBacktrace(dumpFile);
#endif

	printf("Saved dump file to '%s'\n"
	       "If you create a bugreport regarding this crash, please include this file.\n", dumpFilename);
	close(dumpFile);


	sigaction(signum, &oldAction[signum], nullptr);
	raise(signum);
}


#endif // WZ_OS_*

#if defined(WZ_OS_UNIX) && !defined(WZ_OS_MAC)
static bool fetchProgramPath(char *const output_programPath, size_t const bufSize, const char *const programCommand)
{
	FILE *whichProgramStream;
	size_t bytesRead;
	char *linefeed;
	// Construct the "which $(programCommand)" string
	char whichProgramCommand[PATH_MAX];
	snprintf(whichProgramCommand, sizeof(whichProgramCommand), "which %s", programCommand);

	/* Fill the output buffer with zeroes so that we can rely on the output
	 * string being NUL-terminated.
	 */
	memset(output_programPath, 0, bufSize);

	/* Execute the "which" command (constructed above) and collect its
	 * output in output_programPath.
	 */
	whichProgramStream = popen(whichProgramCommand, "r");
	if(!whichProgramStream)
	{
		debug(LOG_WARNING, "failed to popen which");
		return false;
	}
	bytesRead = fread(output_programPath, 1, bufSize, whichProgramStream);
	pclose(whichProgramStream);

	// Check whether our buffer is too small, indicate failure if it is
	if (bytesRead == bufSize)
	{
		debug(LOG_WARNING, "Could not retrieve full path to \"%s\", as our buffer is too small. This may prevent creation of an extended backtrace.", programCommand);
		return false;
	}

	output_programPath[bytesRead] = 0;
	// Cut of the linefeed (and everything following it) if it's present.
	linefeed = strchr(output_programPath, '\n');
	if (linefeed)
	{
		*linefeed = '\0';
	}

	// Check to see whether we retrieved any meaning ful result
	if (strlen(output_programPath) == 0)
	{
		debug(LOG_WARNING, "Could not retrieve full path to \"%s\". This may prevent creation of an extended backtrace.", programCommand);
		return false;
	}

	debug(LOG_WZ, "Found program \"%s\" at path \"%s\"", programCommand, output_programPath);
	return true;
}
#endif

/**
 * Setup the exception handler responsible for target OS.
 *
 * \param programCommand Command used to launch this program. Only used for POSIX handler.
 */
void setupExceptionHandler(int argc, const char * const *argv, const char *packageVersion, const std::string &writeDir, bool portable_mode)
{
#if defined(WZ_OS_UNIX) && !defined(WZ_OS_MAC)
	const char *programCommand;
	time_t currentTime;
#endif
	LaunchInfo::initialize(argc, argv);
#if !defined(WZ_OS_MAC)
	// Initialize info required for the debug dumper
	dbgDumpInit(argc, argv, packageVersion);
#endif

#if defined(WZ_OS_WIN)
	ExchndlSetup(packageVersion, writeDir, portable_mode);
#elif defined(WZ_OS_UNIX) && !defined(WZ_OS_MAC) && !defined(__EMSCRIPTEN__)
	programCommand = argv[0];

	// Get full path to this program. Needed for gdb to find the binary.
	programIsAvailable = fetchProgramPath(programPath, sizeof(programPath), programCommand);

	// Get full path to 'gdb'
	gdbIsAvailable = fetchProgramPath(gdbPath, sizeof(gdbPath), "gdb");

	sysInfoValid = (uname(&sysInfo) == 0);

	currentTime = time(nullptr);
	sstrcpy(executionDate, ctime(&currentTime));

	snprintf(programPID, sizeof(programPID), "%i", getpid());

	setFatalSignalHandler(posixExceptionHandler);
#endif // WZ_OS_*
}
bool OverrideRPTDirectory(const char *newPath)
{
# if defined(WZ_OS_WIN)
	wchar_t buf[MAX_PATH];

	if (!MultiByteToWideChar(CP_UTF8, 0, newPath, -1, buf, MAX_PATH))
	{
		//conversion failed-- we won't use the user's directory.

		LPVOID lpMsgBuf;
		DWORD dw = GetLastError();
		TCHAR szBuffer[4196];

		FormatMessage(
		    FORMAT_MESSAGE_ALLOCATE_BUFFER |
		    FORMAT_MESSAGE_FROM_SYSTEM |
		    FORMAT_MESSAGE_IGNORE_INSERTS,
		    NULL,
		    dw,
		    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		    (LPTSTR) &lpMsgBuf,
		    0, NULL);

		wsprintf(szBuffer, _T("Exception handler failed setting new directory with error %lu: %s\n"), dw, lpMsgBuf);
		MessageBox(NULL, szBuffer, _T("Error"), MB_OK | MB_ICONEXCLAMATION);

		LocalFree(lpMsgBuf);

		return false;
	}
	PathRemoveFileSpecW(buf);
	ResetRPTDirectory(buf);
#elif defined(WZ_OS_UNIX) && !defined(WZ_OS_MAC)
	sstrcpy(WritePath, newPath);
#endif
	return true;
}