]> git.xonotic.org Git - xonotic/darkplaces.git/blobdiff - sys_shared.c
sys: prevent loops in signal handlers
[xonotic/darkplaces.git] / sys_shared.c
index 7b33f3a32a8acaa419cdc0fee89db15bd7d43678..fa733ebf843790abc82ca03f78ca479232a0c718 100644 (file)
@@ -4,11 +4,6 @@
 # endif
 #endif
 
-#include "quakedef.h"
-#include "taskqueue.h"
-#include "thread.h"
-#include "libcurl.h"
-
 #define SUPPORTDLL
 
 #ifdef WIN32
@@ -16,6 +11,7 @@
 # include <mmsystem.h> // timeGetTime
 # include <time.h> // localtime
 # include <conio.h> // _kbhit, _getch, _putch
+# include <io.h> // write; Include this BEFORE darkplaces.h because it uses strncpy which trips DP_STATIC_ASSERT
 #ifdef _MSC_VER
 #pragma comment(lib, "winmm.lib")
 #endif
@@ -23,6 +19,9 @@
 # ifdef __FreeBSD__
 #  include <sys/sysctl.h>
 # endif
+# ifdef __ANDROID__
+#  include <android/log.h>
+# endif
 # include <unistd.h>
 # include <fcntl.h>
 # include <sys/time.h>
 
 #include <signal.h>
 
+#include "quakedef.h"
+#include "taskqueue.h"
+#include "thread.h"
+#include "libcurl.h"
+
+
+sys_t sys;
+
 static char sys_timestring[128];
 char *Sys_TimeString(const char *timeformat)
 {
@@ -49,21 +56,6 @@ char *Sys_TimeString(const char *timeformat)
 }
 
 
-void Sys_Quit (int returnvalue)
-{
-       // Unlock mutexes because the quit command may jump directly here, causing a deadlock
-       if ((cmd_local)->cbuf->lock)
-               Cbuf_Unlock((cmd_local)->cbuf);
-       SV_UnlockThreadMutex();
-       TaskQueue_Frame(true);
-
-       if (Sys_CheckParm("-profilegameonly"))
-               Sys_AllowProfiling(false);
-       host.state = host_shutdown;
-       Host_Shutdown();
-       exit(returnvalue);
-}
-
 #ifdef __cplusplus
 extern "C"
 #endif
