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"
41 static char sys_timestring[128];
42 char *Sys_TimeString(const char *timeformat)
44 time_t mytime = time(NULL);
47 localtime_s(&mytm, &mytime);
48 strftime(sys_timestring, sizeof(sys_timestring), timeformat, &mytm);
50 strftime(sys_timestring, sizeof(sys_timestring), timeformat, localtime(&mytime));
52 return sys_timestring;
56 void Sys_Quit (int returnvalue)
58 // Unlock mutexes because the quit command may jump directly here, causing a deadlock
59 if ((cmd_local)->cbuf->lock)
60 Cbuf_Unlock((cmd_local)->cbuf);
61 SV_UnlockThreadMutex();
62 TaskQueue_Frame(true);
64 if (Sys_CheckParm("-profilegameonly"))
65 Sys_AllowProfiling(false);
66 host.state = host_shutdown;
74 void Sys_AllowProfiling(qbool enable)
78 extern void monstartup(const char *libname);
79 extern void moncleanup(void);
81 monstartup("libmain.so");
85 #elif (defined(__linux__) && (defined(__GLIBC__) || defined(__GNU_LIBRARY__))) || defined(__FreeBSD__)
86 extern int moncontrol(int);
93 ===============================================================================
97 ===============================================================================
100 static qbool Sys_LoadDependencyFunctions(dllhandle_t dllhandle, const dllfunction_t *fcts, qbool complain, qbool has_next)
102 const dllfunction_t *func;
105 for (func = fcts; func && func->name != NULL; func++)
106 if (!(*func->funcvariable = (void *) Sys_GetProcAddress (dllhandle, func->name)))
110 Con_DPrintf (" - missing function \"%s\" - broken library!", func->name);
112 Con_DPrintf("\nContinuing with");
119 for (func = fcts; func && func->name != NULL; func++)
120 *func->funcvariable = NULL;
125 qbool Sys_LoadSelf(dllhandle_t *handle)
127 dllhandle_t dllhandle = 0;
132 dllhandle = LoadLibrary (NULL);
134 dllhandle = dlopen (NULL, RTLD_NOW | RTLD_GLOBAL);
140 qbool Sys_LoadDependency (const char** dllnames, dllhandle_t* handle, const dllfunction_t *fcts)
143 const dllfunction_t *func;
144 dllhandle_t dllhandle = 0;
151 #ifdef PREFER_PRELOAD
152 dllhandle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL);
153 if(Sys_LoadDependencyFunctions(dllhandle, fcts, false, false))
155 Con_DPrintf ("All of %s's functions were already linked in! Not loading dynamically...\n", dllnames[0]);
160 Sys_FreeLibrary(&dllhandle);
166 for (func = fcts; func && func->name != NULL; func++)
167 *func->funcvariable = NULL;
169 // Try every possible name
170 Con_DPrintf ("Trying to load library...");
171 for (i = 0; dllnames[i] != NULL; i++)
173 Con_DPrintf (" \"%s\"", dllnames[i]);
175 # ifndef DONT_USE_SETDLLDIRECTORY
177 SetDllDirectory("bin64");
179 SetDllDirectory("bin32");
183 if(Sys_LoadLibrary(dllnames[i], &dllhandle))
185 if (Sys_LoadDependencyFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
188 Sys_FreeLibrary (&dllhandle);
192 // see if the names can be loaded relative to the executable path
193 // (this is for Mac OSX which does not check next to the executable)
194 if (!dllhandle && strrchr(sys.argv[0], '/'))
196 char path[MAX_OSPATH];
197 strlcpy(path, sys.argv[0], sizeof(path));
198 strrchr(path, '/')[1] = 0;
199 for (i = 0; dllnames[i] != NULL; i++)
201 char temp[MAX_OSPATH];
202 strlcpy(temp, path, sizeof(temp));
203 strlcat(temp, dllnames[i], sizeof(temp));
204 Con_DPrintf (" \"%s\"", temp);
206 if(Sys_LoadLibrary(temp, &dllhandle))
208 if (Sys_LoadDependencyFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
211 Sys_FreeLibrary (&dllhandle);
219 Con_DPrintf(" - failed.\n");
223 Con_DPrintf(" - loaded.\n");
224 Con_Printf("Loaded library \"%s\"\n", dllnames[i]);
233 qbool Sys_LoadLibrary(const char *name, dllhandle_t *handle)
235 dllhandle_t dllhandle = 0;
242 dllhandle = LoadLibrary (name);
244 dllhandle = dlopen (name, RTLD_LAZY | RTLD_GLOBAL);
254 void Sys_FreeLibrary (dllhandle_t* handle)
257 if (handle == NULL || *handle == NULL)
261 FreeLibrary (*handle);
270 void* Sys_GetProcAddress (dllhandle_t handle, const char* name)
274 return (void *)GetProcAddress (handle, name);
276 return (void *)dlsym (handle, name);
284 # define HAVE_TIMEGETTIME 1
285 # define HAVE_QUERYPERFORMANCECOUNTER 1
286 # define HAVE_Sleep 1
290 #if defined(CLOCK_MONOTONIC) || defined(CLOCK_HIRES)
291 # define HAVE_CLOCKGETTIME 1
293 // FIXME improve this check, manpage hints to DST_NONE
294 # define HAVE_GETTIMEOFDAY 1
298 # define HAVE_SELECT 1
302 // FIXME improve this check
303 # define HAVE_USLEEP 1
306 // these are referenced elsewhere
307 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."};
308 cvar_t sys_libdir = {CF_READONLY | CF_SHARED, "sys_libdir", "", "Default engine library directory"};
311 static cvar_t sys_debugsleep = {CF_SHARED, "sys_debugsleep", "0", "write requested and attained sleep times to standard output, to be used with gnuplot"};
312 static cvar_t sys_usesdlgetticks = {CF_SHARED, "sys_usesdlgetticks", "0", "use SDL_GetTicks() timer (less accurate, for debugging)"};
313 static cvar_t sys_usesdldelay = {CF_SHARED, "sys_usesdldelay", "0", "use SDL_Delay() (less accurate, for debugging)"};
314 #if HAVE_QUERYPERFORMANCECOUNTER
315 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)"};
317 #if HAVE_CLOCKGETTIME
318 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)"};
321 static double benchmark_time; // actually always contains an integer amount of milliseconds, will eventually "overflow"
327 Returns the position (1 to argc-1) in the program's argument list
328 where the given parameter apears, or 0 if not present
331 int Sys_CheckParm (const char *parm)
335 for (i=1 ; i<sys.argc ; i++)
338 continue; // NEXTSTEP sometimes clears appkit vars.
339 if (!strcmp (parm,sys.argv[i]))
346 void Sys_Init_Commands (void)
348 Cvar_RegisterVariable(&sys_debugsleep);
349 Cvar_RegisterVariable(&sys_usenoclockbutbenchmark);
350 Cvar_RegisterVariable(&sys_libdir);
351 #if HAVE_TIMEGETTIME || HAVE_QUERYPERFORMANCECOUNTER || HAVE_CLOCKGETTIME || HAVE_GETTIMEOFDAY
352 if(sys_supportsdlgetticks)
354 Cvar_RegisterVariable(&sys_usesdlgetticks);
355 Cvar_RegisterVariable(&sys_usesdldelay);
358 #if HAVE_QUERYPERFORMANCECOUNTER
359 Cvar_RegisterVariable(&sys_usequeryperformancecounter);
361 #if HAVE_CLOCKGETTIME
362 Cvar_RegisterVariable(&sys_useclockgettime);
366 double Sys_DirtyTime(void)
368 // first all the OPTIONAL timers
370 // benchmark timer (fake clock)
371 if(sys_usenoclockbutbenchmark.integer)
373 double old_benchmark_time = benchmark_time;
375 if(benchmark_time == old_benchmark_time)
376 Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
377 return benchmark_time * 0.000001;
379 #if HAVE_QUERYPERFORMANCECOUNTER
380 if (sys_usequeryperformancecounter.integer)
382 // LadyHavoc: note to people modifying this code, DWORD is specifically defined as an unsigned 32bit number, therefore the 65536.0 * 65536.0 is fine.
383 // QueryPerformanceCounter
385 // Windows 95/98/ME/NT/2000/XP
387 // very accurate (CPU cycles)
389 // does not necessarily match realtime too well (tends to get faster and faster in win98)
390 // wraps around occasionally on some platforms (depends on CPU speed and probably other unknown factors)
392 LARGE_INTEGER PerformanceFreq;
393 LARGE_INTEGER PerformanceCount;
395 if (QueryPerformanceFrequency (&PerformanceFreq))
397 QueryPerformanceCounter (&PerformanceCount);
399 timescale = 1.0 / ((double) PerformanceFreq.LowPart + (double) PerformanceFreq.HighPart * 65536.0 * 65536.0);
400 return ((double) PerformanceCount.LowPart + (double) PerformanceCount.HighPart * 65536.0 * 65536.0) * timescale;
404 Con_Printf("No hardware timer available\n");
405 // fall back to other clock sources
406 Cvar_SetValueQuick(&sys_usequeryperformancecounter, false);
411 #if HAVE_CLOCKGETTIME
412 if (sys_useclockgettime.integer)
415 # ifdef CLOCK_MONOTONIC
417 clock_gettime(CLOCK_MONOTONIC, &ts);
420 clock_gettime(CLOCK_HIGHRES, &ts);
422 return (double) ts.tv_sec + ts.tv_nsec / 1000000000.0;
426 // now all the FALLBACK timers
427 if(sys_supportsdlgetticks && sys_usesdlgetticks.integer)
428 return (double) Sys_SDL_GetTicks() / 1000.0;
429 #if HAVE_GETTIMEOFDAY
432 gettimeofday(&tp, NULL);
433 return (double) tp.tv_sec + tp.tv_usec / 1000000.0;
435 #elif HAVE_TIMEGETTIME
437 static int firsttimegettime = true;
440 // Windows 95/98/ME/NT/2000/XP
442 // reasonable accuracy (millisecond)
444 // wraps around every 47 days or so (but this is non-fatal to us, odd times are rejected, only causes a one frame stutter)
446 // make sure the timer is high precision, otherwise different versions of windows have varying accuracy
447 if (firsttimegettime)
450 firsttimegettime = false;
453 return (double) timeGetTime() / 1000.0;
456 // fallback for using the SDL timer if no other timer is available
457 // this calls Sys_Error() if not linking against SDL
458 return (double) Sys_SDL_GetTicks() / 1000.0;
462 extern cvar_t host_maxwait;
463 double Sys_Sleep(double time)
466 uint32_t microseconds;
468 // convert to microseconds
471 if(host_maxwait.value <= 0)
472 time = min(time, 1000000.0);
474 time = min(time, host_maxwait.value * 1000.0);
476 if (time < 1 || host.restless)
477 return 0; // not sleeping this frame
479 microseconds = time; // post-validation to prevent overflow
481 if(sys_usenoclockbutbenchmark.integer)
483 double old_benchmark_time = benchmark_time;
484 benchmark_time += microseconds;
485 if(benchmark_time == old_benchmark_time)
486 Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
490 if(sys_debugsleep.integer)
491 Sys_Printf("sys_debugsleep: requesting %u ", microseconds);
492 dt = Sys_DirtyTime();
494 // less important on newer libcurl so no need to disturb dedicated servers
495 if (cls.state != ca_dedicated && Curl_Select(microseconds))
497 // a transfer is ready or we finished sleeping
499 else if(sys_supportsdlgetticks && sys_usesdldelay.integer)
500 Sys_SDL_Delay(microseconds / 1000);
510 if (cls.state == ca_dedicated && sv_checkforpacketsduringsleep.integer)
512 List_For_Each_Entry(s, &lhnet_socketlist.list, lhnetsocket_t, list)
514 if (s->address.addresstype == LHNETADDRESSTYPE_INET4 || s->address.addresstype == LHNETADDRESSTYPE_INET6)
516 if (lastfd < s->inetsocket)
517 lastfd = s->inetsocket;
518 #if defined(WIN32) && !defined(_MSC_VER)
519 FD_SET((int)s->inetsocket, &fdreadset);
521 FD_SET((unsigned int)s->inetsocket, &fdreadset);
526 tv.tv_sec = microseconds / 1000000;
527 tv.tv_usec = microseconds % 1000000;
528 // on Win32, select() cannot be used with all three FD list args being NULL according to MSDN
529 // (so much for POSIX...)
530 // bones_was_here: but a zeroed fd_set seems to be tolerated (tested on Win 7)
531 select(lastfd + 1, &fdreadset, NULL, NULL, &tv);
535 usleep(microseconds);
538 Sleep(microseconds / 1000);
541 Sys_SDL_Delay(microseconds / 1000);
544 dt = Sys_DirtyTime() - dt;
545 if(sys_debugsleep.integer)
546 Sys_Printf(" got %u oversleep %d\n", (unsigned int)(dt * 1000000), (unsigned int)(dt * 1000000) - microseconds);
547 return (dt < 0 || dt >= 1800) ? 0 : dt;
550 void Sys_Print(const char *text)
553 if (developer.integer > 0)
555 __android_log_write(ANDROID_LOG_DEBUG, sys.argv[0], text);
561 // BUG: for some reason, NDELAY also affects stdout (1) when used on stdin (0).
562 // this is because both go to /dev/tty by default!
564 int origflags = fcntl (sys.outfd, F_GETFL, 0);
565 fcntl (sys.outfd, F_SETFL, origflags & ~O_NONBLOCK);
571 fs_offset_t written = (fs_offset_t)write(sys.outfd, text, (int)strlen(text));
573 break; // sorry, I cannot do anything about this error - without an output
577 fcntl (sys.outfd, F_SETFL, origflags);
580 //fprintf(stdout, "%s", text);
584 void Sys_Printf(const char *fmt, ...)
587 char msg[MAX_INPUTLINE];
589 va_start(argptr,fmt);
590 dpvsnprintf(msg,sizeof(msg),fmt,argptr);
596 char *Sys_ConsoleInput(void)
598 static char text[MAX_INPUTLINE];
599 static unsigned int len = 0;
625 if (len < sizeof (text) - 1)
634 struct timeval timeout;
636 FD_SET(0, &fdset); // stdin
639 if (select (1, &fdset, NULL, NULL, &timeout) != -1 && FD_ISSET(0, &fdset))
641 len = read (0, text, sizeof(text) - 1);
644 // rip off the \n and terminate
645 // div0: WHY? console code can deal with \n just fine
646 // this caused problems with pasting stuff into a terminal window
647 // so, not ripping off the \n, but STILL keeping a NUL terminator
657 void Sys_Error (const char *error, ...)
660 char string[MAX_INPUTLINE];
662 // change stdin to non blocking
664 fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~O_NONBLOCK);
667 va_start (argptr,error);
668 dpvsnprintf (string, sizeof (string), error, argptr);
671 Con_Printf(CON_ERROR "Engine Error: %s\n", string);
673 // don't want a dead window left blocking the OS UI or the crash dialog
676 Sys_SDL_Dialog("Engine Error", string);
682 static const char *Sys_FindInPATH(const char *name, char namesep, const char *PATH, char pathsep, char *buf, size_t bufsize)
684 const char *p = PATH;
688 while((q = strchr(p, ':')))
690 dpsnprintf(buf, bufsize, "%.*s%c%s", (int)(q-p), p, namesep, name);
691 if(FS_SysFileExists(buf))
695 if(!q) // none found - try the last item
697 dpsnprintf(buf, bufsize, "%s%c%s", p, namesep, name);
698 if(FS_SysFileExists(buf))
706 static const char *Sys_FindExecutableName(void)
711 static char exenamebuf[MAX_OSPATH+1];
713 #if defined(__FreeBSD__)
714 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
715 size_t exenamebuflen = sizeof(exenamebuf)-1;
716 if (sysctl(mib, 4, exenamebuf, &exenamebuflen, NULL, 0) == 0)
720 #elif defined(__linux__)
721 n = readlink("/proc/self/exe", exenamebuf, sizeof(exenamebuf)-1);
723 if(n > 0 && (size_t)(n) < sizeof(exenamebuf))
728 if(strchr(sys.argv[0], '/'))
729 return sys.argv[0]; // possibly a relative path
731 return Sys_FindInPATH(sys.argv[0], '/', getenv("PATH"), ':', exenamebuf, sizeof(exenamebuf));
735 void Sys_ProvideSelfFD(void)
739 sys.selffd = FS_SysOpenFD(Sys_FindExecutableName(), "rb", false);
742 // for x86 cpus only... (x64 has SSE2_PRESENT)
743 #if defined(SSE_POSSIBLE) && !defined(SSE2_PRESENT)
744 // code from SDL, shortened as we can expect CPUID to work
745 static int CPUID_Features(void)
748 # if (defined(__GNUC__) || defined(__clang__) || defined(__TINYC__)) && defined(__i386__)
750 " movl %%ebx,%%edi\n"
751 " xorl %%eax,%%eax \n"
753 " cpuid # Get family/model/stepping/features\n"
755 " movl %%edi,%%ebx\n"
758 : "%eax", "%ecx", "%edx", "%edi"
760 # elif (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
764 cpuid ; Get family/model/stepping/features
768 # error SSE_POSSIBLE set but no CPUID implementation
775 qbool Sys_HaveSSE(void)
777 // COMMANDLINEOPTION: SSE: -nosse disables SSE support and detection
778 if(Sys_CheckParm("-nosse"))
783 // COMMANDLINEOPTION: SSE: -forcesse enables SSE support and disables detection
784 if(Sys_CheckParm("-forcesse") || Sys_CheckParm("-forcesse2"))
786 if(CPUID_Features() & (1 << 25))
792 qbool Sys_HaveSSE2(void)
794 // COMMANDLINEOPTION: SSE2: -nosse2 disables SSE2 support and detection
795 if(Sys_CheckParm("-nosse") || Sys_CheckParm("-nosse2"))
800 // COMMANDLINEOPTION: SSE2: -forcesse2 enables SSE2 support and disables detection
801 if(Sys_CheckParm("-forcesse2"))
803 if((CPUID_Features() & (3 << 25)) == (3 << 25)) // SSE is 1<<25, SSE2 is 1<<26
810 /// called to set process priority for dedicated servers
811 #if defined(__linux__)
812 #include <sys/resource.h>
815 void Sys_InitProcessNice (void)
818 sys.nicepossible = false;
819 if(Sys_CheckParm("-nonice"))
822 sys.nicelevel = getpriority(PRIO_PROCESS, 0);
825 Con_Printf("Kernel does not support reading process priority - cannot use niceness\n");
828 if(getrlimit(RLIMIT_NICE, &lim))
830 Con_Printf("Kernel does not support lowering nice level again - cannot use niceness\n");
833 if(lim.rlim_cur != RLIM_INFINITY && sys.nicelevel < (int) (20 - lim.rlim_cur))
835 Con_Printf("Current nice level is below the soft limit - cannot use niceness\n");
838 sys.nicepossible = true;
841 void Sys_MakeProcessNice (void)
843 if(!sys.nicepossible)
847 Con_DPrintf("Process is becoming 'nice'...\n");
848 if(setpriority(PRIO_PROCESS, 0, 19))
849 Con_Printf(CON_ERROR "Failed to raise nice level to %d\n", 19);
852 void Sys_MakeProcessMean (void)
854 if(!sys.nicepossible)
858 Con_DPrintf("Process is becoming 'mean'...\n");
859 if(setpriority(PRIO_PROCESS, 0, sys.nicelevel))
860 Con_Printf(CON_ERROR "Failed to lower nice level to %d\n", sys.nicelevel);
864 void Sys_InitProcessNice (void)
867 void Sys_MakeProcessNice (void)
870 void Sys_MakeProcessMean (void)
875 int main (int argc, char **argv)
877 signal(SIGFPE, SIG_IGN);
880 sys.argv = (const char **)argv;
882 // COMMANDLINEOPTION: -noterminal disables console output on stdout
883 if(Sys_CheckParm("-noterminal"))
885 // COMMANDLINEOPTION: -stderr moves console output to stderr
886 else if(Sys_CheckParm("-stderr"))
892 Sys_ProvideSelfFD(); // may call Con_Printf() so must be after sys.outfd is set
895 fcntl(0, F_SETFL, fcntl (0, F_GETFL, 0) | O_NONBLOCK);
899 Sys_AllowProfiling(true);