2 # ifndef DONT_USE_SETDLLDIRECTORY
3 # define _WIN32_WINNT 0x0502
11 # include <mmsystem.h> // timeGetTime
12 # include <time.h> // localtime
13 # include <conio.h> // _kbhit, _getch, _putch
14 # include <io.h> // write; Include this BEFORE darkplaces.h because it uses strncpy which trips DP_STATIC_ASSERT
16 #pragma comment(lib, "winmm.lib")
20 # include <sys/sysctl.h>
23 # include <android/log.h>
27 # include <sys/time.h>
37 #include "taskqueue.h"
41 static char sys_timestring[128];
42 char *Sys_TimeString(const char *timeformat)
44 time_t mytime = time(NULL);
47 localtime_s(&mytm, &mytime);
48 strftime(sys_timestring, sizeof(sys_timestring), timeformat, &mytm);
50 strftime(sys_timestring, sizeof(sys_timestring), timeformat, localtime(&mytime));
52 return sys_timestring;
56 void Sys_Quit (int returnvalue)
58 // Unlock mutexes because the quit command may jump directly here, causing a deadlock
59 if ((cmd_local)->cbuf->lock)
60 Cbuf_Unlock((cmd_local)->cbuf);
61 SV_UnlockThreadMutex();
62 TaskQueue_Frame(true);
64 if (Sys_CheckParm("-profilegameonly"))
65 Sys_AllowProfiling(false);
66 host.state = host_shutdown;
70 Sys_AllowProfiling(false);
73 fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~O_NONBLOCK);
83 void Sys_AllowProfiling(qbool enable)
87 extern void monstartup(const char *libname);
88 extern void moncleanup(void);
90 monstartup("libmain.so");
94 #elif (defined(__linux__) && (defined(__GLIBC__) || defined(__GNU_LIBRARY__))) || defined(__FreeBSD__)
95 extern int moncontrol(int);
102 ===============================================================================
106 ===============================================================================
109 static qbool Sys_LoadDependencyFunctions(dllhandle_t dllhandle, const dllfunction_t *fcts, qbool complain, qbool has_next)
111 const dllfunction_t *func;
114 for (func = fcts; func && func->name != NULL; func++)
115 if (!(*func->funcvariable = (void *) Sys_GetProcAddress (dllhandle, func->name)))
119 Con_DPrintf (" - missing function \"%s\" - broken library!", func->name);
121 Con_DPrintf("\nContinuing with");
128 for (func = fcts; func && func->name != NULL; func++)
129 *func->funcvariable = NULL;
134 qbool Sys_LoadSelf(dllhandle_t *handle)
136 dllhandle_t dllhandle = 0;
141 dllhandle = LoadLibrary (NULL);
143 dllhandle = dlopen (NULL, RTLD_NOW | RTLD_GLOBAL);
149 qbool Sys_LoadDependency (const char** dllnames, dllhandle_t* handle, const dllfunction_t *fcts)
152 const dllfunction_t *func;
153 dllhandle_t dllhandle = 0;
160 #ifdef PREFER_PRELOAD
161 dllhandle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL);
162 if(Sys_LoadDependencyFunctions(dllhandle, fcts, false, false))
164 Con_DPrintf ("All of %s's functions were already linked in! Not loading dynamically...\n", dllnames[0]);
169 Sys_FreeLibrary(&dllhandle);
175 for (func = fcts; func && func->name != NULL; func++)
176 *func->funcvariable = NULL;
178 // Try every possible name
179 Con_DPrintf ("Trying to load library...");
180 for (i = 0; dllnames[i] != NULL; i++)
182 Con_DPrintf (" \"%s\"", dllnames[i]);
184 # ifndef DONT_USE_SETDLLDIRECTORY
186 SetDllDirectory("bin64");
188 SetDllDirectory("bin32");
192 if(Sys_LoadLibrary(dllnames[i], &dllhandle))
194 if (Sys_LoadDependencyFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
197 Sys_FreeLibrary (&dllhandle);
201 // see if the names can be loaded relative to the executable path
202 // (this is for Mac OSX which does not check next to the executable)
203 if (!dllhandle && strrchr(sys.argv[0], '/'))
205 char path[MAX_OSPATH];
206 strlcpy(path, sys.argv[0], sizeof(path));
207 strrchr(path, '/')[1] = 0;
208 for (i = 0; dllnames[i] != NULL; i++)
210 char temp[MAX_OSPATH];
211 strlcpy(temp, path, sizeof(temp));
212 strlcat(temp, dllnames[i], sizeof(temp));
213 Con_DPrintf (" \"%s\"", temp);
215 if(Sys_LoadLibrary(temp, &dllhandle))
217 if (Sys_LoadDependencyFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
220 Sys_FreeLibrary (&dllhandle);
228 Con_DPrintf(" - failed.\n");
232 Con_DPrintf(" - loaded.\n");
233 Con_Printf("Loaded library \"%s\"\n", dllnames[i]);
242 qbool Sys_LoadLibrary(const char *name, dllhandle_t *handle)
244 dllhandle_t dllhandle = 0;
251 dllhandle = LoadLibrary (name);
253 dllhandle = dlopen (name, RTLD_LAZY | RTLD_GLOBAL);
263 void Sys_FreeLibrary (dllhandle_t* handle)
266 if (handle == NULL || *handle == NULL)
270 FreeLibrary (*handle);
279 void* Sys_GetProcAddress (dllhandle_t handle, const char* name)
283 return (void *)GetProcAddress (handle, name);
285 return (void *)dlsym (handle, name);
293 # define HAVE_TIMEGETTIME 1
294 # define HAVE_QUERYPERFORMANCECOUNTER 1
295 # define HAVE_Sleep 1
299 #if defined(CLOCK_MONOTONIC) || defined(CLOCK_HIRES)
300 # define HAVE_CLOCKGETTIME 1
302 // FIXME improve this check, manpage hints to DST_NONE
303 # define HAVE_GETTIMEOFDAY 1
307 # define HAVE_SELECT 1
311 // FIXME improve this check
312 # define HAVE_USLEEP 1
315 // these are referenced elsewhere
316 cvar_t sys_usenoclockbutbenchmark = {CF_SHARED, "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."};
317 cvar_t sys_libdir = {CF_READONLY | CF_SHARED, "sys_libdir", "", "Default engine library directory"};
320 static cvar_t sys_debugsleep = {CF_SHARED, "sys_debugsleep", "0", "write requested and attained sleep times to standard output, to be used with gnuplot"};
321 static cvar_t sys_usesdlgetticks = {CF_SHARED, "sys_usesdlgetticks", "0", "use SDL_GetTicks() timer (less accurate, for debugging)"};
322 static cvar_t sys_usesdldelay = {CF_SHARED, "sys_usesdldelay", "0", "use SDL_Delay() (less accurate, for debugging)"};
323 #if HAVE_QUERYPERFORMANCECOUNTER
324 static cvar_t sys_usequeryperformancecounter = {CF_SHARED | 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)"};
326 #if HAVE_CLOCKGETTIME
327 static cvar_t sys_useclockgettime = {CF_SHARED | 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)"};
330 static double benchmark_time; // actually always contains an integer amount of milliseconds, will eventually "overflow"
336 Returns the position (1 to argc-1) in the program's argument list
337 where the given parameter apears, or 0 if not present
340 int Sys_CheckParm (const char *parm)
344 for (i=1 ; i<sys.argc ; i++)
347 continue; // NEXTSTEP sometimes clears appkit vars.
348 if (!strcmp (parm,sys.argv[i]))
355 void Sys_Init_Commands (void)
357 Cvar_RegisterVariable(&sys_debugsleep);
358 Cvar_RegisterVariable(&sys_usenoclockbutbenchmark);
359 Cvar_RegisterVariable(&sys_libdir);
360 #if HAVE_TIMEGETTIME || HAVE_QUERYPERFORMANCECOUNTER || HAVE_CLOCKGETTIME || HAVE_GETTIMEOFDAY
361 if(sys_supportsdlgetticks)
363 Cvar_RegisterVariable(&sys_usesdlgetticks);
364 Cvar_RegisterVariable(&sys_usesdldelay);
367 #if HAVE_QUERYPERFORMANCECOUNTER
368 Cvar_RegisterVariable(&sys_usequeryperformancecounter);
370 #if HAVE_CLOCKGETTIME
371 Cvar_RegisterVariable(&sys_useclockgettime);
375 double Sys_DirtyTime(void)
377 // first all the OPTIONAL timers
379 // benchmark timer (fake clock)
380 if(sys_usenoclockbutbenchmark.integer)
382 double old_benchmark_time = benchmark_time;
384 if(benchmark_time == old_benchmark_time)
385 Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
386 return benchmark_time * 0.000001;
388 #if HAVE_QUERYPERFORMANCECOUNTER
389 if (sys_usequeryperformancecounter.integer)
391 // LadyHavoc: note to people modifying this code, DWORD is specifically defined as an unsigned 32bit number, therefore the 65536.0 * 65536.0 is fine.
392 // QueryPerformanceCounter
394 // Windows 95/98/ME/NT/2000/XP
396 // very accurate (CPU cycles)
398 // does not necessarily match realtime too well (tends to get faster and faster in win98)
399 // wraps around occasionally on some platforms (depends on CPU speed and probably other unknown factors)
401 LARGE_INTEGER PerformanceFreq;
402 LARGE_INTEGER PerformanceCount;
404 if (QueryPerformanceFrequency (&PerformanceFreq))
406 QueryPerformanceCounter (&PerformanceCount);
408 timescale = 1.0 / ((double) PerformanceFreq.LowPart + (double) PerformanceFreq.HighPart * 65536.0 * 65536.0);
409 return ((double) PerformanceCount.LowPart + (double) PerformanceCount.HighPart * 65536.0 * 65536.0) * timescale;
413 Con_Printf("No hardware timer available\n");
414 // fall back to other clock sources
415 Cvar_SetValueQuick(&sys_usequeryperformancecounter, false);
420 #if HAVE_CLOCKGETTIME
421 if (sys_useclockgettime.integer)
424 # ifdef CLOCK_MONOTONIC
426 clock_gettime(CLOCK_MONOTONIC, &ts);
429 clock_gettime(CLOCK_HIGHRES, &ts);
431 return (double) ts.tv_sec + ts.tv_nsec / 1000000000.0;
435 // now all the FALLBACK timers
436 if(sys_supportsdlgetticks && sys_usesdlgetticks.integer)
437 return (double) Sys_SDL_GetTicks() / 1000.0;
438 #if HAVE_GETTIMEOFDAY
441 gettimeofday(&tp, NULL);
442 return (double) tp.tv_sec + tp.tv_usec / 1000000.0;
444 #elif HAVE_TIMEGETTIME
446 static int firsttimegettime = true;
449 // Windows 95/98/ME/NT/2000/XP
451 // reasonable accuracy (millisecond)
453 // wraps around every 47 days or so (but this is non-fatal to us, odd times are rejected, only causes a one frame stutter)
455 // make sure the timer is high precision, otherwise different versions of windows have varying accuracy
456 if (firsttimegettime)
459 firsttimegettime = false;
462 return (double) timeGetTime() / 1000.0;
465 // fallback for using the SDL timer if no other timer is available
466 // this calls Sys_Error() if not linking against SDL
467 return (double) Sys_SDL_GetTicks() / 1000.0;
471 extern cvar_t host_maxwait;
472 double Sys_Sleep(double time)
475 uint32_t microseconds;
477 // convert to microseconds
480 if(host_maxwait.value <= 0)
481 time = min(time, 1000000.0);
483 time = min(time, host_maxwait.value * 1000.0);
485 if (time < 1 || host.restless)
486 return 0; // not sleeping this frame
488 microseconds = time; // post-validation to prevent overflow
490 if(sys_usenoclockbutbenchmark.integer)
492 double old_benchmark_time = benchmark_time;
493 benchmark_time += microseconds;
494 if(benchmark_time == old_benchmark_time)
495 Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
499 if(sys_debugsleep.integer)
500 Sys_Printf("sys_debugsleep: requesting %u ", microseconds);
501 dt = Sys_DirtyTime();
503 // less important on newer libcurl so no need to disturb dedicated servers
504 if (cls.state != ca_dedicated && Curl_Select(microseconds))
506 // a transfer is ready or we finished sleeping
508 else if(sys_supportsdlgetticks && sys_usesdldelay.integer)
509 Sys_SDL_Delay(microseconds / 1000);
519 if (cls.state == ca_dedicated && sv_checkforpacketsduringsleep.integer)
521 List_For_Each_Entry(s, &lhnet_socketlist.list, lhnetsocket_t, list)
523 if (s->address.addresstype == LHNETADDRESSTYPE_INET4 || s->address.addresstype == LHNETADDRESSTYPE_INET6)
525 if (lastfd < s->inetsocket)
526 lastfd = s->inetsocket;
527 #if defined(WIN32) && !defined(_MSC_VER)
528 FD_SET((int)s->inetsocket, &fdreadset);
530 FD_SET((unsigned int)s->inetsocket, &fdreadset);
535 tv.tv_sec = microseconds / 1000000;
536 tv.tv_usec = microseconds % 1000000;
537 // on Win32, select() cannot be used with all three FD list args being NULL according to MSDN
538 // (so much for POSIX...)
539 // bones_was_here: but a zeroed fd_set seems to be tolerated (tested on Win 7)
540 select(lastfd + 1, &fdreadset, NULL, NULL, &tv);
544 usleep(microseconds);
547 Sleep(microseconds / 1000);
550 Sys_SDL_Delay(microseconds / 1000);
553 dt = Sys_DirtyTime() - dt;
554 if(sys_debugsleep.integer)
555 Sys_Printf(" got %u oversleep %d\n", (unsigned int)(dt * 1000000), (unsigned int)(dt * 1000000) - microseconds);
556 return (dt < 0 || dt >= 1800) ? 0 : dt;
559 void Sys_Print(const char *text)
562 if (developer.integer > 0)
564 __android_log_write(ANDROID_LOG_DEBUG, sys.argv[0], text);
570 // BUG: for some reason, NDELAY also affects stdout (1) when used on stdin (0).
571 // this is because both go to /dev/tty by default!
573 int origflags = fcntl (sys.outfd, F_GETFL, 0);
574 fcntl (sys.outfd, F_SETFL, origflags & ~O_NONBLOCK);
580 fs_offset_t written = (fs_offset_t)write(sys.outfd, text, (int)strlen(text));
582 break; // sorry, I cannot do anything about this error - without an output
586 fcntl (sys.outfd, F_SETFL, origflags);
589 //fprintf(stdout, "%s", text);
593 void Sys_Printf(const char *fmt, ...)
596 char msg[MAX_INPUTLINE];
598 va_start(argptr,fmt);
599 dpvsnprintf(msg,sizeof(msg),fmt,argptr);
605 char *Sys_ConsoleInput(void)
607 static char text[MAX_INPUTLINE];
608 static unsigned int len = 0;
634 if (len < sizeof (text) - 1)
643 struct timeval timeout;
645 FD_SET(0, &fdset); // stdin
648 if (select (1, &fdset, NULL, NULL, &timeout) != -1 && FD_ISSET(0, &fdset))
650 len = read (0, text, sizeof(text) - 1);
653 // rip off the \n and terminate
654 // div0: WHY? console code can deal with \n just fine
655 // this caused problems with pasting stuff into a terminal window
656 // so, not ripping off the \n, but STILL keeping a NUL terminator
666 void Sys_Error (const char *error, ...)
669 char string[MAX_INPUTLINE];
671 // change stdin to non blocking
673 fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~O_NONBLOCK);
676 va_start (argptr,error);
677 dpvsnprintf (string, sizeof (string), error, argptr);
680 Con_Printf(CON_ERROR "Engine Error: %s\n", string);
682 // don't want a dead window left blocking the OS UI or the crash dialog
685 Sys_SDL_Dialog("Engine Error", string);
691 static const char *Sys_FindInPATH(const char *name, char namesep, const char *PATH, char pathsep, char *buf, size_t bufsize)
693 const char *p = PATH;
697 while((q = strchr(p, ':')))
699 dpsnprintf(buf, bufsize, "%.*s%c%s", (int)(q-p), p, namesep, name);
700 if(FS_SysFileExists(buf))
704 if(!q) // none found - try the last item
706 dpsnprintf(buf, bufsize, "%s%c%s", p, namesep, name);
707 if(FS_SysFileExists(buf))
715 static const char *Sys_FindExecutableName(void)
720 static char exenamebuf[MAX_OSPATH+1];
722 #if defined(__FreeBSD__)
723 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
724 size_t exenamebuflen = sizeof(exenamebuf)-1;
725 if (sysctl(mib, 4, exenamebuf, &exenamebuflen, NULL, 0) == 0)
729 #elif defined(__linux__)
730 n = readlink("/proc/self/exe", exenamebuf, sizeof(exenamebuf)-1);
732 if(n > 0 && (size_t)(n) < sizeof(exenamebuf))
737 if(strchr(sys.argv[0], '/'))
738 return sys.argv[0]; // possibly a relative path
740 return Sys_FindInPATH(sys.argv[0], '/', getenv("PATH"), ':', exenamebuf, sizeof(exenamebuf));
744 void Sys_ProvideSelfFD(void)
748 sys.selffd = FS_SysOpenFD(Sys_FindExecutableName(), "rb", false);
751 // for x86 cpus only... (x64 has SSE2_PRESENT)
752 #if defined(SSE_POSSIBLE) && !defined(SSE2_PRESENT)
753 // code from SDL, shortened as we can expect CPUID to work
754 static int CPUID_Features(void)
757 # if (defined(__GNUC__) || defined(__clang__) || defined(__TINYC__)) && defined(__i386__)
759 " movl %%ebx,%%edi\n"
760 " xorl %%eax,%%eax \n"
762 " cpuid # Get family/model/stepping/features\n"
764 " movl %%edi,%%ebx\n"
767 : "%eax", "%ecx", "%edx", "%edi"
769 # elif (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
773 cpuid ; Get family/model/stepping/features
777 # error SSE_POSSIBLE set but no CPUID implementation
784 qbool Sys_HaveSSE(void)
786 // COMMANDLINEOPTION: SSE: -nosse disables SSE support and detection
787 if(Sys_CheckParm("-nosse"))
792 // COMMANDLINEOPTION: SSE: -forcesse enables SSE support and disables detection
793 if(Sys_CheckParm("-forcesse") || Sys_CheckParm("-forcesse2"))
795 if(CPUID_Features() & (1 << 25))
801 qbool Sys_HaveSSE2(void)
803 // COMMANDLINEOPTION: SSE2: -nosse2 disables SSE2 support and detection
804 if(Sys_CheckParm("-nosse") || Sys_CheckParm("-nosse2"))
809 // COMMANDLINEOPTION: SSE2: -forcesse2 enables SSE2 support and disables detection
810 if(Sys_CheckParm("-forcesse2"))
812 if((CPUID_Features() & (3 << 25)) == (3 << 25)) // SSE is 1<<25, SSE2 is 1<<26
819 /// called to set process priority for dedicated servers
820 #if defined(__linux__)
821 #include <sys/resource.h>
824 void Sys_InitProcessNice (void)
827 sys.nicepossible = false;
828 if(Sys_CheckParm("-nonice"))
831 sys.nicelevel = getpriority(PRIO_PROCESS, 0);
834 Con_Printf("Kernel does not support reading process priority - cannot use niceness\n");
837 if(getrlimit(RLIMIT_NICE, &lim))
839 Con_Printf("Kernel does not support lowering nice level again - cannot use niceness\n");
842 if(lim.rlim_cur != RLIM_INFINITY && sys.nicelevel < (int) (20 - lim.rlim_cur))
844 Con_Printf("Current nice level is below the soft limit - cannot use niceness\n");
847 sys.nicepossible = true;
850 void Sys_MakeProcessNice (void)
852 if(!sys.nicepossible)
856 Con_DPrintf("Process is becoming 'nice'...\n");
857 if(setpriority(PRIO_PROCESS, 0, 19))
858 Con_Printf(CON_ERROR "Failed to raise nice level to %d\n", 19);
861 void Sys_MakeProcessMean (void)
863 if(!sys.nicepossible)
867 Con_DPrintf("Process is becoming 'mean'...\n");
868 if(setpriority(PRIO_PROCESS, 0, sys.nicelevel))
869 Con_Printf(CON_ERROR "Failed to lower nice level to %d\n", sys.nicelevel);
873 void Sys_InitProcessNice (void)
876 void Sys_MakeProcessNice (void)
879 void Sys_MakeProcessMean (void)
884 int main (int argc, char **argv)
886 signal(SIGFPE, SIG_IGN);
889 sys.argv = (const char **)argv;
891 // COMMANDLINEOPTION: -noterminal disables console output on stdout
892 if(Sys_CheckParm("-noterminal"))
894 // COMMANDLINEOPTION: -stderr moves console output to stderr
895 else if(Sys_CheckParm("-stderr"))
901 Sys_ProvideSelfFD(); // may call Con_Printf() so must be after sys.outfd is set
904 fcntl(0, F_SETFL, fcntl (0, F_GETFL, 0) | O_NONBLOCK);
908 Sys_AllowProfiling(true);