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")
23 # include <sys/time.h>
30 static char sys_timestring[128];
31 char *Sys_TimeString(const char *timeformat)
33 time_t mytime = time(NULL);
36 localtime_s(&mytm, &mytime);
37 strftime(sys_timestring, sizeof(sys_timestring), timeformat, &mytm);
39 strftime(sys_timestring, sizeof(sys_timestring), timeformat, localtime(&mytime));
41 return sys_timestring;
45 extern qboolean host_shuttingdown;
46 void Sys_Quit (int returnvalue)
48 // Unlock mutexes because the quit command may jump directly here, causing a deadlock
49 if (cmd_client.text_lock)
50 Cbuf_Unlock(&cmd_client);
51 if (cmd_server.text_lock)
52 Cbuf_Unlock(&cmd_server);
53 SV_UnlockThreadMutex();
54 TaskQueue_Frame(true);
56 if (COM_CheckParm("-profilegameonly"))
57 Sys_AllowProfiling(false);
58 host_shuttingdown = true;
66 void Sys_AllowProfiling(qboolean enable)
70 extern void monstartup(const char *libname);
71 extern void moncleanup(void);
73 monstartup("libmain.so");
77 #elif defined(__linux__) || defined(__FreeBSD__)
78 extern int moncontrol(int);
85 ===============================================================================
89 ===============================================================================
92 static qboolean Sys_LoadLibraryFunctions(dllhandle_t dllhandle, const dllfunction_t *fcts, qboolean complain, qboolean has_next)
94 const dllfunction_t *func;
97 for (func = fcts; func && func->name != NULL; func++)
98 if (!(*func->funcvariable = (void *) Sys_GetProcAddress (dllhandle, func->name)))
102 Con_DPrintf (" - missing function \"%s\" - broken library!", func->name);
104 Con_DPrintf("\nContinuing with");
111 for (func = fcts; func && func->name != NULL; func++)
112 *func->funcvariable = NULL;
117 qboolean Sys_LoadLibrary (const char** dllnames, dllhandle_t* handle, const dllfunction_t *fcts)
120 const dllfunction_t *func;
121 dllhandle_t dllhandle = 0;
128 #ifdef PREFER_PRELOAD
129 dllhandle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL);
130 if(Sys_LoadLibraryFunctions(dllhandle, fcts, false, false))
132 Con_DPrintf ("All of %s's functions were already linked in! Not loading dynamically...\n", dllnames[0]);
137 Sys_UnloadLibrary(&dllhandle);
143 for (func = fcts; func && func->name != NULL; func++)
144 *func->funcvariable = NULL;
146 // Try every possible name
147 Con_DPrintf ("Trying to load library...");
148 for (i = 0; dllnames[i] != NULL; i++)
150 Con_DPrintf (" \"%s\"", dllnames[i]);
152 # ifndef DONT_USE_SETDLLDIRECTORY
154 SetDllDirectory("bin64");
156 SetDllDirectory("bin32");
159 dllhandle = LoadLibrary (dllnames[i]);
160 // no need to unset this - we want ALL dlls to be loaded from there, anyway
162 dllhandle = dlopen (dllnames[i], RTLD_LAZY | RTLD_GLOBAL);
164 if (Sys_LoadLibraryFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(com_argv[0], '/'))))
167 Sys_UnloadLibrary (&dllhandle);
170 // see if the names can be loaded relative to the executable path
171 // (this is for Mac OSX which does not check next to the executable)
172 if (!dllhandle && strrchr(com_argv[0], '/'))
174 char path[MAX_OSPATH];
175 strlcpy(path, com_argv[0], sizeof(path));
176 strrchr(path, '/')[1] = 0;
177 for (i = 0; dllnames[i] != NULL; i++)
179 char temp[MAX_OSPATH];
180 strlcpy(temp, path, sizeof(temp));
181 strlcat(temp, dllnames[i], sizeof(temp));
182 Con_DPrintf (" \"%s\"", temp);
184 dllhandle = LoadLibrary (temp);
186 dllhandle = dlopen (temp, RTLD_LAZY | RTLD_GLOBAL);
188 if (Sys_LoadLibraryFunctions(dllhandle, fcts, true, dllnames[i+1] != NULL))
191 Sys_UnloadLibrary (&dllhandle);
198 Con_DPrintf(" - failed.\n");
202 Con_DPrintf(" - loaded.\n");
211 void Sys_UnloadLibrary (dllhandle_t* handle)
214 if (handle == NULL || *handle == NULL)
218 FreeLibrary (*handle);
227 void* Sys_GetProcAddress (dllhandle_t handle, const char* name)
231 return (void *)GetProcAddress (handle, name);
233 return (void *)dlsym (handle, name);
241 # define HAVE_TIMEGETTIME 1
242 # define HAVE_QUERYPERFORMANCECOUNTER 1
243 # define HAVE_Sleep 1
247 #if defined(CLOCK_MONOTONIC) || defined(CLOCK_HIRES)
248 # define HAVE_CLOCKGETTIME 1
250 // FIXME improve this check, manpage hints to DST_NONE
251 # define HAVE_GETTIMEOFDAY 1
255 // on Win32, select() cannot be used with all three FD list args being NULL according to MSDN
256 // (so much for POSIX...)
258 # define HAVE_SELECT 1
263 // FIXME improve this check
264 # define HAVE_USLEEP 1
267 // this one is referenced elsewhere
268 cvar_t sys_usenoclockbutbenchmark = {CVAR_CLIENT | CVAR_SERVER | 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."};
271 static cvar_t sys_debugsleep = {CVAR_CLIENT | CVAR_SERVER, "sys_debugsleep", "0", "write requested and attained sleep times to standard output, to be used with gnuplot"};
272 static cvar_t sys_usesdlgetticks = {CVAR_CLIENT | CVAR_SERVER | CVAR_SAVE, "sys_usesdlgetticks", "0", "use SDL_GetTicks() timer (less accurate, for debugging)"};
273 static cvar_t sys_usesdldelay = {CVAR_CLIENT | CVAR_SERVER | CVAR_SAVE, "sys_usesdldelay", "0", "use SDL_Delay() (less accurate, for debugging)"};
274 #if HAVE_QUERYPERFORMANCECOUNTER
275 static cvar_t sys_usequeryperformancecounter = {CVAR_CLIENT | CVAR_SERVER | 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)"};
277 #if HAVE_CLOCKGETTIME
278 static cvar_t sys_useclockgettime = {CVAR_CLIENT | CVAR_SERVER | CVAR_SAVE, "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)"};
281 static double benchmark_time; // actually always contains an integer amount of milliseconds, will eventually "overflow"
283 void Sys_Init_Commands (void)
285 Cvar_RegisterVariable(&sys_debugsleep);
286 Cvar_RegisterVariable(&sys_usenoclockbutbenchmark);
287 #if HAVE_TIMEGETTIME || HAVE_QUERYPERFORMANCECOUNTER || HAVE_CLOCKGETTIME || HAVE_GETTIMEOFDAY
288 if(sys_supportsdlgetticks)
290 Cvar_RegisterVariable(&sys_usesdlgetticks);
291 Cvar_RegisterVariable(&sys_usesdldelay);
294 #if HAVE_QUERYPERFORMANCECOUNTER
295 Cvar_RegisterVariable(&sys_usequeryperformancecounter);
297 #if HAVE_CLOCKGETTIME
298 Cvar_RegisterVariable(&sys_useclockgettime);
302 double Sys_DirtyTime(void)
304 // first all the OPTIONAL timers
306 // benchmark timer (fake clock)
307 if(sys_usenoclockbutbenchmark.integer)
309 double old_benchmark_time = benchmark_time;
311 if(benchmark_time == old_benchmark_time)
312 Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
313 return benchmark_time * 0.000001;
315 #if HAVE_QUERYPERFORMANCECOUNTER
316 if (sys_usequeryperformancecounter.integer)
318 // LadyHavoc: note to people modifying this code, DWORD is specifically defined as an unsigned 32bit number, therefore the 65536.0 * 65536.0 is fine.
319 // QueryPerformanceCounter
321 // Windows 95/98/ME/NT/2000/XP
323 // very accurate (CPU cycles)
325 // does not necessarily match realtime too well (tends to get faster and faster in win98)
326 // wraps around occasionally on some platforms (depends on CPU speed and probably other unknown factors)
328 LARGE_INTEGER PerformanceFreq;
329 LARGE_INTEGER PerformanceCount;
331 if (QueryPerformanceFrequency (&PerformanceFreq))
333 QueryPerformanceCounter (&PerformanceCount);
336 timescale = 1.0 / ((double) PerformanceFreq.u.LowPart + (double) PerformanceFreq.u.HighPart * 65536.0 * 65536.0);
337 return ((double) PerformanceCount.u.LowPart + (double) PerformanceCount.u.HighPart * 65536.0 * 65536.0) * timescale;
339 timescale = 1.0 / ((double) PerformanceFreq.LowPart + (double) PerformanceFreq.HighPart * 65536.0 * 65536.0);
340 return ((double) PerformanceCount.LowPart + (double) PerformanceCount.HighPart * 65536.0 * 65536.0) * timescale;
345 Con_Printf("No hardware timer available\n");
346 // fall back to other clock sources
347 Cvar_SetValueQuick(&sys_usequeryperformancecounter, false);
352 #if HAVE_CLOCKGETTIME
353 if (sys_useclockgettime.integer)
356 # ifdef CLOCK_MONOTONIC
358 clock_gettime(CLOCK_MONOTONIC, &ts);
361 clock_gettime(CLOCK_HIGHRES, &ts);
363 return (double) ts.tv_sec + ts.tv_nsec / 1000000000.0;
367 // now all the FALLBACK timers
368 if(sys_supportsdlgetticks && sys_usesdlgetticks.integer)
369 return (double) Sys_SDL_GetTicks() / 1000.0;
370 #if HAVE_GETTIMEOFDAY
373 gettimeofday(&tp, NULL);
374 return (double) tp.tv_sec + tp.tv_usec / 1000000.0;
376 #elif HAVE_TIMEGETTIME
378 static int firsttimegettime = true;
381 // Windows 95/98/ME/NT/2000/XP
383 // reasonable accuracy (millisecond)
385 // wraps around every 47 days or so (but this is non-fatal to us, odd times are rejected, only causes a one frame stutter)
387 // make sure the timer is high precision, otherwise different versions of windows have varying accuracy
388 if (firsttimegettime)
391 firsttimegettime = false;
394 return (double) timeGetTime() / 1000.0;
397 // fallback for using the SDL timer if no other timer is available
398 // this calls Sys_Error() if not linking against SDL
399 return (double) Sys_SDL_GetTicks() / 1000.0;
403 void Sys_Sleep(int microseconds)
406 if(sys_usenoclockbutbenchmark.integer)
410 double old_benchmark_time = benchmark_time;
411 benchmark_time += microseconds;
412 if(benchmark_time == old_benchmark_time)
413 Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
417 if(sys_debugsleep.integer)
421 if(sys_supportsdlgetticks && sys_usesdldelay.integer)
423 Sys_SDL_Delay(microseconds / 1000);
429 tv.tv_sec = microseconds / 1000000;
430 tv.tv_usec = microseconds % 1000000;
431 select(0, NULL, NULL, NULL, &tv);
436 usleep(microseconds);
441 Sleep(microseconds / 1000);
446 Sys_SDL_Delay(microseconds / 1000);
449 if(sys_debugsleep.integer)
451 t = Sys_DirtyTime() - t;
452 Sys_PrintfToTerminal("%d %d # debugsleep\n", microseconds, (unsigned int)(t * 1000000));
456 void Sys_PrintfToTerminal(const char *fmt, ...)
459 char msg[MAX_INPUTLINE];
461 va_start(argptr,fmt);
462 dpvsnprintf(msg,sizeof(msg),fmt,argptr);
465 Sys_PrintToTerminal(msg);
469 static const char *Sys_FindInPATH(const char *name, char namesep, const char *PATH, char pathsep, char *buf, size_t bufsize)
471 const char *p = PATH;
475 while((q = strchr(p, ':')))
477 dpsnprintf(buf, bufsize, "%.*s%c%s", (int)(q-p), p, namesep, name);
478 if(FS_SysFileExists(buf))
482 if(!q) // none found - try the last item
484 dpsnprintf(buf, bufsize, "%s%c%s", p, namesep, name);
485 if(FS_SysFileExists(buf))
493 static const char *Sys_FindExecutableName(void)
498 static char exenamebuf[MAX_OSPATH+1];
500 #if defined(__FreeBSD__)
501 n = readlink("/proc/curproc/file", exenamebuf, sizeof(exenamebuf)-1);
502 #elif defined(__linux__)
503 n = readlink("/proc/self/exe", exenamebuf, sizeof(exenamebuf)-1);
505 if(n > 0 && (size_t)(n) < sizeof(exenamebuf))
510 if(strchr(com_argv[0], '/'))
511 return com_argv[0]; // possibly a relative path
513 return Sys_FindInPATH(com_argv[0], '/', getenv("PATH"), ':', exenamebuf, sizeof(exenamebuf));
517 void Sys_ProvideSelfFD(void)
521 com_selffd = FS_SysOpenFD(Sys_FindExecutableName(), "rb", false);
524 // for x86 cpus only... (x64 has SSE2_PRESENT)
525 #if defined(SSE_POSSIBLE) && !defined(SSE2_PRESENT)
526 // code from SDL, shortened as we can expect CPUID to work
527 static int CPUID_Features(void)
530 # if defined(__GNUC__) && defined(__i386__)
532 " movl %%ebx,%%edi\n"
533 " xorl %%eax,%%eax \n"
535 " cpuid # Get family/model/stepping/features\n"
537 " movl %%edi,%%ebx\n"
540 : "%eax", "%ecx", "%edx", "%edi"
542 # elif (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
546 cpuid ; Get family/model/stepping/features
550 # error SSE_POSSIBLE set but no CPUID implementation
557 qboolean Sys_HaveSSE(void)
559 // COMMANDLINEOPTION: SSE: -nosse disables SSE support and detection
560 if(COM_CheckParm("-nosse"))
565 // COMMANDLINEOPTION: SSE: -forcesse enables SSE support and disables detection
566 if(COM_CheckParm("-forcesse") || COM_CheckParm("-forcesse2"))
568 if(CPUID_Features() & (1 << 25))
574 qboolean Sys_HaveSSE2(void)
576 // COMMANDLINEOPTION: SSE2: -nosse2 disables SSE2 support and detection
577 if(COM_CheckParm("-nosse") || COM_CheckParm("-nosse2"))
582 // COMMANDLINEOPTION: SSE2: -forcesse2 enables SSE2 support and disables detection
583 if(COM_CheckParm("-forcesse2"))
585 if((CPUID_Features() & (3 << 25)) == (3 << 25)) // SSE is 1<<25, SSE2 is 1<<26
592 /// called to set process priority for dedicated servers
593 #if defined(__linux__)
594 #include <sys/resource.h>
596 static int nicelevel;
597 static qboolean nicepossible;
598 static qboolean isnice;
599 void Sys_InitProcessNice (void)
602 nicepossible = false;
603 if(COM_CheckParm("-nonice"))
606 nicelevel = getpriority(PRIO_PROCESS, 0);
609 Con_Printf("Kernel does not support reading process priority - cannot use niceness\n");
612 if(getrlimit(RLIMIT_NICE, &lim))
614 Con_Printf("Kernel does not support lowering nice level again - cannot use niceness\n");
617 if(lim.rlim_cur != RLIM_INFINITY && nicelevel < (int) (20 - lim.rlim_cur))
619 Con_Printf("Current nice level is below the soft limit - cannot use niceness\n");
625 void Sys_MakeProcessNice (void)
631 Con_DPrintf("Process is becoming 'nice'...\n");
632 if(setpriority(PRIO_PROCESS, 0, 19))
633 Con_Printf("Failed to raise nice level to %d\n", 19);
636 void Sys_MakeProcessMean (void)
642 Con_DPrintf("Process is becoming 'mean'...\n");
643 if(setpriority(PRIO_PROCESS, 0, nicelevel))
644 Con_Printf("Failed to lower nice level to %d\n", nicelevel);
648 void Sys_InitProcessNice (void)
651 void Sys_MakeProcessNice (void)
654 void Sys_MakeProcessMean (void)