]> de.git.xonotic.org Git - xonotic/darkplaces.git/blobdiff - sys_shared.c
sys: optimise printing to stdout
[xonotic/darkplaces.git] / sys_shared.c
index 5d19784daf45354765868ebdf13581026b75caf3..26bd27c25e440a57bef9fe50d3632c72bedddd0b 100644 (file)
 #include "thread.h"
 #include "libcurl.h"
 
+#ifdef WIN32
+       // Microsoft's compiler complains about portable code
+       #pragma warning(disable : 4996)
+#endif
+
+sys_t sys;
+
 static char sys_timestring[128];
 char *Sys_TimeString(const char *timeformat)
 {
@@ -69,10 +76,13 @@ void Sys_Quit (int returnvalue)
 #ifdef __ANDROID__
        Sys_AllowProfiling(false);
 #endif
+
 #ifndef WIN32
-       fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~O_NONBLOCK);
+       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);
 
        exit(returnvalue);
 }
@@ -203,13 +213,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))
@@ -327,6 +337,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"
 
 /*
@@ -352,6 +367,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);
@@ -369,6 +395,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
 }
 
@@ -497,7 +528,7 @@ double Sys_Sleep(double time)
        }
 
        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
@@ -552,11 +583,20 @@ 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;
 }
 
-void Sys_Print(const char *text)
+
+/*
+===============================================================================
+
+STDIO
+
+===============================================================================
+*/
+
+void Sys_Print(const char *text, size_t textlen)
 {
 #ifdef __ANDROID__
        if (developer.integer > 0)
@@ -570,20 +610,22 @@ void Sys_Print(const char *text)
        // 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);
-               fcntl (sys.outfd, F_SETFL, origflags & ~O_NONBLOCK);
+               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, (int)strlen(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
-               fcntl (sys.outfd, F_SETFL, origflags);
+               if (sys_stdout_blocks.integer)
+                       fcntl(sys.outfd, F_SETFL, origflags);
        }
   #endif
        //fprintf(stdout, "%s", text);
@@ -594,19 +636,22 @@ 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
@@ -640,37 +685,34 @@ 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_Error (const char *error, ...)
 {
        va_list argptr;
        char string[MAX_INPUTLINE];
 
-// change stdin to non blocking
+       // set output to blocking stderr
+       sys.outfd = fileno(stderr);
 #ifndef WIN32
-       fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~O_NONBLOCK);
+       fcntl(sys.outfd, F_SETFL, fcntl(sys.outfd, F_GETFL, 0) & ~O_NONBLOCK);
 #endif
 
        va_start (argptr,error);
@@ -684,6 +726,8 @@ void Sys_Error (const char *error, ...)
 
        Sys_SDL_Dialog("Engine Error", string);
 
+       fflush(stderr);
+
        exit (1);
 }
 
@@ -881,33 +925,120 @@ void Sys_MakeProcessMean (void)
 }
 #endif
 
-int main (int argc, char **argv)
+/** Halt and try not to catch fire.
+ * Writing to any file could corrupt it,
+ * any uneccessary code could crash while we crash.
+ * No malloc() (libgcc should be loaded already) or Con_Printf() allowed here.
+ */
+static void Sys_HandleCrash(int sig)
 {
-       signal(SIGFPE, SIG_IGN);
+#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);
+#endif
+
+       // Windows doesn't have strsignal()
+       const char *sigdesc;
+       switch (sig)
+       {
+#ifndef WIN32 // or SIGBUS
+               case SIGBUS:  sigdesc = "Bus error"; break;
+#endif
+               case SIGILL:  sigdesc = "Illegal instruction"; break;
+               case SIGABRT: sigdesc = "Aborted"; break;
+               case SIGFPE:  sigdesc = "Floating point exception"; break;
+               case SIGSEGV: sigdesc = "Segmentation fault"; break;
+               default:      sigdesc = "Yo dawg, we hit a bug while hitting a bug";
+       }
+
+       // 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
+
+       fprintf(stderr, "\n\n\e[1;37;41m    Engine Crash: %s (%d)    \e[m\n", sigdesc, sig);
+#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
+       fprintf(stderr, "\e[1m%s\e[m\n", engineversion);
+
+       // DP8 TODO: send a disconnect message indicating we crashed, see CL_DisconnectEx()
+
+       // don't want a dead window left blocking the OS UI or the crash dialog
+       VID_Shutdown();
+       S_StopAllSounds();
+
+       Sys_SDL_Dialog("Engine Crash", sigdesc);
 
+       fflush(stderr);
+
+       exit (sig);
+}
+
+static void Sys_HandleSignal(int sig)
+{
+#ifdef WIN32
+       // Windows users will likely never see this so no point replicating strsignal()
+       Con_Printf("\nReceived signal %d, exiting...\n", sig);
+#else
+       Con_Printf("\nReceived %s signal (%d), exiting...\n", strsignal(sig), sig);
+#endif
+       host.state = host_shutdown;
+}
+
+/// SDL2 only handles SIGINT and SIGTERM by default and doesn't log anything
+static void Sys_InitSignals(void)
+{
+// Windows docs say its signal() only accepts these ones
+       signal(SIGABRT, Sys_HandleCrash);
+       signal(SIGFPE,  Sys_HandleCrash);
+       signal(SIGILL,  Sys_HandleCrash);
+       signal(SIGINT,  Sys_HandleSignal);
+       signal(SIGSEGV, Sys_HandleCrash);
+       signal(SIGTERM, Sys_HandleSignal);
+#ifndef WIN32
+       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);