+/// Reads a line from POSIX stdin or the Windows console
+char *Sys_ConsoleInput(void)
+{
+ static char text[MAX_INPUTLINE];
+#ifdef WIN32
+ static unsigned int len = 0;
+ int c;
+
+ // read a line out
+ while (_kbhit ())
+ {
+ c = _getch ();
+ if (c == '\r')
+ {
+ text[len] = '\0';
+ _putch ('\n');
+ len = 0;
+ return text;
+ }
+ if (c == '\b')
+ {
+ if (len)
+ {
+ _putch (c);
+ _putch (' ');
+ _putch (c);
+ len--;
+ }
+ continue;
+ }
+ if (len < sizeof (text) - 1)
+ {
+ _putch (c);
+ text[len] = c;
+ len++;
+ }
+ }
+#else
+ fd_set fdset;
+ struct timeval timeout = { .tv_sec = 0, .tv_usec = 0 };
+
+ FD_ZERO(&fdset);
+ FD_SET(fileno(stdin), &fdset);
+ if (select(1, &fdset, NULL, NULL, &timeout) != -1 && FD_ISSET(fileno(stdin), &fdset))
+ return fgets(text, sizeof(text), stdin);
+#endif
+ return NULL;
+}
+
+
+/*
+===============================================================================
+
+Startup and Shutdown
+
+===============================================================================
+*/
+
+void Sys_Abort (const char *error, ...)
+{
+ va_list argptr;
+ char string[MAX_INPUTLINE];
+ int i;
+
+ // Disable Sys_HandleSignal() but not Sys_HandleCrash()
+ host.state = host_shutdown;
+
+ // set output to blocking stderr
+ sys.outfd = fileno(stderr);
+#ifndef WIN32
+ fcntl(sys.outfd, F_SETFL, fcntl(sys.outfd, F_GETFL, 0) & ~O_NONBLOCK);
+#endif
+
+ va_start (argptr,error);
+ dpvsnprintf (string, sizeof (string), error, argptr);
+ va_end (argptr);
+
+ Con_Printf(CON_ERROR "Engine Abort: %s\n^9%s\n", string, engineversion);
+
+ dp_strlcat(string, "\n\n", sizeof(string));
+ dp_strlcat(string, engineversion, sizeof(string));
+
+ // Most shutdown funcs can't be called here as they could error while we error.
+
+ // DP8 TODO: send a disconnect message indicating we aborted, see Host_Error() and Sys_HandleCrash()
+
+ if (cls.demorecording)
+ CL_Stop_f(cmd_local);
+ if (sv.active)
+ {
+ sv.active = false; // make SV_DropClient() skip the QC stuff to avoid recursive errors
+ for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
+ if (host_client->active)
+ SV_DropClient(false, "Server abort!"); // closes demo file
+ }
+ // don't want a dead window left blocking the OS UI or the abort dialog
+ VID_Shutdown();
+ S_StopAllSounds();
+
+ host.state = host_failed; // make Sys_HandleSignal() call _Exit()
+ Sys_SDL_Dialog("Engine Abort", string);
+
+ fflush(stderr);
+ exit (1);
+}
+
+#ifndef WIN32
+static const char *Sys_FindInPATH(const char *name, char namesep, const char *PATH, char pathsep, char *buf, size_t bufsize)
+{
+ const char *p = PATH;
+ const char *q;
+ if(p && name)
+ {
+ while((q = strchr(p, ':')))
+ {
+ dpsnprintf(buf, bufsize, "%.*s%c%s", (int)(q-p), p, namesep, name);
+ if(FS_SysFileExists(buf))
+ return buf;
+ p = q + 1;
+ }
+ if(!q) // none found - try the last item
+ {
+ dpsnprintf(buf, bufsize, "%s%c%s", p, namesep, name);
+ if(FS_SysFileExists(buf))
+ return buf;
+ }
+ }
+ return name;
+}
+#endif
+
+static const char *Sys_FindExecutableName(void)
+{
+#if defined(WIN32)
+ return sys.argv[0];
+#else
+ static char exenamebuf[MAX_OSPATH+1];
+ ssize_t n = -1;
+#if defined(__FreeBSD__)
+ int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
+ size_t exenamebuflen = sizeof(exenamebuf)-1;
+ if (sysctl(mib, 4, exenamebuf, &exenamebuflen, NULL, 0) == 0)
+ {
+ n = exenamebuflen;
+ }
+#elif defined(__linux__)
+ n = readlink("/proc/self/exe", exenamebuf, sizeof(exenamebuf)-1);
+#endif
+ if(n > 0 && (size_t)(n) < sizeof(exenamebuf))
+ {
+ exenamebuf[n] = 0;
+ return exenamebuf;
+ }
+ if(strchr(sys.argv[0], '/'))
+ return sys.argv[0]; // possibly a relative path
+ else
+ return Sys_FindInPATH(sys.argv[0], '/', getenv("PATH"), ':', exenamebuf, sizeof(exenamebuf));
+#endif
+}
+
+void Sys_ProvideSelfFD(void)
+{
+ if(sys.selffd != -1)
+ return;
+ sys.selffd = FS_SysOpenFD(Sys_FindExecutableName(), "rb", false);
+}
+
+// for x86 cpus only... (x64 has SSE2_PRESENT)
+#if defined(SSE_POSSIBLE) && !defined(SSE2_PRESENT)
+// code from SDL, shortened as we can expect CPUID to work
+static int CPUID_Features(void)
+{
+ int features = 0;
+# if (defined(__GNUC__) || defined(__clang__) || defined(__TINYC__)) && defined(__i386__)
+ __asm__ (
+" movl %%ebx,%%edi\n"
+" xorl %%eax,%%eax \n"
+" incl %%eax \n"
+" cpuid # Get family/model/stepping/features\n"
+" movl %%edx,%0 \n"
+" movl %%edi,%%ebx\n"
+ : "=m" (features)
+ :
+ : "%eax", "%ecx", "%edx", "%edi"
+ );
+# elif (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
+ __asm {
+ xor eax, eax
+ inc eax
+ cpuid ; Get family/model/stepping/features
+ mov features, edx
+ }
+# else
+# error SSE_POSSIBLE set but no CPUID implementation
+# endif
+ return features;
+}
+#endif
+
+#ifdef SSE_POSSIBLE
+qbool Sys_HaveSSE(void)
+{
+ // COMMANDLINEOPTION: SSE: -nosse disables SSE support and detection
+ if(Sys_CheckParm("-nosse"))
+ return false;
+#ifdef SSE_PRESENT
+ return true;
+#else
+ // COMMANDLINEOPTION: SSE: -forcesse enables SSE support and disables detection
+ if(Sys_CheckParm("-forcesse") || Sys_CheckParm("-forcesse2"))
+ return true;
+ if(CPUID_Features() & (1 << 25))
+ return true;
+ return false;
+#endif
+}
+
+qbool Sys_HaveSSE2(void)
+{
+ // COMMANDLINEOPTION: SSE2: -nosse2 disables SSE2 support and detection
+ if(Sys_CheckParm("-nosse") || Sys_CheckParm("-nosse2"))
+ return false;
+#ifdef SSE2_PRESENT
+ return true;
+#else
+ // COMMANDLINEOPTION: SSE2: -forcesse2 enables SSE2 support and disables detection
+ if(Sys_CheckParm("-forcesse2"))
+ return true;
+ if((CPUID_Features() & (3 << 25)) == (3 << 25)) // SSE is 1<<25, SSE2 is 1<<26
+ return true;
+ return false;
+#endif
+}
+#endif
+
+/// called to set process priority for dedicated servers
+#if defined(__linux__)
+#include <sys/resource.h>
+#include <errno.h>
+
+void Sys_InitProcessNice (void)
+{
+ struct rlimit lim;
+ sys.nicepossible = false;
+ if(Sys_CheckParm("-nonice"))
+ return;
+ errno = 0;
+ sys.nicelevel = getpriority(PRIO_PROCESS, 0);
+ if(errno)
+ {
+ Con_Printf("Kernel does not support reading process priority - cannot use niceness\n");
+ return;
+ }
+ if(getrlimit(RLIMIT_NICE, &lim))
+ {
+ Con_Printf("Kernel does not support lowering nice level again - cannot use niceness\n");
+ return;
+ }
+ if(lim.rlim_cur != RLIM_INFINITY && sys.nicelevel < (int) (20 - lim.rlim_cur))
+ {
+ Con_Printf("Current nice level is below the soft limit - cannot use niceness\n");
+ return;
+ }
+ sys.nicepossible = true;
+ sys.isnice = false;
+}
+void Sys_MakeProcessNice (void)
+{
+ if(!sys.nicepossible)
+ return;
+ if(sys.isnice)
+ return;
+ Con_DPrintf("Process is becoming 'nice'...\n");
+ if(setpriority(PRIO_PROCESS, 0, 19))
+ Con_Printf(CON_ERROR "Failed to raise nice level to %d\n", 19);
+ sys.isnice = true;
+}
+void Sys_MakeProcessMean (void)
+{
+ if(!sys.nicepossible)
+ return;
+ if(!sys.isnice)
+ return;
+ Con_DPrintf("Process is becoming 'mean'...\n");
+ if(setpriority(PRIO_PROCESS, 0, sys.nicelevel))
+ Con_Printf(CON_ERROR "Failed to lower nice level to %d\n", sys.nicelevel);
+ sys.isnice = false;
+}
+#else
+void Sys_InitProcessNice (void)
+{
+}
+void Sys_MakeProcessNice (void)
+{
+}
+void Sys_MakeProcessMean (void)
+{
+}
+#endif
+
+
+static const char *Sys_SigDesc(int sig)
+{
+ switch (sig)
+ {
+ // Windows only supports the C99 signals
+ case SIGINT: return "Interrupt";
+ case SIGILL: return "Illegal instruction";
+ case SIGABRT: return "Aborted";
+ case SIGFPE: return "Floating point exception";
+ case SIGSEGV: return "Segmentation fault";
+ case SIGTERM: return "Termination";
+#ifndef WIN32
+ // POSIX has several others worth catching
+ case SIGHUP: return "Hangup";
+ case SIGQUIT: return "Quit";
+ case SIGBUS: return "Bus error (bad memory access)";
+ case SIGPIPE: return "Broken pipe";
+#endif
+ default: return "Yo dawg, we bugged out while bugging out";
+ }
+}
+
+/** Halt and try not to catch fire.
+ * Writing to any file could corrupt it,
+ * any uneccessary code could crash while we crash.
+ * Try to use only POSIX async-signal-safe library functions here (see: man signal-safety).
+ */
+static void Sys_HandleCrash(int sig)
+{
+#if __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 1
+ // Before doing anything else grab the stack frame addresses
+ #include <execinfo.h>
+ void *stackframes[32];
+ int framecount = backtrace(stackframes, 32);
+ char **btstrings;
+#endif
+ char dialogtext[3072];
+ const char *sigdesc;
+
+ // Break any loop and disable Sys_HandleSignal()
+ if (host.state == host_failing || host.state == host_failed)
+ return;
+ host.state = host_failing;
+
+ sigdesc = Sys_SigDesc(sig);
+
+ // set output to blocking stderr and print header, backtrace, version
+ sys.outfd = fileno(stderr); // not async-signal-safe :(
+#ifndef WIN32
+ fcntl(sys.outfd, F_SETFL, fcntl(sys.outfd, F_GETFL, 0) & ~O_NONBLOCK);
+ Sys_Print("\n\n\e[1;37;41m Engine Crash: ", 30);
+ Sys_Print(sigdesc, strlen(sigdesc));
+ Sys_Print(" \e[m\n", 8);
+ #if __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 1
+ // the first two addresses will be in this function and in signal() in libc
+ backtrace_symbols_fd(stackframes + 2, framecount - 2, sys.outfd);
+ #endif
+ Sys_Print("\e[1m", 4);
+ Sys_Print(engineversion, strlen(engineversion));
+ Sys_Print("\e[m\n", 4);
+#else // Windows console doesn't support colours
+ Sys_Print("\n\nEngine Crash: ", 16);
+ Sys_Print(sigdesc, strlen(sigdesc));
+ Sys_Print("\n", 1);
+ Sys_Print(engineversion, strlen(engineversion));
+ Sys_Print("\n", 1);
+#endif
+
+ // DP8 TODO: send a disconnect message indicating we crashed, see Sys_Abort() and Host_Error()
+
+ // don't want a dead window left blocking the OS UI or the crash dialog
+ VID_Shutdown();
+ S_StopAllSounds();
+
+ // prepare the dialogtext: signal, backtrace, version
+ // the dp_st* funcs are POSIX async-signal-safe IF we don't trigger their warnings
+ dp_strlcpy(dialogtext, sigdesc, sizeof(dialogtext));
+ dp_strlcat(dialogtext, "\n\n", sizeof(dialogtext));
+#if __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 1
+ btstrings = backtrace_symbols(stackframes + 2, framecount - 2); // calls malloc :(
+ if (btstrings)
+ for (int i = 0; i < framecount - 2; ++i)
+ {
+ dp_strlcat(dialogtext, btstrings[i], sizeof(dialogtext));
+ dp_strlcat(dialogtext, "\n", sizeof(dialogtext));
+ }
+#endif
+ dp_strlcat(dialogtext, "\n", sizeof(dialogtext));
+ dp_strlcat(dialogtext, engineversion, sizeof(dialogtext));
+
+ host.state = host_failed; // make Sys_HandleSignal() call _Exit()
+ Sys_SDL_Dialog("Engine Crash", dialogtext);
+
+ fflush(stderr); // not async-signal-safe :(
+ _Exit(sig);
+}
+
+static void Sys_HandleSignal(int sig)
+{
+ const char *sigdesc;
+
+ // Break any loop, eg if each Sys_Print triggers a SIGPIPE
+ if (host.state == host_shutdown || host.state == host_failing)
+ return;
+
+ sigdesc = Sys_SigDesc(sig);
+ Sys_Print("\nReceived ", 10);
+ Sys_Print(sigdesc, strlen(sigdesc));
+ Sys_Print(" signal, exiting...\n", 20);
+ if (host.state == host_failed)
+ {
+ // user is trying to kill the process while the SDL dialog is open
+ fflush(stderr); // not async-signal-safe :(
+ _Exit(sig);
+ }
+ host.state = host_shutdown;
+}
+
+/// SDL2 only handles SIGINT and SIGTERM by default and doesn't log anything
+static void Sys_InitSignals(void)
+{
+ // Windows only supports the C99 signals
+ signal(SIGINT, Sys_HandleSignal);
+ signal(SIGILL, Sys_HandleCrash);
+ signal(SIGABRT, Sys_HandleCrash);
+ signal(SIGFPE, Sys_HandleCrash);
+ signal(SIGSEGV, Sys_HandleCrash);
+ signal(SIGTERM, Sys_HandleSignal);
+#ifndef WIN32
+ // POSIX has several others worth catching
+ signal(SIGHUP, Sys_HandleSignal);
+ signal(SIGQUIT, Sys_HandleSignal);
+ signal(SIGBUS, Sys_HandleCrash);
+ signal(SIGPIPE, Sys_HandleSignal);
+#endif
+}
+
+int main (int argc, char **argv)
+{
+ sys.argc = argc;
+ sys.argv = (const char **)argv;
+
+ // COMMANDLINEOPTION: Console: -nostdout disables text output to the terminal the game was launched from
+ // COMMANDLINEOPTION: -noterminal disables console output on stdout
+ if(Sys_CheckParm("-noterminal") || Sys_CheckParm("-nostdout"))
+ sys_stdout.string = "0";
+ // COMMANDLINEOPTION: -stderr moves console output to stderr
+ else if(Sys_CheckParm("-stderr"))
+ sys_stdout.string = "2";
+ // too early for Cvar_SetQuick
+ sys_stdout.value = sys_stdout.integer = atoi(sys_stdout.string);
+ Sys_UpdateOutFD_c(&sys_stdout);
+#ifndef WIN32
+ fcntl(fileno(stdin), F_SETFL, fcntl(fileno(stdin), F_GETFL, 0) | O_NONBLOCK);
+ // stdout/stderr will be set to blocking in Sys_Print() if so configured, or during a fatal error.
+ fcntl(fileno(stdout), F_SETFL, fcntl(fileno(stdout), F_GETFL, 0) | O_NONBLOCK);
+ fcntl(fileno(stderr), F_SETFL, fcntl(fileno(stderr), F_GETFL, 0) | O_NONBLOCK);
+#endif
+
+ sys.selffd = -1;
+ Sys_ProvideSelfFD(); // may call Con_Printf() so must be after sys.outfd is set
+
+#ifdef __ANDROID__
+ Sys_AllowProfiling(true);
+#endif
+
+ Sys_InitSignals();
+
+ Host_Main();
+
+#ifdef __ANDROID__
+ Sys_AllowProfiling(false);
+#endif
+
+#ifndef WIN32
+ fcntl(fileno(stdout), F_SETFL, fcntl(fileno(stdout), F_GETFL, 0) & ~O_NONBLOCK);
+ fcntl(fileno(stderr), F_SETFL, fcntl(fileno(stderr), F_GETFL, 0) & ~O_NONBLOCK);
+#endif
+ fflush(stdout);
+ fflush(stderr);
+
+ return 0;
+}