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
28 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || defined(__OpenBSD__)
29 #include <sys/types.h>
30 #include <sys/sysctl.h>
31 extern char **environ;
42 #include <sys/utsname.h>
43 #if !defined(__ANDROID__)
49 #include <sys/pstat.h>
51 #if defined(__ANDROID__)
52 #include "porting_android.h"
54 #if defined(__APPLE__)
55 // For _NSGetEnviron()
56 // Related: https://gitlab.haskell.org/ghc/ghc/issues/2458
57 #include <crt_externs.h>
60 #if defined(__HAIKU__)
61 #include <FindDirectory.h>
68 #include "util/string.h"
73 #if !defined(SERVER) && defined(_WIN32)
74 // On Windows export some driver-specific variables to encourage Minetest to be
75 // executed on the discrete GPU in case of systems with two. Portability is fun.
77 __declspec(dllexport) DWORD NvOptimusEnablement = 1;
78 __declspec(dllexport) DWORD AmdPowerXpressRequestHighPerformance = 1;
86 Signal handler (grabs Ctrl-C on POSIX systems)
89 bool g_killed = false;
91 bool *signal_handler_killstatus()
96 #if !defined(_WIN32) // POSIX
99 void signal_handler(int sig)
103 dstream << "INFO: signal_handler(): "
104 << "Ctrl-C pressed, shutting down." << std::endl;
105 } else if (sig == SIGTERM) {
106 dstream << "INFO: signal_handler(): "
107 << "got SIGTERM, shutting down." << std::endl;
110 // Comment out for less clutter when testing scripts
111 /*dstream << "INFO: sigint_handler(): "
112 << "Printing debug stacks" << std::endl;
113 debug_stacks_print();*/
117 (void)signal(sig, SIG_DFL);
121 void signal_handler_init(void)
123 (void)signal(SIGINT, signal_handler);
124 (void)signal(SIGTERM, signal_handler);
130 BOOL WINAPI event_handler(DWORD sig)
134 case CTRL_CLOSE_EVENT:
135 case CTRL_LOGOFF_EVENT:
136 case CTRL_SHUTDOWN_EVENT:
138 dstream << "INFO: event_handler(): "
139 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
140 " shutting down." << std::endl;
143 (void)signal(SIGINT, SIG_DFL);
146 case CTRL_BREAK_EVENT:
153 void signal_handler_init(void)
155 SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
165 // Default to RUN_IN_PLACE style relative paths
166 std::string path_share = "..";
167 std::string path_user = "..";
168 std::string path_locale = path_share + DIR_DELIM + "locale";
169 std::string path_cache = path_user + DIR_DELIM + "cache";
172 std::string getDataPath(const char *subpath)
174 return path_share + DIR_DELIM + subpath;
177 void pathRemoveFile(char *path, char delim)
179 // Remove filename and path delimiter
181 for(i = strlen(path)-1; i>=0; i--)
189 bool detectMSVCBuildDir(const std::string &path)
191 const char *ends[] = {
194 "bin\\RelWithDebInfo",
199 return (!removeStringEnd(path, ends).empty());
202 std::string get_sysinfo()
206 std::ostringstream oss;
207 LPSTR filePath = new char[MAX_PATH];
209 VS_FIXEDFILEINFO *fixedFileInfo;
211 GetSystemDirectoryA(filePath, MAX_PATH);
212 PathAppendA(filePath, "kernel32.dll");
214 DWORD dwVersionSize = GetFileVersionInfoSizeA(filePath, NULL);
215 LPBYTE lpVersionInfo = new BYTE[dwVersionSize];
217 GetFileVersionInfoA(filePath, 0, dwVersionSize, lpVersionInfo);
218 VerQueryValueA(lpVersionInfo, "\\", (LPVOID *)&fixedFileInfo, &blockSize);
221 << HIWORD(fixedFileInfo->dwProductVersionMS) << '.' // Major
222 << LOWORD(fixedFileInfo->dwProductVersionMS) << '.' // Minor
223 << HIWORD(fixedFileInfo->dwProductVersionLS) << ' '; // Build
229 if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
230 oss << "x86_64"; // 32-bit app on 64-bit OS
235 delete[] lpVersionInfo;
240 struct utsname osinfo;
242 return std::string(osinfo.sysname) + "/"
243 + osinfo.release + " " + osinfo.machine;
248 bool getCurrentWorkingDir(char *buf, size_t len)
251 DWORD ret = GetCurrentDirectory(len, buf);
252 return (ret != 0) && (ret <= len);
254 return getcwd(buf, len);
259 bool getExecPathFromProcfs(char *buf, size_t buflen)
265 if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
266 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
267 (len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
280 bool getCurrentExecPath(char *buf, size_t len)
282 DWORD written = GetModuleFileNameA(NULL, buf, len);
283 if (written == 0 || written == len)
291 #elif defined(__linux__)
293 bool getCurrentExecPath(char *buf, size_t len)
295 if (!getExecPathFromProcfs(buf, len))
302 //// Mac OS X, Darwin
303 #elif defined(__APPLE__)
305 bool getCurrentExecPath(char *buf, size_t len)
307 uint32_t lenb = (uint32_t)len;
308 if (_NSGetExecutablePath(buf, &lenb) == -1)
315 //// FreeBSD, NetBSD, DragonFlyBSD
316 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
318 bool getCurrentExecPath(char *buf, size_t len)
320 // Try getting path from procfs first, since valgrind
321 // doesn't work with the latter
322 if (getExecPathFromProcfs(buf, len))
329 mib[2] = KERN_PROC_PATHNAME;
332 if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
338 #elif defined(__HAIKU__)
340 bool getCurrentExecPath(char *buf, size_t len)
342 return find_path(B_APP_IMAGE_SYMBOL, B_FIND_PATH_IMAGE_PATH, NULL, buf, len) == B_OK;
346 #elif defined(__sun) || defined(sun)
348 bool getCurrentExecPath(char *buf, size_t len)
350 const char *exec = getexecname();
354 if (strlcpy(buf, exec, len) >= len)
362 #elif defined(__hpux)
364 bool getCurrentExecPath(char *buf, size_t len)
366 struct pst_status psts;
368 if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
371 if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
380 bool getCurrentExecPath(char *buf, size_t len)
391 const char *getHomeOrFail()
393 const char *home = getenv("HOME");
394 // In rare cases the HOME environment variable may be unset
395 FATAL_ERROR_IF(!home,
396 "Required environment variable HOME is not set");
406 bool setSystemPaths()
410 // Find path of executable and set path_share relative to it
411 FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
412 "Failed to get current executable path");
413 pathRemoveFile(buf, '\\');
415 std::string exepath(buf);
418 path_share = exepath + "\\..";
419 if (detectMSVCBuildDir(exepath)) {
420 // The msvc build dir schould normaly not be present if properly installed,
421 // but its usefull for debugging.
422 path_share += DIR_DELIM "..";
425 // Use "C:\Users\<user>\AppData\Roaming\<PROJECT_NAME_C>"
426 DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
427 FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
429 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME_C;
435 #elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
437 bool setSystemPaths()
441 if (!getCurrentExecPath(buf, sizeof(buf))) {
443 errorstream << "Unable to read bindir "<< std::endl;
445 FATAL_ERROR("Unable to read bindir");
450 pathRemoveFile(buf, '/');
451 std::string bindir(buf);
453 // Find share directory from these.
454 // It is identified by containing the subdirectory "builtin".
455 std::list<std::string> trylist;
456 std::string static_sharedir = STATIC_SHAREDIR;
457 if (!static_sharedir.empty() && static_sharedir != ".")
458 trylist.push_back(static_sharedir);
460 trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
461 DIR_DELIM + PROJECT_NAME);
462 trylist.push_back(bindir + DIR_DELIM "..");
465 trylist.push_back(path_user);
468 for (std::list<std::string>::const_iterator
469 i = trylist.begin(); i != trylist.end(); ++i) {
470 const std::string &trypath = *i;
471 if (!fs::PathExists(trypath) ||
472 !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
473 warningstream << "system-wide share not found at \""
474 << trypath << "\""<< std::endl;
478 // Warn if was not the first alternative
479 if (i != trylist.begin()) {
480 warningstream << "system-wide share found at \""
481 << trypath << "\"" << std::endl;
484 path_share = trypath;
489 path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
498 #elif defined(__APPLE__)
500 bool setSystemPaths()
502 CFBundleRef main_bundle = CFBundleGetMainBundle();
503 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
505 if (CFURLGetFileSystemRepresentation(resources_url,
506 TRUE, (UInt8 *)path, PATH_MAX)) {
507 path_share = std::string(path);
509 warningstream << "Could not determine bundle resource path" << std::endl;
511 CFRelease(resources_url);
513 path_user = std::string(getHomeOrFail())
514 + "/Library/Application Support/"
522 bool setSystemPaths()
524 path_share = STATIC_SHAREDIR;
525 path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
526 + lowercase(PROJECT_NAME);
533 void migrateCachePath()
535 const std::string local_cache_path = path_user + DIR_DELIM + "cache";
537 // Delete tmp folder if it exists (it only ever contained
538 // a temporary ogg file, which is no longer used).
539 if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
540 fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
542 // Bail if migration impossible
543 if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
544 || fs::PathExists(path_cache)) {
547 if (!fs::Rename(local_cache_path, path_cache)) {
548 errorstream << "Failed to migrate local cache path "
549 "to system path!" << std::endl;
553 void initializePaths()
558 infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
561 getCurrentExecPath(buf, sizeof(buf)) ||
562 getExecPathFromProcfs(buf, sizeof(buf));
565 pathRemoveFile(buf, DIR_DELIM_CHAR);
566 std::string execpath(buf);
568 path_share = execpath + DIR_DELIM "..";
569 path_user = execpath + DIR_DELIM "..";
571 if (detectMSVCBuildDir(execpath)) {
572 path_share += DIR_DELIM "..";
573 path_user += DIR_DELIM "..";
576 errorstream << "Failed to get paths by executable location, "
577 "trying cwd" << std::endl;
579 if (!getCurrentWorkingDir(buf, sizeof(buf)))
580 FATAL_ERROR("Ran out of methods to get paths");
582 size_t cwdlen = strlen(buf);
583 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
588 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
589 pathRemoveFile(buf, DIR_DELIM_CHAR);
591 std::string execpath(buf);
593 path_share = execpath;
594 path_user = execpath;
596 path_cache = path_user + DIR_DELIM + "cache";
598 infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
600 if (!setSystemPaths())
601 errorstream << "Failed to get one or more system-wide path" << std::endl;
605 path_cache = path_user + DIR_DELIM + "cache";
607 // Initialize path_cache
608 // First try $XDG_CACHE_HOME/PROJECT_NAME
609 const char *cache_dir = getenv("XDG_CACHE_HOME");
610 const char *home_dir = getenv("HOME");
611 if (cache_dir && cache_dir[0] != '\0') {
612 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
613 } else if (home_dir) {
614 // Then try $HOME/.cache/PROJECT_NAME
615 path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
616 + DIR_DELIM + PROJECT_NAME;
618 // If neither works, use $PATH_USER/cache
619 path_cache = path_user + DIR_DELIM + "cache";
621 // Migrate cache folder to new location if possible
624 #endif // RUN_IN_PLACE
626 infostream << "Detected share path: " << path_share << std::endl;
627 infostream << "Detected user path: " << path_user << std::endl;
628 infostream << "Detected cache path: " << path_cache << std::endl;
631 bool found_localedir = false;
632 # ifdef STATIC_LOCALEDIR
633 /* STATIC_LOCALEDIR may be a generalized path such as /usr/share/locale that
634 * doesn't necessarily contain our locale files, so check data path first. */
635 path_locale = getDataPath("locale");
636 if (fs::PathExists(path_locale)) {
637 found_localedir = true;
638 infostream << "Using in-place locale directory " << path_locale
639 << " even though a static one was provided." << std::endl;
640 } else if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
641 found_localedir = true;
642 path_locale = STATIC_LOCALEDIR;
643 infostream << "Using static locale directory " << STATIC_LOCALEDIR
647 path_locale = getDataPath("locale");
648 if (fs::PathExists(path_locale)) {
649 found_localedir = true;
652 if (!found_localedir) {
653 warningstream << "Couldn't find a locale directory!" << std::endl;
655 #endif // USE_GETTEXT
659 //// OS-specific Secure Random
664 bool secure_rand_fill_buf(void *buf, size_t len)
668 if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
671 CryptGenRandom(wctx, len, (BYTE *)buf);
672 CryptReleaseContext(wctx, 0);
678 bool secure_rand_fill_buf(void *buf, size_t len)
680 // N.B. This function checks *only* for /dev/urandom, because on most
681 // common OSes it is non-blocking, whereas /dev/random is blocking, and it
682 // is exceptionally uncommon for there to be a situation where /dev/random
683 // exists but /dev/urandom does not. This guesswork is necessary since
684 // random devices are not covered by any POSIX standard...
685 FILE *fp = fopen("/dev/urandom", "rb");
689 bool success = fread(buf, len, 1, fp) == 1;
697 void attachOrCreateConsole()
700 static bool consoleAllocated = false;
701 const bool redirected = (_fileno(stdout) == -2 || _fileno(stdout) == -1); // If output is redirected to e.g a file
702 if (!consoleAllocated && redirected && (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())) {
703 freopen("CONOUT$", "w", stdout);
704 freopen("CONOUT$", "w", stderr);
705 consoleAllocated = true;
710 int mt_snprintf(char *buf, const size_t buf_size, const char *fmt, ...)
712 // https://msdn.microsoft.com/en-us/library/bt7tawza.aspx
713 // Many of the MSVC / Windows printf-style functions do not support positional
714 // arguments (eg. "%1$s"). We just forward the call to vsnprintf for sane
715 // platforms, but defer to _vsprintf_p on MSVC / Windows.
716 // https://github.com/FFmpeg/FFmpeg/blob/5ae9fa13f5ac640bec113120d540f70971aa635d/compat/msvcrt/snprintf.c#L46
717 // _vsprintf_p has to be shimmed with _vscprintf_p on -1 (for an example see
718 // above FFmpeg link).
722 int c = vsnprintf(buf, buf_size, fmt, args);
724 int c = _vsprintf_p(buf, buf_size, fmt, args);
726 c = _vscprintf_p(fmt, args);
732 static bool open_uri(const std::string &uri)
734 if (uri.find_first_of("\r\n") != std::string::npos) {
735 errorstream << "Unable to open URI as it is invalid, contains new line: " << uri << std::endl;
740 return (intptr_t)ShellExecuteA(NULL, NULL, uri.c_str(), NULL, NULL, SW_SHOWNORMAL) > 32;
741 #elif defined(__ANDROID__)
744 #elif defined(__APPLE__)
745 const char *argv[] = {"open", uri.c_str(), NULL};
746 return posix_spawnp(NULL, "open", NULL, NULL, (char**)argv,
747 (*_NSGetEnviron())) == 0;
749 const char *argv[] = {"xdg-open", uri.c_str(), NULL};
750 return posix_spawnp(NULL, "xdg-open", NULL, NULL, (char**)argv, environ) == 0;
754 bool open_url(const std::string &url)
756 if (url.substr(0, 7) != "http://" && url.substr(0, 8) != "https://") {
757 errorstream << "Unable to open browser as URL is missing schema: " << url << std::endl;
761 return open_uri(url);
764 bool open_directory(const std::string &path)
766 if (!fs::IsDir(path)) {
767 errorstream << "Unable to open directory as it does not exist: " << path << std::endl;
771 return open_uri(path);
774 // Load performance counter frequency only once at startup
777 inline double get_perf_freq()
779 // Also use this opportunity to enable high-res timers
783 QueryPerformanceFrequency(&freq);
784 return freq.QuadPart;
787 double perf_freq = get_perf_freq();
791 } //namespace porting