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, '\\');
383 std::string exepath(buf);
386 path_share = exepath + "\\..";
387 if (detectMSVCBuildDir(exepath)) {
388 // The msvc build dir schould normaly not be present if properly installed,
389 // but its usefull for debugging.
390 path_share += DIR_DELIM "..";
393 // Use "C:\Users\<user>\AppData\Roaming\<PROJECT_NAME_C>"
394 DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
395 FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
397 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME_C;
403 #elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
405 bool setSystemPaths()
409 if (!getCurrentExecPath(buf, sizeof(buf))) {
411 errorstream << "Unable to read bindir "<< std::endl;
413 FATAL_ERROR("Unable to read bindir");
418 pathRemoveFile(buf, '/');
419 std::string bindir(buf);
421 // Find share directory from these.
422 // It is identified by containing the subdirectory "builtin".
423 std::list<std::string> trylist;
424 std::string static_sharedir = STATIC_SHAREDIR;
425 if (!static_sharedir.empty() && static_sharedir != ".")
426 trylist.push_back(static_sharedir);
428 trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
429 DIR_DELIM + PROJECT_NAME);
430 trylist.push_back(bindir + DIR_DELIM "..");
433 trylist.push_back(path_user);
436 for (std::list<std::string>::const_iterator
437 i = trylist.begin(); i != trylist.end(); ++i) {
438 const std::string &trypath = *i;
439 if (!fs::PathExists(trypath) ||
440 !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
441 warningstream << "system-wide share not found at \""
442 << trypath << "\""<< std::endl;
446 // Warn if was not the first alternative
447 if (i != trylist.begin()) {
448 warningstream << "system-wide share found at \""
449 << trypath << "\"" << std::endl;
452 path_share = trypath;
457 path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
466 #elif defined(__APPLE__)
468 bool setSystemPaths()
470 CFBundleRef main_bundle = CFBundleGetMainBundle();
471 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
473 if (CFURLGetFileSystemRepresentation(resources_url,
474 TRUE, (UInt8 *)path, PATH_MAX)) {
475 path_share = std::string(path);
477 warningstream << "Could not determine bundle resource path" << std::endl;
479 CFRelease(resources_url);
481 path_user = std::string(getHomeOrFail())
482 + "/Library/Application Support/"
490 bool setSystemPaths()
492 path_share = STATIC_SHAREDIR;
493 path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
494 + lowercase(PROJECT_NAME);
501 void migrateCachePath()
503 const std::string local_cache_path = path_user + DIR_DELIM + "cache";
505 // Delete tmp folder if it exists (it only ever contained
506 // a temporary ogg file, which is no longer used).
507 if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
508 fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
510 // Bail if migration impossible
511 if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
512 || fs::PathExists(path_cache)) {
515 if (!fs::Rename(local_cache_path, path_cache)) {
516 errorstream << "Failed to migrate local cache path "
517 "to system path!" << std::endl;
521 void initializePaths()
526 infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
529 getCurrentExecPath(buf, sizeof(buf)) ||
530 getExecPathFromProcfs(buf, sizeof(buf));
533 pathRemoveFile(buf, DIR_DELIM_CHAR);
534 std::string execpath(buf);
536 path_share = execpath + DIR_DELIM "..";
537 path_user = execpath + DIR_DELIM "..";
539 if (detectMSVCBuildDir(execpath)) {
540 path_share += DIR_DELIM "..";
541 path_user += DIR_DELIM "..";
544 errorstream << "Failed to get paths by executable location, "
545 "trying cwd" << std::endl;
547 if (!getCurrentWorkingDir(buf, sizeof(buf)))
548 FATAL_ERROR("Ran out of methods to get paths");
550 size_t cwdlen = strlen(buf);
551 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
556 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
557 pathRemoveFile(buf, DIR_DELIM_CHAR);
559 std::string execpath(buf);
561 path_share = execpath;
562 path_user = execpath;
564 path_cache = path_user + DIR_DELIM + "cache";
566 infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
568 if (!setSystemPaths())
569 errorstream << "Failed to get one or more system-wide path" << std::endl;
573 path_cache = path_user + DIR_DELIM + "cache";
575 // Initialize path_cache
576 // First try $XDG_CACHE_HOME/PROJECT_NAME
577 const char *cache_dir = getenv("XDG_CACHE_HOME");
578 const char *home_dir = getenv("HOME");
580 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
581 } else if (home_dir) {
582 // Then try $HOME/.cache/PROJECT_NAME
583 path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
584 + DIR_DELIM + PROJECT_NAME;
586 // If neither works, use $PATH_USER/cache
587 path_cache = path_user + DIR_DELIM + "cache";
589 // Migrate cache folder to new location if possible
592 #endif // RUN_IN_PLACE
594 infostream << "Detected share path: " << path_share << std::endl;
595 infostream << "Detected user path: " << path_user << std::endl;
596 infostream << "Detected cache path: " << path_cache << std::endl;
599 bool found_localedir = false;
600 # ifdef STATIC_LOCALEDIR
601 if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
602 found_localedir = true;
603 path_locale = STATIC_LOCALEDIR;
604 infostream << "Using locale directory " << STATIC_LOCALEDIR << std::endl;
606 path_locale = getDataPath("locale");
607 if (fs::PathExists(path_locale)) {
608 found_localedir = true;
609 infostream << "Using in-place locale directory " << path_locale
610 << " even though a static one was provided "
611 << "(RUN_IN_PLACE or CUSTOM_LOCALEDIR)." << std::endl;
615 path_locale = getDataPath("locale");
616 if (fs::PathExists(path_locale)) {
617 found_localedir = true;
620 if (!found_localedir) {
621 warningstream << "Couldn't find a locale directory!" << std::endl;
623 #endif // USE_GETTEXT
627 //// OS-specific Secure Random
632 bool secure_rand_fill_buf(void *buf, size_t len)
636 if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
639 CryptGenRandom(wctx, len, (BYTE *)buf);
640 CryptReleaseContext(wctx, 0);
646 bool secure_rand_fill_buf(void *buf, size_t len)
648 // N.B. This function checks *only* for /dev/urandom, because on most
649 // common OSes it is non-blocking, whereas /dev/random is blocking, and it
650 // is exceptionally uncommon for there to be a situation where /dev/random
651 // exists but /dev/urandom does not. This guesswork is necessary since
652 // random devices are not covered by any POSIX standard...
653 FILE *fp = fopen("/dev/urandom", "rb");
657 bool success = fread(buf, len, 1, fp) == 1;
665 void attachOrCreateConsole()
668 static bool consoleAllocated = false;
669 const bool redirected = (_fileno(stdout) == -2 || _fileno(stdout) == -1); // If output is redirected to e.g a file
670 if (!consoleAllocated && redirected && (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())) {
671 freopen("CONOUT$", "w", stdout);
672 freopen("CONOUT$", "w", stderr);
673 consoleAllocated = true;
678 int mt_snprintf(char *buf, const size_t buf_size, const char *fmt, ...)
680 // https://msdn.microsoft.com/en-us/library/bt7tawza.aspx
681 // Many of the MSVC / Windows printf-style functions do not support positional
682 // arguments (eg. "%1$s"). We just forward the call to vsnprintf for sane
683 // platforms, but defer to _vsprintf_p on MSVC / Windows.
684 // https://github.com/FFmpeg/FFmpeg/blob/5ae9fa13f5ac640bec113120d540f70971aa635d/compat/msvcrt/snprintf.c#L46
685 // _vsprintf_p has to be shimmed with _vscprintf_p on -1 (for an example see
686 // above FFmpeg link).
690 int c = vsnprintf(buf, buf_size, fmt, args);
692 int c = _vsprintf_p(buf, buf_size, fmt, args);
694 c = _vscprintf_p(fmt, args);
700 // Load performance counter frequency only once at startup
703 inline double get_perf_freq()
706 QueryPerformanceFrequency(&freq);
707 return freq.QuadPart;
710 double perf_freq = get_perf_freq();
714 } //namespace porting