@@ -190,13 +182,13 @@ notfound:
        if (!dllhandle && strrchr(sys.argv[0], '/'))
        {
                char path[MAX_OSPATH];
-               strlcpy(path, sys.argv[0], sizeof(path));
+               dp_strlcpy(path, sys.argv[0], sizeof(path));
                strrchr(path, '/')[1] = 0;
                for (i = 0; dllnames[i] != NULL; i++)
                {
                        char temp[MAX_OSPATH];
-                       strlcpy(temp, path, sizeof(temp));
-                       strlcat(temp, dllnames[i], sizeof(temp));
+                       dp_strlcpy(temp, path, sizeof(temp));
+                       dp_strlcat(temp, dllnames[i], sizeof(temp));
                        Con_DPrintf (" \"%s\"", temp);
 
                        if(Sys_LoadLibrary(temp, &dllhandle))
@@ -314,6 +306,11 @@ static cvar_t sys_usequeryperformancecounter = {CF_SHARED | CF_ARCHIVE, "sys_use
 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)"};
 #endif
 
+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)"};
+#ifndef WIN32
+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"};
+#endif
+
 static double benchmark_time; // actually always contains an integer amount of milliseconds, will eventually "overflow"
 
 /*
@@ -339,6 +336,17 @@ int Sys_CheckParm (const char *parm)
        return 0;
 }
 
+static void Sys_UpdateOutFD_c(cvar_t *var)
+{
+       switch (sys_stdout.integer)
+       {
+               case 0: sys.outfd = -1; break;
+               default:
+               case 1: sys.outfd = fileno(stdout); break;
+               case 2: sys.outfd = fileno(stderr); break;
+       }
+}
+
 void Sys_Init_Commands (void)
 {
        Cvar_RegisterVariable(&sys_debugsleep);
@@ -356,6 +364,11 @@ void Sys_Init_Commands (void)
 #endif
 #if HAVE_CLOCKGETTIME
        Cvar_RegisterVariable(&sys_useclockgettime);
+#endif
+       Cvar_RegisterVariable(&sys_stdout);
+       Cvar_RegisterCallback(&sys_stdout, Sys_UpdateOutFD_c);
+#ifndef WIN32
+       Cvar_RegisterVariable(&sys_stdout_blocks);
 #endif
 }
 
@@ -369,7 +382,7 @@ double Sys_DirtyTime(void)
                double old_benchmark_time = benchmark_time;
                benchmark_time += 1;
                if(benchmark_time == old_benchmark_time)
-                       Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
+                       Sys_Abort("sys_usenoclockbutbenchmark cannot run any longer, sorry");
                return benchmark_time * 0.000001;
        }
 #if HAVE_QUERYPERFORMANCECOUNTER
@@ -450,7 +463,7 @@ double Sys_DirtyTime(void)
        }
 #else
        // fallback for using the SDL timer if no other timer is available
-       // this calls Sys_Error() if not linking against SDL
+       // this calls Sys_Abort() if not linking against SDL
        return (double) Sys_SDL_GetTicks() / 1000.0;
 #endif
 }
@@ -479,12 +492,12 @@ double Sys_Sleep(double time)
                double old_benchmark_time = benchmark_time;
                benchmark_time += microseconds;
                if(benchmark_time == old_benchmark_time)
-                       Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
+                       Sys_Abort("sys_usenoclockbutbenchmark cannot run any longer, sorry");
                return 0;
        }
 
        if(sys_debugsleep.integer)
-               Sys_Printf("sys_debugsleep: requesting %u ", microseconds);
+               Con_Printf("sys_debugsleep: requesting %u ", microseconds);
        dt = Sys_DirtyTime();
 
        // less important on newer libcurl so no need to disturb dedicated servers
@@ -539,27 +552,76 @@ double Sys_Sleep(double time)
 
        dt = Sys_DirtyTime() - dt;
        if(sys_debugsleep.integer)
-               Sys_Printf(" got %u oversleep %d\n", (unsigned int)(dt * 1000000), (unsigned int)(dt * 1000000) - microseconds);
+               Con_Printf(" got %u oversleep %d\n", (unsigned int)(dt * 1000000), (unsigned int)(dt * 1000000) - microseconds);
        return (dt < 0 || dt >= 1800) ? 0 : dt;
 }
 
+
+/*
+===============================================================================
+
+STDIO
+
+===============================================================================
+*/
+
+// NOTE: use only POSIX async-signal-safe library functions here (see: man signal-safety)
+void Sys_Print(const char *text, size_t textlen)
+{
+#ifdef __ANDROID__
+       if (developer.integer > 0)
+       {
+               __android_log_write(ANDROID_LOG_DEBUG, sys.argv[0], text);
+       }
+#else
+       if(sys.outfd < 0)
+               return;
+  #ifndef WIN32
+       // BUG: for some reason, NDELAY also affects stdout (1) when used on stdin (0).
+       // this is because both go to /dev/tty by default!
+       {
+               int origflags = fcntl(sys.outfd, F_GETFL, 0);
+               if (sys_stdout_blocks.integer)
+                       fcntl(sys.outfd, F_SETFL, origflags & ~O_NONBLOCK);
+  #else
+    #define write _write
+  #endif
+               while(*text)
+               {
+                       fs_offset_t written = (fs_offset_t)write(sys.outfd, text, textlen);
+                       if(written <= 0)
+                               break; // sorry, I cannot do anything about this error - without an output
+                       text += written;
+               }
+  #ifndef WIN32
+               if (sys_stdout_blocks.integer)
+                       fcntl(sys.outfd, F_SETFL, origflags);
+       }
+  #endif
+       //fprintf(stdout, "%s", text);
+#endif
+}
+
 void Sys_Printf(const char *fmt, ...)
 {
        va_list argptr;
        char msg[MAX_INPUTLINE];
+       int msglen;
 
        va_start(argptr,fmt);
-       dpvsnprintf(msg,sizeof(msg),fmt,argptr);
+       msglen = dpvsnprintf(msg, sizeof(msg), fmt, argptr);
        va_end(argptr);
 
-       Sys_Print(msg);
+       if (msglen >= 0)
+               Sys_Print(msg, msglen);
 }
 
+/// Reads a line from POSIX stdin or the Windows console
 char *Sys_ConsoleInput(void)
 {
        static char text[MAX_INPUTLINE];
-       static unsigned int len = 0;
 #ifdef WIN32
+       static unsigned int len = 0;
        int c;
 
        // read a line out
@@ -593,28 +655,73 @@ char *Sys_ConsoleInput(void)
        }
 #else
        fd_set fdset;
-       struct timeval timeout;
+       struct timeval timeout = { .tv_sec = 0, .tv_usec = 0 };
+
        FD_ZERO(&fdset);
-       FD_SET(0, &fdset); // stdin
-       timeout.tv_sec = 0;
-       timeout.tv_usec = 0;
-       if (select (1, &fdset, NULL, NULL, &timeout) != -1 && FD_ISSET(0, &fdset))
-       {
-               len = read (0, text, sizeof(text) - 1);
-               if (len >= 1)
-               {
-                       // rip off the \n and terminate
-                       // div0: WHY? console code can deal with \n just fine
-                       // this caused problems with pasting stuff into a terminal window
-                       // so, not ripping off the \n, but STILL keeping a NUL terminator
-                       text[len] = 0;
-                       return text;
-               }
-       }
+       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)
 {
@@ -809,36 +916,187 @@ void Sys_MakeProcessMean (void)
 }
 #endif
 
-int main (int argc, char **argv)
+
+static const char *Sys_SigDesc(int sig)
 {
-       signal(SIGFPE, SIG_IGN);
+       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.outfd = -1;
+       if(Sys_CheckParm("-noterminal") || Sys_CheckParm("-nostdout"))
+               sys_stdout.string = "0";
        // COMMANDLINEOPTION: -stderr moves console output to stderr
        else if(Sys_CheckParm("-stderr"))
-               sys.outfd = 2;
-       else
-               sys.outfd = 1;
+               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
 
-#ifndef WIN32
-       fcntl(0, F_SETFL, fcntl (0, F_GETFL, 0) | O_NONBLOCK);
-#endif
-
 #ifdef __ANDROID__
        Sys_AllowProfiling(true);
 #endif
 
+       Sys_InitSignals();
+
        Host_Main();
 
-       Sys_Quit(0);
+#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;
 }