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>
39 #include <sys/utsname.h>
43 #include <sys/pstat.h>
50 #include "util/string.h"
60 Signal handler (grabs Ctrl-C on POSIX systems)
63 bool g_killed = false;
65 bool *signal_handler_killstatus()
70 #if !defined(_WIN32) // POSIX
73 void signal_handler(int sig)
77 dstream << "INFO: signal_handler(): "
78 << "Ctrl-C pressed, shutting down." << std::endl;
79 } else if (sig == SIGTERM) {
80 dstream << "INFO: signal_handler(): "
81 << "got SIGTERM, shutting down." << std::endl;
84 // Comment out for less clutter when testing scripts
85 /*dstream << "INFO: sigint_handler(): "
86 << "Printing debug stacks" << std::endl;
87 debug_stacks_print();*/
91 (void)signal(sig, SIG_DFL);
95 void signal_handler_init(void)
97 (void)signal(SIGINT, signal_handler);
98 (void)signal(SIGTERM, signal_handler);
104 BOOL WINAPI event_handler(DWORD sig)
108 case CTRL_CLOSE_EVENT:
109 case CTRL_LOGOFF_EVENT:
110 case CTRL_SHUTDOWN_EVENT:
112 dstream << "INFO: event_handler(): "
113 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
114 " shutting down." << std::endl;
117 (void)signal(SIGINT, SIG_DFL);
120 case CTRL_BREAK_EVENT:
127 void signal_handler_init(void)
129 SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
139 // Default to RUN_IN_PLACE style relative paths
140 std::string path_share = "..";
141 std::string path_user = "..";
142 std::string path_locale = path_share + DIR_DELIM + "locale";
143 std::string path_cache = path_user + DIR_DELIM + "cache";
146 std::string getDataPath(const char *subpath)
148 return path_share + DIR_DELIM + subpath;
151 void pathRemoveFile(char *path, char delim)
153 // Remove filename and path delimiter
155 for(i = strlen(path)-1; i>=0; i--)
163 bool detectMSVCBuildDir(const std::string &path)
165 const char *ends[] = {
168 "bin\\RelWithDebInfo",
173 return (!removeStringEnd(path, ends).empty());
176 std::string get_sysinfo()
180 std::ostringstream oss;
181 LPSTR filePath = new char[MAX_PATH];
183 VS_FIXEDFILEINFO *fixedFileInfo;
185 GetSystemDirectoryA(filePath, MAX_PATH);
186 PathAppendA(filePath, "kernel32.dll");
188 DWORD dwVersionSize = GetFileVersionInfoSizeA(filePath, NULL);
189 LPBYTE lpVersionInfo = new BYTE[dwVersionSize];
191 GetFileVersionInfoA(filePath, 0, dwVersionSize, lpVersionInfo);
192 VerQueryValueA(lpVersionInfo, "\\", (LPVOID *)&fixedFileInfo, &blockSize);
195 << HIWORD(fixedFileInfo->dwProductVersionMS) << '.' // Major
196 << LOWORD(fixedFileInfo->dwProductVersionMS) << '.' // Minor
197 << HIWORD(fixedFileInfo->dwProductVersionLS) << ' '; // Build
203 if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
204 oss << "x86_64"; // 32-bit app on 64-bit OS
209 delete[] lpVersionInfo;
214 struct utsname osinfo;
216 return std::string(osinfo.sysname) + "/"
217 + osinfo.release + " " + osinfo.machine;
222 bool getCurrentWorkingDir(char *buf, size_t len)
225 DWORD ret = GetCurrentDirectory(len, buf);
226 return (ret != 0) && (ret <= len);
228 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)
265 #elif defined(__linux__)
267 bool getCurrentExecPath(char *buf, size_t len)
269 if (!getExecPathFromProcfs(buf, len))
276 //// Mac OS X, Darwin
277 #elif defined(__APPLE__)
279 bool getCurrentExecPath(char *buf, size_t len)
281 uint32_t lenb = (uint32_t)len;
282 if (_NSGetExecutablePath(buf, &lenb) == -1)
289 //// FreeBSD, NetBSD, DragonFlyBSD
290 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
292 bool getCurrentExecPath(char *buf, size_t len)
294 // Try getting path from procfs first, since valgrind
295 // doesn't work with the latter
296 if (getExecPathFromProcfs(buf, len))
303 mib[2] = KERN_PROC_PATHNAME;
306 if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
314 #elif defined(__sun) || defined(sun)
316 bool getCurrentExecPath(char *buf, size_t len)
318 const char *exec = getexecname();
322 if (strlcpy(buf, exec, len) >= len)
330 #elif defined(__hpux)
332 bool getCurrentExecPath(char *buf, size_t len)
334 struct pst_status psts;
336 if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
339 if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
348 bool getCurrentExecPath(char *buf, size_t len)
359 const char *getHomeOrFail()
361 const char *home = getenv("HOME");
362 // In rare cases the HOME environment variable may be unset
363 FATAL_ERROR_IF(!home,
364 "Required environment variable HOME is not set");
374 bool setSystemPaths()
378 // Find path of executable and set path_share relative to it
379 FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
380 "Failed to get current executable path");
381 pathRemoveFile(buf, '\\');
384 path_share = std::string(buf) + "\\..";
386 // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
387 DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
388 FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
390 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
396 #elif defined(__linux__)
398 bool setSystemPaths()
402 if (!getCurrentExecPath(buf, sizeof(buf))) {
404 errorstream << "Unable to read bindir "<< std::endl;
406 FATAL_ERROR("Unable to read bindir");
411 pathRemoveFile(buf, '/');
412 std::string bindir(buf);
414 // Find share directory from these.
415 // It is identified by containing the subdirectory "builtin".
416 std::list<std::string> trylist;
417 std::string static_sharedir = STATIC_SHAREDIR;
418 if (!static_sharedir.empty() && static_sharedir != ".")
419 trylist.push_back(static_sharedir);
421 trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
422 DIR_DELIM + PROJECT_NAME);
423 trylist.push_back(bindir + DIR_DELIM "..");
426 trylist.push_back(path_user);
429 for (std::list<std::string>::const_iterator
430 i = trylist.begin(); i != trylist.end(); ++i) {
431 const std::string &trypath = *i;
432 if (!fs::PathExists(trypath) ||
433 !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
434 warningstream << "system-wide share not found at \""
435 << trypath << "\""<< std::endl;
439 // Warn if was not the first alternative
440 if (i != trylist.begin()) {
441 warningstream << "system-wide share found at \""
442 << trypath << "\"" << std::endl;
445 path_share = trypath;
450 path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
459 #elif defined(__APPLE__)
461 bool setSystemPaths()
463 CFBundleRef main_bundle = CFBundleGetMainBundle();
464 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
466 if (CFURLGetFileSystemRepresentation(resources_url,
467 TRUE, (UInt8 *)path, PATH_MAX)) {
468 path_share = std::string(path);
470 warningstream << "Could not determine bundle resource path" << std::endl;
472 CFRelease(resources_url);
474 path_user = std::string(getHomeOrFail())
475 + "/Library/Application Support/"
483 bool setSystemPaths()
485 path_share = STATIC_SHAREDIR;
486 path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
487 + lowercase(PROJECT_NAME);
494 void migrateCachePath()
496 const std::string local_cache_path = path_user + DIR_DELIM + "cache";
498 // Delete tmp folder if it exists (it only ever contained
499 // a temporary ogg file, which is no longer used).
500 if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
501 fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
503 // Bail if migration impossible
504 if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
505 || fs::PathExists(path_cache)) {
508 if (!fs::Rename(local_cache_path, path_cache)) {
509 errorstream << "Failed to migrate local cache path "
510 "to system path!" << std::endl;
514 void initializePaths()
519 infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
522 getCurrentExecPath(buf, sizeof(buf)) ||
523 getExecPathFromProcfs(buf, sizeof(buf));
526 pathRemoveFile(buf, DIR_DELIM_CHAR);
527 std::string execpath(buf);
529 path_share = execpath + DIR_DELIM "..";
530 path_user = execpath + DIR_DELIM "..";
532 if (detectMSVCBuildDir(execpath)) {
533 path_share += DIR_DELIM "..";
534 path_user += DIR_DELIM "..";
537 errorstream << "Failed to get paths by executable location, "
538 "trying cwd" << std::endl;
540 if (!getCurrentWorkingDir(buf, sizeof(buf)))
541 FATAL_ERROR("Ran out of methods to get paths");
543 size_t cwdlen = strlen(buf);
544 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
549 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
550 pathRemoveFile(buf, DIR_DELIM_CHAR);
552 std::string execpath(buf);
554 path_share = execpath;
555 path_user = execpath;
557 path_cache = path_user + DIR_DELIM + "cache";
559 infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
561 if (!setSystemPaths())
562 errorstream << "Failed to get one or more system-wide path" << std::endl;
564 // Initialize path_cache
565 // First try $XDG_CACHE_HOME/PROJECT_NAME
566 const char *cache_dir = getenv("XDG_CACHE_HOME");
567 const char *home_dir = getenv("HOME");
569 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
570 } else if (home_dir) {
571 // Then try $HOME/.cache/PROJECT_NAME
572 path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
573 + DIR_DELIM + PROJECT_NAME;
575 // If neither works, use $PATH_USER/cache
576 path_cache = path_user + DIR_DELIM + "cache";
578 // Migrate cache folder to new location if possible
582 infostream << "Detected share path: " << path_share << std::endl;
583 infostream << "Detected user path: " << path_user << std::endl;
584 infostream << "Detected cache path: " << path_cache << std::endl;
587 bool found_localedir = false;
588 # ifdef STATIC_LOCALEDIR
589 if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
590 found_localedir = true;
591 path_locale = STATIC_LOCALEDIR;
592 infostream << "Using locale directory " << STATIC_LOCALEDIR << std::endl;
594 path_locale = getDataPath("locale");
595 if (fs::PathExists(path_locale)) {
596 found_localedir = true;
597 infostream << "Using in-place locale directory " << path_locale
598 << " even though a static one was provided "
599 << "(RUN_IN_PLACE or CUSTOM_LOCALEDIR)." << std::endl;
603 path_locale = getDataPath("locale");
604 if (fs::PathExists(path_locale)) {
605 found_localedir = true;
608 if (!found_localedir) {
609 warningstream << "Couldn't find a locale directory!" << std::endl;
611 #endif // USE_GETTEXT
615 //// OS-specific Secure Random
620 bool secure_rand_fill_buf(void *buf, size_t len)
624 if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
627 CryptGenRandom(wctx, len, (BYTE *)buf);
628 CryptReleaseContext(wctx, 0);
634 bool secure_rand_fill_buf(void *buf, size_t len)
636 // N.B. This function checks *only* for /dev/urandom, because on most
637 // common OSes it is non-blocking, whereas /dev/random is blocking, and it
638 // is exceptionally uncommon for there to be a situation where /dev/random
639 // exists but /dev/urandom does not. This guesswork is necessary since
640 // random devices are not covered by any POSIX standard...
641 FILE *fp = fopen("/dev/urandom", "rb");
645 bool success = fread(buf, len, 1, fp) == 1;
653 void attachOrCreateConsole()
656 static bool consoleAllocated = false;
657 const bool redirected = (_fileno(stdout) == -2 || _fileno(stdout) == -1); // If output is redirected to e.g a file
658 if (!consoleAllocated && redirected && (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())) {
659 freopen("CONOUT$", "w", stdout);
660 freopen("CONOUT$", "w", stderr);
661 consoleAllocated = true;
666 int mt_snprintf(char *buf, const size_t buf_size, const char *fmt, ...)
668 // https://msdn.microsoft.com/en-us/library/bt7tawza.aspx
669 // Many of the MSVC / Windows printf-style functions do not support positional
670 // arguments (eg. "%1$s"). We just forward the call to vsnprintf for sane
671 // platforms, but defer to _vsprintf_p on MSVC / Windows.
672 // https://github.com/FFmpeg/FFmpeg/blob/5ae9fa13f5ac640bec113120d540f70971aa635d/compat/msvcrt/snprintf.c#L46
673 // _vsprintf_p has to be shimmed with _vscprintf_p on -1 (for an example see
674 // above FFmpeg link).
678 int c = vsnprintf(buf, buf_size, fmt, args);
680 int c = _vsprintf_p(buf, buf_size, fmt, args);
682 c = _vscprintf_p(fmt, args);
688 // Load performance counter frequency only once at startup
691 inline double get_perf_freq()
694 QueryPerformanceFrequency(&freq);
695 return freq.QuadPart;
698 double perf_freq = get_perf_freq();
702 } //namespace porting