2 # ifndef DONT_USE_SETDLLDIRECTORY
3 # define _WIN32_WINNT 0x0502
16 # include <mmsystem.h> // timeGetTime
17 # include <time.h> // localtime
18 # include <conio.h> // _kbhit, _getch, _putch
20 #pragma comment(lib, "winmm.lib")
24 # include <sys/sysctl.h>
28 # include <sys/time.h>
37 static char sys_timestring[128];
38 char *Sys_TimeString(const char *timeformat)
40 time_t mytime = time(NULL);
43 localtime_s(&mytm, &mytime);
44 strftime(sys_timestring, sizeof(sys_timestring), timeformat, &mytm);
46 strftime(sys_timestring, sizeof(sys_timestring), timeformat, localtime(&mytime));
48 return sys_timestring;
52 void Sys_Quit (int returnvalue)
54 // Unlock mutexes because the quit command may jump directly here, causing a deadlock
55 if ((cmd_local)->cbuf->lock)
56 Cbuf_Unlock((cmd_local)->cbuf);
57 SV_UnlockThreadMutex();
58 TaskQueue_Frame(true);
60 if (Sys_CheckParm("-profilegameonly"))
61 Sys_AllowProfiling(false);
62 host.state = host_shutdown;
70 void Sys_AllowProfiling(qbool enable)
74 extern void monstartup(const char *libname);
75 extern void moncleanup(void);
77 monstartup("libmain.so");
81 #elif (defined(__linux__) && (defined(__GLIBC__) || defined(__GNU_LIBRARY__))) || defined(__FreeBSD__)
82 extern int moncontrol(int);
89 ===============================================================================
93 ===============================================================================
96 static qbool Sys_LoadDependencyFunctions(dllhandle_t dllhandle, const dllfunction_t *fcts, qbool complain, qbool has_next)
98 const dllfunction_t *func;
101 for (func = fcts; func && func->name != NULL; func++)
102 if (!(*func->funcvariable = (void *) Sys_GetProcAddress (dllhandle, func->name)))
106 Con_DPrintf (" - missing function \"%s\" - broken library!", func->name);
108 Con_DPrintf("\nContinuing with");
115 for (func = fcts; func && func->name != NULL; func++)
116 *func->funcvariable = NULL;
121 qbool Sys_LoadSelf(dllhandle_t *handle)
123 dllhandle_t dllhandle = 0;
128 dllhandle = LoadLibrary (NULL);
130 dllhandle = dlopen (NULL, RTLD_NOW | RTLD_GLOBAL);
136 qbool Sys_LoadDependency (const char** dllnames, dllhandle_t* handle, const dllfunction_t *fcts)
139 const dllfunction_t *func;
140 dllhandle_t dllhandle = 0;
147 #ifdef PREFER_PRELOAD
148 dllhandle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL);
149 if(Sys_LoadDependencyFunctions(dllhandle, fcts, false, false))
151 Con_DPrintf ("All of %s's functions were already linked in! Not loading dynamically...\n", dllnames[0]);
156 Sys_FreeLibrary(&dllhandle);
162 for (func = fcts; func && func->name != NULL; func++)
163 *func->funcvariable = NULL;
165 // Try every possible name
166 Con_DPrintf ("Trying to load library...");
167 for (i = 0; dllnames[i] != NULL; i++)
169 Con_DPrintf (" \"%s\"", dllnames[i]);
171 # ifndef DONT_USE_SETDLLDIRECTORY
173 SetDllDirectory("bin64");
175 SetDllDirectory("bin32");
179 if(Sys_LoadLibrary(dllnames[i], &dllhandle))
181 if (Sys_LoadDependencyFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
184 Sys_FreeLibrary (&dllhandle);
188 // see if the names can be loaded relative to the executable path
189 // (this is for Mac OSX which does not check next to the executable)
190 if (!dllhandle && strrchr(sys.argv[0], '/'))
192 char path[MAX_OSPATH];
193 strlcpy(path, sys.argv[0], sizeof(path));
194 strrchr(path, '/')[1] = 0;
195 for (i = 0; dllnames[i] != NULL; i++)
197 char temp[MAX_OSPATH];
198 strlcpy(temp, path, sizeof(temp));
199 strlcat(temp, dllnames[i], sizeof(temp));
200 Con_DPrintf (" \"%s\"", temp);
202 if(Sys_LoadLibrary(temp, &dllhandle))
204 if (Sys_LoadDependencyFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
207 Sys_FreeLibrary (&dllhandle);
215 Con_DPrintf(" - failed.\n");
219 Con_DPrintf(" - loaded.\n");
220 Con_Printf("Loaded library \"%s\"\n", dllnames[i]);
229 qbool Sys_LoadLibrary(const char *name, dllhandle_t *handle)
231 dllhandle_t dllhandle = 0;
238 dllhandle = LoadLibrary (name);
240 dllhandle = dlopen (name, RTLD_LAZY | RTLD_GLOBAL);
250 void Sys_FreeLibrary (dllhandle_t* handle)
253 if (handle == NULL || *handle == NULL)
257 FreeLibrary (*handle);
266 void* Sys_GetProcAddress (dllhandle_t handle, const char* name)
270 return (void *)GetProcAddress (handle, name);
272 return (void *)dlsym (handle, name);
280 # define HAVE_TIMEGETTIME 1
281 # define HAVE_QUERYPERFORMANCECOUNTER 1
282 # define HAVE_Sleep 1
286 #if defined(CLOCK_MONOTONIC) || defined(CLOCK_HIRES)
287 # define HAVE_CLOCKGETTIME 1
289 // FIXME improve this check, manpage hints to DST_NONE
290 # define HAVE_GETTIMEOFDAY 1
294 # define HAVE_SELECT 1
298 // FIXME improve this check
299 # define HAVE_USLEEP 1
302 // these are referenced elsewhere
303 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."};
304 cvar_t sys_libdir = {CF_READONLY | CF_SHARED, "sys_libdir", "", "Default engine library directory"};
307 static cvar_t sys_debugsleep = {CF_SHARED, "sys_debugsleep", "0", "write requested and attained sleep times to standard output, to be used with gnuplot"};
308 static cvar_t sys_usesdlgetticks = {CF_SHARED, "sys_usesdlgetticks", "0", "use SDL_GetTicks() timer (less accurate, for debugging)"};
309 static cvar_t sys_usesdldelay = {CF_SHARED, "sys_usesdldelay", "0", "use SDL_Delay() (less accurate, for debugging)"};
310 #if HAVE_QUERYPERFORMANCECOUNTER
311 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)"};
313 #if HAVE_CLOCKGETTIME
314 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)"};
317 static double benchmark_time; // actually always contains an integer amount of milliseconds, will eventually "overflow"
323 Returns the position (1 to argc-1) in the program's argument list
324 where the given parameter apears, or 0 if not present
327 int Sys_CheckParm (const char *parm)
331 for (i=1 ; i<sys.argc ; i++)
334 continue; // NEXTSTEP sometimes clears appkit vars.
335 if (!strcmp (parm,sys.argv[i]))
342 void Sys_Init_Commands (void)
344 Cvar_RegisterVariable(&sys_debugsleep);
345 Cvar_RegisterVariable(&sys_usenoclockbutbenchmark);
346 Cvar_RegisterVariable(&sys_libdir);
347 #if HAVE_TIMEGETTIME || HAVE_QUERYPERFORMANCECOUNTER || HAVE_CLOCKGETTIME || HAVE_GETTIMEOFDAY
348 if(sys_supportsdlgetticks)
350 Cvar_RegisterVariable(&sys_usesdlgetticks);
351 Cvar_RegisterVariable(&sys_usesdldelay);
354 #if HAVE_QUERYPERFORMANCECOUNTER
355 Cvar_RegisterVariable(&sys_usequeryperformancecounter);
357 #if HAVE_CLOCKGETTIME
358 Cvar_RegisterVariable(&sys_useclockgettime);
362 double Sys_DirtyTime(void)
364 // first all the OPTIONAL timers
366 // benchmark timer (fake clock)
367 if(sys_usenoclockbutbenchmark.integer)
369 double old_benchmark_time = benchmark_time;
371 if(benchmark_time == old_benchmark_time)
372 Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
373 return benchmark_time * 0.000001;
375 #if HAVE_QUERYPERFORMANCECOUNTER
376 if (sys_usequeryperformancecounter.integer)
378 // LadyHavoc: note to people modifying this code, DWORD is specifically defined as an unsigned 32bit number, therefore the 65536.0 * 65536.0 is fine.
379 // QueryPerformanceCounter
381 // Windows 95/98/ME/NT/2000/XP
383 // very accurate (CPU cycles)
385 // does not necessarily match realtime too well (tends to get faster and faster in win98)
386 // wraps around occasionally on some platforms (depends on CPU speed and probably other unknown factors)
388 LARGE_INTEGER PerformanceFreq;
389 LARGE_INTEGER PerformanceCount;
391 if (QueryPerformanceFrequency (&PerformanceFreq))
393 QueryPerformanceCounter (&PerformanceCount);
395 timescale = 1.0 / ((double) PerformanceFreq.LowPart + (double) PerformanceFreq.HighPart * 65536.0 * 65536.0);
396 return ((double) PerformanceCount.LowPart + (double) PerformanceCount.HighPart * 65536.0 * 65536.0) * timescale;
400 Con_Printf("No hardware timer available\n");
401 // fall back to other clock sources
402 Cvar_SetValueQuick(&sys_usequeryperformancecounter, false);
407 #if HAVE_CLOCKGETTIME
408 if (sys_useclockgettime.integer)
411 # ifdef CLOCK_MONOTONIC
413 clock_gettime(CLOCK_MONOTONIC, &ts);
416 clock_gettime(CLOCK_HIGHRES, &ts);
418 return (double) ts.tv_sec + ts.tv_nsec / 1000000000.0;
422 // now all the FALLBACK timers
423 if(sys_supportsdlgetticks && sys_usesdlgetticks.integer)
424 return (double) Sys_SDL_GetTicks() / 1000.0;
425 #if HAVE_GETTIMEOFDAY
428 gettimeofday(&tp, NULL);
429 return (double) tp.tv_sec + tp.tv_usec / 1000000.0;
431 #elif HAVE_TIMEGETTIME
433 static int firsttimegettime = true;
436 // Windows 95/98/ME/NT/2000/XP
438 // reasonable accuracy (millisecond)
440 // wraps around every 47 days or so (but this is non-fatal to us, odd times are rejected, only causes a one frame stutter)
442 // make sure the timer is high precision, otherwise different versions of windows have varying accuracy
443 if (firsttimegettime)
446 firsttimegettime = false;
449 return (double) timeGetTime() / 1000.0;
452 // fallback for using the SDL timer if no other timer is available
453 // this calls Sys_Error() if not linking against SDL
454 return (double) Sys_SDL_GetTicks() / 1000.0;
458 extern cvar_t host_maxwait;
459 double Sys_Sleep(double time)
462 uint32_t microseconds;
464 // convert to microseconds
467 if(host_maxwait.value <= 0)
468 time = min(time, 1000000.0);
470 time = min(time, host_maxwait.value * 1000.0);
472 if (time < 1 || host.restless)
473 return 0; // not sleeping this frame
475 microseconds = time; // post-validation to prevent overflow
477 if(sys_usenoclockbutbenchmark.integer)
479 double old_benchmark_time = benchmark_time;
480 benchmark_time += microseconds;
481 if(benchmark_time == old_benchmark_time)
482 Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
486 if(sys_debugsleep.integer)
487 Sys_Printf("sys_debugsleep: requesting %u ", microseconds);
488 dt = Sys_DirtyTime();
490 // less important on newer libcurl so no need to disturb dedicated servers
491 if (cls.state != ca_dedicated && Curl_Select(microseconds))
493 // a transfer is ready or we finished sleeping
495 else if(sys_supportsdlgetticks && sys_usesdldelay.integer)
496 Sys_SDL_Delay(microseconds / 1000);
506 if (cls.state == ca_dedicated && sv_checkforpacketsduringsleep.integer)
508 List_For_Each_Entry(s, &lhnet_socketlist.list, lhnetsocket_t, list)
510 if (s->address.addresstype == LHNETADDRESSTYPE_INET4 || s->address.addresstype == LHNETADDRESSTYPE_INET6)
512 if (lastfd < s->inetsocket)
513 lastfd = s->inetsocket;
514 #if defined(WIN32) && !defined(_MSC_VER)
515 FD_SET((int)s->inetsocket, &fdreadset);
517 FD_SET((unsigned int)s->inetsocket, &fdreadset);
522 tv.tv_sec = microseconds / 1000000;
523 tv.tv_usec = microseconds % 1000000;
524 // on Win32, select() cannot be used with all three FD list args being NULL according to MSDN
525 // (so much for POSIX...)
526 // bones_was_here: but a zeroed fd_set seems to be tolerated (tested on Win 7)
527 select(lastfd + 1, &fdreadset, NULL, NULL, &tv);
531 usleep(microseconds);
534 Sleep(microseconds / 1000);
537 Sys_SDL_Delay(microseconds / 1000);
540 dt = Sys_DirtyTime() - dt;
541 if(sys_debugsleep.integer)
542 Sys_Printf(" got %u oversleep %d\n", (unsigned int)(dt * 1000000), (unsigned int)(dt * 1000000) - microseconds);
543 return (dt < 0 || dt >= 1800) ? 0 : dt;
546 void Sys_Printf(const char *fmt, ...)
549 char msg[MAX_INPUTLINE];
551 va_start(argptr,fmt);
552 dpvsnprintf(msg,sizeof(msg),fmt,argptr);
558 char *Sys_ConsoleInput(void)
560 static char text[MAX_INPUTLINE];
561 static unsigned int len = 0;
587 if (len < sizeof (text) - 1)
596 struct timeval timeout;
598 FD_SET(0, &fdset); // stdin
601 if (select (1, &fdset, NULL, NULL, &timeout) != -1 && FD_ISSET(0, &fdset))
603 len = read (0, text, sizeof(text) - 1);
606 // rip off the \n and terminate
607 // div0: WHY? console code can deal with \n just fine
608 // this caused problems with pasting stuff into a terminal window
609 // so, not ripping off the \n, but STILL keeping a NUL terminator
619 void Sys_Error (const char *error, ...)
622 char string[MAX_INPUTLINE];
624 // change stdin to non blocking
626 fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~O_NONBLOCK);
629 va_start (argptr,error);
630 dpvsnprintf (string, sizeof (string), error, argptr);
633 Con_Printf(CON_ERROR "Engine Error: %s\n", string);
635 // don't want a dead window left blocking the OS UI or the crash dialog
638 Sys_SDL_Dialog("Engine Error", string);
644 static const char *Sys_FindInPATH(const char *name, char namesep, const char *PATH, char pathsep, char *buf, size_t bufsize)
646 const char *p = PATH;
650 while((q = strchr(p, ':')))
652 dpsnprintf(buf, bufsize, "%.*s%c%s", (int)(q-p), p, namesep, name);
653 if(FS_SysFileExists(buf))
657 if(!q) // none found - try the last item
659 dpsnprintf(buf, bufsize, "%s%c%s", p, namesep, name);
660 if(FS_SysFileExists(buf))
668 static const char *Sys_FindExecutableName(void)
673 static char exenamebuf[MAX_OSPATH+1];
675 #if defined(__FreeBSD__)
676 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
677 size_t exenamebuflen = sizeof(exenamebuf)-1;
678 if (sysctl(mib, 4, exenamebuf, &exenamebuflen, NULL, 0) == 0)
682 #elif defined(__linux__)
683 n = readlink("/proc/self/exe", exenamebuf, sizeof(exenamebuf)-1);
685 if(n > 0 && (size_t)(n) < sizeof(exenamebuf))
690 if(strchr(sys.argv[0], '/'))
691 return sys.argv[0]; // possibly a relative path
693 return Sys_FindInPATH(sys.argv[0], '/', getenv("PATH"), ':', exenamebuf, sizeof(exenamebuf));
697 void Sys_ProvideSelfFD(void)
701 sys.selffd = FS_SysOpenFD(Sys_FindExecutableName(), "rb", false);
704 // for x86 cpus only... (x64 has SSE2_PRESENT)
705 #if defined(SSE_POSSIBLE) && !defined(SSE2_PRESENT)
706 // code from SDL, shortened as we can expect CPUID to work
707 static int CPUID_Features(void)
710 # if (defined(__GNUC__) || defined(__clang__) || defined(__TINYC__)) && defined(__i386__)
712 " movl %%ebx,%%edi\n"
713 " xorl %%eax,%%eax \n"
715 " cpuid # Get family/model/stepping/features\n"
717 " movl %%edi,%%ebx\n"
720 : "%eax", "%ecx", "%edx", "%edi"
722 # elif (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
726 cpuid ; Get family/model/stepping/features
730 # error SSE_POSSIBLE set but no CPUID implementation
737 qbool Sys_HaveSSE(void)
739 // COMMANDLINEOPTION: SSE: -nosse disables SSE support and detection
740 if(Sys_CheckParm("-nosse"))
745 // COMMANDLINEOPTION: SSE: -forcesse enables SSE support and disables detection
746 if(Sys_CheckParm("-forcesse") || Sys_CheckParm("-forcesse2"))
748 if(CPUID_Features() & (1 << 25))
754 qbool Sys_HaveSSE2(void)
756 // COMMANDLINEOPTION: SSE2: -nosse2 disables SSE2 support and detection
757 if(Sys_CheckParm("-nosse") || Sys_CheckParm("-nosse2"))
762 // COMMANDLINEOPTION: SSE2: -forcesse2 enables SSE2 support and disables detection
763 if(Sys_CheckParm("-forcesse2"))
765 if((CPUID_Features() & (3 << 25)) == (3 << 25)) // SSE is 1<<25, SSE2 is 1<<26
772 /// called to set process priority for dedicated servers
773 #if defined(__linux__)
774 #include <sys/resource.h>
777 void Sys_InitProcessNice (void)
780 sys.nicepossible = false;
781 if(Sys_CheckParm("-nonice"))
784 sys.nicelevel = getpriority(PRIO_PROCESS, 0);
787 Con_Printf("Kernel does not support reading process priority - cannot use niceness\n");
790 if(getrlimit(RLIMIT_NICE, &lim))
792 Con_Printf("Kernel does not support lowering nice level again - cannot use niceness\n");
795 if(lim.rlim_cur != RLIM_INFINITY && sys.nicelevel < (int) (20 - lim.rlim_cur))
797 Con_Printf("Current nice level is below the soft limit - cannot use niceness\n");
800 sys.nicepossible = true;
803 void Sys_MakeProcessNice (void)
805 if(!sys.nicepossible)
809 Con_DPrintf("Process is becoming 'nice'...\n");
810 if(setpriority(PRIO_PROCESS, 0, 19))
811 Con_Printf(CON_ERROR "Failed to raise nice level to %d\n", 19);
814 void Sys_MakeProcessMean (void)
816 if(!sys.nicepossible)
820 Con_DPrintf("Process is becoming 'mean'...\n");
821 if(setpriority(PRIO_PROCESS, 0, sys.nicelevel))
822 Con_Printf(CON_ERROR "Failed to lower nice level to %d\n", sys.nicelevel);
826 void Sys_InitProcessNice (void)
829 void Sys_MakeProcessNice (void)
832 void Sys_MakeProcessMean (void)
837 int main (int argc, char **argv)
839 signal(SIGFPE, SIG_IGN);
842 sys.argv = (const char **)argv;
844 // COMMANDLINEOPTION: -noterminal disables console output on stdout
845 if(Sys_CheckParm("-noterminal"))
847 // COMMANDLINEOPTION: -stderr moves console output to stderr
848 else if(Sys_CheckParm("-stderr"))
854 Sys_ProvideSelfFD(); // may call Con_Printf() so must be after sys.outfd is set
857 fcntl(0, F_SETFL, fcntl (0, F_GETFL, 0) | O_NONBLOCK);
861 Sys_AllowProfiling(true);