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"
43 static char sys_timestring[128];
44 char *Sys_TimeString(const char *timeformat)
46 time_t mytime = time(NULL);
49 localtime_s(&mytm, &mytime);
50 strftime(sys_timestring, sizeof(sys_timestring), timeformat, &mytm);
52 strftime(sys_timestring, sizeof(sys_timestring), timeformat, localtime(&mytime));
54 return sys_timestring;
58 void Sys_Quit (int returnvalue)
60 // Unlock mutexes because the quit command may jump directly here, causing a deadlock
61 if ((cmd_local)->cbuf->lock)
62 Cbuf_Unlock((cmd_local)->cbuf);
63 SV_UnlockThreadMutex();
64 TaskQueue_Frame(true);
66 if (Sys_CheckParm("-profilegameonly"))
67 Sys_AllowProfiling(false);
68 host.state = host_shutdown;
72 Sys_AllowProfiling(false);
76 fcntl(fileno(stdout), F_SETFL, fcntl(fileno(stdout), F_GETFL, 0) & ~O_NONBLOCK);
77 fcntl(fileno(stderr), F_SETFL, fcntl(fileno(stderr), F_GETFL, 0) & ~O_NONBLOCK);
88 void Sys_AllowProfiling(qbool enable)
92 extern void monstartup(const char *libname);
93 extern void moncleanup(void);
95 monstartup("libmain.so");
99 #elif (defined(__linux__) && (defined(__GLIBC__) || defined(__GNU_LIBRARY__))) || defined(__FreeBSD__)
100 extern int moncontrol(int);
107 ===============================================================================
111 ===============================================================================
114 static qbool Sys_LoadDependencyFunctions(dllhandle_t dllhandle, const dllfunction_t *fcts, qbool complain, qbool has_next)
116 const dllfunction_t *func;
119 for (func = fcts; func && func->name != NULL; func++)
120 if (!(*func->funcvariable = (void *) Sys_GetProcAddress (dllhandle, func->name)))
124 Con_DPrintf (" - missing function \"%s\" - broken library!", func->name);
126 Con_DPrintf("\nContinuing with");
133 for (func = fcts; func && func->name != NULL; func++)
134 *func->funcvariable = NULL;
139 qbool Sys_LoadSelf(dllhandle_t *handle)
141 dllhandle_t dllhandle = 0;
146 dllhandle = LoadLibrary (NULL);
148 dllhandle = dlopen (NULL, RTLD_NOW | RTLD_GLOBAL);
154 qbool Sys_LoadDependency (const char** dllnames, dllhandle_t* handle, const dllfunction_t *fcts)
157 const dllfunction_t *func;
158 dllhandle_t dllhandle = 0;
165 #ifdef PREFER_PRELOAD
166 dllhandle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL);
167 if(Sys_LoadDependencyFunctions(dllhandle, fcts, false, false))
169 Con_DPrintf ("All of %s's functions were already linked in! Not loading dynamically...\n", dllnames[0]);
174 Sys_FreeLibrary(&dllhandle);
180 for (func = fcts; func && func->name != NULL; func++)
181 *func->funcvariable = NULL;
183 // Try every possible name
184 Con_DPrintf ("Trying to load library...");
185 for (i = 0; dllnames[i] != NULL; i++)
187 Con_DPrintf (" \"%s\"", dllnames[i]);
189 # ifndef DONT_USE_SETDLLDIRECTORY
191 SetDllDirectory("bin64");
193 SetDllDirectory("bin32");
197 if(Sys_LoadLibrary(dllnames[i], &dllhandle))
199 if (Sys_LoadDependencyFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
202 Sys_FreeLibrary (&dllhandle);
206 // see if the names can be loaded relative to the executable path
207 // (this is for Mac OSX which does not check next to the executable)
208 if (!dllhandle && strrchr(sys.argv[0], '/'))
210 char path[MAX_OSPATH];
211 strlcpy(path, sys.argv[0], sizeof(path));
212 strrchr(path, '/')[1] = 0;
213 for (i = 0; dllnames[i] != NULL; i++)
215 char temp[MAX_OSPATH];
216 strlcpy(temp, path, sizeof(temp));
217 strlcat(temp, dllnames[i], sizeof(temp));
218 Con_DPrintf (" \"%s\"", temp);
220 if(Sys_LoadLibrary(temp, &dllhandle))
222 if (Sys_LoadDependencyFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
225 Sys_FreeLibrary (&dllhandle);
233 Con_DPrintf(" - failed.\n");
237 Con_DPrintf(" - loaded.\n");
238 Con_Printf("Loaded library \"%s\"\n", dllnames[i]);
247 qbool Sys_LoadLibrary(const char *name, dllhandle_t *handle)
249 dllhandle_t dllhandle = 0;
256 dllhandle = LoadLibrary (name);
258 dllhandle = dlopen (name, RTLD_LAZY | RTLD_GLOBAL);
268 void Sys_FreeLibrary (dllhandle_t* handle)
271 if (handle == NULL || *handle == NULL)
275 FreeLibrary (*handle);
284 void* Sys_GetProcAddress (dllhandle_t handle, const char* name)
288 return (void *)GetProcAddress (handle, name);
290 return (void *)dlsym (handle, name);
298 # define HAVE_TIMEGETTIME 1
299 # define HAVE_QUERYPERFORMANCECOUNTER 1
300 # define HAVE_Sleep 1
304 #if defined(CLOCK_MONOTONIC) || defined(CLOCK_HIRES)
305 # define HAVE_CLOCKGETTIME 1
307 // FIXME improve this check, manpage hints to DST_NONE
308 # define HAVE_GETTIMEOFDAY 1
312 # define HAVE_SELECT 1
316 // FIXME improve this check
317 # define HAVE_USLEEP 1
320 // these are referenced elsewhere
321 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."};
322 cvar_t sys_libdir = {CF_READONLY | CF_SHARED, "sys_libdir", "", "Default engine library directory"};
325 static cvar_t sys_debugsleep = {CF_SHARED, "sys_debugsleep", "0", "write requested and attained sleep times to standard output, to be used with gnuplot"};
326 static cvar_t sys_usesdlgetticks = {CF_SHARED, "sys_usesdlgetticks", "0", "use SDL_GetTicks() timer (less accurate, for debugging)"};
327 static cvar_t sys_usesdldelay = {CF_SHARED, "sys_usesdldelay", "0", "use SDL_Delay() (less accurate, for debugging)"};
328 #if HAVE_QUERYPERFORMANCECOUNTER
329 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)"};
331 #if HAVE_CLOCKGETTIME
332 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)"};
335 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)"};
337 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"};
340 static double benchmark_time; // actually always contains an integer amount of milliseconds, will eventually "overflow"
346 Returns the position (1 to argc-1) in the program's argument list
347 where the given parameter apears, or 0 if not present
350 int Sys_CheckParm (const char *parm)
354 for (i=1 ; i<sys.argc ; i++)
357 continue; // NEXTSTEP sometimes clears appkit vars.
358 if (!strcmp (parm,sys.argv[i]))
365 static void Sys_UpdateOutFD_c(cvar_t *var)
367 switch (sys_stdout.integer)
369 case 0: sys.outfd = -1; break;
371 case 1: sys.outfd = fileno(stdout); break;
372 case 2: sys.outfd = fileno(stderr); break;
376 void Sys_Init_Commands (void)
378 Cvar_RegisterVariable(&sys_debugsleep);
379 Cvar_RegisterVariable(&sys_usenoclockbutbenchmark);
380 Cvar_RegisterVariable(&sys_libdir);
381 #if HAVE_TIMEGETTIME || HAVE_QUERYPERFORMANCECOUNTER || HAVE_CLOCKGETTIME || HAVE_GETTIMEOFDAY
382 if(sys_supportsdlgetticks)
384 Cvar_RegisterVariable(&sys_usesdlgetticks);
385 Cvar_RegisterVariable(&sys_usesdldelay);
388 #if HAVE_QUERYPERFORMANCECOUNTER
389 Cvar_RegisterVariable(&sys_usequeryperformancecounter);
391 #if HAVE_CLOCKGETTIME
392 Cvar_RegisterVariable(&sys_useclockgettime);
394 Cvar_RegisterVariable(&sys_stdout);
395 Cvar_RegisterCallback(&sys_stdout, Sys_UpdateOutFD_c);
397 Cvar_RegisterVariable(&sys_stdout_blocks);
401 double Sys_DirtyTime(void)
403 // first all the OPTIONAL timers
405 // benchmark timer (fake clock)
406 if(sys_usenoclockbutbenchmark.integer)
408 double old_benchmark_time = benchmark_time;
410 if(benchmark_time == old_benchmark_time)
411 Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
412 return benchmark_time * 0.000001;
414 #if HAVE_QUERYPERFORMANCECOUNTER
415 if (sys_usequeryperformancecounter.integer)
417 // LadyHavoc: note to people modifying this code, DWORD is specifically defined as an unsigned 32bit number, therefore the 65536.0 * 65536.0 is fine.
418 // QueryPerformanceCounter
420 // Windows 95/98/ME/NT/2000/XP
422 // very accurate (CPU cycles)
424 // does not necessarily match realtime too well (tends to get faster and faster in win98)
425 // wraps around occasionally on some platforms (depends on CPU speed and probably other unknown factors)
427 LARGE_INTEGER PerformanceFreq;
428 LARGE_INTEGER PerformanceCount;
430 if (QueryPerformanceFrequency (&PerformanceFreq))
432 QueryPerformanceCounter (&PerformanceCount);
434 timescale = 1.0 / ((double) PerformanceFreq.LowPart + (double) PerformanceFreq.HighPart * 65536.0 * 65536.0);
435 return ((double) PerformanceCount.LowPart + (double) PerformanceCount.HighPart * 65536.0 * 65536.0) * timescale;
439 Con_Printf("No hardware timer available\n");
440 // fall back to other clock sources
441 Cvar_SetValueQuick(&sys_usequeryperformancecounter, false);
446 #if HAVE_CLOCKGETTIME
447 if (sys_useclockgettime.integer)
450 # ifdef CLOCK_MONOTONIC
452 clock_gettime(CLOCK_MONOTONIC, &ts);
455 clock_gettime(CLOCK_HIGHRES, &ts);
457 return (double) ts.tv_sec + ts.tv_nsec / 1000000000.0;
461 // now all the FALLBACK timers
462 if(sys_supportsdlgetticks && sys_usesdlgetticks.integer)
463 return (double) Sys_SDL_GetTicks() / 1000.0;
464 #if HAVE_GETTIMEOFDAY
467 gettimeofday(&tp, NULL);
468 return (double) tp.tv_sec + tp.tv_usec / 1000000.0;
470 #elif HAVE_TIMEGETTIME
472 static int firsttimegettime = true;
475 // Windows 95/98/ME/NT/2000/XP
477 // reasonable accuracy (millisecond)
479 // wraps around every 47 days or so (but this is non-fatal to us, odd times are rejected, only causes a one frame stutter)
481 // make sure the timer is high precision, otherwise different versions of windows have varying accuracy
482 if (firsttimegettime)
485 firsttimegettime = false;
488 return (double) timeGetTime() / 1000.0;
491 // fallback for using the SDL timer if no other timer is available
492 // this calls Sys_Error() if not linking against SDL
493 return (double) Sys_SDL_GetTicks() / 1000.0;
497 extern cvar_t host_maxwait;
498 double Sys_Sleep(double time)
501 uint32_t microseconds;
503 // convert to microseconds
506 if(host_maxwait.value <= 0)
507 time = min(time, 1000000.0);
509 time = min(time, host_maxwait.value * 1000.0);
511 if (time < 1 || host.restless)
512 return 0; // not sleeping this frame
514 microseconds = time; // post-validation to prevent overflow
516 if(sys_usenoclockbutbenchmark.integer)
518 double old_benchmark_time = benchmark_time;
519 benchmark_time += microseconds;
520 if(benchmark_time == old_benchmark_time)
521 Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
525 if(sys_debugsleep.integer)
526 Con_Printf("sys_debugsleep: requesting %u ", microseconds);
527 dt = Sys_DirtyTime();
529 // less important on newer libcurl so no need to disturb dedicated servers
530 if (cls.state != ca_dedicated && Curl_Select(microseconds))
532 // a transfer is ready or we finished sleeping
534 else if(sys_supportsdlgetticks && sys_usesdldelay.integer)
535 Sys_SDL_Delay(microseconds / 1000);
545 if (cls.state == ca_dedicated && sv_checkforpacketsduringsleep.integer)
547 List_For_Each_Entry(s, &lhnet_socketlist.list, lhnetsocket_t, list)
549 if (s->address.addresstype == LHNETADDRESSTYPE_INET4 || s->address.addresstype == LHNETADDRESSTYPE_INET6)
551 if (lastfd < s->inetsocket)
552 lastfd = s->inetsocket;
553 #if defined(WIN32) && !defined(_MSC_VER)
554 FD_SET((int)s->inetsocket, &fdreadset);
556 FD_SET((unsigned int)s->inetsocket, &fdreadset);
561 tv.tv_sec = microseconds / 1000000;
562 tv.tv_usec = microseconds % 1000000;
563 // on Win32, select() cannot be used with all three FD list args being NULL according to MSDN
564 // (so much for POSIX...)
565 // bones_was_here: but a zeroed fd_set seems to be tolerated (tested on Win 7)
566 select(lastfd + 1, &fdreadset, NULL, NULL, &tv);
570 usleep(microseconds);
573 Sleep(microseconds / 1000);
576 Sys_SDL_Delay(microseconds / 1000);
579 dt = Sys_DirtyTime() - dt;
580 if(sys_debugsleep.integer)
581 Con_Printf(" got %u oversleep %d\n", (unsigned int)(dt * 1000000), (unsigned int)(dt * 1000000) - microseconds);
582 return (dt < 0 || dt >= 1800) ? 0 : dt;
587 ===============================================================================
591 ===============================================================================
594 void Sys_Print(const char *text)
597 if (developer.integer > 0)
599 __android_log_write(ANDROID_LOG_DEBUG, sys.argv[0], text);
605 // BUG: for some reason, NDELAY also affects stdout (1) when used on stdin (0).
606 // this is because both go to /dev/tty by default!
608 int origflags = fcntl(sys.outfd, F_GETFL, 0);
609 if (sys_stdout_blocks.integer)
610 fcntl(sys.outfd, F_SETFL, origflags & ~O_NONBLOCK);
616 fs_offset_t written = (fs_offset_t)write(sys.outfd, text, (int)strlen(text));
618 break; // sorry, I cannot do anything about this error - without an output
622 if (sys_stdout_blocks.integer)
623 fcntl(sys.outfd, F_SETFL, origflags);
626 //fprintf(stdout, "%s", text);
630 /// for the console to report failures inside Con_Printf()
631 void Sys_Printf(const char *fmt, ...)
634 char msg[MAX_INPUTLINE];
636 va_start(argptr,fmt);
637 dpvsnprintf(msg,sizeof(msg),fmt,argptr);
643 /// Reads a line from POSIX stdin or the Windows console
644 char *Sys_ConsoleInput(void)
646 static char text[MAX_INPUTLINE];
648 static unsigned int len = 0;
673 if (len < sizeof (text) - 1)
682 struct timeval timeout = { .tv_sec = 0, .tv_usec = 0 };
685 FD_SET(fileno(stdin), &fdset);
686 if (select(1, &fdset, NULL, NULL, &timeout) != -1 && FD_ISSET(fileno(stdin), &fdset))
687 return fgets(text, sizeof(text), stdin);
694 ===============================================================================
698 ===============================================================================
701 void Sys_Error (const char *error, ...)
704 char string[MAX_INPUTLINE];
706 // set output to blocking stderr
707 sys.outfd = fileno(stderr);
709 fcntl(sys.outfd, F_SETFL, fcntl(sys.outfd, F_GETFL, 0) & ~O_NONBLOCK);
712 va_start (argptr,error);
713 dpvsnprintf (string, sizeof (string), error, argptr);
716 Con_Printf(CON_ERROR "Engine Error: %s\n", string);
718 // don't want a dead window left blocking the OS UI or the crash dialog
721 Sys_SDL_Dialog("Engine Error", string);
729 static const char *Sys_FindInPATH(const char *name, char namesep, const char *PATH, char pathsep, char *buf, size_t bufsize)
731 const char *p = PATH;
735 while((q = strchr(p, ':')))
737 dpsnprintf(buf, bufsize, "%.*s%c%s", (int)(q-p), p, namesep, name);
738 if(FS_SysFileExists(buf))
742 if(!q) // none found - try the last item
744 dpsnprintf(buf, bufsize, "%s%c%s", p, namesep, name);
745 if(FS_SysFileExists(buf))
753 static const char *Sys_FindExecutableName(void)
758 static char exenamebuf[MAX_OSPATH+1];
760 #if defined(__FreeBSD__)
761 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
762 size_t exenamebuflen = sizeof(exenamebuf)-1;
763 if (sysctl(mib, 4, exenamebuf, &exenamebuflen, NULL, 0) == 0)
767 #elif defined(__linux__)
768 n = readlink("/proc/self/exe", exenamebuf, sizeof(exenamebuf)-1);
770 if(n > 0 && (size_t)(n) < sizeof(exenamebuf))
775 if(strchr(sys.argv[0], '/'))
776 return sys.argv[0]; // possibly a relative path
778 return Sys_FindInPATH(sys.argv[0], '/', getenv("PATH"), ':', exenamebuf, sizeof(exenamebuf));
782 void Sys_ProvideSelfFD(void)
786 sys.selffd = FS_SysOpenFD(Sys_FindExecutableName(), "rb", false);
789 // for x86 cpus only... (x64 has SSE2_PRESENT)
790 #if defined(SSE_POSSIBLE) && !defined(SSE2_PRESENT)
791 // code from SDL, shortened as we can expect CPUID to work
792 static int CPUID_Features(void)
795 # if (defined(__GNUC__) || defined(__clang__) || defined(__TINYC__)) && defined(__i386__)
797 " movl %%ebx,%%edi\n"
798 " xorl %%eax,%%eax \n"
800 " cpuid # Get family/model/stepping/features\n"
802 " movl %%edi,%%ebx\n"
805 : "%eax", "%ecx", "%edx", "%edi"
807 # elif (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
811 cpuid ; Get family/model/stepping/features
815 # error SSE_POSSIBLE set but no CPUID implementation
822 qbool Sys_HaveSSE(void)
824 // COMMANDLINEOPTION: SSE: -nosse disables SSE support and detection
825 if(Sys_CheckParm("-nosse"))
830 // COMMANDLINEOPTION: SSE: -forcesse enables SSE support and disables detection
831 if(Sys_CheckParm("-forcesse") || Sys_CheckParm("-forcesse2"))
833 if(CPUID_Features() & (1 << 25))
839 qbool Sys_HaveSSE2(void)
841 // COMMANDLINEOPTION: SSE2: -nosse2 disables SSE2 support and detection
842 if(Sys_CheckParm("-nosse") || Sys_CheckParm("-nosse2"))
847 // COMMANDLINEOPTION: SSE2: -forcesse2 enables SSE2 support and disables detection
848 if(Sys_CheckParm("-forcesse2"))
850 if((CPUID_Features() & (3 << 25)) == (3 << 25)) // SSE is 1<<25, SSE2 is 1<<26
857 /// called to set process priority for dedicated servers
858 #if defined(__linux__)
859 #include <sys/resource.h>
862 void Sys_InitProcessNice (void)
865 sys.nicepossible = false;
866 if(Sys_CheckParm("-nonice"))
869 sys.nicelevel = getpriority(PRIO_PROCESS, 0);
872 Con_Printf("Kernel does not support reading process priority - cannot use niceness\n");
875 if(getrlimit(RLIMIT_NICE, &lim))
877 Con_Printf("Kernel does not support lowering nice level again - cannot use niceness\n");
880 if(lim.rlim_cur != RLIM_INFINITY && sys.nicelevel < (int) (20 - lim.rlim_cur))
882 Con_Printf("Current nice level is below the soft limit - cannot use niceness\n");
885 sys.nicepossible = true;
888 void Sys_MakeProcessNice (void)
890 if(!sys.nicepossible)
894 Con_DPrintf("Process is becoming 'nice'...\n");
895 if(setpriority(PRIO_PROCESS, 0, 19))
896 Con_Printf(CON_ERROR "Failed to raise nice level to %d\n", 19);
899 void Sys_MakeProcessMean (void)
901 if(!sys.nicepossible)
905 Con_DPrintf("Process is becoming 'mean'...\n");
906 if(setpriority(PRIO_PROCESS, 0, sys.nicelevel))
907 Con_Printf(CON_ERROR "Failed to lower nice level to %d\n", sys.nicelevel);
911 void Sys_InitProcessNice (void)
914 void Sys_MakeProcessNice (void)
917 void Sys_MakeProcessMean (void)
922 /** Halt and try not to catch fire.
923 * Writing to any file could corrupt it,
924 * any uneccessary code could crash while we crash.
925 * No malloc() (libgcc should be loaded already) or Con_Printf() allowed here.
927 static void Sys_HandleCrash(int sig)
929 #if __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 1
930 // Before doing anything else grab the stack frame addresses
931 #include <execinfo.h>
932 void *stackframes[32];
933 int framecount = backtrace(stackframes, 32);
936 // Windows doesn't have strsignal()
940 #ifndef WIN32 // or SIGBUS
941 case SIGBUS: sigdesc = "Bus error"; break;
943 case SIGILL: sigdesc = "Illegal instruction"; break;
944 case SIGABRT: sigdesc = "Aborted"; break;
945 case SIGFPE: sigdesc = "Floating point exception"; break;
946 case SIGSEGV: sigdesc = "Segmentation fault"; break;
947 default: sigdesc = "Yo dawg, we hit a bug while hitting a bug";
950 // set output to blocking stderr
951 sys.outfd = fileno(stderr);
953 fcntl(sys.outfd, F_SETFL, fcntl(sys.outfd, F_GETFL, 0) & ~O_NONBLOCK);
956 fprintf(stderr, "\n\n\e[1;37;41m Engine Crash: %s (%d) \e[m\n", sigdesc, sig);
957 #if __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 1
958 // the first two addresses will be in this function and in signal() in libc
959 backtrace_symbols_fd(stackframes + 2, framecount - 2, sys.outfd);
961 fprintf(stderr, "\e[1m%s\e[m\n", engineversion);
963 // DP8 TODO: send a disconnect message indicating we crashed, see CL_DisconnectEx()
965 // don't want a dead window left blocking the OS UI or the crash dialog
969 Sys_SDL_Dialog("Engine Crash", sigdesc);
976 static void Sys_HandleSignal(int sig)
979 // Windows users will likely never see this so no point replicating strsignal()
980 Con_Printf("\nReceived signal %d, exiting...\n", sig);
982 Con_Printf("\nReceived %s signal (%d), exiting...\n", strsignal(sig), sig);
984 host.state = host_shutdown;
987 /// SDL2 only handles SIGINT and SIGTERM by default and doesn't log anything
988 static void Sys_InitSignals(void)
990 // Windows docs say its signal() only accepts these ones
991 signal(SIGABRT, Sys_HandleCrash);
992 signal(SIGFPE, Sys_HandleCrash);
993 signal(SIGILL, Sys_HandleCrash);
994 signal(SIGINT, Sys_HandleSignal);
995 signal(SIGSEGV, Sys_HandleCrash);
996 signal(SIGTERM, Sys_HandleSignal);
998 signal(SIGHUP, Sys_HandleSignal);
999 signal(SIGQUIT, Sys_HandleSignal);
1000 signal(SIGBUS, Sys_HandleCrash);
1001 signal(SIGPIPE, Sys_HandleSignal);
1005 int main (int argc, char **argv)
1008 sys.argv = (const char **)argv;
1010 // COMMANDLINEOPTION: Console: -nostdout disables text output to the terminal the game was launched from
1011 // COMMANDLINEOPTION: -noterminal disables console output on stdout
1012 if(Sys_CheckParm("-noterminal") || Sys_CheckParm("-nostdout"))
1013 sys_stdout.string = "0";
1014 // COMMANDLINEOPTION: -stderr moves console output to stderr
1015 else if(Sys_CheckParm("-stderr"))
1016 sys_stdout.string = "2";
1017 // too early for Cvar_SetQuick
1018 sys_stdout.value = sys_stdout.integer = atoi(sys_stdout.string);
1019 Sys_UpdateOutFD_c(&sys_stdout);
1021 fcntl(fileno(stdin), F_SETFL, fcntl(fileno(stdin), F_GETFL, 0) | O_NONBLOCK);
1022 // stdout/stderr will be set to blocking in Sys_Print() if so configured, or during a fatal error.
1023 fcntl(fileno(stdout), F_SETFL, fcntl(fileno(stdout), F_GETFL, 0) | O_NONBLOCK);
1024 fcntl(fileno(stderr), F_SETFL, fcntl(fileno(stderr), F_GETFL, 0) | O_NONBLOCK);
1028 Sys_ProvideSelfFD(); // may call Con_Printf() so must be after sys.outfd is set
1031 Sys_AllowProfiling(true);