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"
57 #include "util/string.h"
66 Signal handler (grabs Ctrl-C on POSIX systems)
69 bool g_killed = false;
71 bool *signal_handler_killstatus()
76 #if !defined(_WIN32) // POSIX
79 void signal_handler(int sig)
83 dstream << "INFO: signal_handler(): "
84 << "Ctrl-C pressed, shutting down." << std::endl;
85 } else if (sig == SIGTERM) {
86 dstream << "INFO: signal_handler(): "
87 << "got SIGTERM, shutting down." << std::endl;
90 // Comment out for less clutter when testing scripts
91 /*dstream << "INFO: sigint_handler(): "
92 << "Printing debug stacks" << std::endl;
93 debug_stacks_print();*/
97 (void)signal(sig, SIG_DFL);
101 void signal_handler_init(void)
103 (void)signal(SIGINT, signal_handler);
104 (void)signal(SIGTERM, signal_handler);
110 BOOL WINAPI event_handler(DWORD sig)
114 case CTRL_CLOSE_EVENT:
115 case CTRL_LOGOFF_EVENT:
116 case CTRL_SHUTDOWN_EVENT:
118 dstream << "INFO: event_handler(): "
119 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
120 " shutting down." << std::endl;
123 (void)signal(SIGINT, SIG_DFL);
126 case CTRL_BREAK_EVENT:
133 void signal_handler_init(void)
135 SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
145 // Default to RUN_IN_PLACE style relative paths
146 std::string path_share = "..";
147 std::string path_user = "..";
148 std::string path_locale = path_share + DIR_DELIM + "locale";
149 std::string path_cache = path_user + DIR_DELIM + "cache";
152 std::string getDataPath(const char *subpath)
154 return path_share + DIR_DELIM + subpath;
157 void pathRemoveFile(char *path, char delim)
159 // Remove filename and path delimiter
161 for(i = strlen(path)-1; i>=0; i--)
169 bool detectMSVCBuildDir(const std::string &path)
171 const char *ends[] = {
174 "bin\\RelWithDebInfo",
179 return (!removeStringEnd(path, ends).empty());
182 std::string get_sysinfo()
186 std::ostringstream oss;
187 LPSTR filePath = new char[MAX_PATH];
189 VS_FIXEDFILEINFO *fixedFileInfo;
191 GetSystemDirectoryA(filePath, MAX_PATH);
192 PathAppendA(filePath, "kernel32.dll");
194 DWORD dwVersionSize = GetFileVersionInfoSizeA(filePath, NULL);
195 LPBYTE lpVersionInfo = new BYTE[dwVersionSize];
197 GetFileVersionInfoA(filePath, 0, dwVersionSize, lpVersionInfo);
198 VerQueryValueA(lpVersionInfo, "\\", (LPVOID *)&fixedFileInfo, &blockSize);
201 << HIWORD(fixedFileInfo->dwProductVersionMS) << '.' // Major
202 << LOWORD(fixedFileInfo->dwProductVersionMS) << '.' // Minor
203 << HIWORD(fixedFileInfo->dwProductVersionLS) << ' '; // Build
209 if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
210 oss << "x86_64"; // 32-bit app on 64-bit OS
215 delete[] lpVersionInfo;
220 struct utsname osinfo;
222 return std::string(osinfo.sysname) + "/"
223 + osinfo.release + " " + osinfo.machine;
228 bool getCurrentWorkingDir(char *buf, size_t len)
231 DWORD ret = GetCurrentDirectory(len, buf);
232 return (ret != 0) && (ret <= len);
234 return getcwd(buf, len);
239 bool getExecPathFromProcfs(char *buf, size_t buflen)
245 if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
246 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
247 (len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
260 bool getCurrentExecPath(char *buf, size_t len)
262 DWORD written = GetModuleFileNameA(NULL, buf, len);
263 if (written == 0 || written == len)
271 #elif defined(__linux__)
273 bool getCurrentExecPath(char *buf, size_t len)
275 if (!getExecPathFromProcfs(buf, len))
282 //// Mac OS X, Darwin
283 #elif defined(__APPLE__)
285 bool getCurrentExecPath(char *buf, size_t len)
287 uint32_t lenb = (uint32_t)len;
288 if (_NSGetExecutablePath(buf, &lenb) == -1)
295 //// FreeBSD, NetBSD, DragonFlyBSD
296 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
298 bool getCurrentExecPath(char *buf, size_t len)
300 // Try getting path from procfs first, since valgrind
301 // doesn't work with the latter
302 if (getExecPathFromProcfs(buf, len))
309 mib[2] = KERN_PROC_PATHNAME;
312 if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
320 #elif defined(__sun) || defined(sun)
322 bool getCurrentExecPath(char *buf, size_t len)
324 const char *exec = getexecname();
328 if (strlcpy(buf, exec, len) >= len)
336 #elif defined(__hpux)
338 bool getCurrentExecPath(char *buf, size_t len)
340 struct pst_status psts;
342 if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
345 if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
354 bool getCurrentExecPath(char *buf, size_t len)
365 const char *getHomeOrFail()
367 const char *home = getenv("HOME");
368 // In rare cases the HOME environment variable may be unset
369 FATAL_ERROR_IF(!home,
370 "Required environment variable HOME is not set");
380 bool setSystemPaths()
384 // Find path of executable and set path_share relative to it
385 FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
386 "Failed to get current executable path");
387 pathRemoveFile(buf, '\\');
389 std::string exepath(buf);
392 path_share = exepath + "\\..";
393 if (detectMSVCBuildDir(exepath)) {
394 // The msvc build dir schould normaly not be present if properly installed,
395 // but its usefull for debugging.
396 path_share += DIR_DELIM "..";
399 // Use "C:\Users\<user>\AppData\Roaming\<PROJECT_NAME_C>"
400 DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
401 FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
403 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME_C;
409 #elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
411 bool setSystemPaths()
415 if (!getCurrentExecPath(buf, sizeof(buf))) {
417 errorstream << "Unable to read bindir "<< std::endl;
419 FATAL_ERROR("Unable to read bindir");
424 pathRemoveFile(buf, '/');
425 std::string bindir(buf);
427 // Find share directory from these.
428 // It is identified by containing the subdirectory "builtin".
429 std::list<std::string> trylist;
430 std::string static_sharedir = STATIC_SHAREDIR;
431 if (!static_sharedir.empty() && static_sharedir != ".")
432 trylist.push_back(static_sharedir);
434 trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
435 DIR_DELIM + PROJECT_NAME);
436 trylist.push_back(bindir + DIR_DELIM "..");
439 trylist.push_back(path_user);
442 for (std::list<std::string>::const_iterator
443 i = trylist.begin(); i != trylist.end(); ++i) {
444 const std::string &trypath = *i;
445 if (!fs::PathExists(trypath) ||
446 !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
447 warningstream << "system-wide share not found at \""
448 << trypath << "\""<< std::endl;
452 // Warn if was not the first alternative
453 if (i != trylist.begin()) {
454 warningstream << "system-wide share found at \""
455 << trypath << "\"" << std::endl;
458 path_share = trypath;
463 path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
472 #elif defined(__APPLE__)
474 bool setSystemPaths()
476 CFBundleRef main_bundle = CFBundleGetMainBundle();
477 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
479 if (CFURLGetFileSystemRepresentation(resources_url,
480 TRUE, (UInt8 *)path, PATH_MAX)) {
481 path_share = std::string(path);
483 warningstream << "Could not determine bundle resource path" << std::endl;
485 CFRelease(resources_url);
487 path_user = std::string(getHomeOrFail())
488 + "/Library/Application Support/"
496 bool setSystemPaths()
498 path_share = STATIC_SHAREDIR;
499 path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
500 + lowercase(PROJECT_NAME);
507 void migrateCachePath()
509 const std::string local_cache_path = path_user + DIR_DELIM + "cache";
511 // Delete tmp folder if it exists (it only ever contained
512 // a temporary ogg file, which is no longer used).
513 if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
514 fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
516 // Bail if migration impossible
517 if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
518 || fs::PathExists(path_cache)) {
521 if (!fs::Rename(local_cache_path, path_cache)) {
522 errorstream << "Failed to migrate local cache path "
523 "to system path!" << std::endl;
527 void initializePaths()
532 infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
535 getCurrentExecPath(buf, sizeof(buf)) ||
536 getExecPathFromProcfs(buf, sizeof(buf));
539 pathRemoveFile(buf, DIR_DELIM_CHAR);
540 std::string execpath(buf);
542 path_share = execpath + DIR_DELIM "..";
543 path_user = execpath + DIR_DELIM "..";
545 if (detectMSVCBuildDir(execpath)) {
546 path_share += DIR_DELIM "..";
547 path_user += DIR_DELIM "..";
550 errorstream << "Failed to get paths by executable location, "
551 "trying cwd" << std::endl;
553 if (!getCurrentWorkingDir(buf, sizeof(buf)))
554 FATAL_ERROR("Ran out of methods to get paths");
556 size_t cwdlen = strlen(buf);
557 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
562 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
563 pathRemoveFile(buf, DIR_DELIM_CHAR);
565 std::string execpath(buf);
567 path_share = execpath;
568 path_user = execpath;
570 path_cache = path_user + DIR_DELIM + "cache";
572 infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
574 if (!setSystemPaths())
575 errorstream << "Failed to get one or more system-wide path" << std::endl;
579 path_cache = path_user + DIR_DELIM + "cache";
581 // Initialize path_cache
582 // First try $XDG_CACHE_HOME/PROJECT_NAME
583 const char *cache_dir = getenv("XDG_CACHE_HOME");
584 const char *home_dir = getenv("HOME");
586 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
587 } else if (home_dir) {
588 // Then try $HOME/.cache/PROJECT_NAME
589 path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
590 + DIR_DELIM + PROJECT_NAME;
592 // If neither works, use $PATH_USER/cache
593 path_cache = path_user + DIR_DELIM + "cache";
595 // Migrate cache folder to new location if possible
598 #endif // RUN_IN_PLACE
600 infostream << "Detected share path: " << path_share << std::endl;
601 infostream << "Detected user path: " << path_user << std::endl;
602 infostream << "Detected cache path: " << path_cache << std::endl;
605 bool found_localedir = false;
606 # ifdef STATIC_LOCALEDIR
607 /* STATIC_LOCALEDIR may be a generalized path such as /usr/share/locale that
608 * doesn't necessarily contain our locale files, so check data path first. */
609 path_locale = getDataPath("locale");
610 if (fs::PathExists(path_locale)) {
611 found_localedir = true;
612 infostream << "Using in-place locale directory " << path_locale
613 << " even though a static one was provided." << std::endl;
614 } else if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
615 found_localedir = true;
616 path_locale = STATIC_LOCALEDIR;
617 infostream << "Using static locale directory " << STATIC_LOCALEDIR
621 path_locale = getDataPath("locale");
622 if (fs::PathExists(path_locale)) {
623 found_localedir = true;
626 if (!found_localedir) {
627 warningstream << "Couldn't find a locale directory!" << std::endl;
629 #endif // USE_GETTEXT
633 //// OS-specific Secure Random
638 bool secure_rand_fill_buf(void *buf, size_t len)
642 if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
645 CryptGenRandom(wctx, len, (BYTE *)buf);
646 CryptReleaseContext(wctx, 0);
652 bool secure_rand_fill_buf(void *buf, size_t len)
654 // N.B. This function checks *only* for /dev/urandom, because on most
655 // common OSes it is non-blocking, whereas /dev/random is blocking, and it
656 // is exceptionally uncommon for there to be a situation where /dev/random
657 // exists but /dev/urandom does not. This guesswork is necessary since
658 // random devices are not covered by any POSIX standard...
659 FILE *fp = fopen("/dev/urandom", "rb");
663 bool success = fread(buf, len, 1, fp) == 1;
671 void attachOrCreateConsole()
674 static bool consoleAllocated = false;
675 const bool redirected = (_fileno(stdout) == -2 || _fileno(stdout) == -1); // If output is redirected to e.g a file
676 if (!consoleAllocated && redirected && (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())) {
677 freopen("CONOUT$", "w", stdout);
678 freopen("CONOUT$", "w", stderr);
679 consoleAllocated = true;
684 int mt_snprintf(char *buf, const size_t buf_size, const char *fmt, ...)
686 // https://msdn.microsoft.com/en-us/library/bt7tawza.aspx
687 // Many of the MSVC / Windows printf-style functions do not support positional
688 // arguments (eg. "%1$s"). We just forward the call to vsnprintf for sane
689 // platforms, but defer to _vsprintf_p on MSVC / Windows.
690 // https://github.com/FFmpeg/FFmpeg/blob/5ae9fa13f5ac640bec113120d540f70971aa635d/compat/msvcrt/snprintf.c#L46
691 // _vsprintf_p has to be shimmed with _vscprintf_p on -1 (for an example see
692 // above FFmpeg link).
696 int c = vsnprintf(buf, buf_size, fmt, args);
698 int c = _vsprintf_p(buf, buf_size, fmt, args);
700 c = _vscprintf_p(fmt, args);
706 bool openURL(const std::string &url)
708 if ((url.substr(0, 7) != "http://" && url.substr(0, 8) != "https://") ||
709 url.find_first_of("\r\n") != std::string::npos) {
710 errorstream << "Invalid url: " << url << std::endl;
715 return (intptr_t)ShellExecuteA(NULL, NULL, url.c_str(), NULL, NULL, SW_SHOWNORMAL) > 32;
716 #elif defined(__ANDROID__)
719 #elif defined(__APPLE__)
720 const char *argv[] = {"open", url.c_str(), NULL};
721 return posix_spawnp(NULL, "open", NULL, NULL, (char**)argv, environ) == 0;
723 const char *argv[] = {"xdg-open", url.c_str(), NULL};
724 return posix_spawnp(NULL, "xdg-open", NULL, NULL, (char**)argv, environ) == 0;
728 // Load performance counter frequency only once at startup
731 inline double get_perf_freq()
734 QueryPerformanceFrequency(&freq);
735 return freq.QuadPart;
738 double perf_freq = get_perf_freq();
742 } //namespace porting