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__)
29 #include <sys/types.h>
30 #include <sys/sysctl.h>
40 #include <sys/utsname.h>
41 #if !defined(__ANDROID__)
47 #include <sys/pstat.h>
49 #if defined(__ANDROID__)
50 #include "porting_android.h"
52 #if defined(__APPLE__)
53 // For _NSGetEnviron()
54 // Related: https://gitlab.haskell.org/ghc/ghc/issues/2458
55 #include <crt_externs.h>
62 #include "util/string.h"
71 Signal handler (grabs Ctrl-C on POSIX systems)
74 bool g_killed = false;
76 bool *signal_handler_killstatus()
81 #if !defined(_WIN32) // POSIX
84 void signal_handler(int sig)
88 dstream << "INFO: signal_handler(): "
89 << "Ctrl-C pressed, shutting down." << std::endl;
90 } else if (sig == SIGTERM) {
91 dstream << "INFO: signal_handler(): "
92 << "got SIGTERM, shutting down." << std::endl;
95 // Comment out for less clutter when testing scripts
96 /*dstream << "INFO: sigint_handler(): "
97 << "Printing debug stacks" << std::endl;
98 debug_stacks_print();*/
102 (void)signal(sig, SIG_DFL);
106 void signal_handler_init(void)
108 (void)signal(SIGINT, signal_handler);
109 (void)signal(SIGTERM, signal_handler);
115 BOOL WINAPI event_handler(DWORD sig)
119 case CTRL_CLOSE_EVENT:
120 case CTRL_LOGOFF_EVENT:
121 case CTRL_SHUTDOWN_EVENT:
123 dstream << "INFO: event_handler(): "
124 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
125 " shutting down." << std::endl;
128 (void)signal(SIGINT, SIG_DFL);
131 case CTRL_BREAK_EVENT:
138 void signal_handler_init(void)
140 SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
150 // Default to RUN_IN_PLACE style relative paths
151 std::string path_share = "..";
152 std::string path_user = "..";
153 std::string path_locale = path_share + DIR_DELIM + "locale";
154 std::string path_cache = path_user + DIR_DELIM + "cache";
157 std::string getDataPath(const char *subpath)
159 return path_share + DIR_DELIM + subpath;
162 void pathRemoveFile(char *path, char delim)
164 // Remove filename and path delimiter
166 for(i = strlen(path)-1; i>=0; i--)
174 bool detectMSVCBuildDir(const std::string &path)
176 const char *ends[] = {
179 "bin\\RelWithDebInfo",
184 return (!removeStringEnd(path, ends).empty());
187 std::string get_sysinfo()
191 std::ostringstream oss;
192 LPSTR filePath = new char[MAX_PATH];
194 VS_FIXEDFILEINFO *fixedFileInfo;
196 GetSystemDirectoryA(filePath, MAX_PATH);
197 PathAppendA(filePath, "kernel32.dll");
199 DWORD dwVersionSize = GetFileVersionInfoSizeA(filePath, NULL);
200 LPBYTE lpVersionInfo = new BYTE[dwVersionSize];
202 GetFileVersionInfoA(filePath, 0, dwVersionSize, lpVersionInfo);
203 VerQueryValueA(lpVersionInfo, "\\", (LPVOID *)&fixedFileInfo, &blockSize);
206 << HIWORD(fixedFileInfo->dwProductVersionMS) << '.' // Major
207 << LOWORD(fixedFileInfo->dwProductVersionMS) << '.' // Minor
208 << HIWORD(fixedFileInfo->dwProductVersionLS) << ' '; // Build
214 if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
215 oss << "x86_64"; // 32-bit app on 64-bit OS
220 delete[] lpVersionInfo;
225 struct utsname osinfo;
227 return std::string(osinfo.sysname) + "/"
228 + osinfo.release + " " + osinfo.machine;
233 bool getCurrentWorkingDir(char *buf, size_t len)
236 DWORD ret = GetCurrentDirectory(len, buf);
237 return (ret != 0) && (ret <= len);
239 return getcwd(buf, len);
244 bool getExecPathFromProcfs(char *buf, size_t buflen)
250 if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
251 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
252 (len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
265 bool getCurrentExecPath(char *buf, size_t len)
267 DWORD written = GetModuleFileNameA(NULL, buf, len);
268 if (written == 0 || written == len)
276 #elif defined(__linux__)
278 bool getCurrentExecPath(char *buf, size_t len)
280 if (!getExecPathFromProcfs(buf, len))
287 //// Mac OS X, Darwin
288 #elif defined(__APPLE__)
290 bool getCurrentExecPath(char *buf, size_t len)
292 uint32_t lenb = (uint32_t)len;
293 if (_NSGetExecutablePath(buf, &lenb) == -1)
300 //// FreeBSD, NetBSD, DragonFlyBSD
301 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
303 bool getCurrentExecPath(char *buf, size_t len)
305 // Try getting path from procfs first, since valgrind
306 // doesn't work with the latter
307 if (getExecPathFromProcfs(buf, len))
314 mib[2] = KERN_PROC_PATHNAME;
317 if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
325 #elif defined(__sun) || defined(sun)
327 bool getCurrentExecPath(char *buf, size_t len)
329 const char *exec = getexecname();
333 if (strlcpy(buf, exec, len) >= len)
341 #elif defined(__hpux)
343 bool getCurrentExecPath(char *buf, size_t len)
345 struct pst_status psts;
347 if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
350 if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
359 bool getCurrentExecPath(char *buf, size_t len)
370 const char *getHomeOrFail()
372 const char *home = getenv("HOME");
373 // In rare cases the HOME environment variable may be unset
374 FATAL_ERROR_IF(!home,
375 "Required environment variable HOME is not set");
385 bool setSystemPaths()
389 // Find path of executable and set path_share relative to it
390 FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
391 "Failed to get current executable path");
392 pathRemoveFile(buf, '\\');
394 std::string exepath(buf);
397 path_share = exepath + "\\..";
398 if (detectMSVCBuildDir(exepath)) {
399 // The msvc build dir schould normaly not be present if properly installed,
400 // but its usefull for debugging.
401 path_share += DIR_DELIM "..";
404 // Use "C:\Users\<user>\AppData\Roaming\<PROJECT_NAME_C>"
405 DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
406 FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
408 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME_C;
414 #elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
416 bool setSystemPaths()
420 if (!getCurrentExecPath(buf, sizeof(buf))) {
422 errorstream << "Unable to read bindir "<< std::endl;
424 FATAL_ERROR("Unable to read bindir");
429 pathRemoveFile(buf, '/');
430 std::string bindir(buf);
432 // Find share directory from these.
433 // It is identified by containing the subdirectory "builtin".
434 std::list<std::string> trylist;
435 std::string static_sharedir = STATIC_SHAREDIR;
436 if (!static_sharedir.empty() && static_sharedir != ".")
437 trylist.push_back(static_sharedir);
439 trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
440 DIR_DELIM + PROJECT_NAME);
441 trylist.push_back(bindir + DIR_DELIM "..");
444 trylist.push_back(path_user);
447 for (std::list<std::string>::const_iterator
448 i = trylist.begin(); i != trylist.end(); ++i) {
449 const std::string &trypath = *i;
450 if (!fs::PathExists(trypath) ||
451 !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
452 warningstream << "system-wide share not found at \""
453 << trypath << "\""<< std::endl;
457 // Warn if was not the first alternative
458 if (i != trylist.begin()) {
459 warningstream << "system-wide share found at \""
460 << trypath << "\"" << std::endl;
463 path_share = trypath;
468 path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
477 #elif defined(__APPLE__)
479 bool setSystemPaths()
481 CFBundleRef main_bundle = CFBundleGetMainBundle();
482 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
484 if (CFURLGetFileSystemRepresentation(resources_url,
485 TRUE, (UInt8 *)path, PATH_MAX)) {
486 path_share = std::string(path);
488 warningstream << "Could not determine bundle resource path" << std::endl;
490 CFRelease(resources_url);
492 path_user = std::string(getHomeOrFail())
493 + "/Library/Application Support/"
501 bool setSystemPaths()
503 path_share = STATIC_SHAREDIR;
504 path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
505 + lowercase(PROJECT_NAME);
512 void migrateCachePath()
514 const std::string local_cache_path = path_user + DIR_DELIM + "cache";
516 // Delete tmp folder if it exists (it only ever contained
517 // a temporary ogg file, which is no longer used).
518 if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
519 fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
521 // Bail if migration impossible
522 if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
523 || fs::PathExists(path_cache)) {
526 if (!fs::Rename(local_cache_path, path_cache)) {
527 errorstream << "Failed to migrate local cache path "
528 "to system path!" << std::endl;
532 void initializePaths()
537 infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
540 getCurrentExecPath(buf, sizeof(buf)) ||
541 getExecPathFromProcfs(buf, sizeof(buf));
544 pathRemoveFile(buf, DIR_DELIM_CHAR);
545 std::string execpath(buf);
547 path_share = execpath + DIR_DELIM "..";
548 path_user = execpath + DIR_DELIM "..";
550 if (detectMSVCBuildDir(execpath)) {
551 path_share += DIR_DELIM "..";
552 path_user += DIR_DELIM "..";
555 errorstream << "Failed to get paths by executable location, "
556 "trying cwd" << std::endl;
558 if (!getCurrentWorkingDir(buf, sizeof(buf)))
559 FATAL_ERROR("Ran out of methods to get paths");
561 size_t cwdlen = strlen(buf);
562 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
567 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
568 pathRemoveFile(buf, DIR_DELIM_CHAR);
570 std::string execpath(buf);
572 path_share = execpath;
573 path_user = execpath;
575 path_cache = path_user + DIR_DELIM + "cache";
577 infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
579 if (!setSystemPaths())
580 errorstream << "Failed to get one or more system-wide path" << std::endl;
584 path_cache = path_user + DIR_DELIM + "cache";
586 // Initialize path_cache
587 // First try $XDG_CACHE_HOME/PROJECT_NAME
588 const char *cache_dir = getenv("XDG_CACHE_HOME");
589 const char *home_dir = getenv("HOME");
591 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
592 } else if (home_dir) {
593 // Then try $HOME/.cache/PROJECT_NAME
594 path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
595 + DIR_DELIM + PROJECT_NAME;
597 // If neither works, use $PATH_USER/cache
598 path_cache = path_user + DIR_DELIM + "cache";
600 // Migrate cache folder to new location if possible
603 #endif // RUN_IN_PLACE
605 infostream << "Detected share path: " << path_share << std::endl;
606 infostream << "Detected user path: " << path_user << std::endl;
607 infostream << "Detected cache path: " << path_cache << std::endl;
610 bool found_localedir = false;
611 # ifdef STATIC_LOCALEDIR
612 /* STATIC_LOCALEDIR may be a generalized path such as /usr/share/locale that
613 * doesn't necessarily contain our locale files, so check data path first. */
614 path_locale = getDataPath("locale");
615 if (fs::PathExists(path_locale)) {
616 found_localedir = true;
617 infostream << "Using in-place locale directory " << path_locale
618 << " even though a static one was provided." << std::endl;
619 } else if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
620 found_localedir = true;
621 path_locale = STATIC_LOCALEDIR;
622 infostream << "Using static locale directory " << STATIC_LOCALEDIR
626 path_locale = getDataPath("locale");
627 if (fs::PathExists(path_locale)) {
628 found_localedir = true;
631 if (!found_localedir) {
632 warningstream << "Couldn't find a locale directory!" << std::endl;
634 #endif // USE_GETTEXT
638 //// OS-specific Secure Random
643 bool secure_rand_fill_buf(void *buf, size_t len)
647 if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
650 CryptGenRandom(wctx, len, (BYTE *)buf);
651 CryptReleaseContext(wctx, 0);
657 bool secure_rand_fill_buf(void *buf, size_t len)
659 // N.B. This function checks *only* for /dev/urandom, because on most
660 // common OSes it is non-blocking, whereas /dev/random is blocking, and it
661 // is exceptionally uncommon for there to be a situation where /dev/random
662 // exists but /dev/urandom does not. This guesswork is necessary since
663 // random devices are not covered by any POSIX standard...
664 FILE *fp = fopen("/dev/urandom", "rb");
668 bool success = fread(buf, len, 1, fp) == 1;
676 void attachOrCreateConsole()
679 static bool consoleAllocated = false;
680 const bool redirected = (_fileno(stdout) == -2 || _fileno(stdout) == -1); // If output is redirected to e.g a file
681 if (!consoleAllocated && redirected && (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())) {
682 freopen("CONOUT$", "w", stdout);
683 freopen("CONOUT$", "w", stderr);
684 consoleAllocated = true;
689 int mt_snprintf(char *buf, const size_t buf_size, const char *fmt, ...)
691 // https://msdn.microsoft.com/en-us/library/bt7tawza.aspx
692 // Many of the MSVC / Windows printf-style functions do not support positional
693 // arguments (eg. "%1$s"). We just forward the call to vsnprintf for sane
694 // platforms, but defer to _vsprintf_p on MSVC / Windows.
695 // https://github.com/FFmpeg/FFmpeg/blob/5ae9fa13f5ac640bec113120d540f70971aa635d/compat/msvcrt/snprintf.c#L46
696 // _vsprintf_p has to be shimmed with _vscprintf_p on -1 (for an example see
697 // above FFmpeg link).
701 int c = vsnprintf(buf, buf_size, fmt, args);
703 int c = _vsprintf_p(buf, buf_size, fmt, args);
705 c = _vscprintf_p(fmt, args);
711 bool openURL(const std::string &url)
713 if ((url.substr(0, 7) != "http://" && url.substr(0, 8) != "https://") ||
714 url.find_first_of("\r\n") != std::string::npos) {
715 errorstream << "Invalid url: " << url << std::endl;
720 return (intptr_t)ShellExecuteA(NULL, NULL, url.c_str(), NULL, NULL, SW_SHOWNORMAL) > 32;
721 #elif defined(__ANDROID__)
724 #elif defined(__APPLE__)
725 const char *argv[] = {"open", url.c_str(), NULL};
726 return posix_spawnp(NULL, "open", NULL, NULL, (char**)argv,
727 (*_NSGetEnviron())) == 0;
729 const char *argv[] = {"xdg-open", url.c_str(), NULL};
730 return posix_spawnp(NULL, "xdg-open", NULL, NULL, (char**)argv, environ) == 0;
734 // Load performance counter frequency only once at startup
737 inline double get_perf_freq()
740 QueryPerformanceFrequency(&freq);
741 return freq.QuadPart;
744 double perf_freq = get_perf_freq();
748 } //namespace porting