incrementaltp: respect physics overrides
[waspsaliva.git] / src / porting.cpp
blobe7ed4e0901b8e928cdd2cd564dca46236151f3b0
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 Random portability stuff
23 See comments in porting.h
26 #include "porting.h"
28 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || defined(__OpenBSD__)
29 #include <sys/types.h>
30 #include <sys/sysctl.h>
31 extern char **environ;
32 #elif defined(_WIN32)
33 #include <windows.h>
34 #include <wincrypt.h>
35 #include <algorithm>
36 #include <shlwapi.h>
37 #include <shellapi.h>
38 #endif
39 #if !defined(_WIN32)
40 #include <unistd.h>
41 #include <sys/utsname.h>
42 #if !defined(__ANDROID__)
43 #include <spawn.h>
44 #endif
45 #endif
46 #if defined(__hpux)
47 #define _PSTAT64
48 #include <sys/pstat.h>
49 #endif
50 #if defined(__ANDROID__)
51 #include "porting_android.h"
52 #endif
53 #if defined(__APPLE__)
54 // For _NSGetEnviron()
55 // Related: https://gitlab.haskell.org/ghc/ghc/issues/2458
56 #include <crt_externs.h>
57 #endif
59 #if defined(__HAIKU__)
60 #include <FindDirectory.h>
61 #endif
63 #include "config.h"
64 #include "debug.h"
65 #include "filesys.h"
66 #include "log.h"
67 #include "util/string.h"
68 #include <list>
69 #include <cstdarg>
70 #include <cstdio>
72 namespace porting
76 Signal handler (grabs Ctrl-C on POSIX systems)
79 bool g_killed = false;
81 bool *signal_handler_killstatus()
83 return &g_killed;
86 #if !defined(_WIN32) // POSIX
87 #include <signal.h>
89 void signal_handler(int sig)
91 if (!g_killed) {
92 if (sig == SIGINT) {
93 dstream << "INFO: signal_handler(): "
94 << "Ctrl-C pressed, shutting down." << std::endl;
95 } else if (sig == SIGTERM) {
96 dstream << "INFO: signal_handler(): "
97 << "got SIGTERM, shutting down." << std::endl;
100 // Comment out for less clutter when testing scripts
101 /*dstream << "INFO: sigint_handler(): "
102 << "Printing debug stacks" << std::endl;
103 debug_stacks_print();*/
105 g_killed = true;
106 } else {
107 (void)signal(sig, SIG_DFL);
111 void signal_handler_init(void)
113 (void)signal(SIGINT, signal_handler);
114 (void)signal(SIGTERM, signal_handler);
117 #else // _WIN32
118 #include <signal.h>
120 BOOL WINAPI event_handler(DWORD sig)
122 switch (sig) {
123 case CTRL_C_EVENT:
124 case CTRL_CLOSE_EVENT:
125 case CTRL_LOGOFF_EVENT:
126 case CTRL_SHUTDOWN_EVENT:
127 if (!g_killed) {
128 dstream << "INFO: event_handler(): "
129 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
130 " shutting down." << std::endl;
131 g_killed = true;
132 } else {
133 (void)signal(SIGINT, SIG_DFL);
135 break;
136 case CTRL_BREAK_EVENT:
137 break;
140 return TRUE;
143 void signal_handler_init(void)
145 SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
148 #endif
152 Path mangler
155 // Default to RUN_IN_PLACE style relative paths
156 std::string path_share = "..";
157 std::string path_user = "..";
158 std::string path_locale = path_share + DIR_DELIM + "locale";
159 std::string path_cache = path_user + DIR_DELIM + "cache";
162 std::string getDataPath(const char *subpath)
164 return path_share + DIR_DELIM + subpath;
167 void pathRemoveFile(char *path, char delim)
169 // Remove filename and path delimiter
170 int i;
171 for(i = strlen(path)-1; i>=0; i--)
173 if(path[i] == delim)
174 break;
176 path[i] = 0;
179 bool detectMSVCBuildDir(const std::string &path)
181 const char *ends[] = {
182 "bin\\Release",
183 "bin\\MinSizeRel",
184 "bin\\RelWithDebInfo",
185 "bin\\Debug",
186 "bin\\Build",
187 NULL
189 return (!removeStringEnd(path, ends).empty());
192 std::string get_sysinfo()
194 #ifdef _WIN32
196 std::ostringstream oss;
197 LPSTR filePath = new char[MAX_PATH];
198 UINT blockSize;
199 VS_FIXEDFILEINFO *fixedFileInfo;
201 GetSystemDirectoryA(filePath, MAX_PATH);
202 PathAppendA(filePath, "kernel32.dll");
204 DWORD dwVersionSize = GetFileVersionInfoSizeA(filePath, NULL);
205 LPBYTE lpVersionInfo = new BYTE[dwVersionSize];
207 GetFileVersionInfoA(filePath, 0, dwVersionSize, lpVersionInfo);
208 VerQueryValueA(lpVersionInfo, "\\", (LPVOID *)&fixedFileInfo, &blockSize);
210 oss << "Windows/"
211 << HIWORD(fixedFileInfo->dwProductVersionMS) << '.' // Major
212 << LOWORD(fixedFileInfo->dwProductVersionMS) << '.' // Minor
213 << HIWORD(fixedFileInfo->dwProductVersionLS) << ' '; // Build
215 #ifdef _WIN64
216 oss << "x86_64";
217 #else
218 BOOL is64 = FALSE;
219 if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
220 oss << "x86_64"; // 32-bit app on 64-bit OS
221 else
222 oss << "x86";
223 #endif
225 delete[] lpVersionInfo;
226 delete[] filePath;
228 return oss.str();
229 #else
230 struct utsname osinfo;
231 uname(&osinfo);
232 return std::string(osinfo.sysname) + "/"
233 + osinfo.release + " " + osinfo.machine;
234 #endif
238 bool getCurrentWorkingDir(char *buf, size_t len)
240 #ifdef _WIN32
241 DWORD ret = GetCurrentDirectory(len, buf);
242 return (ret != 0) && (ret <= len);
243 #else
244 return getcwd(buf, len);
245 #endif
249 bool getExecPathFromProcfs(char *buf, size_t buflen)
251 #ifndef _WIN32
252 buflen--;
254 ssize_t len;
255 if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
256 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
257 (len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
258 return false;
260 buf[len] = '\0';
261 return true;
262 #else
263 return false;
264 #endif
267 //// Windows
268 #if defined(_WIN32)
270 bool getCurrentExecPath(char *buf, size_t len)
272 DWORD written = GetModuleFileNameA(NULL, buf, len);
273 if (written == 0 || written == len)
274 return false;
276 return true;
280 //// Linux
281 #elif defined(__linux__)
283 bool getCurrentExecPath(char *buf, size_t len)
285 if (!getExecPathFromProcfs(buf, len))
286 return false;
288 return true;
292 //// Mac OS X, Darwin
293 #elif defined(__APPLE__)
295 bool getCurrentExecPath(char *buf, size_t len)
297 uint32_t lenb = (uint32_t)len;
298 if (_NSGetExecutablePath(buf, &lenb) == -1)
299 return false;
301 return true;
305 //// FreeBSD, NetBSD, DragonFlyBSD
306 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
308 bool getCurrentExecPath(char *buf, size_t len)
310 // Try getting path from procfs first, since valgrind
311 // doesn't work with the latter
312 if (getExecPathFromProcfs(buf, len))
313 return true;
315 int mib[4];
317 mib[0] = CTL_KERN;
318 mib[1] = KERN_PROC;
319 mib[2] = KERN_PROC_PATHNAME;
320 mib[3] = -1;
322 if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
323 return false;
325 return true;
328 #elif defined(__HAIKU__)
330 bool getCurrentExecPath(char *buf, size_t len)
332 return find_path(B_APP_IMAGE_SYMBOL, B_FIND_PATH_IMAGE_PATH, NULL, buf, len) == B_OK;
335 //// Solaris
336 #elif defined(__sun) || defined(sun)
338 bool getCurrentExecPath(char *buf, size_t len)
340 const char *exec = getexecname();
341 if (exec == NULL)
342 return false;
344 if (strlcpy(buf, exec, len) >= len)
345 return false;
347 return true;
351 // HP-UX
352 #elif defined(__hpux)
354 bool getCurrentExecPath(char *buf, size_t len)
356 struct pst_status psts;
358 if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
359 return false;
361 if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
362 return false;
364 return true;
368 #else
370 bool getCurrentExecPath(char *buf, size_t len)
372 return false;
375 #endif
378 //// Non-Windows
379 #if !defined(_WIN32)
381 const char *getHomeOrFail()
383 const char *home = getenv("HOME");
384 // In rare cases the HOME environment variable may be unset
385 FATAL_ERROR_IF(!home,
386 "Required environment variable HOME is not set");
387 return home;
390 #endif
393 //// Windows
394 #if defined(_WIN32)
396 bool setSystemPaths()
398 char buf[BUFSIZ];
400 // Find path of executable and set path_share relative to it
401 FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
402 "Failed to get current executable path");
403 pathRemoveFile(buf, '\\');
405 std::string exepath(buf);
407 // Use ".\bin\.."
408 path_share = exepath + "\\..";
409 if (detectMSVCBuildDir(exepath)) {
410 // The msvc build dir schould normaly not be present if properly installed,
411 // but its usefull for debugging.
412 path_share += DIR_DELIM "..";
415 // Use "C:\Users\<user>\AppData\Roaming\<PROJECT_NAME_C>"
416 DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
417 FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
419 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME_C;
420 return true;
424 //// Linux
425 #elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
427 bool setSystemPaths()
429 char buf[BUFSIZ];
431 if (!getCurrentExecPath(buf, sizeof(buf))) {
432 #ifdef __ANDROID__
433 errorstream << "Unable to read bindir "<< std::endl;
434 #else
435 FATAL_ERROR("Unable to read bindir");
436 #endif
437 return false;
440 pathRemoveFile(buf, '/');
441 std::string bindir(buf);
443 // Find share directory from these.
444 // It is identified by containing the subdirectory "builtin".
445 std::list<std::string> trylist;
446 std::string static_sharedir = STATIC_SHAREDIR;
447 if (!static_sharedir.empty() && static_sharedir != ".")
448 trylist.push_back(static_sharedir);
450 trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
451 DIR_DELIM + PROJECT_NAME);
452 trylist.push_back(bindir + DIR_DELIM "..");
454 #ifdef __ANDROID__
455 trylist.push_back(path_user);
456 #endif
458 for (std::list<std::string>::const_iterator
459 i = trylist.begin(); i != trylist.end(); ++i) {
460 const std::string &trypath = *i;
461 if (!fs::PathExists(trypath) ||
462 !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
463 warningstream << "system-wide share not found at \""
464 << trypath << "\""<< std::endl;
465 continue;
468 // Warn if was not the first alternative
469 if (i != trylist.begin()) {
470 warningstream << "system-wide share found at \""
471 << trypath << "\"" << std::endl;
474 path_share = trypath;
475 break;
478 #ifndef __ANDROID__
479 path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
480 + PROJECT_NAME;
481 #endif
483 return true;
487 //// Mac OS X
488 #elif defined(__APPLE__)
490 bool setSystemPaths()
492 CFBundleRef main_bundle = CFBundleGetMainBundle();
493 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
494 char path[PATH_MAX];
495 if (CFURLGetFileSystemRepresentation(resources_url,
496 TRUE, (UInt8 *)path, PATH_MAX)) {
497 path_share = std::string(path);
498 } else {
499 warningstream << "Could not determine bundle resource path" << std::endl;
501 CFRelease(resources_url);
503 path_user = std::string(getHomeOrFail())
504 + "/Library/Application Support/"
505 + PROJECT_NAME;
506 return true;
510 #else
512 bool setSystemPaths()
514 path_share = STATIC_SHAREDIR;
515 path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
516 + lowercase(PROJECT_NAME);
517 return true;
521 #endif
523 void migrateCachePath()
525 const std::string local_cache_path = path_user + DIR_DELIM + "cache";
527 // Delete tmp folder if it exists (it only ever contained
528 // a temporary ogg file, which is no longer used).
529 if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
530 fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
532 // Bail if migration impossible
533 if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
534 || fs::PathExists(path_cache)) {
535 return;
537 if (!fs::Rename(local_cache_path, path_cache)) {
538 errorstream << "Failed to migrate local cache path "
539 "to system path!" << std::endl;
543 void initializePaths()
545 #if RUN_IN_PLACE
546 char buf[BUFSIZ];
548 infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
550 bool success =
551 getCurrentExecPath(buf, sizeof(buf)) ||
552 getExecPathFromProcfs(buf, sizeof(buf));
554 if (success) {
555 pathRemoveFile(buf, DIR_DELIM_CHAR);
556 std::string execpath(buf);
558 path_share = execpath + DIR_DELIM "..";
559 path_user = execpath + DIR_DELIM "..";
561 if (detectMSVCBuildDir(execpath)) {
562 path_share += DIR_DELIM "..";
563 path_user += DIR_DELIM "..";
565 } else {
566 errorstream << "Failed to get paths by executable location, "
567 "trying cwd" << std::endl;
569 if (!getCurrentWorkingDir(buf, sizeof(buf)))
570 FATAL_ERROR("Ran out of methods to get paths");
572 size_t cwdlen = strlen(buf);
573 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
574 cwdlen--;
575 buf[cwdlen] = '\0';
578 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
579 pathRemoveFile(buf, DIR_DELIM_CHAR);
581 std::string execpath(buf);
583 path_share = execpath;
584 path_user = execpath;
586 path_cache = path_user + DIR_DELIM + "cache";
587 #else
588 infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
590 if (!setSystemPaths())
591 errorstream << "Failed to get one or more system-wide path" << std::endl;
594 # ifdef _WIN32
595 path_cache = path_user + DIR_DELIM + "cache";
596 # else
597 // Initialize path_cache
598 // First try $XDG_CACHE_HOME/PROJECT_NAME
599 const char *cache_dir = getenv("XDG_CACHE_HOME");
600 const char *home_dir = getenv("HOME");
601 if (cache_dir) {
602 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
603 } else if (home_dir) {
604 // Then try $HOME/.cache/PROJECT_NAME
605 path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
606 + DIR_DELIM + PROJECT_NAME;
607 } else {
608 // If neither works, use $PATH_USER/cache
609 path_cache = path_user + DIR_DELIM + "cache";
611 // Migrate cache folder to new location if possible
612 migrateCachePath();
613 # endif // _WIN32
614 #endif // RUN_IN_PLACE
616 infostream << "Detected share path: " << path_share << std::endl;
617 infostream << "Detected user path: " << path_user << std::endl;
618 infostream << "Detected cache path: " << path_cache << std::endl;
620 #if USE_GETTEXT
621 bool found_localedir = false;
622 # ifdef STATIC_LOCALEDIR
623 /* STATIC_LOCALEDIR may be a generalized path such as /usr/share/locale that
624 * doesn't necessarily contain our locale files, so check data path first. */
625 path_locale = getDataPath("locale");
626 if (fs::PathExists(path_locale)) {
627 found_localedir = true;
628 infostream << "Using in-place locale directory " << path_locale
629 << " even though a static one was provided." << std::endl;
630 } else if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
631 found_localedir = true;
632 path_locale = STATIC_LOCALEDIR;
633 infostream << "Using static locale directory " << STATIC_LOCALEDIR
634 << std::endl;
636 # else
637 path_locale = getDataPath("locale");
638 if (fs::PathExists(path_locale)) {
639 found_localedir = true;
641 # endif
642 if (!found_localedir) {
643 warningstream << "Couldn't find a locale directory!" << std::endl;
645 #endif // USE_GETTEXT
648 ////
649 //// OS-specific Secure Random
650 ////
652 #ifdef WIN32
654 bool secure_rand_fill_buf(void *buf, size_t len)
656 HCRYPTPROV wctx;
658 if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
659 return false;
661 CryptGenRandom(wctx, len, (BYTE *)buf);
662 CryptReleaseContext(wctx, 0);
663 return true;
666 #else
668 bool secure_rand_fill_buf(void *buf, size_t len)
670 // N.B. This function checks *only* for /dev/urandom, because on most
671 // common OSes it is non-blocking, whereas /dev/random is blocking, and it
672 // is exceptionally uncommon for there to be a situation where /dev/random
673 // exists but /dev/urandom does not. This guesswork is necessary since
674 // random devices are not covered by any POSIX standard...
675 FILE *fp = fopen("/dev/urandom", "rb");
676 if (!fp)
677 return false;
679 bool success = fread(buf, len, 1, fp) == 1;
681 fclose(fp);
682 return success;
685 #endif
687 void attachOrCreateConsole()
689 #ifdef _WIN32
690 static bool consoleAllocated = false;
691 const bool redirected = (_fileno(stdout) == -2 || _fileno(stdout) == -1); // If output is redirected to e.g a file
692 if (!consoleAllocated && redirected && (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())) {
693 freopen("CONOUT$", "w", stdout);
694 freopen("CONOUT$", "w", stderr);
695 consoleAllocated = true;
697 #endif
700 int mt_snprintf(char *buf, const size_t buf_size, const char *fmt, ...)
702 // https://msdn.microsoft.com/en-us/library/bt7tawza.aspx
703 // Many of the MSVC / Windows printf-style functions do not support positional
704 // arguments (eg. "%1$s"). We just forward the call to vsnprintf for sane
705 // platforms, but defer to _vsprintf_p on MSVC / Windows.
706 // https://github.com/FFmpeg/FFmpeg/blob/5ae9fa13f5ac640bec113120d540f70971aa635d/compat/msvcrt/snprintf.c#L46
707 // _vsprintf_p has to be shimmed with _vscprintf_p on -1 (for an example see
708 // above FFmpeg link).
709 va_list args;
710 va_start(args, fmt);
711 #ifndef _MSC_VER
712 int c = vsnprintf(buf, buf_size, fmt, args);
713 #else // _MSC_VER
714 int c = _vsprintf_p(buf, buf_size, fmt, args);
715 if (c == -1)
716 c = _vscprintf_p(fmt, args);
717 #endif // _MSC_VER
718 va_end(args);
719 return c;
722 bool openURL(const std::string &url)
724 if ((url.substr(0, 7) != "http://" && url.substr(0, 8) != "https://") ||
725 url.find_first_of("\r\n") != std::string::npos) {
726 errorstream << "Invalid url: " << url << std::endl;
727 return false;
730 #if defined(_WIN32)
731 return (intptr_t)ShellExecuteA(NULL, NULL, url.c_str(), NULL, NULL, SW_SHOWNORMAL) > 32;
732 #elif defined(__ANDROID__)
733 openURLAndroid(url);
734 return true;
735 #elif defined(__APPLE__)
736 const char *argv[] = {"open", url.c_str(), NULL};
737 return posix_spawnp(NULL, "open", NULL, NULL, (char**)argv,
738 (*_NSGetEnviron())) == 0;
739 #else
740 const char *argv[] = {"xdg-open", url.c_str(), NULL};
741 return posix_spawnp(NULL, "xdg-open", NULL, NULL, (char**)argv, environ) == 0;
742 #endif
745 // Load performance counter frequency only once at startup
746 #ifdef _WIN32
748 inline double get_perf_freq()
750 LARGE_INTEGER freq;
751 QueryPerformanceFrequency(&freq);
752 return freq.QuadPart;
755 double perf_freq = get_perf_freq();
757 #endif
759 } //namespace porting