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"
77 Signal handler (grabs Ctrl-C on POSIX systems)
80 bool g_killed = false;
82 bool *signal_handler_killstatus()
87 #if !defined(_WIN32) // POSIX
90 void signal_handler(int sig)
94 dstream << "INFO: signal_handler(): "
95 << "Ctrl-C pressed, shutting down." << std::endl;
96 } else if (sig == SIGTERM) {
97 dstream << "INFO: signal_handler(): "
98 << "got SIGTERM, shutting down." << std::endl;
101 // Comment out for less clutter when testing scripts
102 /*dstream << "INFO: sigint_handler(): "
103 << "Printing debug stacks" << std::endl;
104 debug_stacks_print();*/
108 (void)signal(sig, SIG_DFL);
112 void signal_handler_init(void)
114 (void)signal(SIGINT, signal_handler);
115 (void)signal(SIGTERM, signal_handler);
121 BOOL WINAPI event_handler(DWORD sig)
125 case CTRL_CLOSE_EVENT:
126 case CTRL_LOGOFF_EVENT:
127 case CTRL_SHUTDOWN_EVENT:
129 dstream << "INFO: event_handler(): "
130 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
131 " shutting down." << std::endl;
134 (void)signal(SIGINT, SIG_DFL);
137 case CTRL_BREAK_EVENT:
144 void signal_handler_init(void)
146 SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
156 // Default to RUN_IN_PLACE style relative paths
157 std::string path_share = "..";
158 std::string path_user = "..";
159 std::string path_locale = path_share + DIR_DELIM + "locale";
160 std::string path_cache = path_user + DIR_DELIM + "cache";
163 std::string getDataPath(const char *subpath)
165 return path_share + DIR_DELIM + subpath;
168 void pathRemoveFile(char *path, char delim)
170 // Remove filename and path delimiter
172 for(i = strlen(path)-1; i>=0; i--)
180 bool detectMSVCBuildDir(const std::string &path)
182 const char *ends[] = {
185 "bin\\RelWithDebInfo",
190 return (!removeStringEnd(path, ends).empty());
193 std::string get_sysinfo()
197 std::ostringstream oss;
198 LPSTR filePath = new char[MAX_PATH];
200 VS_FIXEDFILEINFO *fixedFileInfo;
202 GetSystemDirectoryA(filePath, MAX_PATH);
203 PathAppendA(filePath, "kernel32.dll");
205 DWORD dwVersionSize = GetFileVersionInfoSizeA(filePath, NULL);
206 LPBYTE lpVersionInfo = new BYTE[dwVersionSize];
208 GetFileVersionInfoA(filePath, 0, dwVersionSize, lpVersionInfo);
209 VerQueryValueA(lpVersionInfo, "\\", (LPVOID *)&fixedFileInfo, &blockSize);
212 << HIWORD(fixedFileInfo->dwProductVersionMS) << '.' // Major
213 << LOWORD(fixedFileInfo->dwProductVersionMS) << '.' // Minor
214 << HIWORD(fixedFileInfo->dwProductVersionLS) << ' '; // Build
220 if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
221 oss << "x86_64"; // 32-bit app on 64-bit OS
226 delete[] lpVersionInfo;
231 struct utsname osinfo;
233 return std::string(osinfo.sysname) + "/"
234 + osinfo.release + " " + osinfo.machine;
239 bool getCurrentWorkingDir(char *buf, size_t len)
242 DWORD ret = GetCurrentDirectory(len, buf);
243 return (ret != 0) && (ret <= len);
245 return getcwd(buf, len);
250 bool getExecPathFromProcfs(char *buf, size_t buflen)
256 if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
257 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
258 (len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
271 bool getCurrentExecPath(char *buf, size_t len)
273 DWORD written = GetModuleFileNameA(NULL, buf, len);
274 if (written == 0 || written == len)
282 #elif defined(__linux__)
284 bool getCurrentExecPath(char *buf, size_t len)
286 if (!getExecPathFromProcfs(buf, len))
293 //// Mac OS X, Darwin
294 #elif defined(__APPLE__)
296 bool getCurrentExecPath(char *buf, size_t len)
298 uint32_t lenb = (uint32_t)len;
299 if (_NSGetExecutablePath(buf, &lenb) == -1)
306 //// FreeBSD, NetBSD, DragonFlyBSD
307 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
309 bool getCurrentExecPath(char *buf, size_t len)
311 // Try getting path from procfs first, since valgrind
312 // doesn't work with the latter
313 if (getExecPathFromProcfs(buf, len))
320 mib[2] = KERN_PROC_PATHNAME;
323 if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
329 #elif defined(__HAIKU__)
331 bool getCurrentExecPath(char *buf, size_t len)
333 return find_path(B_APP_IMAGE_SYMBOL, B_FIND_PATH_IMAGE_PATH, NULL, buf, len) == B_OK;
337 #elif defined(__sun) || defined(sun)
339 bool getCurrentExecPath(char *buf, size_t len)
341 const char *exec = getexecname();
345 if (strlcpy(buf, exec, len) >= len)
353 #elif defined(__hpux)
355 bool getCurrentExecPath(char *buf, size_t len)
357 struct pst_status psts;
359 if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
362 if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
371 bool getCurrentExecPath(char *buf, size_t len)
382 const char *getHomeOrFail()
384 const char *home = getenv("HOME");
385 // In rare cases the HOME environment variable may be unset
386 FATAL_ERROR_IF(!home,
387 "Required environment variable HOME is not set");
397 bool setSystemPaths()
401 // Find path of executable and set path_share relative to it
402 FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
403 "Failed to get current executable path");
404 pathRemoveFile(buf, '\\');
406 std::string exepath(buf);
409 path_share = exepath + "\\..";
410 if (detectMSVCBuildDir(exepath)) {
411 // The msvc build dir schould normaly not be present if properly installed,
412 // but its usefull for debugging.
413 path_share += DIR_DELIM "..";
416 // Use "C:\Users\<user>\AppData\Roaming\<PROJECT_NAME_C>"
417 DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
418 FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
420 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME_C;
426 #elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
428 bool setSystemPaths()
432 if (!getCurrentExecPath(buf, sizeof(buf))) {
434 errorstream << "Unable to read bindir "<< std::endl;
436 FATAL_ERROR("Unable to read bindir");
441 pathRemoveFile(buf, '/');
442 std::string bindir(buf);
444 // Find share directory from these.
445 // It is identified by containing the subdirectory "builtin".
446 std::list<std::string> trylist;
447 std::string static_sharedir = STATIC_SHAREDIR;
448 if (!static_sharedir.empty() && static_sharedir != ".")
449 trylist.push_back(static_sharedir);
451 trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
452 DIR_DELIM + PROJECT_NAME);
453 trylist.push_back(bindir + DIR_DELIM "..");
456 trylist.push_back(path_user);
459 for (std::list<std::string>::const_iterator
460 i = trylist.begin(); i != trylist.end(); ++i) {
461 const std::string &trypath = *i;
462 if (!fs::PathExists(trypath) ||
463 !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
464 warningstream << "system-wide share not found at \""
465 << trypath << "\""<< std::endl;
469 // Warn if was not the first alternative
470 if (i != trylist.begin()) {
471 warningstream << "system-wide share found at \""
472 << trypath << "\"" << std::endl;
475 path_share = trypath;
480 path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
489 #elif defined(__APPLE__)
491 bool setSystemPaths()
493 CFBundleRef main_bundle = CFBundleGetMainBundle();
494 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
496 if (CFURLGetFileSystemRepresentation(resources_url,
497 TRUE, (UInt8 *)path, PATH_MAX)) {
498 path_share = std::string(path);
500 warningstream << "Could not determine bundle resource path" << std::endl;
502 CFRelease(resources_url);
504 path_user = std::string(getHomeOrFail())
505 + "/Library/Application Support/"
513 bool setSystemPaths()
515 path_share = STATIC_SHAREDIR;
516 path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
517 + lowercase(PROJECT_NAME);
524 void migrateCachePath()
526 const std::string local_cache_path = path_user + DIR_DELIM + "cache";
528 // Delete tmp folder if it exists (it only ever contained
529 // a temporary ogg file, which is no longer used).
530 if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
531 fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
533 // Bail if migration impossible
534 if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
535 || fs::PathExists(path_cache)) {
538 if (!fs::Rename(local_cache_path, path_cache)) {
539 errorstream << "Failed to migrate local cache path "
540 "to system path!" << std::endl;
544 void initializePaths()
549 infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
552 getCurrentExecPath(buf, sizeof(buf)) ||
553 getExecPathFromProcfs(buf, sizeof(buf));
556 pathRemoveFile(buf, DIR_DELIM_CHAR);
557 std::string execpath(buf);
559 path_share = execpath + DIR_DELIM "..";
560 path_user = execpath + DIR_DELIM "..";
562 if (detectMSVCBuildDir(execpath)) {
563 path_share += DIR_DELIM "..";
564 path_user += DIR_DELIM "..";
567 errorstream << "Failed to get paths by executable location, "
568 "trying cwd" << std::endl;
570 if (!getCurrentWorkingDir(buf, sizeof(buf)))
571 FATAL_ERROR("Ran out of methods to get paths");
573 size_t cwdlen = strlen(buf);
574 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
579 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
580 pathRemoveFile(buf, DIR_DELIM_CHAR);
582 std::string execpath(buf);
584 path_share = execpath;
585 path_user = execpath;
587 path_cache = path_user + DIR_DELIM + "cache";
589 infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
591 if (!setSystemPaths())
592 errorstream << "Failed to get one or more system-wide path" << std::endl;
596 path_cache = path_user + DIR_DELIM + "cache";
598 // Initialize path_cache
599 // First try $XDG_CACHE_HOME/PROJECT_NAME
600 const char *cache_dir = getenv("XDG_CACHE_HOME");
601 const char *home_dir = getenv("HOME");
603 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
604 } else if (home_dir) {
605 // Then try $HOME/.cache/PROJECT_NAME
606 path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
607 + DIR_DELIM + PROJECT_NAME;
609 // If neither works, use $PATH_USER/cache
610 path_cache = path_user + DIR_DELIM + "cache";
612 // Migrate cache folder to new location if possible
615 #endif // RUN_IN_PLACE
617 infostream << "Detected share path: " << path_share << std::endl;
618 infostream << "Detected user path: " << path_user << std::endl;
619 infostream << "Detected cache path: " << path_cache << std::endl;
622 bool found_localedir = false;
623 # ifdef STATIC_LOCALEDIR
624 /* STATIC_LOCALEDIR may be a generalized path such as /usr/share/locale that
625 * doesn't necessarily contain our locale files, so check data path first. */
626 path_locale = getDataPath("locale");
627 if (fs::PathExists(path_locale)) {
628 found_localedir = true;
629 infostream << "Using in-place locale directory " << path_locale
630 << " even though a static one was provided." << std::endl;
631 } else if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
632 found_localedir = true;
633 path_locale = STATIC_LOCALEDIR;
634 infostream << "Using static locale directory " << STATIC_LOCALEDIR
638 path_locale = getDataPath("locale");
639 if (fs::PathExists(path_locale)) {
640 found_localedir = true;
643 if (!found_localedir) {
644 warningstream << "Couldn't find a locale directory!" << std::endl;
646 #endif // USE_GETTEXT
650 //// OS-specific Secure Random
655 bool secure_rand_fill_buf(void *buf, size_t len)
659 if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
662 CryptGenRandom(wctx, len, (BYTE *)buf);
663 CryptReleaseContext(wctx, 0);
669 bool secure_rand_fill_buf(void *buf, size_t len)
671 // N.B. This function checks *only* for /dev/urandom, because on most
672 // common OSes it is non-blocking, whereas /dev/random is blocking, and it
673 // is exceptionally uncommon for there to be a situation where /dev/random
674 // exists but /dev/urandom does not. This guesswork is necessary since
675 // random devices are not covered by any POSIX standard...
676 FILE *fp = fopen("/dev/urandom", "rb");
680 bool success = fread(buf, len, 1, fp) == 1;
688 void attachOrCreateConsole()
691 static bool consoleAllocated = false;
692 const bool redirected = (_fileno(stdout) == -2 || _fileno(stdout) == -1); // If output is redirected to e.g a file
693 if (!consoleAllocated && redirected && (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())) {
694 freopen("CONOUT$", "w", stdout);
695 freopen("CONOUT$", "w", stderr);
696 consoleAllocated = true;
701 int mt_snprintf(char *buf, const size_t buf_size, const char *fmt, ...)
703 // https://msdn.microsoft.com/en-us/library/bt7tawza.aspx
704 // Many of the MSVC / Windows printf-style functions do not support positional
705 // arguments (eg. "%1$s"). We just forward the call to vsnprintf for sane
706 // platforms, but defer to _vsprintf_p on MSVC / Windows.
707 // https://github.com/FFmpeg/FFmpeg/blob/5ae9fa13f5ac640bec113120d540f70971aa635d/compat/msvcrt/snprintf.c#L46
708 // _vsprintf_p has to be shimmed with _vscprintf_p on -1 (for an example see
709 // above FFmpeg link).
713 int c = vsnprintf(buf, buf_size, fmt, args);
715 int c = _vsprintf_p(buf, buf_size, fmt, args);
717 c = _vscprintf_p(fmt, args);
723 static bool open_uri(const std::string &uri)
725 if (uri.find_first_of("\r\n") != std::string::npos) {
726 errorstream << "Unable to open URI as it is invalid, contains new line: " << uri << std::endl;
731 return (intptr_t)ShellExecuteA(NULL, NULL, uri.c_str(), NULL, NULL, SW_SHOWNORMAL) > 32;
732 #elif defined(__ANDROID__)
735 #elif defined(__APPLE__)
736 const char *argv[] = {"open", uri.c_str(), NULL};
737 return posix_spawnp(NULL, "open", NULL, NULL, (char**)argv,
738 (*_NSGetEnviron())) == 0;
740 const char *argv[] = {"xdg-open", uri.c_str(), NULL};
741 return posix_spawnp(NULL, "xdg-open", NULL, NULL, (char**)argv, environ) == 0;
745 bool open_url(const std::string &url)
747 if (url.substr(0, 7) != "http://" && url.substr(0, 8) != "https://") {
748 errorstream << "Unable to open browser as URL is missing schema: " << url << std::endl;
752 return open_uri(url);
755 bool open_directory(const std::string &path)
757 if (!fs::IsDir(path)) {
758 errorstream << "Unable to open directory as it does not exist: " << path << std::endl;
762 return open_uri(path);
765 // Load performance counter frequency only once at startup
768 inline double get_perf_freq()
770 // Also use this opportunity to enable high-res timers
774 QueryPerformanceFrequency(&freq);
775 return freq.QuadPart;
778 double perf_freq = get_perf_freq();
782 } //namespace porting