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 extern qboolean host_shuttingdown;
49 void Sys_Quit (int returnvalue)
51 // Unlock mutexes because the quit command may jump directly here, causing a deadlock
52 if (cmd_client.text_lock)
53 Cbuf_Unlock(&cmd_client);
54 if (cmd_server.text_lock)
55 Cbuf_Unlock(&cmd_server);
56 SV_UnlockThreadMutex();
57 TaskQueue_Frame(true);
59 if (COM_CheckParm("-profilegameonly"))
60 Sys_AllowProfiling(false);
61 host_shuttingdown = true;
69 void Sys_AllowProfiling(qboolean enable)
73 extern void monstartup(const char *libname);
74 extern void moncleanup(void);
76 monstartup("libmain.so");
80 #elif (defined(__linux__) && (defined(__GLIBC__) || defined(__GNU_LIBRARY__))) || defined(__FreeBSD__)
81 extern int moncontrol(int);
88 ===============================================================================
92 ===============================================================================
95 static qboolean Sys_LoadLibraryFunctions(dllhandle_t dllhandle, const dllfunction_t *fcts, qboolean complain, qboolean has_next)
97 const dllfunction_t *func;
100 for (func = fcts; func && func->name != NULL; func++)
101 if (!(*func->funcvariable = (void *) Sys_GetProcAddress (dllhandle, func->name)))
105 Con_DPrintf (" - missing function \"%s\" - broken library!", func->name);
107 Con_DPrintf("\nContinuing with");
114 for (func = fcts; func && func->name != NULL; func++)
115 *func->funcvariable = NULL;
120 qboolean Sys_LoadLibrary (const char** dllnames, dllhandle_t* handle, const dllfunction_t *fcts)
123 const dllfunction_t *func;
124 dllhandle_t dllhandle = 0;
131 #ifdef PREFER_PRELOAD
132 dllhandle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL);
133 if(Sys_LoadLibraryFunctions(dllhandle, fcts, false, false))
135 Con_DPrintf ("All of %s's functions were already linked in! Not loading dynamically...\n", dllnames[0]);
140 Sys_UnloadLibrary(&dllhandle);
146 for (func = fcts; func && func->name != NULL; func++)
147 *func->funcvariable = NULL;
149 // Try every possible name
150 Con_DPrintf ("Trying to load library...");
151 for (i = 0; dllnames[i] != NULL; i++)
153 Con_DPrintf (" \"%s\"", dllnames[i]);
155 # ifndef DONT_USE_SETDLLDIRECTORY
157 SetDllDirectory("bin64");
159 SetDllDirectory("bin32");
162 dllhandle = LoadLibrary (dllnames[i]);
163 // no need to unset this - we want ALL dlls to be loaded from there, anyway
165 dllhandle = dlopen (dllnames[i], RTLD_LAZY | RTLD_GLOBAL);
167 if (Sys_LoadLibraryFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(com_argv[0], '/'))))
170 Sys_UnloadLibrary (&dllhandle);
173 // see if the names can be loaded relative to the executable path
174 // (this is for Mac OSX which does not check next to the executable)
175 if (!dllhandle && strrchr(com_argv[0], '/'))
177 char path[MAX_OSPATH];
178 strlcpy(path, com_argv[0], sizeof(path));
179 strrchr(path, '/')[1] = 0;
180 for (i = 0; dllnames[i] != NULL; i++)
182 char temp[MAX_OSPATH];
183 strlcpy(temp, path, sizeof(temp));
184 strlcat(temp, dllnames[i], sizeof(temp));
185 Con_DPrintf (" \"%s\"", temp);
187 dllhandle = LoadLibrary (temp);
189 dllhandle = dlopen (temp, RTLD_LAZY | RTLD_GLOBAL);
191 if (Sys_LoadLibraryFunctions(dllhandle, fcts, true, dllnames[i+1] != NULL))
194 Sys_UnloadLibrary (&dllhandle);
201 Con_DPrintf(" - failed.\n");
205 Con_DPrintf(" - loaded.\n");
214 void Sys_UnloadLibrary (dllhandle_t* handle)
217 if (handle == NULL || *handle == NULL)
221 FreeLibrary (*handle);
230 void* Sys_GetProcAddress (dllhandle_t handle, const char* name)
234 return (void *)GetProcAddress (handle, name);
236 return (void *)dlsym (handle, name);
244 # define HAVE_TIMEGETTIME 1
245 # define HAVE_QUERYPERFORMANCECOUNTER 1
246 # define HAVE_Sleep 1
250 #if defined(CLOCK_MONOTONIC) || defined(CLOCK_HIRES)
251 # define HAVE_CLOCKGETTIME 1
253 // FIXME improve this check, manpage hints to DST_NONE
254 # define HAVE_GETTIMEOFDAY 1
258 // on Win32, select() cannot be used with all three FD list args being NULL according to MSDN
259 // (so much for POSIX...)
261 # define HAVE_SELECT 1
266 // FIXME improve this check
267 # define HAVE_USLEEP 1
270 // this one is referenced elsewhere
271 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."};
274 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"};
275 static cvar_t sys_usesdlgetticks = {CVAR_CLIENT | CVAR_SERVER | CVAR_SAVE, "sys_usesdlgetticks", "0", "use SDL_GetTicks() timer (less accurate, for debugging)"};
276 static cvar_t sys_usesdldelay = {CVAR_CLIENT | CVAR_SERVER | CVAR_SAVE, "sys_usesdldelay", "0", "use SDL_Delay() (less accurate, for debugging)"};
277 #if HAVE_QUERYPERFORMANCECOUNTER
278 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)"};
280 #if HAVE_CLOCKGETTIME
281 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)"};
284 static double benchmark_time; // actually always contains an integer amount of milliseconds, will eventually "overflow"
286 void Sys_Init_Commands (void)
288 Cvar_RegisterVariable(&sys_debugsleep);
289 Cvar_RegisterVariable(&sys_usenoclockbutbenchmark);
290 #if HAVE_TIMEGETTIME || HAVE_QUERYPERFORMANCECOUNTER || HAVE_CLOCKGETTIME || HAVE_GETTIMEOFDAY
291 if(sys_supportsdlgetticks)
293 Cvar_RegisterVariable(&sys_usesdlgetticks);
294 Cvar_RegisterVariable(&sys_usesdldelay);
297 #if HAVE_QUERYPERFORMANCECOUNTER
298 Cvar_RegisterVariable(&sys_usequeryperformancecounter);
300 #if HAVE_CLOCKGETTIME
301 Cvar_RegisterVariable(&sys_useclockgettime);
305 double Sys_DirtyTime(void)
307 // first all the OPTIONAL timers
309 // benchmark timer (fake clock)
310 if(sys_usenoclockbutbenchmark.integer)
312 double old_benchmark_time = benchmark_time;
314 if(benchmark_time == old_benchmark_time)
315 Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
316 return benchmark_time * 0.000001;
318 #if HAVE_QUERYPERFORMANCECOUNTER
319 if (sys_usequeryperformancecounter.integer)
321 // LadyHavoc: note to people modifying this code, DWORD is specifically defined as an unsigned 32bit number, therefore the 65536.0 * 65536.0 is fine.
322 // QueryPerformanceCounter
324 // Windows 95/98/ME/NT/2000/XP
326 // very accurate (CPU cycles)
328 // does not necessarily match realtime too well (tends to get faster and faster in win98)
329 // wraps around occasionally on some platforms (depends on CPU speed and probably other unknown factors)
331 LARGE_INTEGER PerformanceFreq;
332 LARGE_INTEGER PerformanceCount;
334 if (QueryPerformanceFrequency (&PerformanceFreq))
336 QueryPerformanceCounter (&PerformanceCount);
339 timescale = 1.0 / ((double) PerformanceFreq.u.LowPart + (double) PerformanceFreq.u.HighPart * 65536.0 * 65536.0);
340 return ((double) PerformanceCount.u.LowPart + (double) PerformanceCount.u.HighPart * 65536.0 * 65536.0) * timescale;
342 timescale = 1.0 / ((double) PerformanceFreq.LowPart + (double) PerformanceFreq.HighPart * 65536.0 * 65536.0);
343 return ((double) PerformanceCount.LowPart + (double) PerformanceCount.HighPart * 65536.0 * 65536.0) * timescale;
348 Con_Printf("No hardware timer available\n");
349 // fall back to other clock sources
350 Cvar_SetValueQuick(&sys_usequeryperformancecounter, false);
355 #if HAVE_CLOCKGETTIME
356 if (sys_useclockgettime.integer)
359 # ifdef CLOCK_MONOTONIC
361 clock_gettime(CLOCK_MONOTONIC, &ts);
364 clock_gettime(CLOCK_HIGHRES, &ts);
366 return (double) ts.tv_sec + ts.tv_nsec / 1000000000.0;
370 // now all the FALLBACK timers
371 if(sys_supportsdlgetticks && sys_usesdlgetticks.integer)
372 return (double) Sys_SDL_GetTicks() / 1000.0;
373 #if HAVE_GETTIMEOFDAY
376 gettimeofday(&tp, NULL);
377 return (double) tp.tv_sec + tp.tv_usec / 1000000.0;
379 #elif HAVE_TIMEGETTIME
381 static int firsttimegettime = true;
384 // Windows 95/98/ME/NT/2000/XP
386 // reasonable accuracy (millisecond)
388 // wraps around every 47 days or so (but this is non-fatal to us, odd times are rejected, only causes a one frame stutter)
390 // make sure the timer is high precision, otherwise different versions of windows have varying accuracy
391 if (firsttimegettime)
394 firsttimegettime = false;
397 return (double) timeGetTime() / 1000.0;
400 // fallback for using the SDL timer if no other timer is available
401 // this calls Sys_Error() if not linking against SDL
402 return (double) Sys_SDL_GetTicks() / 1000.0;
406 void Sys_Sleep(int microseconds)
409 if(sys_usenoclockbutbenchmark.integer)
413 double old_benchmark_time = benchmark_time;
414 benchmark_time += microseconds;
415 if(benchmark_time == old_benchmark_time)
416 Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
420 if(sys_debugsleep.integer)
424 if(sys_supportsdlgetticks && sys_usesdldelay.integer)
426 Sys_SDL_Delay(microseconds / 1000);
432 tv.tv_sec = microseconds / 1000000;
433 tv.tv_usec = microseconds % 1000000;
434 select(0, NULL, NULL, NULL, &tv);
439 usleep(microseconds);
444 Sleep(microseconds / 1000);
449 Sys_SDL_Delay(microseconds / 1000);
452 if(sys_debugsleep.integer)
454 t = Sys_DirtyTime() - t;
455 Sys_PrintfToTerminal("%d %d # debugsleep\n", microseconds, (unsigned int)(t * 1000000));
459 void Sys_PrintfToTerminal(const char *fmt, ...)
462 char msg[MAX_INPUTLINE];
464 va_start(argptr,fmt);
465 dpvsnprintf(msg,sizeof(msg),fmt,argptr);
468 Sys_PrintToTerminal(msg);
472 static const char *Sys_FindInPATH(const char *name, char namesep, const char *PATH, char pathsep, char *buf, size_t bufsize)
474 const char *p = PATH;
478 while((q = strchr(p, ':')))
480 dpsnprintf(buf, bufsize, "%.*s%c%s", (int)(q-p), p, namesep, name);
481 if(FS_SysFileExists(buf))
485 if(!q) // none found - try the last item
487 dpsnprintf(buf, bufsize, "%s%c%s", p, namesep, name);
488 if(FS_SysFileExists(buf))
496 static const char *Sys_FindExecutableName(void)
501 static char exenamebuf[MAX_OSPATH+1];
503 #if defined(__FreeBSD__)
504 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
505 size_t exenamebuflen = sizeof(exenamebuf)-1;
506 if (sysctl(mib, 4, exenamebuf, &exenamebuflen, NULL, 0) == 0)
510 #elif defined(__linux__)
511 n = readlink("/proc/self/exe", exenamebuf, sizeof(exenamebuf)-1);
513 if(n > 0 && (size_t)(n) < sizeof(exenamebuf))
518 if(strchr(com_argv[0], '/'))
519 return com_argv[0]; // possibly a relative path
521 return Sys_FindInPATH(com_argv[0], '/', getenv("PATH"), ':', exenamebuf, sizeof(exenamebuf));
525 void Sys_ProvideSelfFD(void)
529 com_selffd = FS_SysOpenFD(Sys_FindExecutableName(), "rb", false);
532 // for x86 cpus only... (x64 has SSE2_PRESENT)
533 #if defined(SSE_POSSIBLE) && !defined(SSE2_PRESENT)
534 // code from SDL, shortened as we can expect CPUID to work
535 static int CPUID_Features(void)
538 # if defined(__GNUC__) && defined(__i386__)
540 " movl %%ebx,%%edi\n"
541 " xorl %%eax,%%eax \n"
543 " cpuid # Get family/model/stepping/features\n"
545 " movl %%edi,%%ebx\n"
548 : "%eax", "%ecx", "%edx", "%edi"
550 # elif (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
554 cpuid ; Get family/model/stepping/features
558 # error SSE_POSSIBLE set but no CPUID implementation
565 qboolean Sys_HaveSSE(void)
567 // COMMANDLINEOPTION: SSE: -nosse disables SSE support and detection
568 if(COM_CheckParm("-nosse"))
573 // COMMANDLINEOPTION: SSE: -forcesse enables SSE support and disables detection
574 if(COM_CheckParm("-forcesse") || COM_CheckParm("-forcesse2"))
576 if(CPUID_Features() & (1 << 25))
582 qboolean Sys_HaveSSE2(void)
584 // COMMANDLINEOPTION: SSE2: -nosse2 disables SSE2 support and detection
585 if(COM_CheckParm("-nosse") || COM_CheckParm("-nosse2"))
590 // COMMANDLINEOPTION: SSE2: -forcesse2 enables SSE2 support and disables detection
591 if(COM_CheckParm("-forcesse2"))
593 if((CPUID_Features() & (3 << 25)) == (3 << 25)) // SSE is 1<<25, SSE2 is 1<<26
600 /// called to set process priority for dedicated servers
601 #if defined(__linux__)
602 #include <sys/resource.h>
604 static int nicelevel;
605 static qboolean nicepossible;
606 static qboolean isnice;
607 void Sys_InitProcessNice (void)
610 nicepossible = false;
611 if(COM_CheckParm("-nonice"))
614 nicelevel = getpriority(PRIO_PROCESS, 0);
617 Con_Printf("Kernel does not support reading process priority - cannot use niceness\n");
620 if(getrlimit(RLIMIT_NICE, &lim))
622 Con_Printf("Kernel does not support lowering nice level again - cannot use niceness\n");
625 if(lim.rlim_cur != RLIM_INFINITY && nicelevel < (int) (20 - lim.rlim_cur))
627 Con_Printf("Current nice level is below the soft limit - cannot use niceness\n");
633 void Sys_MakeProcessNice (void)
639 Con_DPrintf("Process is becoming 'nice'...\n");
640 if(setpriority(PRIO_PROCESS, 0, 19))
641 Con_Errorf("Failed to raise nice level to %d\n", 19);
644 void Sys_MakeProcessMean (void)
650 Con_DPrintf("Process is becoming 'mean'...\n");
651 if(setpriority(PRIO_PROCESS, 0, nicelevel))
652 Con_Errorf("Failed to lower nice level to %d\n", nicelevel);
656 void Sys_InitProcessNice (void)
659 void Sys_MakeProcessNice (void)
662 void Sys_MakeProcessMean (void)