2 # ifndef DONT_USE_SETDLLDIRECTORY
3 # define _WIN32_WINNT 0x0502
15 # include <mmsystem.h> // timeGetTime
16 # include <time.h> // localtime
18 #pragma comment(lib, "winmm.lib")
22 # include <sys/sysctl.h>
26 # include <sys/time.h>
33 static char sys_timestring[128];
34 char *Sys_TimeString(const char *timeformat)
36 time_t mytime = time(NULL);
39 localtime_s(&mytm, &mytime);
40 strftime(sys_timestring, sizeof(sys_timestring), timeformat, &mytm);
42 strftime(sys_timestring, sizeof(sys_timestring), timeformat, localtime(&mytime));
44 return sys_timestring;
48 void Sys_Quit (int returnvalue)
50 // Unlock mutexes because the quit command may jump directly here, causing a deadlock
51 if ((&cmd_client)->cbuf->lock)
52 Cbuf_Unlock((&cmd_client)->cbuf);
53 if ((&cmd_server)->cbuf->lock)
54 Cbuf_Unlock((&cmd_server)->cbuf);
55 SV_UnlockThreadMutex();
56 TaskQueue_Frame(true);
58 if (Sys_CheckParm("-profilegameonly"))
59 Sys_AllowProfiling(false);
60 host.state = host_shutdown;
68 void Sys_AllowProfiling(qbool enable)
72 extern void monstartup(const char *libname);
73 extern void moncleanup(void);
75 monstartup("libmain.so");
79 #elif (defined(__linux__) && (defined(__GLIBC__) || defined(__GNU_LIBRARY__))) || defined(__FreeBSD__)
80 extern int moncontrol(int);
87 ===============================================================================
91 ===============================================================================
94 static qbool Sys_LoadLibraryFunctions(dllhandle_t dllhandle, const dllfunction_t *fcts, qbool complain, qbool has_next)
96 const dllfunction_t *func;
99 for (func = fcts; func && func->name != NULL; func++)
100 if (!(*func->funcvariable = (void *) Sys_GetProcAddress (dllhandle, func->name)))
104 Con_DPrintf (" - missing function \"%s\" - broken library!", func->name);
106 Con_DPrintf("\nContinuing with");
113 for (func = fcts; func && func->name != NULL; func++)
114 *func->funcvariable = NULL;
119 qbool Sys_LoadSelf(dllhandle_t *handle)
121 dllhandle_t dllhandle = 0;
126 dllhandle = LoadLibrary (NULL);
128 dllhandle = dlopen (NULL, RTLD_NOW | RTLD_GLOBAL);
134 qbool Sys_LoadLibrary (const char** dllnames, dllhandle_t* handle, const dllfunction_t *fcts)
137 const dllfunction_t *func;
138 dllhandle_t dllhandle = 0;
145 #ifdef PREFER_PRELOAD
146 dllhandle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL);
147 if(Sys_LoadLibraryFunctions(dllhandle, fcts, false, false))
149 Con_DPrintf ("All of %s's functions were already linked in! Not loading dynamically...\n", dllnames[0]);
154 Sys_UnloadLibrary(&dllhandle);
160 for (func = fcts; func && func->name != NULL; func++)
161 *func->funcvariable = NULL;
163 // Try every possible name
164 Con_DPrintf ("Trying to load library...");
165 for (i = 0; dllnames[i] != NULL; i++)
167 Con_DPrintf (" \"%s\"", dllnames[i]);
169 # ifndef DONT_USE_SETDLLDIRECTORY
171 SetDllDirectory("bin64");
173 SetDllDirectory("bin32");
176 dllhandle = LoadLibrary (dllnames[i]);
177 // no need to unset this - we want ALL dlls to be loaded from there, anyway
179 dllhandle = dlopen (dllnames[i], RTLD_LAZY | RTLD_GLOBAL);
181 if (Sys_LoadLibraryFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
184 Sys_UnloadLibrary (&dllhandle);
187 // see if the names can be loaded relative to the executable path
188 // (this is for Mac OSX which does not check next to the executable)
189 if (!dllhandle && strrchr(sys.argv[0], '/'))
191 char path[MAX_OSPATH];
192 strlcpy(path, sys.argv[0], sizeof(path));
193 strrchr(path, '/')[1] = 0;
194 for (i = 0; dllnames[i] != NULL; i++)
196 char temp[MAX_OSPATH];
197 strlcpy(temp, path, sizeof(temp));
198 strlcat(temp, dllnames[i], sizeof(temp));
199 Con_DPrintf (" \"%s\"", temp);
201 dllhandle = LoadLibrary (temp);
203 dllhandle = dlopen (temp, RTLD_LAZY | RTLD_GLOBAL);
205 if (Sys_LoadLibraryFunctions(dllhandle, fcts, true, dllnames[i+1] != NULL))
208 Sys_UnloadLibrary (&dllhandle);
215 Con_DPrintf(" - failed.\n");
219 Con_DPrintf(" - loaded.\n");
220 Con_Printf("Loaded library \"%s\"\n", dllnames[i]);
229 void Sys_UnloadLibrary (dllhandle_t* handle)
232 if (handle == NULL || *handle == NULL)
236 FreeLibrary (*handle);
245 void* Sys_GetProcAddress (dllhandle_t handle, const char* name)
249 return (void *)GetProcAddress (handle, name);
251 return (void *)dlsym (handle, name);
259 # define HAVE_TIMEGETTIME 1
260 # define HAVE_QUERYPERFORMANCECOUNTER 1
261 # define HAVE_Sleep 1
265 #if defined(CLOCK_MONOTONIC) || defined(CLOCK_HIRES)
266 # define HAVE_CLOCKGETTIME 1
268 // FIXME improve this check, manpage hints to DST_NONE
269 # define HAVE_GETTIMEOFDAY 1
273 // on Win32, select() cannot be used with all three FD list args being NULL according to MSDN
274 // (so much for POSIX...)
276 # define HAVE_SELECT 1
281 // FIXME improve this check
282 # define HAVE_USLEEP 1
285 // this one is referenced elsewhere
286 cvar_t sys_usenoclockbutbenchmark = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "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."};
289 static cvar_t sys_debugsleep = {CF_CLIENT | CF_SERVER, "sys_debugsleep", "0", "write requested and attained sleep times to standard output, to be used with gnuplot"};
290 static cvar_t sys_usesdlgetticks = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "sys_usesdlgetticks", "0", "use SDL_GetTicks() timer (less accurate, for debugging)"};
291 static cvar_t sys_usesdldelay = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "sys_usesdldelay", "0", "use SDL_Delay() (less accurate, for debugging)"};
292 #if HAVE_QUERYPERFORMANCECOUNTER
293 static cvar_t sys_usequeryperformancecounter = {CF_CLIENT | CF_SERVER | 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)"};
295 #if HAVE_CLOCKGETTIME
296 static cvar_t sys_useclockgettime = {CF_CLIENT | CF_SERVER | 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)"};
299 static double benchmark_time; // actually always contains an integer amount of milliseconds, will eventually "overflow"
305 Returns the position (1 to argc-1) in the program's argument list
306 where the given parameter apears, or 0 if not present
309 int Sys_CheckParm (const char *parm)
313 for (i=1 ; i<sys.argc ; i++)
316 continue; // NEXTSTEP sometimes clears appkit vars.
317 if (!strcmp (parm,sys.argv[i]))
324 void Sys_Init_Commands (void)
326 Cvar_RegisterVariable(&sys_debugsleep);
327 Cvar_RegisterVariable(&sys_usenoclockbutbenchmark);
328 #if HAVE_TIMEGETTIME || HAVE_QUERYPERFORMANCECOUNTER || HAVE_CLOCKGETTIME || HAVE_GETTIMEOFDAY
329 if(sys_supportsdlgetticks)
331 Cvar_RegisterVariable(&sys_usesdlgetticks);
332 Cvar_RegisterVariable(&sys_usesdldelay);
335 #if HAVE_QUERYPERFORMANCECOUNTER
336 Cvar_RegisterVariable(&sys_usequeryperformancecounter);
338 #if HAVE_CLOCKGETTIME
339 Cvar_RegisterVariable(&sys_useclockgettime);
343 double Sys_DirtyTime(void)
345 // first all the OPTIONAL timers
347 // benchmark timer (fake clock)
348 if(sys_usenoclockbutbenchmark.integer)
350 double old_benchmark_time = benchmark_time;
352 if(benchmark_time == old_benchmark_time)
353 Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
354 return benchmark_time * 0.000001;
356 #if HAVE_QUERYPERFORMANCECOUNTER
357 if (sys_usequeryperformancecounter.integer)
359 // LadyHavoc: note to people modifying this code, DWORD is specifically defined as an unsigned 32bit number, therefore the 65536.0 * 65536.0 is fine.
360 // QueryPerformanceCounter
362 // Windows 95/98/ME/NT/2000/XP
364 // very accurate (CPU cycles)
366 // does not necessarily match realtime too well (tends to get faster and faster in win98)
367 // wraps around occasionally on some platforms (depends on CPU speed and probably other unknown factors)
369 LARGE_INTEGER PerformanceFreq;
370 LARGE_INTEGER PerformanceCount;
372 if (QueryPerformanceFrequency (&PerformanceFreq))
374 QueryPerformanceCounter (&PerformanceCount);
376 timescale = 1.0 / ((double) PerformanceFreq.LowPart + (double) PerformanceFreq.HighPart * 65536.0 * 65536.0);
377 return ((double) PerformanceCount.LowPart + (double) PerformanceCount.HighPart * 65536.0 * 65536.0) * timescale;
381 Con_Printf("No hardware timer available\n");
382 // fall back to other clock sources
383 Cvar_SetValueQuick(&sys_usequeryperformancecounter, false);
388 #if HAVE_CLOCKGETTIME
389 if (sys_useclockgettime.integer)
392 # ifdef CLOCK_MONOTONIC
394 clock_gettime(CLOCK_MONOTONIC, &ts);
397 clock_gettime(CLOCK_HIGHRES, &ts);
399 return (double) ts.tv_sec + ts.tv_nsec / 1000000000.0;
403 // now all the FALLBACK timers
404 if(sys_supportsdlgetticks && sys_usesdlgetticks.integer)
405 return (double) Sys_SDL_GetTicks() / 1000.0;
406 #if HAVE_GETTIMEOFDAY
409 gettimeofday(&tp, NULL);
410 return (double) tp.tv_sec + tp.tv_usec / 1000000.0;
412 #elif HAVE_TIMEGETTIME
414 static int firsttimegettime = true;
417 // Windows 95/98/ME/NT/2000/XP
419 // reasonable accuracy (millisecond)
421 // wraps around every 47 days or so (but this is non-fatal to us, odd times are rejected, only causes a one frame stutter)
423 // make sure the timer is high precision, otherwise different versions of windows have varying accuracy
424 if (firsttimegettime)
427 firsttimegettime = false;
430 return (double) timeGetTime() / 1000.0;
433 // fallback for using the SDL timer if no other timer is available
434 // this calls Sys_Error() if not linking against SDL
435 return (double) Sys_SDL_GetTicks() / 1000.0;
439 void Sys_Sleep(int microseconds)
442 if(sys_usenoclockbutbenchmark.integer)
446 double old_benchmark_time = benchmark_time;
447 benchmark_time += microseconds;
448 if(benchmark_time == old_benchmark_time)
449 Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
453 if(sys_debugsleep.integer)
457 if(sys_supportsdlgetticks && sys_usesdldelay.integer)
459 Sys_SDL_Delay(microseconds / 1000);
465 tv.tv_sec = microseconds / 1000000;
466 tv.tv_usec = microseconds % 1000000;
467 select(0, NULL, NULL, NULL, &tv);
472 usleep(microseconds);
477 Sleep(microseconds / 1000);
482 Sys_SDL_Delay(microseconds / 1000);
485 if(sys_debugsleep.integer)
487 t = Sys_DirtyTime() - t;
488 Sys_PrintfToTerminal("%d %d # debugsleep\n", microseconds, (unsigned int)(t * 1000000));
492 void Sys_PrintfToTerminal(const char *fmt, ...)
495 char msg[MAX_INPUTLINE];
497 va_start(argptr,fmt);
498 dpvsnprintf(msg,sizeof(msg),fmt,argptr);
501 Sys_PrintToTerminal(msg);
505 static const char *Sys_FindInPATH(const char *name, char namesep, const char *PATH, char pathsep, char *buf, size_t bufsize)
507 const char *p = PATH;
511 while((q = strchr(p, ':')))
513 dpsnprintf(buf, bufsize, "%.*s%c%s", (int)(q-p), p, namesep, name);
514 if(FS_SysFileExists(buf))
518 if(!q) // none found - try the last item
520 dpsnprintf(buf, bufsize, "%s%c%s", p, namesep, name);
521 if(FS_SysFileExists(buf))
529 static const char *Sys_FindExecutableName(void)
534 static char exenamebuf[MAX_OSPATH+1];
536 #if defined(__FreeBSD__)
537 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
538 size_t exenamebuflen = sizeof(exenamebuf)-1;
539 if (sysctl(mib, 4, exenamebuf, &exenamebuflen, NULL, 0) == 0)
543 #elif defined(__linux__)
544 n = readlink("/proc/self/exe", exenamebuf, sizeof(exenamebuf)-1);
546 if(n > 0 && (size_t)(n) < sizeof(exenamebuf))
551 if(strchr(sys.argv[0], '/'))
552 return sys.argv[0]; // possibly a relative path
554 return Sys_FindInPATH(sys.argv[0], '/', getenv("PATH"), ':', exenamebuf, sizeof(exenamebuf));
558 void Sys_ProvideSelfFD(void)
562 sys.selffd = FS_SysOpenFD(Sys_FindExecutableName(), "rb", false);
565 // for x86 cpus only... (x64 has SSE2_PRESENT)
566 #if defined(SSE_POSSIBLE) && !defined(SSE2_PRESENT)
567 // code from SDL, shortened as we can expect CPUID to work
568 static int CPUID_Features(void)
571 # if (defined(__GNUC__) || defined(__clang__) || defined(__TINYC__)) && defined(__i386__)
573 " movl %%ebx,%%edi\n"
574 " xorl %%eax,%%eax \n"
576 " cpuid # Get family/model/stepping/features\n"
578 " movl %%edi,%%ebx\n"
581 : "%eax", "%ecx", "%edx", "%edi"
583 # elif (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
587 cpuid ; Get family/model/stepping/features
591 # error SSE_POSSIBLE set but no CPUID implementation
598 qbool Sys_HaveSSE(void)
600 // COMMANDLINEOPTION: SSE: -nosse disables SSE support and detection
601 if(Sys_CheckParm("-nosse"))
606 // COMMANDLINEOPTION: SSE: -forcesse enables SSE support and disables detection
607 if(Sys_CheckParm("-forcesse") || Sys_CheckParm("-forcesse2"))
609 if(CPUID_Features() & (1 << 25))
615 qbool Sys_HaveSSE2(void)
617 // COMMANDLINEOPTION: SSE2: -nosse2 disables SSE2 support and detection
618 if(Sys_CheckParm("-nosse") || Sys_CheckParm("-nosse2"))
623 // COMMANDLINEOPTION: SSE2: -forcesse2 enables SSE2 support and disables detection
624 if(Sys_CheckParm("-forcesse2"))
626 if((CPUID_Features() & (3 << 25)) == (3 << 25)) // SSE is 1<<25, SSE2 is 1<<26
633 /// called to set process priority for dedicated servers
634 #if defined(__linux__)
635 #include <sys/resource.h>
638 void Sys_InitProcessNice (void)
641 sys.nicepossible = false;
642 if(Sys_CheckParm("-nonice"))
645 sys.nicelevel = getpriority(PRIO_PROCESS, 0);
648 Con_Printf("Kernel does not support reading process priority - cannot use niceness\n");
651 if(getrlimit(RLIMIT_NICE, &lim))
653 Con_Printf("Kernel does not support lowering nice level again - cannot use niceness\n");
656 if(lim.rlim_cur != RLIM_INFINITY && sys.nicelevel < (int) (20 - lim.rlim_cur))
658 Con_Printf("Current nice level is below the soft limit - cannot use niceness\n");
661 sys.nicepossible = true;
664 void Sys_MakeProcessNice (void)
666 if(!sys.nicepossible)
670 Con_DPrintf("Process is becoming 'nice'...\n");
671 if(setpriority(PRIO_PROCESS, 0, 19))
672 Con_Printf(CON_ERROR "Failed to raise nice level to %d\n", 19);
675 void Sys_MakeProcessMean (void)
677 if(!sys.nicepossible)
681 Con_DPrintf("Process is becoming 'mean'...\n");
682 if(setpriority(PRIO_PROCESS, 0, sys.nicelevel))
683 Con_Printf(CON_ERROR "Failed to lower nice level to %d\n", sys.nicelevel);
687 void Sys_InitProcessNice (void)
690 void Sys_MakeProcessNice (void)
693 void Sys_MakeProcessMean (void)