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>
31 extern char **environ;
41 #include <sys/utsname.h>
42 #if !defined(__ANDROID__)
48 #include <sys/pstat.h>
50 #if defined(__ANDROID__)
51 #include "porting_android.h"
53 #if defined(__APPLE__)
54 // For _NSGetEnviron()
55 // Related: https://gitlab.haskell.org/ghc/ghc/issues/2458
56 #include <crt_externs.h>
63 #include "util/string.h"
72 Signal handler (grabs Ctrl-C on POSIX systems)
75 bool g_killed = false;
77 bool *signal_handler_killstatus()
82 #if !defined(_WIN32) // POSIX
85 void signal_handler(int sig)
89 dstream << "INFO: signal_handler(): "
90 << "Ctrl-C pressed, shutting down." << std::endl;
91 } else if (sig == SIGTERM) {
92 dstream << "INFO: signal_handler(): "
93 << "got SIGTERM, shutting down." << std::endl;
96 // Comment out for less clutter when testing scripts
97 /*dstream << "INFO: sigint_handler(): "
98 << "Printing debug stacks" << std::endl;
99 debug_stacks_print();*/
103 (void)signal(sig, SIG_DFL);
107 void signal_handler_init(void)
109 (void)signal(SIGINT, signal_handler);
110 (void)signal(SIGTERM, signal_handler);
116 BOOL WINAPI event_handler(DWORD sig)
120 case CTRL_CLOSE_EVENT:
121 case CTRL_LOGOFF_EVENT:
122 case CTRL_SHUTDOWN_EVENT:
124 dstream << "INFO: event_handler(): "
125 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
130 (void)signal(SIGINT, SIG_DFL);
133 case CTRL_BREAK_EVENT:
140 void signal_handler_init(void)
142 SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
151 // Default to RUN_IN_PLACE style relative paths
152 std::string path_share = "..";
153 std::string path_user = "..";
154 std::string path_locale = path_share + DIR_DELIM + "locale";
155 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--) {
167 if (path[i] == delim)
173 bool detectMSVCBuildDir(const std::string &path)
175 const char *ends[] = {"bin\\Release", "bin\\MinSizeRel", "bin\\RelWithDebInfo",
176 "bin\\Debug", "bin\\Build", NULL};
177 return (!removeStringEnd(path, ends).empty());
180 std::string get_sysinfo()
184 std::ostringstream oss;
185 LPSTR filePath = new char[MAX_PATH];
187 VS_FIXEDFILEINFO *fixedFileInfo;
189 GetSystemDirectoryA(filePath, MAX_PATH);
190 PathAppendA(filePath, "kernel32.dll");
192 DWORD dwVersionSize = GetFileVersionInfoSizeA(filePath, NULL);
193 LPBYTE lpVersionInfo = new BYTE[dwVersionSize];
195 GetFileVersionInfoA(filePath, 0, dwVersionSize, lpVersionInfo);
196 VerQueryValueA(lpVersionInfo, "\\", (LPVOID *)&fixedFileInfo, &blockSize);
198 oss << "Windows/" << HIWORD(fixedFileInfo->dwProductVersionMS) << '.' // Major
199 << LOWORD(fixedFileInfo->dwProductVersionMS) << '.' // Minor
200 << HIWORD(fixedFileInfo->dwProductVersionLS) << ' '; // Build
206 if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
207 oss << "x86_64"; // 32-bit app on 64-bit OS
212 delete[] lpVersionInfo;
217 struct utsname osinfo;
219 return std::string(osinfo.sysname) + "/" + osinfo.release + " " + osinfo.machine;
223 bool getCurrentWorkingDir(char *buf, size_t len)
226 DWORD ret = GetCurrentDirectory(len, buf);
227 return (ret != 0) && (ret <= len);
229 return getcwd(buf, len);
233 bool getExecPathFromProcfs(char *buf, size_t buflen)
239 if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
240 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
241 (len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
254 bool getCurrentExecPath(char *buf, size_t len)
256 DWORD written = GetModuleFileNameA(NULL, buf, len);
257 if (written == 0 || written == len)
264 #elif defined(__linux__)
266 bool getCurrentExecPath(char *buf, size_t len)
268 if (!getExecPathFromProcfs(buf, len))
274 //// Mac OS X, Darwin
275 #elif defined(__APPLE__)
277 bool getCurrentExecPath(char *buf, size_t len)
279 uint32_t lenb = (uint32_t)len;
280 if (_NSGetExecutablePath(buf, &lenb) == -1)
286 //// FreeBSD, NetBSD, DragonFlyBSD
287 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
289 bool getCurrentExecPath(char *buf, size_t len)
291 // Try getting path from procfs first, since valgrind
292 // doesn't work with the latter
293 if (getExecPathFromProcfs(buf, len))
300 mib[2] = KERN_PROC_PATHNAME;
303 if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
310 #elif defined(__sun) || defined(sun)
312 bool getCurrentExecPath(char *buf, size_t len)
314 const char *exec = getexecname();
318 if (strlcpy(buf, exec, len) >= len)
325 #elif defined(__hpux)
327 bool getCurrentExecPath(char *buf, size_t len)
329 struct pst_status psts;
331 if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
334 if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
342 bool getCurrentExecPath(char *buf, size_t len)
352 const char *getHomeOrFail()
354 const char *home = getenv("HOME");
355 // In rare cases the HOME environment variable may be unset
356 FATAL_ERROR_IF(!home, "Required environment variable HOME is not set");
365 bool setSystemPaths()
369 // Find path of executable and set path_share relative to it
370 FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
371 "Failed to get current executable path");
372 pathRemoveFile(buf, '\\');
374 std::string exepath(buf);
377 path_share = exepath + "\\..";
378 if (detectMSVCBuildDir(exepath)) {
379 // The msvc build dir schould normaly not be present if properly
380 // installed, but its usefull for debugging.
381 path_share += DIR_DELIM "..";
384 // Use "C:\Users\<user>\AppData\Roaming\<PROJECT_NAME_C>"
385 DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
386 FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
388 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME_C;
393 #elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
394 defined(__DragonFly__)
396 bool setSystemPaths()
400 if (!getCurrentExecPath(buf, sizeof(buf))) {
402 errorstream << "Unable to read bindir " << std::endl;
404 FATAL_ERROR("Unable to read bindir");
409 pathRemoveFile(buf, '/');
410 std::string bindir(buf);
412 // Find share directory from these.
413 // It is identified by containing the subdirectory "builtin".
414 std::list<std::string> trylist;
415 std::string static_sharedir = STATIC_SHAREDIR;
416 if (!static_sharedir.empty() && static_sharedir != ".")
417 trylist.push_back(static_sharedir);
419 trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share" DIR_DELIM +
421 trylist.push_back(bindir + DIR_DELIM "..");
424 trylist.push_back(path_user);
427 for (std::list<std::string>::const_iterator i = trylist.begin();
428 i != trylist.end(); ++i) {
429 const std::string &trypath = *i;
430 if (!fs::PathExists(trypath) ||
431 !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
432 warningstream << "system-wide share not found at \"" << trypath
433 << "\"" << std::endl;
437 // Warn if was not the first alternative
438 if (i != trylist.begin()) {
439 warningstream << "system-wide share found at \"" << trypath
440 << "\"" << std::endl;
443 path_share = trypath;
448 path_user = std::string(getHomeOrFail()) + DIR_DELIM "." + PROJECT_NAME;
455 #elif defined(__APPLE__)
457 bool setSystemPaths()
459 CFBundleRef main_bundle = CFBundleGetMainBundle();
460 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
462 if (CFURLGetFileSystemRepresentation(
463 resources_url, TRUE, (UInt8 *)path, PATH_MAX)) {
464 path_share = std::string(path);
466 warningstream << "Could not determine bundle resource path" << std::endl;
468 CFRelease(resources_url);
470 path_user = std::string(getHomeOrFail()) + "/Library/Application Support/" +
477 bool setSystemPaths()
479 path_share = STATIC_SHAREDIR;
480 path_user = std::string(getHomeOrFail()) + DIR_DELIM "." +
481 lowercase(PROJECT_NAME);
487 void migrateCachePath()
489 const std::string local_cache_path = path_user + DIR_DELIM + "cache";
491 // Delete tmp folder if it exists (it only ever contained
492 // a temporary ogg file, which is no longer used).
493 if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
494 fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
496 // Bail if migration impossible
497 if (path_cache == local_cache_path || !fs::PathExists(local_cache_path) ||
498 fs::PathExists(path_cache)) {
501 if (!fs::Rename(local_cache_path, path_cache)) {
502 errorstream << "Failed to migrate local cache path "
508 void initializePaths()
513 infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
515 bool success = getCurrentExecPath(buf, sizeof(buf)) ||
516 getExecPathFromProcfs(buf, sizeof(buf));
519 pathRemoveFile(buf, DIR_DELIM_CHAR);
520 std::string execpath(buf);
522 path_share = execpath + DIR_DELIM "..";
523 path_user = execpath + DIR_DELIM "..";
525 if (detectMSVCBuildDir(execpath)) {
526 path_share += DIR_DELIM "..";
527 path_user += DIR_DELIM "..";
530 errorstream << "Failed to get paths by executable location, "
534 if (!getCurrentWorkingDir(buf, sizeof(buf)))
535 FATAL_ERROR("Ran out of methods to get paths");
537 size_t cwdlen = strlen(buf);
538 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
543 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
544 pathRemoveFile(buf, DIR_DELIM_CHAR);
546 std::string execpath(buf);
548 path_share = execpath;
549 path_user = execpath;
551 path_cache = path_user + DIR_DELIM + "cache";
553 infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
555 if (!setSystemPaths())
556 errorstream << "Failed to get one or more system-wide path" << std::endl;
559 path_cache = path_user + DIR_DELIM + "cache";
561 // Initialize path_cache
562 // First try $XDG_CACHE_HOME/PROJECT_NAME
563 const char *cache_dir = getenv("XDG_CACHE_HOME");
564 const char *home_dir = getenv("HOME");
566 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
567 } else if (home_dir) {
568 // Then try $HOME/.cache/PROJECT_NAME
569 path_cache = std::string(home_dir) + DIR_DELIM + ".cache" + DIR_DELIM +
572 // If neither works, use $PATH_USER/cache
573 path_cache = path_user + DIR_DELIM + "cache";
575 // Migrate cache folder to new location if possible
578 #endif // RUN_IN_PLACE
580 infostream << "Detected share path: " << path_share << std::endl;
581 infostream << "Detected user path: " << path_user << std::endl;
582 infostream << "Detected cache path: " << path_cache << std::endl;
585 bool found_localedir = false;
586 #ifdef STATIC_LOCALEDIR
587 /* STATIC_LOCALEDIR may be a generalized path such as /usr/share/locale that
588 * doesn't necessarily contain our locale files, so check data path first. */
589 path_locale = getDataPath("locale");
590 if (fs::PathExists(path_locale)) {
591 found_localedir = true;
592 infostream << "Using in-place locale directory " << path_locale
593 << " even though a static one was provided." << std::endl;
594 } else if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
595 found_localedir = true;
596 path_locale = STATIC_LOCALEDIR;
597 infostream << "Using static locale directory " << STATIC_LOCALEDIR
601 path_locale = getDataPath("locale");
602 if (fs::PathExists(path_locale)) {
603 found_localedir = true;
606 if (!found_localedir) {
607 warningstream << "Couldn't find a locale directory!" << std::endl;
609 #endif // USE_GETTEXT
613 //// OS-specific Secure Random
618 bool secure_rand_fill_buf(void *buf, size_t len)
622 if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
625 CryptGenRandom(wctx, len, (BYTE *)buf);
626 CryptReleaseContext(wctx, 0);
632 bool secure_rand_fill_buf(void *buf, size_t len)
634 // N.B. This function checks *only* for /dev/urandom, because on most
635 // common OSes it is non-blocking, whereas /dev/random is blocking, and it
636 // is exceptionally uncommon for there to be a situation where /dev/random
637 // exists but /dev/urandom does not. This guesswork is necessary since
638 // random devices are not covered by any POSIX standard...
639 FILE *fp = fopen("/dev/urandom", "rb");
643 bool success = fread(buf, len, 1, fp) == 1;
651 void attachOrCreateConsole()
654 static bool consoleAllocated = false;
655 const bool redirected = (_fileno(stdout) == -2 ||
656 _fileno(stdout) == -1); // If output is redirected to e.g
658 if (!consoleAllocated && redirected &&
659 (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())) {
660 freopen("CONOUT$", "w", stdout);
661 freopen("CONOUT$", "w", stderr);
662 consoleAllocated = true;
667 int mt_snprintf(char *buf, const size_t buf_size, const char *fmt, ...)
669 // https://msdn.microsoft.com/en-us/library/bt7tawza.aspx
670 // Many of the MSVC / Windows printf-style functions do not support positional
671 // arguments (eg. "%1$s"). We just forward the call to vsnprintf for sane
672 // platforms, but defer to _vsprintf_p on MSVC / Windows.
673 // https://github.com/FFmpeg/FFmpeg/blob/5ae9fa13f5ac640bec113120d540f70971aa635d/compat/msvcrt/snprintf.c#L46
674 // _vsprintf_p has to be shimmed with _vscprintf_p on -1 (for an example see
675 // above FFmpeg link).
679 int c = vsnprintf(buf, buf_size, fmt, args);
681 int c = _vsprintf_p(buf, buf_size, fmt, args);
683 c = _vscprintf_p(fmt, args);
689 bool openURL(const std::string &url)
691 if ((url.substr(0, 7) != "http://" && url.substr(0, 8) != "https://") ||
692 url.find_first_of("\r\n") != std::string::npos) {
693 errorstream << "Invalid url: " << url << std::endl;
698 return (intptr_t)ShellExecuteA(
699 NULL, NULL, url.c_str(), NULL, NULL, SW_SHOWNORMAL) > 32;
700 #elif defined(__ANDROID__)
703 #elif defined(__APPLE__)
704 const char *argv[] = {"open", url.c_str(), NULL};
705 return posix_spawnp(NULL, "open", NULL, NULL, (char **)argv,
706 (*_NSGetEnviron())) == 0;
708 const char *argv[] = {"xdg-open", url.c_str(), NULL};
709 return posix_spawnp(NULL, "xdg-open", NULL, NULL, (char **)argv, environ) == 0;
713 // Load performance counter frequency only once at startup
716 inline double get_perf_freq()
719 QueryPerformanceFrequency(&freq);
720 return freq.QuadPart;
723 double perf_freq = get_perf_freq();
727 } // namespace porting