2 # ifndef DONT_USE_SETDLLDIRECTORY
3 # define _WIN32_WINNT 0x0502
13 # include <mmsystem.h> // timeGetTime
14 # include <time.h> // localtime
16 #pragma comment(lib, "winmm.lib")
21 # include <sys/time.h>
28 static char sys_timestring[128];
29 char *Sys_TimeString(const char *timeformat)
31 time_t mytime = time(NULL);
34 localtime_s(&mytm, &mytime);
35 strftime(sys_timestring, sizeof(sys_timestring), timeformat, &mytm);
37 strftime(sys_timestring, sizeof(sys_timestring), timeformat, localtime(&mytime));
39 return sys_timestring;
43 extern qboolean host_shuttingdown;
44 void Sys_Quit (int returnvalue)
46 if (COM_CheckParm("-profilegameonly"))
47 Sys_AllowProfiling(false);
48 host_shuttingdown = true;
53 #if defined(__linux__) || defined(__FreeBSD__)
60 void Sys_AllowProfiling(qboolean enable)
62 #if defined(__linux__) || defined(__FreeBSD__)
69 ===============================================================================
73 ===============================================================================
76 static qboolean Sys_LoadLibraryFunctions(dllhandle_t dllhandle, const dllfunction_t *fcts, qboolean complain, qboolean has_next)
78 const dllfunction_t *func;
81 for (func = fcts; func && func->name != NULL; func++)
82 if (!(*func->funcvariable = (void *) Sys_GetProcAddress (dllhandle, func->name)))
86 Con_DPrintf (" - missing function \"%s\" - broken library!", func->name);
88 Con_DPrintf("\nContinuing with");
95 for (func = fcts; func && func->name != NULL; func++)
96 *func->funcvariable = NULL;
101 qboolean Sys_LoadLibrary (const char** dllnames, dllhandle_t* handle, const dllfunction_t *fcts)
104 const dllfunction_t *func;
105 dllhandle_t dllhandle = 0;
112 #ifdef PREFER_PRELOAD
113 dllhandle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL);
114 if(Sys_LoadLibraryFunctions(dllhandle, fcts, false, false))
116 Con_DPrintf ("All of %s's functions were already linked in! Not loading dynamically...\n", dllnames[0]);
121 Sys_UnloadLibrary(&dllhandle);
127 for (func = fcts; func && func->name != NULL; func++)
128 *func->funcvariable = NULL;
130 // Try every possible name
131 Con_DPrintf ("Trying to load library...");
132 for (i = 0; dllnames[i] != NULL; i++)
134 Con_DPrintf (" \"%s\"", dllnames[i]);
136 # ifndef DONT_USE_SETDLLDIRECTORY
138 SetDllDirectory("bin64");
140 SetDllDirectory("bin32");
143 dllhandle = LoadLibrary (dllnames[i]);
144 // no need to unset this - we want ALL dlls to be loaded from there, anyway
146 dllhandle = dlopen (dllnames[i], RTLD_LAZY | RTLD_GLOBAL);
148 if (Sys_LoadLibraryFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(com_argv[0], '/'))))
151 Sys_UnloadLibrary (&dllhandle);
154 // see if the names can be loaded relative to the executable path
155 // (this is for Mac OSX which does not check next to the executable)
156 if (!dllhandle && strrchr(com_argv[0], '/'))
158 char path[MAX_OSPATH];
159 strlcpy(path, com_argv[0], sizeof(path));
160 strrchr(path, '/')[1] = 0;
161 for (i = 0; dllnames[i] != NULL; i++)
163 char temp[MAX_OSPATH];
164 strlcpy(temp, path, sizeof(temp));
165 strlcat(temp, dllnames[i], sizeof(temp));
166 Con_DPrintf (" \"%s\"", temp);
168 dllhandle = LoadLibrary (temp);
170 dllhandle = dlopen (temp, RTLD_LAZY | RTLD_GLOBAL);
172 if (Sys_LoadLibraryFunctions(dllhandle, fcts, true, dllnames[i+1] != NULL))
175 Sys_UnloadLibrary (&dllhandle);
182 Con_DPrintf(" - failed.\n");
186 Con_DPrintf(" - loaded.\n");
195 void Sys_UnloadLibrary (dllhandle_t* handle)
198 if (handle == NULL || *handle == NULL)
202 FreeLibrary (*handle);
211 void* Sys_GetProcAddress (dllhandle_t handle, const char* name)
215 return (void *)GetProcAddress (handle, name);
217 return (void *)dlsym (handle, name);
225 # define HAVE_TIMEGETTIME 1
226 # define HAVE_QUERYPERFORMANCECOUNTER 1
227 # define HAVE_Sleep 1
230 #if defined(CLOCK_MONOTONIC) || defined(CLOCK_HIRES)
231 # define HAVE_CLOCKGETTIME 1
235 // FIXME improve this check, manpage hints to DST_NONE
236 # define HAVE_GETTIMEOFDAY 1
240 // on Win32, select() cannot be used with all three FD list args being NULL according to MSDN
241 // (so much for POSIX...)
243 # define HAVE_SELECT 1
248 // FIXME improve this check
249 # define HAVE_USLEEP 1
252 // this one is referenced elsewhere
253 cvar_t sys_usenoclockbutbenchmark = {CVAR_SAVE, "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."};
256 static cvar_t sys_debugsleep = {0, "sys_debugsleep", "0", "write requested and attained sleep times to standard output, to be used with gnuplot"};
257 static cvar_t sys_usesdlgetticks = {CVAR_SAVE, "sys_usesdlgetticks", "0", "use SDL_GetTicks() timer (less accurate, for debugging)"};
258 static cvar_t sys_usesdldelay = {CVAR_SAVE, "sys_usesdldelay", "0", "use SDL_Delay() (less accurate, for debugging)"};
259 #if HAVE_QUERYPERFORMANCECOUNTER
260 static cvar_t sys_usequeryperformancecounter = {CVAR_SAVE, "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)"};
262 #if HAVE_CLOCKGETTIME
263 static cvar_t sys_useclockgettime = {CVAR_SAVE, "sys_useclockgettime", "0", "use POSIX clock_gettime function (which has issues if the system clock speed is far off, as it can't get fixed by NTP) for timing rather than gettimeofday (which has issues if the system time is stepped by ntpdate, or apparently on some Xen installations)"};
266 static double benchmark_time; // actually always contains an integer amount of milliseconds, will eventually "overflow"
268 void Sys_Init_Commands (void)
270 Cvar_RegisterVariable(&sys_debugsleep);
271 Cvar_RegisterVariable(&sys_usenoclockbutbenchmark);
272 #if HAVE_TIMEGETTIME || HAVE_QUERYPERFORMANCECOUNTER || HAVE_CLOCKGETTIME || HAVE_GETTIMEOFDAY
273 if(sys_supportsdlgetticks)
275 Cvar_RegisterVariable(&sys_usesdlgetticks);
276 Cvar_RegisterVariable(&sys_usesdldelay);
279 #if HAVE_QUERYPERFORMANCECOUNTER
280 Cvar_RegisterVariable(&sys_usequeryperformancecounter);
282 #if HAVE_CLOCKGETTIME
283 Cvar_RegisterVariable(&sys_useclockgettime);
287 double Sys_DirtyTime(void)
289 // first all the OPTIONAL timers
291 // benchmark timer (fake clock)
292 if(sys_usenoclockbutbenchmark.integer)
294 double old_benchmark_time = benchmark_time;
296 if(benchmark_time == old_benchmark_time)
297 Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
298 return benchmark_time * 0.000001;
300 #if HAVE_QUERYPERFORMANCECOUNTER
301 if (sys_usequeryperformancecounter.integer)
303 // LordHavoc: note to people modifying this code, DWORD is specifically defined as an unsigned 32bit number, therefore the 65536.0 * 65536.0 is fine.
304 // QueryPerformanceCounter
306 // Windows 95/98/ME/NT/2000/XP
308 // very accurate (CPU cycles)
310 // does not necessarily match realtime too well (tends to get faster and faster in win98)
311 // wraps around occasionally on some platforms (depends on CPU speed and probably other unknown factors)
313 LARGE_INTEGER PerformanceFreq;
314 LARGE_INTEGER PerformanceCount;
316 if (QueryPerformanceFrequency (&PerformanceFreq))
318 QueryPerformanceCounter (&PerformanceCount);
321 timescale = 1.0 / ((double) PerformanceFreq.u.LowPart + (double) PerformanceFreq.u.HighPart * 65536.0 * 65536.0);
322 return ((double) PerformanceCount.u.LowPart + (double) PerformanceCount.u.HighPart * 65536.0 * 65536.0) * timescale;
324 timescale = 1.0 / ((double) PerformanceFreq.LowPart + (double) PerformanceFreq.HighPart * 65536.0 * 65536.0);
325 return ((double) PerformanceCount.LowPart + (double) PerformanceCount.HighPart * 65536.0 * 65536.0) * timescale;
330 Con_Printf("No hardware timer available\n");
331 // fall back to other clock sources
332 Cvar_SetValueQuick(&sys_usequeryperformancecounter, false);
337 #if HAVE_CLOCKGETTIME
338 if (sys_useclockgettime.integer)
341 # ifdef CLOCK_MONOTONIC
343 clock_gettime(CLOCK_MONOTONIC, &ts);
346 clock_gettime(CLOCK_HIGHRES, &ts);
348 return (double) ts.tv_sec + ts.tv_nsec / 1000000000.0;
352 // now all the FALLBACK timers
353 if(sys_supportsdlgetticks && sys_usesdlgetticks.integer)
354 return (double) Sys_SDL_GetTicks() / 1000.0;
355 #if HAVE_GETTIMEOFDAY
358 gettimeofday(&tp, NULL);
359 return (double) tp.tv_sec + tp.tv_usec / 1000000.0;
361 #elif HAVE_TIMEGETTIME
363 static int firsttimegettime = true;
366 // Windows 95/98/ME/NT/2000/XP
368 // reasonable accuracy (millisecond)
370 // wraps around every 47 days or so (but this is non-fatal to us, odd times are rejected, only causes a one frame stutter)
372 // make sure the timer is high precision, otherwise different versions of windows have varying accuracy
373 if (firsttimegettime)
376 firsttimegettime = false;
379 return (double) timeGetTime() / 1000.0;
382 // fallback for using the SDL timer if no other timer is available
383 // this calls Sys_Error() if not linking against SDL
384 return (double) Sys_SDL_GetTicks() / 1000.0;
388 void Sys_Sleep(int microseconds)
391 if(sys_usenoclockbutbenchmark.integer)
395 double old_benchmark_time = benchmark_time;
396 benchmark_time += microseconds;
397 if(benchmark_time == old_benchmark_time)
398 Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
402 if(sys_debugsleep.integer)
406 if(sys_supportsdlgetticks && sys_usesdldelay.integer)
408 Sys_SDL_Delay(microseconds / 1000);
414 tv.tv_sec = microseconds / 1000000;
415 tv.tv_usec = microseconds % 1000000;
416 select(0, NULL, NULL, NULL, &tv);
421 usleep(microseconds);
426 Sleep(microseconds / 1000);
431 Sys_SDL_Delay(microseconds / 1000);
434 if(sys_debugsleep.integer)
436 t = Sys_DirtyTime() - t;
437 Sys_PrintfToTerminal("%d %d # debugsleep\n", microseconds, (unsigned int)(t * 1000000));
441 void Sys_PrintfToTerminal(const char *fmt, ...)
444 char msg[MAX_INPUTLINE];
446 va_start(argptr,fmt);
447 dpvsnprintf(msg,sizeof(msg),fmt,argptr);
450 Sys_PrintToTerminal(msg);
454 static const char *Sys_FindInPATH(const char *name, char namesep, const char *PATH, char pathsep, char *buf, size_t bufsize)
456 const char *p = PATH;
460 while((q = strchr(p, ':')))
462 dpsnprintf(buf, bufsize, "%.*s%c%s", (int)(q-p), p, namesep, name);
463 if(FS_SysFileExists(buf))
467 if(!q) // none found - try the last item
469 dpsnprintf(buf, bufsize, "%s%c%s", p, namesep, name);
470 if(FS_SysFileExists(buf))
478 static const char *Sys_FindExecutableName(void)
483 static char exenamebuf[MAX_OSPATH+1];
485 #if defined(__FreeBSD__)
486 n = readlink("/proc/curproc/file", exenamebuf, sizeof(exenamebuf)-1);
487 #elif defined(__linux__)
488 n = readlink("/proc/self/exe", exenamebuf, sizeof(exenamebuf)-1);
490 if(n > 0 && (size_t)(n) < sizeof(exenamebuf))
495 if(strchr(com_argv[0], '/'))
496 return com_argv[0]; // possibly a relative path
498 return Sys_FindInPATH(com_argv[0], '/', getenv("PATH"), ':', exenamebuf, sizeof(exenamebuf));
502 void Sys_ProvideSelfFD(void)
506 com_selffd = FS_SysOpenFD(Sys_FindExecutableName(), "rb", false);
509 // for x86 cpus only... (x64 has SSE2_PRESENT)
510 #if defined(SSE_POSSIBLE) && !defined(SSE2_PRESENT)
511 // code from SDL, shortened as we can expect CPUID to work
512 static int CPUID_Features(void)
515 # if defined(__GNUC__) && defined(__i386__)
517 " movl %%ebx,%%edi\n"
518 " xorl %%eax,%%eax \n"
520 " cpuid # Get family/model/stepping/features\n"
522 " movl %%edi,%%ebx\n"
525 : "%eax", "%ecx", "%edx", "%edi"
527 # elif (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
531 cpuid ; Get family/model/stepping/features
535 # error SSE_POSSIBLE set but no CPUID implementation
540 qboolean Sys_HaveSSE(void)
542 // COMMANDLINEOPTION: SSE: -nosse disables SSE support and detection
543 if(COM_CheckParm("-nosse"))
545 // COMMANDLINEOPTION: SSE: -forcesse enables SSE support and disables detection
546 if(COM_CheckParm("-forcesse") || COM_CheckParm("-forcesse2"))
548 if(CPUID_Features() & (1 << 25))
553 qboolean Sys_HaveSSE2(void)
555 // COMMANDLINEOPTION: SSE2: -nosse2 disables SSE2 support and detection
556 if(COM_CheckParm("-nosse") || COM_CheckParm("-nosse2"))
558 // COMMANDLINEOPTION: SSE2: -forcesse2 enables SSE2 support and disables detection
559 if(COM_CheckParm("-forcesse2"))
561 if((CPUID_Features() & (3 << 25)) == (3 << 25)) // SSE is 1<<25, SSE2 is 1<<26
567 /// called to set process priority for dedicated servers
568 #if defined(__linux__)
569 #include <sys/resource.h>
571 static int nicelevel;
572 static qboolean nicepossible;
573 static qboolean isnice;
574 void Sys_InitProcessNice (void)
577 nicepossible = false;
578 if(COM_CheckParm("-nonice"))
581 nicelevel = getpriority(PRIO_PROCESS, 0);
584 Con_Printf("Kernel does not support reading process priority - cannot use niceness\n");
587 if(getrlimit(RLIMIT_NICE, &lim))
589 Con_Printf("Kernel does not support lowering nice level again - cannot use niceness\n");
592 if(lim.rlim_cur != RLIM_INFINITY && nicelevel < (int) (20 - lim.rlim_cur))
594 Con_Printf("Current nice level is below the soft limit - cannot use niceness\n");
600 void Sys_MakeProcessNice (void)
606 Con_DPrintf("Process is becoming 'nice'...\n");
607 if(setpriority(PRIO_PROCESS, 0, 19))
608 Con_Printf("Failed to raise nice level to %d\n", 19);
611 void Sys_MakeProcessMean (void)
617 Con_DPrintf("Process is becoming 'mean'...\n");
618 if(setpriority(PRIO_PROCESS, 0, nicelevel))
619 Con_Printf("Failed to lower nice level to %d\n", nicelevel);
623 void Sys_InitProcessNice (void)
626 void Sys_MakeProcessNice (void)
629 void Sys_MakeProcessMean (void)