2 # ifndef DONT_USE_SETDLLDIRECTORY
3 # define _WIN32_WINNT 0x0502
11 # include <mmsystem.h> // timeGetTime
12 # include <time.h> // localtime
13 # include <conio.h> // _kbhit, _getch, _putch
14 # include <io.h> // write; Include this BEFORE darkplaces.h because it uses strncpy which trips DP_STATIC_ASSERT
16 #pragma comment(lib, "winmm.lib")
20 # include <sys/sysctl.h>
23 # include <android/log.h>
27 # include <sys/time.h>
37 #include "taskqueue.h"
42 // Microsoft's compiler complains about portable code
43 #pragma warning(disable : 4996)
48 static char sys_timestring[128];
49 char *Sys_TimeString(const char *timeformat)
51 time_t mytime = time(NULL);
54 localtime_s(&mytm, &mytime);
55 strftime(sys_timestring, sizeof(sys_timestring), timeformat, &mytm);
57 strftime(sys_timestring, sizeof(sys_timestring), timeformat, localtime(&mytime));
59 return sys_timestring;
63 void Sys_Quit (int returnvalue)
65 // Unlock mutexes because the quit command may jump directly here, causing a deadlock
66 if ((cmd_local)->cbuf->lock)
67 Cbuf_Unlock((cmd_local)->cbuf);
68 SV_UnlockThreadMutex();
69 TaskQueue_Frame(true);
71 if (Sys_CheckParm("-profilegameonly"))
72 Sys_AllowProfiling(false);
73 host.state = host_shutdown;
77 Sys_AllowProfiling(false);
81 fcntl(fileno(stdout), F_SETFL, fcntl(fileno(stdout), F_GETFL, 0) & ~O_NONBLOCK);
82 fcntl(fileno(stderr), F_SETFL, fcntl(fileno(stderr), F_GETFL, 0) & ~O_NONBLOCK);
93 void Sys_AllowProfiling(qbool enable)
97 extern void monstartup(const char *libname);
98 extern void moncleanup(void);
100 monstartup("libmain.so");
104 #elif (defined(__linux__) && (defined(__GLIBC__) || defined(__GNU_LIBRARY__))) || defined(__FreeBSD__)
105 extern int moncontrol(int);
112 ===============================================================================
116 ===============================================================================
119 static qbool Sys_LoadDependencyFunctions(dllhandle_t dllhandle, const dllfunction_t *fcts, qbool complain, qbool has_next)
121 const dllfunction_t *func;
124 for (func = fcts; func && func->name != NULL; func++)
125 if (!(*func->funcvariable = (void *) Sys_GetProcAddress (dllhandle, func->name)))
129 Con_DPrintf (" - missing function \"%s\" - broken library!", func->name);
131 Con_DPrintf("\nContinuing with");
138 for (func = fcts; func && func->name != NULL; func++)
139 *func->funcvariable = NULL;
144 qbool Sys_LoadSelf(dllhandle_t *handle)
146 dllhandle_t dllhandle = 0;
151 dllhandle = LoadLibrary (NULL);
153 dllhandle = dlopen (NULL, RTLD_NOW | RTLD_GLOBAL);
159 qbool Sys_LoadDependency (const char** dllnames, dllhandle_t* handle, const dllfunction_t *fcts)
162 const dllfunction_t *func;
163 dllhandle_t dllhandle = 0;
170 #ifdef PREFER_PRELOAD
171 dllhandle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL);
172 if(Sys_LoadDependencyFunctions(dllhandle, fcts, false, false))
174 Con_DPrintf ("All of %s's functions were already linked in! Not loading dynamically...\n", dllnames[0]);
179 Sys_FreeLibrary(&dllhandle);
185 for (func = fcts; func && func->name != NULL; func++)
186 *func->funcvariable = NULL;
188 // Try every possible name
189 Con_DPrintf ("Trying to load library...");
190 for (i = 0; dllnames[i] != NULL; i++)
192 Con_DPrintf (" \"%s\"", dllnames[i]);
194 # ifndef DONT_USE_SETDLLDIRECTORY
196 SetDllDirectory("bin64");
198 SetDllDirectory("bin32");
202 if(Sys_LoadLibrary(dllnames[i], &dllhandle))
204 if (Sys_LoadDependencyFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
207 Sys_FreeLibrary (&dllhandle);
211 // see if the names can be loaded relative to the executable path
212 // (this is for Mac OSX which does not check next to the executable)
213 if (!dllhandle && strrchr(sys.argv[0], '/'))
215 char path[MAX_OSPATH];
216 dp_strlcpy(path, sys.argv[0], sizeof(path));
217 strrchr(path, '/')[1] = 0;
218 for (i = 0; dllnames[i] != NULL; i++)
220 char temp[MAX_OSPATH];
221 dp_strlcpy(temp, path, sizeof(temp));
222 dp_strlcat(temp, dllnames[i], sizeof(temp));
223 Con_DPrintf (" \"%s\"", temp);
225 if(Sys_LoadLibrary(temp, &dllhandle))
227 if (Sys_LoadDependencyFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
230 Sys_FreeLibrary (&dllhandle);
238 Con_DPrintf(" - failed.\n");
242 Con_DPrintf(" - loaded.\n");
243 Con_Printf("Loaded library \"%s\"\n", dllnames[i]);
252 qbool Sys_LoadLibrary(const char *name, dllhandle_t *handle)
254 dllhandle_t dllhandle = 0;
261 dllhandle = LoadLibrary (name);
263 dllhandle = dlopen (name, RTLD_LAZY | RTLD_GLOBAL);
273 void Sys_FreeLibrary (dllhandle_t* handle)
276 if (handle == NULL || *handle == NULL)
280 FreeLibrary (*handle);
289 void* Sys_GetProcAddress (dllhandle_t handle, const char* name)
293 return (void *)GetProcAddress (handle, name);
295 return (void *)dlsym (handle, name);
303 # define HAVE_TIMEGETTIME 1
304 # define HAVE_QUERYPERFORMANCECOUNTER 1
305 # define HAVE_Sleep 1
309 #if defined(CLOCK_MONOTONIC) || defined(CLOCK_HIRES)
310 # define HAVE_CLOCKGETTIME 1
312 // FIXME improve this check, manpage hints to DST_NONE
313 # define HAVE_GETTIMEOFDAY 1
317 # define HAVE_SELECT 1
321 // FIXME improve this check
322 # define HAVE_USLEEP 1
325 // these are referenced elsewhere
326 cvar_t sys_usenoclockbutbenchmark = {CF_SHARED, "sys_usenoclockbutbenchmark", "0", "don't use ANY real timing, and simulate a clock (for benchmarking); the game then runs as fast as possible. Run a QC mod with bots that does some stuff, then does a quit at the end, to benchmark a server. NEVER do this on a public server."};
327 cvar_t sys_libdir = {CF_READONLY | CF_SHARED, "sys_libdir", "", "Default engine library directory"};
330 static cvar_t sys_debugsleep = {CF_SHARED, "sys_debugsleep", "0", "write requested and attained sleep times to standard output, to be used with gnuplot"};
331 static cvar_t sys_usesdlgetticks = {CF_SHARED, "sys_usesdlgetticks", "0", "use SDL_GetTicks() timer (less accurate, for debugging)"};
332 static cvar_t sys_usesdldelay = {CF_SHARED, "sys_usesdldelay", "0", "use SDL_Delay() (less accurate, for debugging)"};
333 #if HAVE_QUERYPERFORMANCECOUNTER
334 static cvar_t sys_usequeryperformancecounter = {CF_SHARED | CF_ARCHIVE, "sys_usequeryperformancecounter", "0", "use windows QueryPerformanceCounter timer (which has issues on multicore/multiprocessor machines and processors which are designed to conserve power) for timing rather than timeGetTime function (which has issues on some motherboards)"};
336 #if HAVE_CLOCKGETTIME
337 static cvar_t sys_useclockgettime = {CF_SHARED | CF_ARCHIVE, "sys_useclockgettime", "1", "use POSIX clock_gettime function (not adjusted by NTP on some older Linux kernels) for timing rather than gettimeofday (which has issues if the system time is stepped by ntpdate, or apparently on some Xen installations)"};
340 static cvar_t sys_stdout = {CF_SHARED, "sys_stdout", "1", "0: nothing is written to stdout (-nostdout cmdline option sets this), 1: normal messages are written to stdout, 2: normal messages are written to stderr (-stderr cmdline option sets this)"};
342 static cvar_t sys_stdout_blocks = {CF_SHARED, "sys_stdout_blocks", "0", "1: writes to stdout and stderr streams will block (causing a stutter or complete halt) if the buffer is full, ensuring no messages are lost at a price"};
345 static double benchmark_time; // actually always contains an integer amount of milliseconds, will eventually "overflow"
351 Returns the position (1 to argc-1) in the program's argument list
352 where the given parameter apears, or 0 if not present
355 int Sys_CheckParm (const char *parm)
359 for (i=1 ; i<sys.argc ; i++)
362 continue; // NEXTSTEP sometimes clears appkit vars.
363 if (!strcmp (parm,sys.argv[i]))
370 static void Sys_UpdateOutFD_c(cvar_t *var)
372 switch (sys_stdout.integer)
374 case 0: sys.outfd = -1; break;
376 case 1: sys.outfd = fileno(stdout); break;
377 case 2: sys.outfd = fileno(stderr); break;
381 void Sys_Init_Commands (void)
383 Cvar_RegisterVariable(&sys_debugsleep);
384 Cvar_RegisterVariable(&sys_usenoclockbutbenchmark);
385 Cvar_RegisterVariable(&sys_libdir);
386 #if HAVE_TIMEGETTIME || HAVE_QUERYPERFORMANCECOUNTER || HAVE_CLOCKGETTIME || HAVE_GETTIMEOFDAY
387 if(sys_supportsdlgetticks)
389 Cvar_RegisterVariable(&sys_usesdlgetticks);
390 Cvar_RegisterVariable(&sys_usesdldelay);
393 #if HAVE_QUERYPERFORMANCECOUNTER
394 Cvar_RegisterVariable(&sys_usequeryperformancecounter);
396 #if HAVE_CLOCKGETTIME
397 Cvar_RegisterVariable(&sys_useclockgettime);
399 Cvar_RegisterVariable(&sys_stdout);
400 Cvar_RegisterCallback(&sys_stdout, Sys_UpdateOutFD_c);
402 Cvar_RegisterVariable(&sys_stdout_blocks);
406 double Sys_DirtyTime(void)
408 // first all the OPTIONAL timers
410 // benchmark timer (fake clock)
411 if(sys_usenoclockbutbenchmark.integer)
413 double old_benchmark_time = benchmark_time;
415 if(benchmark_time == old_benchmark_time)
416 Sys_Abort("sys_usenoclockbutbenchmark cannot run any longer, sorry");
417 return benchmark_time * 0.000001;
419 #if HAVE_QUERYPERFORMANCECOUNTER
420 if (sys_usequeryperformancecounter.integer)
422 // LadyHavoc: note to people modifying this code, DWORD is specifically defined as an unsigned 32bit number, therefore the 65536.0 * 65536.0 is fine.
423 // QueryPerformanceCounter
425 // Windows 95/98/ME/NT/2000/XP
427 // very accurate (CPU cycles)
429 // does not necessarily match realtime too well (tends to get faster and faster in win98)
430 // wraps around occasionally on some platforms (depends on CPU speed and probably other unknown factors)
432 LARGE_INTEGER PerformanceFreq;
433 LARGE_INTEGER PerformanceCount;
435 if (QueryPerformanceFrequency (&PerformanceFreq))
437 QueryPerformanceCounter (&PerformanceCount);
439 timescale = 1.0 / ((double) PerformanceFreq.LowPart + (double) PerformanceFreq.HighPart * 65536.0 * 65536.0);
440 return ((double) PerformanceCount.LowPart + (double) PerformanceCount.HighPart * 65536.0 * 65536.0) * timescale;
444 Con_Printf("No hardware timer available\n");
445 // fall back to other clock sources
446 Cvar_SetValueQuick(&sys_usequeryperformancecounter, false);
451 #if HAVE_CLOCKGETTIME
452 if (sys_useclockgettime.integer)
455 # ifdef CLOCK_MONOTONIC
457 clock_gettime(CLOCK_MONOTONIC, &ts);
460 clock_gettime(CLOCK_HIGHRES, &ts);
462 return (double) ts.tv_sec + ts.tv_nsec / 1000000000.0;
466 // now all the FALLBACK timers
467 if(sys_supportsdlgetticks && sys_usesdlgetticks.integer)
468 return (double) Sys_SDL_GetTicks() / 1000.0;
469 #if HAVE_GETTIMEOFDAY
472 gettimeofday(&tp, NULL);
473 return (double) tp.tv_sec + tp.tv_usec / 1000000.0;
475 #elif HAVE_TIMEGETTIME
477 static int firsttimegettime = true;
480 // Windows 95/98/ME/NT/2000/XP
482 // reasonable accuracy (millisecond)
484 // wraps around every 47 days or so (but this is non-fatal to us, odd times are rejected, only causes a one frame stutter)
486 // make sure the timer is high precision, otherwise different versions of windows have varying accuracy
487 if (firsttimegettime)
490 firsttimegettime = false;
493 return (double) timeGetTime() / 1000.0;
496 // fallback for using the SDL timer if no other timer is available
497 // this calls Sys_Abort() if not linking against SDL
498 return (double) Sys_SDL_GetTicks() / 1000.0;
502 extern cvar_t host_maxwait;
503 double Sys_Sleep(double time)
506 uint32_t microseconds;
508 // convert to microseconds
511 if(host_maxwait.value <= 0)
512 time = min(time, 1000000.0);
514 time = min(time, host_maxwait.value * 1000.0);
516 if (time < 1 || host.restless)
517 return 0; // not sleeping this frame
519 microseconds = time; // post-validation to prevent overflow
521 if(sys_usenoclockbutbenchmark.integer)
523 double old_benchmark_time = benchmark_time;
524 benchmark_time += microseconds;
525 if(benchmark_time == old_benchmark_time)
526 Sys_Abort("sys_usenoclockbutbenchmark cannot run any longer, sorry");
530 if(sys_debugsleep.integer)
531 Con_Printf("sys_debugsleep: requesting %u ", microseconds);
532 dt = Sys_DirtyTime();
534 // less important on newer libcurl so no need to disturb dedicated servers
535 if (cls.state != ca_dedicated && Curl_Select(microseconds))
537 // a transfer is ready or we finished sleeping
539 else if(sys_supportsdlgetticks && sys_usesdldelay.integer)
540 Sys_SDL_Delay(microseconds / 1000);
550 if (cls.state == ca_dedicated && sv_checkforpacketsduringsleep.integer)
552 List_For_Each_Entry(s, &lhnet_socketlist.list, lhnetsocket_t, list)
554 if (s->address.addresstype == LHNETADDRESSTYPE_INET4 || s->address.addresstype == LHNETADDRESSTYPE_INET6)
556 if (lastfd < s->inetsocket)
557 lastfd = s->inetsocket;
558 #if defined(WIN32) && !defined(_MSC_VER)
559 FD_SET((int)s->inetsocket, &fdreadset);
561 FD_SET((unsigned int)s->inetsocket, &fdreadset);
566 tv.tv_sec = microseconds / 1000000;
567 tv.tv_usec = microseconds % 1000000;
568 // on Win32, select() cannot be used with all three FD list args being NULL according to MSDN
569 // (so much for POSIX...)
570 // bones_was_here: but a zeroed fd_set seems to be tolerated (tested on Win 7)
571 select(lastfd + 1, &fdreadset, NULL, NULL, &tv);
575 usleep(microseconds);
578 Sleep(microseconds / 1000);
581 Sys_SDL_Delay(microseconds / 1000);
584 dt = Sys_DirtyTime() - dt;
585 if(sys_debugsleep.integer)
586 Con_Printf(" got %u oversleep %d\n", (unsigned int)(dt * 1000000), (unsigned int)(dt * 1000000) - microseconds);
587 return (dt < 0 || dt >= 1800) ? 0 : dt;
592 ===============================================================================
596 ===============================================================================
599 // NOTE: use only POSIX async-signal-safe library functions here (see: man signal-safety)
600 void Sys_Print(const char *text, size_t textlen)
603 if (developer.integer > 0)
605 __android_log_write(ANDROID_LOG_DEBUG, sys.argv[0], text);
611 // BUG: for some reason, NDELAY also affects stdout (1) when used on stdin (0).
612 // this is because both go to /dev/tty by default!
614 int origflags = fcntl(sys.outfd, F_GETFL, 0);
615 if (sys_stdout_blocks.integer)
616 fcntl(sys.outfd, F_SETFL, origflags & ~O_NONBLOCK);
622 fs_offset_t written = (fs_offset_t)write(sys.outfd, text, textlen);
624 break; // sorry, I cannot do anything about this error - without an output
628 if (sys_stdout_blocks.integer)
629 fcntl(sys.outfd, F_SETFL, origflags);
632 //fprintf(stdout, "%s", text);
636 void Sys_Printf(const char *fmt, ...)
639 char msg[MAX_INPUTLINE];
642 va_start(argptr,fmt);
643 msglen = dpvsnprintf(msg, sizeof(msg), fmt, argptr);
647 Sys_Print(msg, msglen);
650 /// Reads a line from POSIX stdin or the Windows console
651 char *Sys_ConsoleInput(void)
653 static char text[MAX_INPUTLINE];
655 static unsigned int len = 0;
680 if (len < sizeof (text) - 1)
689 struct timeval timeout = { .tv_sec = 0, .tv_usec = 0 };
692 FD_SET(fileno(stdin), &fdset);
693 if (select(1, &fdset, NULL, NULL, &timeout) != -1 && FD_ISSET(fileno(stdin), &fdset))
694 return fgets(text, sizeof(text), stdin);
701 ===============================================================================
705 ===============================================================================
708 void Sys_Abort (const char *error, ...)
711 char string[MAX_INPUTLINE];
714 // set output to blocking stderr
715 sys.outfd = fileno(stderr);
717 fcntl(sys.outfd, F_SETFL, fcntl(sys.outfd, F_GETFL, 0) & ~O_NONBLOCK);
720 va_start (argptr,error);
721 dpvsnprintf (string, sizeof (string), error, argptr);
724 Con_Printf(CON_ERROR "Engine Abort: %s\n^9%s\n", string, engineversion);
726 dp_strlcat(string, "\n\n", sizeof(string));
727 dp_strlcat(string, engineversion, sizeof(string));
729 // Most shutdown funcs can't be called here as they could error while we error.
731 // DP8 TODO: send a disconnect message indicating we aborted, see Host_Error() and Sys_HandleCrash()
733 if (cls.demorecording)
734 CL_Stop_f(cmd_local);
737 sv.active = false; // make SV_DropClient() skip the QC stuff to avoid recursive errors
738 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
739 if (host_client->active)
740 SV_DropClient(false, "Server abort!"); // closes demo file
742 // don't want a dead window left blocking the OS UI or the abort dialog
746 host.state = host_failed; // make Sys_HandleSignal() call exit()
747 Sys_SDL_Dialog("Engine Abort", string);
755 static const char *Sys_FindInPATH(const char *name, char namesep, const char *PATH, char pathsep, char *buf, size_t bufsize)
757 const char *p = PATH;
761 while((q = strchr(p, ':')))
763 dpsnprintf(buf, bufsize, "%.*s%c%s", (int)(q-p), p, namesep, name);
764 if(FS_SysFileExists(buf))
768 if(!q) // none found - try the last item
770 dpsnprintf(buf, bufsize, "%s%c%s", p, namesep, name);
771 if(FS_SysFileExists(buf))
779 static const char *Sys_FindExecutableName(void)
784 static char exenamebuf[MAX_OSPATH+1];
786 #if defined(__FreeBSD__)
787 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
788 size_t exenamebuflen = sizeof(exenamebuf)-1;
789 if (sysctl(mib, 4, exenamebuf, &exenamebuflen, NULL, 0) == 0)
793 #elif defined(__linux__)
794 n = readlink("/proc/self/exe", exenamebuf, sizeof(exenamebuf)-1);
796 if(n > 0 && (size_t)(n) < sizeof(exenamebuf))
801 if(strchr(sys.argv[0], '/'))
802 return sys.argv[0]; // possibly a relative path
804 return Sys_FindInPATH(sys.argv[0], '/', getenv("PATH"), ':', exenamebuf, sizeof(exenamebuf));
808 void Sys_ProvideSelfFD(void)
812 sys.selffd = FS_SysOpenFD(Sys_FindExecutableName(), "rb", false);
815 // for x86 cpus only... (x64 has SSE2_PRESENT)
816 #if defined(SSE_POSSIBLE) && !defined(SSE2_PRESENT)
817 // code from SDL, shortened as we can expect CPUID to work
818 static int CPUID_Features(void)
821 # if (defined(__GNUC__) || defined(__clang__) || defined(__TINYC__)) && defined(__i386__)
823 " movl %%ebx,%%edi\n"
824 " xorl %%eax,%%eax \n"
826 " cpuid # Get family/model/stepping/features\n"
828 " movl %%edi,%%ebx\n"
831 : "%eax", "%ecx", "%edx", "%edi"
833 # elif (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
837 cpuid ; Get family/model/stepping/features
841 # error SSE_POSSIBLE set but no CPUID implementation
848 qbool Sys_HaveSSE(void)
850 // COMMANDLINEOPTION: SSE: -nosse disables SSE support and detection
851 if(Sys_CheckParm("-nosse"))
856 // COMMANDLINEOPTION: SSE: -forcesse enables SSE support and disables detection
857 if(Sys_CheckParm("-forcesse") || Sys_CheckParm("-forcesse2"))
859 if(CPUID_Features() & (1 << 25))
865 qbool Sys_HaveSSE2(void)
867 // COMMANDLINEOPTION: SSE2: -nosse2 disables SSE2 support and detection
868 if(Sys_CheckParm("-nosse") || Sys_CheckParm("-nosse2"))
873 // COMMANDLINEOPTION: SSE2: -forcesse2 enables SSE2 support and disables detection
874 if(Sys_CheckParm("-forcesse2"))
876 if((CPUID_Features() & (3 << 25)) == (3 << 25)) // SSE is 1<<25, SSE2 is 1<<26
883 /// called to set process priority for dedicated servers
884 #if defined(__linux__)
885 #include <sys/resource.h>
888 void Sys_InitProcessNice (void)
891 sys.nicepossible = false;
892 if(Sys_CheckParm("-nonice"))
895 sys.nicelevel = getpriority(PRIO_PROCESS, 0);
898 Con_Printf("Kernel does not support reading process priority - cannot use niceness\n");
901 if(getrlimit(RLIMIT_NICE, &lim))
903 Con_Printf("Kernel does not support lowering nice level again - cannot use niceness\n");
906 if(lim.rlim_cur != RLIM_INFINITY && sys.nicelevel < (int) (20 - lim.rlim_cur))
908 Con_Printf("Current nice level is below the soft limit - cannot use niceness\n");
911 sys.nicepossible = true;
914 void Sys_MakeProcessNice (void)
916 if(!sys.nicepossible)
920 Con_DPrintf("Process is becoming 'nice'...\n");
921 if(setpriority(PRIO_PROCESS, 0, 19))
922 Con_Printf(CON_ERROR "Failed to raise nice level to %d\n", 19);
925 void Sys_MakeProcessMean (void)
927 if(!sys.nicepossible)
931 Con_DPrintf("Process is becoming 'mean'...\n");
932 if(setpriority(PRIO_PROCESS, 0, sys.nicelevel))
933 Con_Printf(CON_ERROR "Failed to lower nice level to %d\n", sys.nicelevel);
937 void Sys_InitProcessNice (void)
940 void Sys_MakeProcessNice (void)
943 void Sys_MakeProcessMean (void)
949 static const char *Sys_SigDesc(int sig)
953 // Windows only supports the C99 signals
954 case SIGINT: return "Interrupt";
955 case SIGILL: return "Illegal instruction";
956 case SIGABRT: return "Aborted";
957 case SIGFPE: return "Floating point exception";
958 case SIGSEGV: return "Segmentation fault";
959 case SIGTERM: return "Termination";
961 // POSIX has several others worth catching
962 case SIGHUP: return "Hangup";
963 case SIGQUIT: return "Quit";
964 case SIGBUS: return "Bus error (bad memory access)";
965 case SIGPIPE: return "Broken pipe";
967 default: return "Yo dawg, we bugged out while bugging out";
971 /** Halt and try not to catch fire.
972 * Writing to any file could corrupt it,
973 * any uneccessary code could crash while we crash.
974 * Try to use only POSIX async-signal-safe library functions here (see: man signal-safety).
976 static void Sys_HandleCrash(int sig)
978 #if __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 1
979 // Before doing anything else grab the stack frame addresses
980 #include <execinfo.h>
981 void *stackframes[32];
982 int framecount = backtrace(stackframes, 32);
985 char dialogtext[3072];
986 const char *sigdesc = Sys_SigDesc(sig);
988 // set output to blocking stderr and print header, backtrace, version
989 sys.outfd = fileno(stderr); // not async-signal-safe :(
991 fcntl(sys.outfd, F_SETFL, fcntl(sys.outfd, F_GETFL, 0) & ~O_NONBLOCK);
992 Sys_Print("\n\n\e[1;37;41m Engine Crash: ", 30);
993 Sys_Print(sigdesc, strlen(sigdesc));
994 Sys_Print(" \e[m\n", 8);
995 #if __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 1
996 // the first two addresses will be in this function and in signal() in libc
997 backtrace_symbols_fd(stackframes + 2, framecount - 2, sys.outfd);
999 Sys_Print("\e[1m", 4);
1000 Sys_Print(engineversion, strlen(engineversion));
1001 Sys_Print("\e[m\n", 4);
1002 #else // Windows console doesn't support colours
1003 Sys_Print("\n\nEngine Crash: ", 16);
1004 Sys_Print(sigdesc, strlen(sigdesc));
1006 Sys_Print(engineversion, strlen(engineversion));
1010 // DP8 TODO: send a disconnect message indicating we crashed, see Sys_Abort() and Host_Error()
1012 // don't want a dead window left blocking the OS UI or the crash dialog
1016 // prepare the dialogtext: signal, backtrace, version
1017 // the dp_st* funcs are POSIX async-signal-safe IF we don't trigger their warnings
1018 dp_strlcpy(dialogtext, sigdesc, sizeof(dialogtext));
1019 dp_strlcat(dialogtext, "\n\n", sizeof(dialogtext));
1020 #if __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 1
1021 btstrings = backtrace_symbols(stackframes + 2, framecount - 2); // calls malloc :(
1023 for (int i = 0; i < framecount - 2; ++i)
1025 dp_strlcat(dialogtext, btstrings[i], sizeof(dialogtext));
1026 dp_strlcat(dialogtext, "\n", sizeof(dialogtext));
1029 dp_strlcat(dialogtext, "\n", sizeof(dialogtext));
1030 dp_strlcat(dialogtext, engineversion, sizeof(dialogtext));
1032 host.state = host_failed; // make Sys_HandleSignal() call _Exit()
1033 Sys_SDL_Dialog("Engine Crash", dialogtext);
1035 fflush(stderr); // not async-signal-safe :(
1039 static void Sys_HandleSignal(int sig)
1041 const char *sigdesc = Sys_SigDesc(sig);
1042 Sys_Print("\nReceived ", 10);
1043 Sys_Print(sigdesc, strlen(sigdesc));
1044 Sys_Print(" signal, exiting...\n", 20);
1045 if (host.state == host_failed)
1047 // user is trying to kill the process while the dialog is open
1048 fflush(stderr); // not async-signal-safe :(
1051 host.state = host_shutdown;
1054 /// SDL2 only handles SIGINT and SIGTERM by default and doesn't log anything
1055 static void Sys_InitSignals(void)
1057 // Windows only supports the C99 signals
1058 signal(SIGINT, Sys_HandleSignal);
1059 signal(SIGILL, Sys_HandleCrash);
1060 signal(SIGABRT, Sys_HandleCrash);
1061 signal(SIGFPE, Sys_HandleCrash);
1062 signal(SIGSEGV, Sys_HandleCrash);
1063 signal(SIGTERM, Sys_HandleSignal);
1065 // POSIX has several others worth catching
1066 signal(SIGHUP, Sys_HandleSignal);
1067 signal(SIGQUIT, Sys_HandleSignal);
1068 signal(SIGBUS, Sys_HandleCrash);
1069 signal(SIGPIPE, Sys_HandleSignal);
1073 int main (int argc, char **argv)
1076 sys.argv = (const char **)argv;
1078 // COMMANDLINEOPTION: Console: -nostdout disables text output to the terminal the game was launched from
1079 // COMMANDLINEOPTION: -noterminal disables console output on stdout
1080 if(Sys_CheckParm("-noterminal") || Sys_CheckParm("-nostdout"))
1081 sys_stdout.string = "0";
1082 // COMMANDLINEOPTION: -stderr moves console output to stderr
1083 else if(Sys_CheckParm("-stderr"))
1084 sys_stdout.string = "2";
1085 // too early for Cvar_SetQuick
1086 sys_stdout.value = sys_stdout.integer = atoi(sys_stdout.string);
1087 Sys_UpdateOutFD_c(&sys_stdout);
1089 fcntl(fileno(stdin), F_SETFL, fcntl(fileno(stdin), F_GETFL, 0) | O_NONBLOCK);
1090 // stdout/stderr will be set to blocking in Sys_Print() if so configured, or during a fatal error.
1091 fcntl(fileno(stdout), F_SETFL, fcntl(fileno(stdout), F_GETFL, 0) | O_NONBLOCK);
1092 fcntl(fileno(stderr), F_SETFL, fcntl(fileno(stderr), F_GETFL, 0) | O_NONBLOCK);
1096 Sys_ProvideSelfFD(); // may call Con_Printf() so must be after sys.outfd is set
1099 Sys_AllowProfiling(true);