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_LoadLibrary (const char** dllnames, dllhandle_t* handle, const dllfunction_t *fcts)
122 const dllfunction_t *func;
123 dllhandle_t dllhandle = 0;
130 #ifdef PREFER_PRELOAD
131 dllhandle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL);
132 if(Sys_LoadLibraryFunctions(dllhandle, fcts, false, false))
134 Con_DPrintf ("All of %s's functions were already linked in! Not loading dynamically...\n", dllnames[0]);
139 Sys_UnloadLibrary(&dllhandle);
145 for (func = fcts; func && func->name != NULL; func++)
146 *func->funcvariable = NULL;
148 // Try every possible name
149 Con_DPrintf ("Trying to load library...");
150 for (i = 0; dllnames[i] != NULL; i++)
152 Con_DPrintf (" \"%s\"", dllnames[i]);
154 # ifndef DONT_USE_SETDLLDIRECTORY
156 SetDllDirectory("bin64");
158 SetDllDirectory("bin32");
161 dllhandle = LoadLibrary (dllnames[i]);
162 // no need to unset this - we want ALL dlls to be loaded from there, anyway
164 dllhandle = dlopen (dllnames[i], RTLD_LAZY | RTLD_GLOBAL);
166 if (Sys_LoadLibraryFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
169 Sys_UnloadLibrary (&dllhandle);
172 // see if the names can be loaded relative to the executable path
173 // (this is for Mac OSX which does not check next to the executable)
174 if (!dllhandle && strrchr(sys.argv[0], '/'))
176 char path[MAX_OSPATH];
177 strlcpy(path, sys.argv[0], sizeof(path));
178 strrchr(path, '/')[1] = 0;
179 for (i = 0; dllnames[i] != NULL; i++)
181 char temp[MAX_OSPATH];
182 strlcpy(temp, path, sizeof(temp));
183 strlcat(temp, dllnames[i], sizeof(temp));
184 Con_DPrintf (" \"%s\"", temp);
186 dllhandle = LoadLibrary (temp);
188 dllhandle = dlopen (temp, RTLD_LAZY | RTLD_GLOBAL);
190 if (Sys_LoadLibraryFunctions(dllhandle, fcts, true, dllnames[i+1] != NULL))
193 Sys_UnloadLibrary (&dllhandle);
200 Con_DPrintf(" - failed.\n");
204 Con_DPrintf(" - loaded.\n");
205 Con_Printf("Loaded library \"%s\"\n", dllnames[i]);
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 = {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."};
274 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"};
275 static cvar_t sys_usesdlgetticks = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "sys_usesdlgetticks", "0", "use SDL_GetTicks() timer (less accurate, for debugging)"};
276 static cvar_t sys_usesdldelay = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "sys_usesdldelay", "0", "use SDL_Delay() (less accurate, for debugging)"};
277 #if HAVE_QUERYPERFORMANCECOUNTER
278 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)"};
280 #if HAVE_CLOCKGETTIME
281 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)"};
284 static double benchmark_time; // actually always contains an integer amount of milliseconds, will eventually "overflow"
290 Returns the position (1 to argc-1) in the program's argument list
291 where the given parameter apears, or 0 if not present
294 int Sys_CheckParm (const char *parm)
298 for (i=1 ; i<sys.argc ; i++)
301 continue; // NEXTSTEP sometimes clears appkit vars.
302 if (!strcmp (parm,sys.argv[i]))
309 void Sys_Init_Commands (void)
311 Cvar_RegisterVariable(&sys_debugsleep);
312 Cvar_RegisterVariable(&sys_usenoclockbutbenchmark);
313 #if HAVE_TIMEGETTIME || HAVE_QUERYPERFORMANCECOUNTER || HAVE_CLOCKGETTIME || HAVE_GETTIMEOFDAY
314 if(sys_supportsdlgetticks)
316 Cvar_RegisterVariable(&sys_usesdlgetticks);
317 Cvar_RegisterVariable(&sys_usesdldelay);
320 #if HAVE_QUERYPERFORMANCECOUNTER
321 Cvar_RegisterVariable(&sys_usequeryperformancecounter);
323 #if HAVE_CLOCKGETTIME
324 Cvar_RegisterVariable(&sys_useclockgettime);
328 double Sys_DirtyTime(void)
330 // first all the OPTIONAL timers
332 // benchmark timer (fake clock)
333 if(sys_usenoclockbutbenchmark.integer)
335 double old_benchmark_time = benchmark_time;
337 if(benchmark_time == old_benchmark_time)
338 Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
339 return benchmark_time * 0.000001;
341 #if HAVE_QUERYPERFORMANCECOUNTER
342 if (sys_usequeryperformancecounter.integer)
344 // LadyHavoc: note to people modifying this code, DWORD is specifically defined as an unsigned 32bit number, therefore the 65536.0 * 65536.0 is fine.
345 // QueryPerformanceCounter
347 // Windows 95/98/ME/NT/2000/XP
349 // very accurate (CPU cycles)
351 // does not necessarily match realtime too well (tends to get faster and faster in win98)
352 // wraps around occasionally on some platforms (depends on CPU speed and probably other unknown factors)
354 LARGE_INTEGER PerformanceFreq;
355 LARGE_INTEGER PerformanceCount;
357 if (QueryPerformanceFrequency (&PerformanceFreq))
359 QueryPerformanceCounter (&PerformanceCount);
361 timescale = 1.0 / ((double) PerformanceFreq.LowPart + (double) PerformanceFreq.HighPart * 65536.0 * 65536.0);
362 return ((double) PerformanceCount.LowPart + (double) PerformanceCount.HighPart * 65536.0 * 65536.0) * timescale;
366 Con_Printf("No hardware timer available\n");
367 // fall back to other clock sources
368 Cvar_SetValueQuick(&sys_usequeryperformancecounter, false);
373 #if HAVE_CLOCKGETTIME
374 if (sys_useclockgettime.integer)
377 # ifdef CLOCK_MONOTONIC
379 clock_gettime(CLOCK_MONOTONIC, &ts);
382 clock_gettime(CLOCK_HIGHRES, &ts);
384 return (double) ts.tv_sec + ts.tv_nsec / 1000000000.0;
388 // now all the FALLBACK timers
389 if(sys_supportsdlgetticks && sys_usesdlgetticks.integer)
390 return (double) Sys_SDL_GetTicks() / 1000.0;
391 #if HAVE_GETTIMEOFDAY
394 gettimeofday(&tp, NULL);
395 return (double) tp.tv_sec + tp.tv_usec / 1000000.0;
397 #elif HAVE_TIMEGETTIME
399 static int firsttimegettime = true;
402 // Windows 95/98/ME/NT/2000/XP
404 // reasonable accuracy (millisecond)
406 // wraps around every 47 days or so (but this is non-fatal to us, odd times are rejected, only causes a one frame stutter)
408 // make sure the timer is high precision, otherwise different versions of windows have varying accuracy
409 if (firsttimegettime)
412 firsttimegettime = false;
415 return (double) timeGetTime() / 1000.0;
418 // fallback for using the SDL timer if no other timer is available
419 // this calls Sys_Error() if not linking against SDL
420 return (double) Sys_SDL_GetTicks() / 1000.0;
424 void Sys_Sleep(int microseconds)
427 if(sys_usenoclockbutbenchmark.integer)
431 double old_benchmark_time = benchmark_time;
432 benchmark_time += microseconds;
433 if(benchmark_time == old_benchmark_time)
434 Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
438 if(sys_debugsleep.integer)
442 if(sys_supportsdlgetticks && sys_usesdldelay.integer)
444 Sys_SDL_Delay(microseconds / 1000);
450 tv.tv_sec = microseconds / 1000000;
451 tv.tv_usec = microseconds % 1000000;
452 select(0, NULL, NULL, NULL, &tv);
457 usleep(microseconds);
462 Sleep(microseconds / 1000);
467 Sys_SDL_Delay(microseconds / 1000);
470 if(sys_debugsleep.integer)
472 t = Sys_DirtyTime() - t;
473 Sys_PrintfToTerminal("%d %d # debugsleep\n", microseconds, (unsigned int)(t * 1000000));
477 void Sys_PrintfToTerminal(const char *fmt, ...)
480 char msg[MAX_INPUTLINE];
482 va_start(argptr,fmt);
483 dpvsnprintf(msg,sizeof(msg),fmt,argptr);
486 Sys_PrintToTerminal(msg);
490 static const char *Sys_FindInPATH(const char *name, char namesep, const char *PATH, char pathsep, char *buf, size_t bufsize)
492 const char *p = PATH;
496 while((q = strchr(p, ':')))
498 dpsnprintf(buf, bufsize, "%.*s%c%s", (int)(q-p), p, namesep, name);
499 if(FS_SysFileExists(buf))
503 if(!q) // none found - try the last item
505 dpsnprintf(buf, bufsize, "%s%c%s", p, namesep, name);
506 if(FS_SysFileExists(buf))
514 static const char *Sys_FindExecutableName(void)
519 static char exenamebuf[MAX_OSPATH+1];
521 #if defined(__FreeBSD__)
522 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
523 size_t exenamebuflen = sizeof(exenamebuf)-1;
524 if (sysctl(mib, 4, exenamebuf, &exenamebuflen, NULL, 0) == 0)
528 #elif defined(__linux__)
529 n = readlink("/proc/self/exe", exenamebuf, sizeof(exenamebuf)-1);
531 if(n > 0 && (size_t)(n) < sizeof(exenamebuf))
536 if(strchr(sys.argv[0], '/'))
537 return sys.argv[0]; // possibly a relative path
539 return Sys_FindInPATH(sys.argv[0], '/', getenv("PATH"), ':', exenamebuf, sizeof(exenamebuf));
543 void Sys_ProvideSelfFD(void)
547 sys.selffd = FS_SysOpenFD(Sys_FindExecutableName(), "rb", false);
550 // for x86 cpus only... (x64 has SSE2_PRESENT)
551 #if defined(SSE_POSSIBLE) && !defined(SSE2_PRESENT)
552 // code from SDL, shortened as we can expect CPUID to work
553 static int CPUID_Features(void)
556 # if defined((__GNUC__) || (__clang__) || (__TINYC__)) && defined(__i386__)
558 " movl %%ebx,%%edi\n"
559 " xorl %%eax,%%eax \n"
561 " cpuid # Get family/model/stepping/features\n"
563 " movl %%edi,%%ebx\n"
566 : "%eax", "%ecx", "%edx", "%edi"
568 # elif (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
572 cpuid ; Get family/model/stepping/features
576 # error SSE_POSSIBLE set but no CPUID implementation
583 qbool Sys_HaveSSE(void)
585 // COMMANDLINEOPTION: SSE: -nosse disables SSE support and detection
586 if(Sys_CheckParm("-nosse"))
591 // COMMANDLINEOPTION: SSE: -forcesse enables SSE support and disables detection
592 if(Sys_CheckParm("-forcesse") || Sys_CheckParm("-forcesse2"))
594 if(CPUID_Features() & (1 << 25))
600 qbool Sys_HaveSSE2(void)
602 // COMMANDLINEOPTION: SSE2: -nosse2 disables SSE2 support and detection
603 if(Sys_CheckParm("-nosse") || Sys_CheckParm("-nosse2"))
608 // COMMANDLINEOPTION: SSE2: -forcesse2 enables SSE2 support and disables detection
609 if(Sys_CheckParm("-forcesse2"))
611 if((CPUID_Features() & (3 << 25)) == (3 << 25)) // SSE is 1<<25, SSE2 is 1<<26
618 /// called to set process priority for dedicated servers
619 #if defined(__linux__)
620 #include <sys/resource.h>
623 void Sys_InitProcessNice (void)
626 sys.nicepossible = false;
627 if(Sys_CheckParm("-nonice"))
630 sys.nicelevel = getpriority(PRIO_PROCESS, 0);
633 Con_Printf("Kernel does not support reading process priority - cannot use niceness\n");
636 if(getrlimit(RLIMIT_NICE, &lim))
638 Con_Printf("Kernel does not support lowering nice level again - cannot use niceness\n");
641 if(lim.rlim_cur != RLIM_INFINITY && sys.nicelevel < (int) (20 - lim.rlim_cur))
643 Con_Printf("Current nice level is below the soft limit - cannot use niceness\n");
646 sys.nicepossible = true;
649 void Sys_MakeProcessNice (void)
651 if(!sys.nicepossible)
655 Con_DPrintf("Process is becoming 'nice'...\n");
656 if(setpriority(PRIO_PROCESS, 0, 19))
657 Con_Printf(CON_ERROR "Failed to raise nice level to %d\n", 19);
660 void Sys_MakeProcessMean (void)
662 if(!sys.nicepossible)
666 Con_DPrintf("Process is becoming 'mean'...\n");
667 if(setpriority(PRIO_PROCESS, 0, sys.nicelevel))
668 Con_Printf(CON_ERROR "Failed to lower nice level to %d\n", sys.nicelevel);
672 void Sys_InitProcessNice (void)
675 void Sys_MakeProcessNice (void)
678 void Sys_MakeProcessMean (void)