]> git.xonotic.org Git - xonotic/darkplaces.git/blob - sys_shared.c
0dcdd87556b8ed10211bf1938ee217e9ff57e99a
[xonotic/darkplaces.git] / sys_shared.c
1 #ifdef WIN32
2 # ifndef DONT_USE_SETDLLDIRECTORY
3 #  define _WIN32_WINNT 0x0502
4 # endif
5 #endif
6
7 #define SUPPORTDLL
8
9 #ifdef WIN32
10 # include <windows.h>
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
15 #ifdef _MSC_VER
16 #pragma comment(lib, "winmm.lib")
17 #endif
18 #else
19 # ifdef __FreeBSD__
20 #  include <sys/sysctl.h>
21 # endif
22 # ifdef __ANDROID__
23 #  include <android/log.h>
24 # endif
25 # include <unistd.h>
26 # include <fcntl.h>
27 # include <sys/time.h>
28 # include <time.h>
29 # ifdef SUPPORTDLL
30 #  include <dlfcn.h>
31 # endif
32 #endif
33
34 #include <signal.h>
35
36 #include "quakedef.h"
37 #include "taskqueue.h"
38 #include "thread.h"
39 #include "libcurl.h"
40
41
42 sys_t sys;
43
44 static char sys_timestring[128];
45 char *Sys_TimeString(const char *timeformat)
46 {
47         time_t mytime = time(NULL);
48 #if _MSC_VER >= 1400
49         struct tm mytm;
50         localtime_s(&mytm, &mytime);
51         strftime(sys_timestring, sizeof(sys_timestring), timeformat, &mytm);
52 #else
53         strftime(sys_timestring, sizeof(sys_timestring), timeformat, localtime(&mytime));
54 #endif
55         return sys_timestring;
56 }
57
58
59 #ifdef __cplusplus
60 extern "C"
61 #endif
62 void Sys_AllowProfiling(qbool enable)
63 {
64 #ifdef __ANDROID__
65 #ifdef USE_PROFILER
66         extern void monstartup(const char *libname);
67         extern void moncleanup(void);
68         if (enable)
69                 monstartup("libmain.so");
70         else
71                 moncleanup();
72 #endif
73 #elif (defined(__linux__) && (defined(__GLIBC__) || defined(__GNU_LIBRARY__))) || defined(__FreeBSD__)
74         extern int moncontrol(int);
75         moncontrol(enable);
76 #endif
77 }
78
79
80 /*
81 ===============================================================================
82
83 DLL MANAGEMENT
84
85 ===============================================================================
86 */
87
88 static qbool Sys_LoadDependencyFunctions(dllhandle_t dllhandle, const dllfunction_t *fcts, qbool complain, qbool has_next)
89 {
90         const dllfunction_t *func;
91         if(dllhandle)
92         {
93                 for (func = fcts; func && func->name != NULL; func++)
94                         if (!(*func->funcvariable = (void *) Sys_GetProcAddress (dllhandle, func->name)))
95                         {
96                                 if(complain)
97                                 {
98                                         Con_DPrintf (" - missing function \"%s\" - broken library!", func->name);
99                                         if(has_next)
100                                                 Con_DPrintf("\nContinuing with");
101                                 }
102                                 goto notfound;
103                         }
104                 return true;
105
106         notfound:
107                 for (func = fcts; func && func->name != NULL; func++)
108                         *func->funcvariable = NULL;
109         }
110         return false;
111 }
112
113 qbool Sys_LoadSelf(dllhandle_t *handle)
114 {
115         dllhandle_t dllhandle = 0;
116
117         if (handle == NULL)
118                 return false;
119 #ifdef WIN32
120         dllhandle = LoadLibrary (NULL);
121 #else
122         dllhandle = dlopen (NULL, RTLD_NOW | RTLD_GLOBAL);
123 #endif
124         *handle = dllhandle;
125         return true;
126 }
127
128 qbool Sys_LoadDependency (const char** dllnames, dllhandle_t* handle, const dllfunction_t *fcts)
129 {
130 #ifdef SUPPORTDLL
131         const dllfunction_t *func;
132         dllhandle_t dllhandle = 0;
133         unsigned int i;
134
135         if (handle == NULL)
136                 return false;
137
138 #ifndef WIN32
139 #ifdef PREFER_PRELOAD
140         dllhandle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL);
141         if(Sys_LoadDependencyFunctions(dllhandle, fcts, false, false))
142         {
143                 Con_DPrintf ("All of %s's functions were already linked in! Not loading dynamically...\n", dllnames[0]);
144                 *handle = dllhandle;
145                 return true;
146         }
147         else
148                 Sys_FreeLibrary(&dllhandle);
149 notfound:
150 #endif
151 #endif
152
153         // Initializations
154         for (func = fcts; func && func->name != NULL; func++)
155                 *func->funcvariable = NULL;
156
157         // Try every possible name
158         Con_DPrintf ("Trying to load library...");
159         for (i = 0; dllnames[i] != NULL; i++)
160         {
161                 Con_DPrintf (" \"%s\"", dllnames[i]);
162 #ifdef WIN32
163 # ifndef DONT_USE_SETDLLDIRECTORY
164 #  ifdef _WIN64
165                 SetDllDirectory("bin64");
166 #  else
167                 SetDllDirectory("bin32");
168 #  endif
169 # endif
170 #endif
171                 if(Sys_LoadLibrary(dllnames[i], &dllhandle))
172                 {
173                         if (Sys_LoadDependencyFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
174                                 break;
175                         else
176                                 Sys_FreeLibrary (&dllhandle);
177                 }
178         }
179
180         // see if the names can be loaded relative to the executable path
181         // (this is for Mac OSX which does not check next to the executable)
182         if (!dllhandle && strrchr(sys.argv[0], '/'))
183         {
184                 char path[MAX_OSPATH];
185                 dp_strlcpy(path, sys.argv[0], sizeof(path));
186                 strrchr(path, '/')[1] = 0;
187                 for (i = 0; dllnames[i] != NULL; i++)
188                 {
189                         char temp[MAX_OSPATH];
190                         dp_strlcpy(temp, path, sizeof(temp));
191                         dp_strlcat(temp, dllnames[i], sizeof(temp));
192                         Con_DPrintf (" \"%s\"", temp);
193
194                         if(Sys_LoadLibrary(temp, &dllhandle))
195                         {
196                                 if (Sys_LoadDependencyFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
197                                         break;
198                                 else
199                                         Sys_FreeLibrary (&dllhandle);
200                         }
201                 }
202         }
203
204         // No DLL found
205         if (! dllhandle)
206         {
207                 Con_DPrintf(" - failed.\n");
208                 return false;
209         }
210
211         Con_DPrintf(" - loaded.\n");
212         Con_Printf("Loaded library \"%s\"\n", dllnames[i]);
213
214         *handle = dllhandle;
215         return true;
216 #else
217         return false;
218 #endif
219 }
220
221 qbool Sys_LoadLibrary(const char *name, dllhandle_t *handle)
222 {
223         dllhandle_t dllhandle = 0;
224
225         if(handle == NULL)
226                 return false;
227
228 #ifdef SUPPORTDLL
229 # ifdef WIN32
230         dllhandle = LoadLibrary (name);
231 # else
232         dllhandle = dlopen (name, RTLD_LAZY | RTLD_GLOBAL);
233 # endif
234 #endif
235         if(!dllhandle)
236                 return false;
237
238         *handle = dllhandle;
239         return true;
240 }
241
242 void Sys_FreeLibrary (dllhandle_t* handle)
243 {
244 #ifdef SUPPORTDLL
245         if (handle == NULL || *handle == NULL)
246                 return;
247
248 #ifdef WIN32
249         FreeLibrary (*handle);
250 #else
251         dlclose (*handle);
252 #endif
253
254         *handle = NULL;
255 #endif
256 }
257
258 void* Sys_GetProcAddress (dllhandle_t handle, const char* name)
259 {
260 #ifdef SUPPORTDLL
261 #ifdef WIN32
262         return (void *)GetProcAddress (handle, name);
263 #else
264         return (void *)dlsym (handle, name);
265 #endif
266 #else
267         return NULL;
268 #endif
269 }
270
271 #ifdef WIN32
272 # define HAVE_TIMEGETTIME 1
273 # define HAVE_QUERYPERFORMANCECOUNTER 1
274 # define HAVE_WIN32_USLEEP 1
275 # define HAVE_Sleep 1
276 #endif
277
278 #ifndef WIN32
279 #if defined(CLOCK_MONOTONIC) || defined(CLOCK_HIRES)
280 # define HAVE_CLOCKGETTIME 1
281 #endif
282 // FIXME improve this check, manpage hints to DST_NONE
283 # define HAVE_GETTIMEOFDAY 1
284 #endif
285
286 #ifdef FD_SET
287 # define HAVE_SELECT 1
288 #endif
289
290 #ifndef WIN32
291 // FIXME improve this check
292 # define HAVE_USLEEP 1
293 #endif
294
295 // these are referenced elsewhere
296 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."};
297 cvar_t sys_libdir = {CF_READONLY | CF_SHARED, "sys_libdir", "", "Default engine library directory"};
298
299 // these are not
300 static cvar_t sys_debugsleep = {CF_SHARED, "sys_debugsleep", "0", "write requested and attained sleep times to standard output, to be used with gnuplot"};
301 static cvar_t sys_usesdlgetticks = {CF_SHARED, "sys_usesdlgetticks", "0", "use SDL_GetTicks() timer (low precision, for debugging)"};
302 static cvar_t sys_usesdldelay = {CF_SHARED, "sys_usesdldelay", "0", "use SDL_Delay() (low precision, for debugging)"};
303 #if HAVE_QUERYPERFORMANCECOUNTER
304 static cvar_t sys_usequeryperformancecounter = {CF_SHARED | CF_ARCHIVE, "sys_usequeryperformancecounter", "1", "use windows QueryPerformanceCounter timer (which has issues on systems lacking constant-rate TSCs synchronised across all cores, such as ancient PCs or VMs) for timing rather than timeGetTime function (which is low precision and had issues on some old motherboards)"};
305 #endif
306 #if HAVE_CLOCKGETTIME
307 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)"};
308 #endif
309
310 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)"};
311 #ifndef WIN32
312 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"};
313 #endif
314
315 static double benchmark_time; // actually always contains an integer amount of milliseconds, will eventually "overflow"
316
317 /*
318 ================
319 Sys_CheckParm
320
321 Returns the position (1 to argc-1) in the program's argument list
322 where the given parameter apears, or 0 if not present
323 ================
324 */
325 int Sys_CheckParm (const char *parm)
326 {
327         int i;
328
329         for (i=1 ; i<sys.argc ; i++)
330         {
331                 if (!sys.argv[i])
332                         continue;               // NEXTSTEP sometimes clears appkit vars.
333                 if (!strcmp (parm,sys.argv[i]))
334                         return i;
335         }
336
337         return 0;
338 }
339
340 static void Sys_UpdateOutFD_c(cvar_t *var)
341 {
342         switch (sys_stdout.integer)
343         {
344                 case 0: sys.outfd = -1; break;
345                 default:
346                 case 1: sys.outfd = fileno(stdout); break;
347                 case 2: sys.outfd = fileno(stderr); break;
348         }
349 }
350
351 void Sys_Init_Commands (void)
352 {
353         Cvar_RegisterVariable(&sys_debugsleep);
354         Cvar_RegisterVariable(&sys_usenoclockbutbenchmark);
355         Cvar_RegisterVariable(&sys_libdir);
356 #if HAVE_TIMEGETTIME || HAVE_QUERYPERFORMANCECOUNTER || HAVE_CLOCKGETTIME || HAVE_GETTIMEOFDAY
357         if(sys_supportsdlgetticks)
358         {
359                 Cvar_RegisterVariable(&sys_usesdlgetticks);
360                 Cvar_RegisterVariable(&sys_usesdldelay);
361         }
362 #endif
363 #if HAVE_QUERYPERFORMANCECOUNTER
364         Cvar_RegisterVariable(&sys_usequeryperformancecounter);
365 #endif
366 #if HAVE_CLOCKGETTIME
367         Cvar_RegisterVariable(&sys_useclockgettime);
368 #endif
369         Cvar_RegisterVariable(&sys_stdout);
370         Cvar_RegisterCallback(&sys_stdout, Sys_UpdateOutFD_c);
371 #ifndef WIN32
372         Cvar_RegisterVariable(&sys_stdout_blocks);
373 #endif
374 }
375
376 #ifdef WIN32
377 static LARGE_INTEGER PerformanceFreq;
378 /// Windows default timer resolution is only 15.625ms,
379 /// this affects (at least) timeGetTime() and all forms of sleeping.
380 static void Sys_SetTimerResolution(void)
381 {
382         NTSTATUS(NTAPI *qNtQueryTimerResolution)(OUT PULONG MinRes, OUT PULONG MaxRes, OUT PULONG CurrentRes);
383         NTSTATUS(NTAPI *qNtSetTimerResolution)(IN ULONG DesiredRes, IN BOOLEAN SetRes, OUT PULONG ActualRes);
384         const char* ntdll_names [] =
385         {
386                 "ntdll.dll",
387                 NULL
388         };
389         dllfunction_t ntdll_funcs[] =
390         {
391                 {"NtQueryTimerResolution", (void **) &qNtQueryTimerResolution},
392                 {"NtSetTimerResolution",   (void **) &qNtSetTimerResolution},
393                 {NULL, NULL}
394         };
395         dllhandle_t ntdll;
396         unsigned long WorstRes, BestRes, CurrentRes;
397
398         timeBeginPeriod(1); // 1ms, documented
399
400         // the best Windows can manage (typically 0.5ms)
401         // http://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FTime%2FNtSetTimerResolution.html
402         if (Sys_LoadDependency(ntdll_names, &ntdll, ntdll_funcs))
403         {
404                 qNtQueryTimerResolution(&WorstRes, &BestRes, &CurrentRes); // no pointers may be NULL
405                 if (CurrentRes > BestRes)
406                         qNtSetTimerResolution(BestRes, true, &CurrentRes);
407
408                 Sys_FreeLibrary(&ntdll);
409         }
410
411         // Microsoft says the freq is fixed at boot and consistent across all processors
412         // and that it need only be queried once and cached.
413         QueryPerformanceFrequency (&PerformanceFreq);
414 }
415 #endif // WIN32
416
417 double Sys_DirtyTime(void)
418 {
419         // first all the OPTIONAL timers
420
421         // benchmark timer (fake clock)
422         if(sys_usenoclockbutbenchmark.integer)
423         {
424                 double old_benchmark_time = benchmark_time;
425                 benchmark_time += 1;
426                 if(benchmark_time == old_benchmark_time)
427                         Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
428                 return benchmark_time * 0.000001;
429         }
430 #if HAVE_QUERYPERFORMANCECOUNTER
431         if (sys_usequeryperformancecounter.integer)
432         {
433                 // QueryPerformanceCounter
434                 // platform:
435                 // Windows 95/98/ME/NT/2000/XP
436                 // features:
437                 // + very accurate (constant-rate TSCs on modern systems)
438                 // known issues:
439                 // - does not necessarily match realtime too well (tends to get faster and faster in win98)
440                 // - wraps around occasionally on some platforms (depends on CPU speed and probably other unknown factors)
441                 // - higher access latency on Vista
442                 // Microsoft says on Win 7 or later, latency and overhead are very low, synchronisation is excellent.
443                 LARGE_INTEGER PerformanceCount;
444
445                 if (PerformanceFreq.QuadPart)
446                 {
447                         QueryPerformanceCounter (&PerformanceCount);
448                         return (double)PerformanceCount.QuadPart * (1.0 / (double)PerformanceFreq.QuadPart);
449                 }
450                 else
451                 {
452                         Con_Printf("No hardware timer available\n");
453                         // fall back to other clock sources
454                         Cvar_SetValueQuick(&sys_usequeryperformancecounter, false);
455                 }
456         }
457 #endif
458
459 #if HAVE_CLOCKGETTIME
460         if (sys_useclockgettime.integer)
461         {
462                 struct timespec ts;
463 #  ifdef CLOCK_MONOTONIC
464                 // linux
465                 clock_gettime(CLOCK_MONOTONIC, &ts);
466 #  else
467                 // sunos
468                 clock_gettime(CLOCK_HIGHRES, &ts);
469 #  endif
470                 return (double) ts.tv_sec + ts.tv_nsec / 1000000000.0;
471         }
472 #endif
473
474         // now all the FALLBACK timers
475         if(sys_supportsdlgetticks && sys_usesdlgetticks.integer)
476                 return (double) Sys_SDL_GetTicks() / 1000.0;
477 #if HAVE_GETTIMEOFDAY
478         {
479                 struct timeval tp;
480                 gettimeofday(&tp, NULL);
481                 return (double) tp.tv_sec + tp.tv_usec / 1000000.0;
482         }
483 #elif HAVE_TIMEGETTIME
484         {
485                 // timeGetTime
486                 // platform:
487                 // Windows 95/98/ME/NT/2000/XP
488                 // features:
489                 // reasonable accuracy (millisecond)
490                 // issues:
491                 // wraps around every 47 days or so (but this is non-fatal to us, odd times are rejected, only causes a one frame stutter)
492                 // requires Sys_SetTimerResolution()
493                 return (double) timeGetTime() / 1000.0;
494         }
495 #else
496         // fallback for using the SDL timer if no other timer is available
497         // this calls Sys_Error() if not linking against SDL
498         return (double) Sys_SDL_GetTicks() / 1000.0;
499 #endif
500 }
501
502 extern cvar_t host_maxwait;
503 double Sys_Sleep(double time)
504 {
505         double dt;
506         uint32_t microseconds;
507
508         // convert to microseconds
509         time *= 1000000.0;
510
511         if(host_maxwait.value <= 0)
512                 time = min(time, 1000000.0);
513         else
514                 time = min(time, host_maxwait.value * 1000.0);
515
516         if (time < 1 || host.restless)
517                 return 0; // not sleeping this frame
518
519         microseconds = time; // post-validation to prevent overflow
520
521         if(sys_usenoclockbutbenchmark.integer)
522         {
523                 double old_benchmark_time = benchmark_time;
524                 benchmark_time += microseconds;
525                 if(benchmark_time == old_benchmark_time)
526                         Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
527                 return 0;
528         }
529
530         if(sys_debugsleep.integer)
531                 Con_Printf("sys_debugsleep: requesting %u ", microseconds);
532         dt = Sys_DirtyTime();
533
534         // less important on newer libcurl so no need to disturb dedicated servers
535         if (cls.state != ca_dedicated && Curl_Select(microseconds))
536         {
537                 // a transfer is ready or we finished sleeping
538         }
539         else if(sys_supportsdlgetticks && sys_usesdldelay.integer)
540                 Sys_SDL_Delay(microseconds / 1000);
541 #if HAVE_SELECT
542         else if (cls.state == ca_dedicated && sv_checkforpacketsduringsleep.integer)
543         {
544                 struct timeval tv;
545                 lhnetsocket_t *s;
546                 fd_set fdreadset;
547                 int lastfd = -1;
548
549                 FD_ZERO(&fdreadset);
550                 List_For_Each_Entry(s, &lhnet_socketlist.list, lhnetsocket_t, list)
551                 {
552                         if (s->address.addresstype == LHNETADDRESSTYPE_INET4 || s->address.addresstype == LHNETADDRESSTYPE_INET6)
553                         {
554                                 if (lastfd < s->inetsocket)
555                                         lastfd = s->inetsocket;
556         #if defined(WIN32) && !defined(_MSC_VER)
557                                 FD_SET((int)s->inetsocket, &fdreadset);
558         #else
559                                 FD_SET((unsigned int)s->inetsocket, &fdreadset);
560         #endif
561                         }
562                 }
563                 tv.tv_sec = microseconds / 1000000;
564                 tv.tv_usec = microseconds % 1000000;
565                 // on Win32, select() cannot be used with all three FD list args being NULL according to MSDN
566                 // (so much for POSIX...), not with an empty fd_set either.
567                 select(lastfd + 1, &fdreadset, NULL, NULL, &tv);
568         }
569 #endif
570 #if HAVE_USLEEP
571         else
572                 usleep(microseconds);
573 #elif HAVE_WIN32_USLEEP // Windows XP/2003 minimum
574         else
575         {
576                 HANDLE timer;
577                 LARGE_INTEGER sleeptime;
578
579                 // takes 100ns units, negative indicates relative time
580                 sleeptime.QuadPart = -(10 * (int64_t)microseconds);
581                 timer = CreateWaitableTimer(NULL, true, NULL);
582                 SetWaitableTimer(timer, &sleeptime, 0, NULL, NULL, 0);
583                 WaitForSingleObject(timer, INFINITE);
584                 CloseHandle(timer);
585         }
586 #elif HAVE_Sleep
587         else
588                 Sleep(microseconds / 1000);
589 #else
590         else
591                 Sys_SDL_Delay(microseconds / 1000);
592 #endif
593
594         dt = Sys_DirtyTime() - dt;
595         if(sys_debugsleep.integer)
596                 Con_Printf(" got %u oversleep %d\n", (unsigned int)(dt * 1000000), (unsigned int)(dt * 1000000) - microseconds);
597         return (dt < 0 || dt >= 1800) ? 0 : dt;
598 }
599
600
601 /*
602 ===============================================================================
603
604 STDIO
605
606 ===============================================================================
607 */
608
609 // NOTE: use only POSIX async-signal-safe library functions here (see: man signal-safety)
610 void Sys_Print(const char *text, size_t textlen)
611 {
612 #ifdef __ANDROID__
613         if (developer.integer > 0)
614         {
615                 __android_log_write(ANDROID_LOG_DEBUG, sys.argv[0], text);
616         }
617 #else
618         if(sys.outfd < 0)
619                 return;
620   #ifndef WIN32
621         // BUG: for some reason, NDELAY also affects stdout (1) when used on stdin (0).
622         // this is because both go to /dev/tty by default!
623         {
624                 int origflags = fcntl(sys.outfd, F_GETFL, 0);
625                 if (sys_stdout_blocks.integer)
626                         fcntl(sys.outfd, F_SETFL, origflags & ~O_NONBLOCK);
627   #else
628     #define write _write
629   #endif
630                 while(*text)
631                 {
632                         fs_offset_t written = (fs_offset_t)write(sys.outfd, text, textlen);
633                         if(written <= 0)
634                                 break; // sorry, I cannot do anything about this error - without an output
635                         text += written;
636                 }
637   #ifndef WIN32
638                 if (sys_stdout_blocks.integer)
639                         fcntl(sys.outfd, F_SETFL, origflags);
640         }
641   #endif
642         //fprintf(stdout, "%s", text);
643 #endif
644 }
645
646 void Sys_Printf(const char *fmt, ...)
647 {
648         va_list argptr;
649         char msg[MAX_INPUTLINE];
650         int msglen;
651
652         va_start(argptr,fmt);
653         msglen = dpvsnprintf(msg, sizeof(msg), fmt, argptr);
654         va_end(argptr);
655
656         if (msglen >= 0)
657                 Sys_Print(msg, msglen);
658 }
659
660 /// Reads a line from POSIX stdin or the Windows console
661 char *Sys_ConsoleInput(void)
662 {
663         static char text[MAX_INPUTLINE];
664 #ifdef WIN32
665         static unsigned int len = 0;
666         int c;
667
668         // read a line out
669         while (_kbhit ())
670         {
671                 c = _getch ();
672                 if (c == '\r')
673                 {
674                         text[len] = '\0';
675                         _putch ('\n');
676                         len = 0;
677                         return text;
678                 }
679                 if (c == '\b')
680                 {
681                         if (len)
682                         {
683                                 _putch (c);
684                                 _putch (' ');
685                                 _putch (c);
686                                 len--;
687                         }
688                         continue;
689                 }
690                 if (len < sizeof (text) - 1)
691                 {
692                         _putch (c);
693                         text[len] = c;
694                         len++;
695                 }
696         }
697 #else
698         fd_set fdset;
699         struct timeval timeout = { .tv_sec = 0, .tv_usec = 0 };
700
701         FD_ZERO(&fdset);
702         FD_SET(fileno(stdin), &fdset);
703         if (select(1, &fdset, NULL, NULL, &timeout) != -1 && FD_ISSET(fileno(stdin), &fdset))
704                 return fgets(text, sizeof(text), stdin);
705 #endif
706         return NULL;
707 }
708
709
710 /*
711 ===============================================================================
712
713 Startup and Shutdown
714
715 ===============================================================================
716 */
717
718 void Sys_Error (const char *error, ...)
719 {
720         va_list argptr;
721         char string[MAX_INPUTLINE];
722         int i;
723
724         // Disable Sys_HandleSignal() but not Sys_HandleCrash()
725         host.state = host_shutdown;
726
727         // set output to blocking stderr
728         sys.outfd = fileno(stderr);
729 #ifndef WIN32
730         fcntl(sys.outfd, F_SETFL, fcntl(sys.outfd, F_GETFL, 0) & ~O_NONBLOCK);
731 #endif
732
733         va_start (argptr,error);
734         dpvsnprintf (string, sizeof (string), error, argptr);
735         va_end (argptr);
736
737         Con_Printf(CON_ERROR "Engine Aborted: %s\n^9%s\n", string, engineversion);
738
739         dp_strlcat(string, "\n\n", sizeof(string));
740         dp_strlcat(string, engineversion, sizeof(string));
741
742         // Most shutdown funcs can't be called here as they could error while we error.
743
744         // DP8 TODO: send a disconnect message indicating we aborted, see Host_Error() and Sys_HandleCrash()
745
746         if (cls.demorecording)
747                 CL_Stop_f(cmd_local);
748         if (sv.active)
749         {
750                 sv.active = false; // make SV_DropClient() skip the QC stuff to avoid recursive errors
751                 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
752                         if (host_client->active)
753                                 SV_DropClient(false, "Server aborted!"); // closes demo file
754         }
755         // don't want a dead window left blocking the OS UI or the abort dialog
756         VID_Shutdown();
757         S_StopAllSounds();
758
759         host.state = host_failed; // make Sys_HandleSignal() call _Exit()
760         Sys_SDL_Dialog("Engine Aborted", string);
761
762         fflush(stderr);
763         exit (1);
764 }
765
766 #ifndef WIN32
767 static const char *Sys_FindInPATH(const char *name, char namesep, const char *PATH, char pathsep, char *buf, size_t bufsize)
768 {
769         const char *p = PATH;
770         const char *q;
771         if(p && name)
772         {
773                 while((q = strchr(p, ':')))
774                 {
775                         dpsnprintf(buf, bufsize, "%.*s%c%s", (int)(q-p), p, namesep, name);
776                         if(FS_SysFileExists(buf))
777                                 return buf;
778                         p = q + 1;
779                 }
780                 if(!q) // none found - try the last item
781                 {
782                         dpsnprintf(buf, bufsize, "%s%c%s", p, namesep, name);
783                         if(FS_SysFileExists(buf))
784                                 return buf;
785                 }
786         }
787         return name;
788 }
789 #endif
790
791 static const char *Sys_FindExecutableName(void)
792 {
793 #if defined(WIN32)
794         return sys.argv[0];
795 #else
796         static char exenamebuf[MAX_OSPATH+1];
797         ssize_t n = -1;
798 #if defined(__FreeBSD__)
799         int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
800         size_t exenamebuflen = sizeof(exenamebuf)-1;
801         if (sysctl(mib, 4, exenamebuf, &exenamebuflen, NULL, 0) == 0)
802         {
803                 n = exenamebuflen;
804         }
805 #elif defined(__linux__)
806         n = readlink("/proc/self/exe", exenamebuf, sizeof(exenamebuf)-1);
807 #endif
808         if(n > 0 && (size_t)(n) < sizeof(exenamebuf))
809         {
810                 exenamebuf[n] = 0;
811                 return exenamebuf;
812         }
813         if(strchr(sys.argv[0], '/'))
814                 return sys.argv[0]; // possibly a relative path
815         else
816                 return Sys_FindInPATH(sys.argv[0], '/', getenv("PATH"), ':', exenamebuf, sizeof(exenamebuf));
817 #endif
818 }
819
820 void Sys_ProvideSelfFD(void)
821 {
822         if(sys.selffd != -1)
823                 return;
824         sys.selffd = FS_SysOpenFD(Sys_FindExecutableName(), "rb", false);
825 }
826
827 // for x86 cpus only...  (x64 has SSE2_PRESENT)
828 #if defined(SSE_POSSIBLE) && !defined(SSE2_PRESENT)
829 // code from SDL, shortened as we can expect CPUID to work
830 static int CPUID_Features(void)
831 {
832         int features = 0;
833 # if (defined(__GNUC__) || defined(__clang__) || defined(__TINYC__)) && defined(__i386__)
834         __asm__ (
835 "        movl    %%ebx,%%edi\n"
836 "        xorl    %%eax,%%eax                                           \n"
837 "        incl    %%eax                                                 \n"
838 "        cpuid                       # Get family/model/stepping/features\n"
839 "        movl    %%edx,%0                                              \n"
840 "        movl    %%edi,%%ebx\n"
841         : "=m" (features)
842         :
843         : "%eax", "%ecx", "%edx", "%edi"
844         );
845 # elif (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
846         __asm {
847         xor     eax, eax
848         inc     eax
849         cpuid                       ; Get family/model/stepping/features
850         mov     features, edx
851         }
852 # else
853 #  error SSE_POSSIBLE set but no CPUID implementation
854 # endif
855         return features;
856 }
857 #endif
858
859 #ifdef SSE_POSSIBLE
860 qbool Sys_HaveSSE(void)
861 {
862         // COMMANDLINEOPTION: SSE: -nosse disables SSE support and detection
863         if(Sys_CheckParm("-nosse"))
864                 return false;
865 #ifdef SSE_PRESENT
866         return true;
867 #else
868         // COMMANDLINEOPTION: SSE: -forcesse enables SSE support and disables detection
869         if(Sys_CheckParm("-forcesse") || Sys_CheckParm("-forcesse2"))
870                 return true;
871         if(CPUID_Features() & (1 << 25))
872                 return true;
873         return false;
874 #endif
875 }
876
877 qbool Sys_HaveSSE2(void)
878 {
879         // COMMANDLINEOPTION: SSE2: -nosse2 disables SSE2 support and detection
880         if(Sys_CheckParm("-nosse") || Sys_CheckParm("-nosse2"))
881                 return false;
882 #ifdef SSE2_PRESENT
883         return true;
884 #else
885         // COMMANDLINEOPTION: SSE2: -forcesse2 enables SSE2 support and disables detection
886         if(Sys_CheckParm("-forcesse2"))
887                 return true;
888         if((CPUID_Features() & (3 << 25)) == (3 << 25)) // SSE is 1<<25, SSE2 is 1<<26
889                 return true;
890         return false;
891 #endif
892 }
893 #endif
894
895 /// called to set process priority for dedicated servers
896 #if defined(__linux__)
897 #include <sys/resource.h>
898 #include <errno.h>
899
900 void Sys_InitProcessNice (void)
901 {
902         struct rlimit lim;
903         sys.nicepossible = false;
904         if(Sys_CheckParm("-nonice"))
905                 return;
906         errno = 0;
907         sys.nicelevel = getpriority(PRIO_PROCESS, 0);
908         if(errno)
909         {
910                 Con_Printf("Kernel does not support reading process priority - cannot use niceness\n");
911                 return;
912         }
913         if(getrlimit(RLIMIT_NICE, &lim))
914         {
915                 Con_Printf("Kernel does not support lowering nice level again - cannot use niceness\n");
916                 return;
917         }
918         if(lim.rlim_cur != RLIM_INFINITY && sys.nicelevel < (int) (20 - lim.rlim_cur))
919         {
920                 Con_Printf("Current nice level is below the soft limit - cannot use niceness\n");
921                 return;
922         }
923         sys.nicepossible = true;
924         sys.isnice = false;
925 }
926 void Sys_MakeProcessNice (void)
927 {
928         if(!sys.nicepossible)
929                 return;
930         if(sys.isnice)
931                 return;
932         Con_DPrintf("Process is becoming 'nice'...\n");
933         if(setpriority(PRIO_PROCESS, 0, 19))
934                 Con_Printf(CON_ERROR "Failed to raise nice level to %d\n", 19);
935         sys.isnice = true;
936 }
937 void Sys_MakeProcessMean (void)
938 {
939         if(!sys.nicepossible)
940                 return;
941         if(!sys.isnice)
942                 return;
943         Con_DPrintf("Process is becoming 'mean'...\n");
944         if(setpriority(PRIO_PROCESS, 0, sys.nicelevel))
945                 Con_Printf(CON_ERROR "Failed to lower nice level to %d\n", sys.nicelevel);
946         sys.isnice = false;
947 }
948 #else
949 void Sys_InitProcessNice (void)
950 {
951 }
952 void Sys_MakeProcessNice (void)
953 {
954 }
955 void Sys_MakeProcessMean (void)
956 {
957 }
958 #endif
959
960
961 static const char *Sys_SigDesc(int sig)
962 {
963         switch (sig)
964         {
965                 // Windows only supports the C99 signals
966                 case SIGINT:  return "Interrupt";
967                 case SIGILL:  return "Illegal instruction";
968                 case SIGABRT: return "Aborted";
969                 case SIGFPE:  return "Floating point exception";
970                 case SIGSEGV: return "Segmentation fault";
971                 case SIGTERM: return "Termination";
972 #ifndef WIN32
973                 // POSIX has several others worth catching
974                 case SIGHUP:  return "Hangup";
975                 case SIGQUIT: return "Quit";
976                 case SIGBUS:  return "Bus error (bad memory access)";
977                 case SIGPIPE: return "Broken pipe";
978 #endif
979                 default:      return "Yo dawg, we bugged out while bugging out";
980         }
981 }
982
983 /** Halt and try not to catch fire.
984  * Writing to any file could corrupt it,
985  * any uneccessary code could crash while we crash.
986  * Try to use only POSIX async-signal-safe library functions here (see: man signal-safety).
987  */
988 static void Sys_HandleCrash(int sig)
989 {
990 #if __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 1
991         // Before doing anything else grab the stack frame addresses
992         #include <execinfo.h>
993         void *stackframes[32];
994         int framecount = backtrace(stackframes, 32);
995         char **btstrings;
996 #endif
997         char dialogtext[3072];
998         const char *sigdesc;
999
1000         // Break any loop and disable Sys_HandleSignal()
1001         if (host.state == host_failing || host.state == host_failed)
1002                 return;
1003         host.state = host_failing;
1004
1005         sigdesc = Sys_SigDesc(sig);
1006
1007         // set output to blocking stderr and print header, backtrace, version
1008         sys.outfd = fileno(stderr); // not async-signal-safe :(
1009 #ifndef WIN32
1010         fcntl(sys.outfd, F_SETFL, fcntl(sys.outfd, F_GETFL, 0) & ~O_NONBLOCK);
1011         Sys_Print("\n\n\e[1;37;41m    Engine Crash: ", 30);
1012         Sys_Print(sigdesc, strlen(sigdesc));
1013         Sys_Print("    \e[m\n", 8);
1014   #if __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 1
1015         // the first two addresses will be in this function and in signal() in libc
1016         backtrace_symbols_fd(stackframes + 2, framecount - 2, sys.outfd);
1017   #endif
1018         Sys_Print("\e[1m", 4);
1019         Sys_Print(engineversion, strlen(engineversion));
1020         Sys_Print("\e[m\n", 4);
1021 #else // Windows console doesn't support colours
1022         Sys_Print("\n\nEngine Crash: ", 16);
1023         Sys_Print(sigdesc, strlen(sigdesc));
1024         Sys_Print("\n", 1);
1025         Sys_Print(engineversion, strlen(engineversion));
1026         Sys_Print("\n", 1);
1027 #endif
1028
1029         // DP8 TODO: send a disconnect message indicating we crashed, see Sys_Error() and Host_Error()
1030
1031         // don't want a dead window left blocking the OS UI or the crash dialog
1032         VID_Shutdown();
1033         S_StopAllSounds();
1034
1035         // prepare the dialogtext: signal, backtrace, version
1036         // the dp_st* funcs are POSIX async-signal-safe IF we don't trigger their warnings
1037         dp_strlcpy(dialogtext, sigdesc, sizeof(dialogtext));
1038         dp_strlcat(dialogtext, "\n\n", sizeof(dialogtext));
1039 #if __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 1
1040         btstrings = backtrace_symbols(stackframes + 2, framecount - 2); // calls malloc :(
1041         if (btstrings)
1042                 for (int i = 0; i < framecount - 2; ++i)
1043                 {
1044                         dp_strlcat(dialogtext, btstrings[i], sizeof(dialogtext));
1045                         dp_strlcat(dialogtext, "\n", sizeof(dialogtext));
1046                 }
1047 #endif
1048         dp_strlcat(dialogtext, "\n", sizeof(dialogtext));
1049         dp_strlcat(dialogtext, engineversion, sizeof(dialogtext));
1050
1051         host.state = host_failed; // make Sys_HandleSignal() call _Exit()
1052         Sys_SDL_Dialog("Engine Crash", dialogtext);
1053
1054         fflush(stderr); // not async-signal-safe :(
1055
1056         // Continue execution with default signal handling.
1057         // A real crash will be re-triggered so the platform can handle it,
1058         // a fake crash (kill -SEGV) will cause a graceful shutdown.
1059         signal(sig, SIG_DFL);
1060 }
1061
1062 static void Sys_HandleSignal(int sig)
1063 {
1064         const char *sigdesc;
1065
1066         // Break any loop, eg if each Sys_Print triggers a SIGPIPE
1067         if (host.state == host_shutdown || host.state == host_failing)
1068                 return;
1069
1070         sigdesc = Sys_SigDesc(sig);
1071         Sys_Print("\nReceived ", 10);
1072         Sys_Print(sigdesc, strlen(sigdesc));
1073         Sys_Print(" signal, exiting...\n", 20);
1074         if (host.state == host_failed)
1075         {
1076                 // user is trying to kill the process while the SDL dialog is open
1077                 fflush(stderr); // not async-signal-safe :(
1078                 _Exit(sig);
1079         }
1080         host.state = host_shutdown;
1081 }
1082
1083 /// SDL2 only handles SIGINT and SIGTERM by default and doesn't log anything
1084 static void Sys_InitSignals(void)
1085 {
1086         // Windows only supports the C99 signals
1087         signal(SIGINT,  Sys_HandleSignal);
1088         signal(SIGILL,  Sys_HandleCrash);
1089         signal(SIGABRT, Sys_HandleCrash);
1090         signal(SIGFPE,  Sys_HandleCrash);
1091         signal(SIGSEGV, Sys_HandleCrash);
1092         signal(SIGTERM, Sys_HandleSignal);
1093 #ifndef WIN32
1094         // POSIX has several others worth catching
1095         signal(SIGHUP,  Sys_HandleSignal);
1096         signal(SIGQUIT, Sys_HandleSignal);
1097         signal(SIGBUS,  Sys_HandleCrash);
1098         signal(SIGPIPE, Sys_HandleSignal);
1099 #endif
1100 }
1101
1102 int main (int argc, char **argv)
1103 {
1104         sys.argc = argc;
1105         sys.argv = (const char **)argv;
1106
1107         // COMMANDLINEOPTION: Console: -nostdout disables text output to the terminal the game was launched from
1108         // COMMANDLINEOPTION: -noterminal disables console output on stdout
1109         if(Sys_CheckParm("-noterminal") || Sys_CheckParm("-nostdout"))
1110                 sys_stdout.string = "0";
1111         // COMMANDLINEOPTION: -stderr moves console output to stderr
1112         else if(Sys_CheckParm("-stderr"))
1113                 sys_stdout.string = "2";
1114         // too early for Cvar_SetQuick
1115         sys_stdout.value = sys_stdout.integer = atoi(sys_stdout.string);
1116         Sys_UpdateOutFD_c(&sys_stdout);
1117 #ifndef WIN32
1118         fcntl(fileno(stdin), F_SETFL, fcntl(fileno(stdin), F_GETFL, 0) | O_NONBLOCK);
1119         // stdout/stderr will be set to blocking in Sys_Print() if so configured, or during a fatal error.
1120         fcntl(fileno(stdout), F_SETFL, fcntl(fileno(stdout), F_GETFL, 0) | O_NONBLOCK);
1121         fcntl(fileno(stderr), F_SETFL, fcntl(fileno(stderr), F_GETFL, 0) | O_NONBLOCK);
1122 #endif
1123
1124         sys.selffd = -1;
1125         Sys_ProvideSelfFD(); // may call Con_Printf() so must be after sys.outfd is set
1126
1127 #ifdef __ANDROID__
1128         Sys_AllowProfiling(true);
1129 #endif
1130
1131         Sys_InitSignals();
1132
1133 #ifdef WIN32
1134         Sys_SetTimerResolution();
1135 #endif
1136
1137         Host_Main();
1138
1139 #ifdef __ANDROID__
1140         Sys_AllowProfiling(false);
1141 #endif
1142
1143 #ifndef WIN32
1144         fcntl(fileno(stdout), F_SETFL, fcntl(fileno(stdout), F_GETFL, 0) & ~O_NONBLOCK);
1145         fcntl(fileno(stderr), F_SETFL, fcntl(fileno(stderr), F_GETFL, 0) & ~O_NONBLOCK);
1146 #endif
1147         fflush(stdout);
1148         fflush(stderr);
1149
1150         return 0;
1151 }