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_local)->cbuf->lock)
52 Cbuf_Unlock((cmd_local)->cbuf);
53 SV_UnlockThreadMutex();
54 TaskQueue_Frame(true);
56 if (Sys_CheckParm("-profilegameonly"))
57 Sys_AllowProfiling(false);
58 host.state = host_shutdown;
66 void Sys_AllowProfiling(qbool enable)
70 extern void monstartup(const char *libname);
71 extern void moncleanup(void);
73 monstartup("libmain.so");
77 #elif (defined(__linux__) && (defined(__GLIBC__) || defined(__GNU_LIBRARY__))) || defined(__FreeBSD__)
78 extern int moncontrol(int);
85 ===============================================================================
89 ===============================================================================
92 static qbool Sys_LoadDependencyFunctions(dllhandle_t dllhandle, const dllfunction_t *fcts, qbool complain, qbool 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 qbool Sys_LoadSelf(dllhandle_t *handle)
119 dllhandle_t dllhandle = 0;
124 dllhandle = LoadLibrary (NULL);
126 dllhandle = dlopen (NULL, RTLD_NOW | RTLD_GLOBAL);
132 qbool Sys_LoadDependency (const char** dllnames, dllhandle_t* handle, const dllfunction_t *fcts)
135 const dllfunction_t *func;
136 dllhandle_t dllhandle = 0;
143 #ifdef PREFER_PRELOAD
144 dllhandle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL);
145 if(Sys_LoadDependencyFunctions(dllhandle, fcts, false, false))
147 Con_DPrintf ("All of %s's functions were already linked in! Not loading dynamically...\n", dllnames[0]);
152 Sys_FreeLibrary(&dllhandle);
158 for (func = fcts; func && func->name != NULL; func++)
159 *func->funcvariable = NULL;
161 // Try every possible name
162 Con_DPrintf ("Trying to load library...");
163 for (i = 0; dllnames[i] != NULL; i++)
165 Con_DPrintf (" \"%s\"", dllnames[i]);
167 # ifndef DONT_USE_SETDLLDIRECTORY
169 SetDllDirectory("bin64");
171 SetDllDirectory("bin32");
175 if(Sys_LoadLibrary(dllnames[i], &dllhandle))
177 if (Sys_LoadDependencyFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
180 Sys_FreeLibrary (&dllhandle);
184 // see if the names can be loaded relative to the executable path
185 // (this is for Mac OSX which does not check next to the executable)
186 if (!dllhandle && strrchr(sys.argv[0], '/'))
188 char path[MAX_OSPATH];
189 strlcpy(path, sys.argv[0], sizeof(path));
190 strrchr(path, '/')[1] = 0;
191 for (i = 0; dllnames[i] != NULL; i++)
193 char temp[MAX_OSPATH];
194 strlcpy(temp, path, sizeof(temp));
195 strlcat(temp, dllnames[i], sizeof(temp));
196 Con_DPrintf (" \"%s\"", temp);
198 if(Sys_LoadLibrary(temp, &dllhandle))
200 if (Sys_LoadDependencyFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
203 Sys_FreeLibrary (&dllhandle);
211 Con_DPrintf(" - failed.\n");
215 Con_DPrintf(" - loaded.\n");
216 Con_Printf("Loaded library \"%s\"\n", dllnames[i]);
225 qbool Sys_LoadLibrary(const char *name, dllhandle_t *handle)
227 dllhandle_t dllhandle = 0;
234 dllhandle = LoadLibrary (name);
236 dllhandle = dlopen (name, RTLD_LAZY | RTLD_GLOBAL);
246 void Sys_FreeLibrary (dllhandle_t* handle)
249 if (handle == NULL || *handle == NULL)
253 FreeLibrary (*handle);
262 void* Sys_GetProcAddress (dllhandle_t handle, const char* name)
266 return (void *)GetProcAddress (handle, name);
268 return (void *)dlsym (handle, name);
276 # define HAVE_TIMEGETTIME 1
277 # define HAVE_QUERYPERFORMANCECOUNTER 1
278 # define HAVE_Sleep 1
282 #if defined(CLOCK_MONOTONIC) || defined(CLOCK_HIRES)
283 # define HAVE_CLOCKGETTIME 1
285 // FIXME improve this check, manpage hints to DST_NONE
286 # define HAVE_GETTIMEOFDAY 1
290 // on Win32, select() cannot be used with all three FD list args being NULL according to MSDN
291 // (so much for POSIX...)
293 # define HAVE_SELECT 1
298 // FIXME improve this check
299 # define HAVE_USLEEP 1
302 // these are referenced elsewhere
303 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."};
304 cvar_t sys_libdir = {CF_READONLY | CF_CLIENT | CF_SERVER, "sys_libdir", "", "Default engine library directory"};
307 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"};
308 static cvar_t sys_usesdlgetticks = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "sys_usesdlgetticks", "0", "use SDL_GetTicks() timer (less accurate, for debugging)"};
309 static cvar_t sys_usesdldelay = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "sys_usesdldelay", "0", "use SDL_Delay() (less accurate, for debugging)"};
310 #if HAVE_QUERYPERFORMANCECOUNTER
311 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)"};
313 #if HAVE_CLOCKGETTIME
314 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)"};
317 static double benchmark_time; // actually always contains an integer amount of milliseconds, will eventually "overflow"
323 Returns the position (1 to argc-1) in the program's argument list
324 where the given parameter apears, or 0 if not present
327 int Sys_CheckParm (const char *parm)
331 for (i=1 ; i<sys.argc ; i++)
334 continue; // NEXTSTEP sometimes clears appkit vars.
335 if (!strcmp (parm,sys.argv[i]))
342 void Sys_Init_Commands (void)
344 Cvar_RegisterVariable(&sys_debugsleep);
345 Cvar_RegisterVariable(&sys_usenoclockbutbenchmark);
346 Cvar_RegisterVariable(&sys_libdir);
347 #if HAVE_TIMEGETTIME || HAVE_QUERYPERFORMANCECOUNTER || HAVE_CLOCKGETTIME || HAVE_GETTIMEOFDAY
348 if(sys_supportsdlgetticks)
350 Cvar_RegisterVariable(&sys_usesdlgetticks);
351 Cvar_RegisterVariable(&sys_usesdldelay);
354 #if HAVE_QUERYPERFORMANCECOUNTER
355 Cvar_RegisterVariable(&sys_usequeryperformancecounter);
357 #if HAVE_CLOCKGETTIME
358 Cvar_RegisterVariable(&sys_useclockgettime);
362 double Sys_DirtyTime(void)
364 // first all the OPTIONAL timers
366 // benchmark timer (fake clock)
367 if(sys_usenoclockbutbenchmark.integer)
369 double old_benchmark_time = benchmark_time;
371 if(benchmark_time == old_benchmark_time)
372 Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
373 return benchmark_time * 0.000001;
375 #if HAVE_QUERYPERFORMANCECOUNTER
376 if (sys_usequeryperformancecounter.integer)
378 // LadyHavoc: note to people modifying this code, DWORD is specifically defined as an unsigned 32bit number, therefore the 65536.0 * 65536.0 is fine.
379 // QueryPerformanceCounter
381 // Windows 95/98/ME/NT/2000/XP
383 // very accurate (CPU cycles)
385 // does not necessarily match realtime too well (tends to get faster and faster in win98)
386 // wraps around occasionally on some platforms (depends on CPU speed and probably other unknown factors)
388 LARGE_INTEGER PerformanceFreq;
389 LARGE_INTEGER PerformanceCount;
391 if (QueryPerformanceFrequency (&PerformanceFreq))
393 QueryPerformanceCounter (&PerformanceCount);
395 timescale = 1.0 / ((double) PerformanceFreq.LowPart + (double) PerformanceFreq.HighPart * 65536.0 * 65536.0);
396 return ((double) PerformanceCount.LowPart + (double) PerformanceCount.HighPart * 65536.0 * 65536.0) * timescale;
400 Con_Printf("No hardware timer available\n");
401 // fall back to other clock sources
402 Cvar_SetValueQuick(&sys_usequeryperformancecounter, false);
407 #if HAVE_CLOCKGETTIME
408 if (sys_useclockgettime.integer)
411 # ifdef CLOCK_MONOTONIC
413 clock_gettime(CLOCK_MONOTONIC, &ts);
416 clock_gettime(CLOCK_HIGHRES, &ts);
418 return (double) ts.tv_sec + ts.tv_nsec / 1000000000.0;
422 // now all the FALLBACK timers
423 if(sys_supportsdlgetticks && sys_usesdlgetticks.integer)
424 return (double) Sys_SDL_GetTicks() / 1000.0;
425 #if HAVE_GETTIMEOFDAY
428 gettimeofday(&tp, NULL);
429 return (double) tp.tv_sec + tp.tv_usec / 1000000.0;
431 #elif HAVE_TIMEGETTIME
433 static int firsttimegettime = true;
436 // Windows 95/98/ME/NT/2000/XP
438 // reasonable accuracy (millisecond)
440 // wraps around every 47 days or so (but this is non-fatal to us, odd times are rejected, only causes a one frame stutter)
442 // make sure the timer is high precision, otherwise different versions of windows have varying accuracy
443 if (firsttimegettime)
446 firsttimegettime = false;
449 return (double) timeGetTime() / 1000.0;
452 // fallback for using the SDL timer if no other timer is available
453 // this calls Sys_Error() if not linking against SDL
454 return (double) Sys_SDL_GetTicks() / 1000.0;
458 void Sys_Sleep(int microseconds)
461 if(sys_usenoclockbutbenchmark.integer)
465 double old_benchmark_time = benchmark_time;
466 benchmark_time += microseconds;
467 if(benchmark_time == old_benchmark_time)
468 Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
472 if(sys_debugsleep.integer)
476 if(sys_supportsdlgetticks && sys_usesdldelay.integer)
478 Sys_SDL_Delay(microseconds / 1000);
484 tv.tv_sec = microseconds / 1000000;
485 tv.tv_usec = microseconds % 1000000;
486 select(0, NULL, NULL, NULL, &tv);
491 usleep(microseconds);
496 Sleep(microseconds / 1000);
501 Sys_SDL_Delay(microseconds / 1000);
504 if(sys_debugsleep.integer)
506 t = Sys_DirtyTime() - t;
507 Sys_PrintfToTerminal("%d %d # debugsleep\n", microseconds, (unsigned int)(t * 1000000));
511 void Sys_PrintfToTerminal(const char *fmt, ...)
514 char msg[MAX_INPUTLINE];
516 va_start(argptr,fmt);
517 dpvsnprintf(msg,sizeof(msg),fmt,argptr);
520 Sys_PrintToTerminal(msg);
524 static const char *Sys_FindInPATH(const char *name, char namesep, const char *PATH, char pathsep, char *buf, size_t bufsize)
526 const char *p = PATH;
530 while((q = strchr(p, ':')))
532 dpsnprintf(buf, bufsize, "%.*s%c%s", (int)(q-p), p, namesep, name);
533 if(FS_SysFileExists(buf))
537 if(!q) // none found - try the last item
539 dpsnprintf(buf, bufsize, "%s%c%s", p, namesep, name);
540 if(FS_SysFileExists(buf))
548 static const char *Sys_FindExecutableName(void)
553 static char exenamebuf[MAX_OSPATH+1];
555 #if defined(__FreeBSD__)
556 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
557 size_t exenamebuflen = sizeof(exenamebuf)-1;
558 if (sysctl(mib, 4, exenamebuf, &exenamebuflen, NULL, 0) == 0)
562 #elif defined(__linux__)
563 n = readlink("/proc/self/exe", exenamebuf, sizeof(exenamebuf)-1);
565 if(n > 0 && (size_t)(n) < sizeof(exenamebuf))
570 if(strchr(sys.argv[0], '/'))
571 return sys.argv[0]; // possibly a relative path
573 return Sys_FindInPATH(sys.argv[0], '/', getenv("PATH"), ':', exenamebuf, sizeof(exenamebuf));
577 void Sys_ProvideSelfFD(void)
581 sys.selffd = FS_SysOpenFD(Sys_FindExecutableName(), "rb", false);
584 // for x86 cpus only... (x64 has SSE2_PRESENT)
585 #if defined(SSE_POSSIBLE) && !defined(SSE2_PRESENT)
586 // code from SDL, shortened as we can expect CPUID to work
587 static int CPUID_Features(void)
590 # if (defined(__GNUC__) || defined(__clang__) || defined(__TINYC__)) && defined(__i386__)
592 " movl %%ebx,%%edi\n"
593 " xorl %%eax,%%eax \n"
595 " cpuid # Get family/model/stepping/features\n"
597 " movl %%edi,%%ebx\n"
600 : "%eax", "%ecx", "%edx", "%edi"
602 # elif (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
606 cpuid ; Get family/model/stepping/features
610 # error SSE_POSSIBLE set but no CPUID implementation
617 qbool Sys_HaveSSE(void)
619 // COMMANDLINEOPTION: SSE: -nosse disables SSE support and detection
620 if(Sys_CheckParm("-nosse"))
625 // COMMANDLINEOPTION: SSE: -forcesse enables SSE support and disables detection
626 if(Sys_CheckParm("-forcesse") || Sys_CheckParm("-forcesse2"))
628 if(CPUID_Features() & (1 << 25))
634 qbool Sys_HaveSSE2(void)
636 // COMMANDLINEOPTION: SSE2: -nosse2 disables SSE2 support and detection
637 if(Sys_CheckParm("-nosse") || Sys_CheckParm("-nosse2"))
642 // COMMANDLINEOPTION: SSE2: -forcesse2 enables SSE2 support and disables detection
643 if(Sys_CheckParm("-forcesse2"))
645 if((CPUID_Features() & (3 << 25)) == (3 << 25)) // SSE is 1<<25, SSE2 is 1<<26
652 /// called to set process priority for dedicated servers
653 #if defined(__linux__)
654 #include <sys/resource.h>
657 void Sys_InitProcessNice (void)
660 sys.nicepossible = false;
661 if(Sys_CheckParm("-nonice"))
664 sys.nicelevel = getpriority(PRIO_PROCESS, 0);
667 Con_Printf("Kernel does not support reading process priority - cannot use niceness\n");
670 if(getrlimit(RLIMIT_NICE, &lim))
672 Con_Printf("Kernel does not support lowering nice level again - cannot use niceness\n");
675 if(lim.rlim_cur != RLIM_INFINITY && sys.nicelevel < (int) (20 - lim.rlim_cur))
677 Con_Printf("Current nice level is below the soft limit - cannot use niceness\n");
680 sys.nicepossible = true;
683 void Sys_MakeProcessNice (void)
685 if(!sys.nicepossible)
689 Con_DPrintf("Process is becoming 'nice'...\n");
690 if(setpriority(PRIO_PROCESS, 0, 19))
691 Con_Printf(CON_ERROR "Failed to raise nice level to %d\n", 19);
694 void Sys_MakeProcessMean (void)
696 if(!sys.nicepossible)
700 Con_DPrintf("Process is becoming 'mean'...\n");
701 if(setpriority(PRIO_PROCESS, 0, sys.nicelevel))
702 Con_Printf(CON_ERROR "Failed to lower nice level to %d\n", sys.nicelevel);
706 void Sys_InitProcessNice (void)
709 void Sys_MakeProcessNice (void)
712 void Sys_MakeProcessMean (void)