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"
58 Signal handler (grabs Ctrl-C on POSIX systems)
61 bool g_killed = false;
63 bool *signal_handler_killstatus()
68 #if !defined(_WIN32) // POSIX
71 void signal_handler(int sig)
75 dstream << "INFO: signal_handler(): "
76 << "Ctrl-C pressed, shutting down." << std::endl;
77 } else if (sig == SIGTERM) {
78 dstream << "INFO: signal_handler(): "
79 << "got SIGTERM, shutting down." << std::endl;
82 // Comment out for less clutter when testing scripts
83 /*dstream << "INFO: sigint_handler(): "
84 << "Printing debug stacks" << std::endl;
85 debug_stacks_print();*/
89 (void)signal(sig, SIG_DFL);
93 void signal_handler_init(void)
95 (void)signal(SIGINT, signal_handler);
96 (void)signal(SIGTERM, signal_handler);
102 BOOL WINAPI event_handler(DWORD sig)
106 case CTRL_CLOSE_EVENT:
107 case CTRL_LOGOFF_EVENT:
108 case CTRL_SHUTDOWN_EVENT:
110 dstream << "INFO: event_handler(): "
111 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
112 " shutting down." << std::endl;
115 (void)signal(SIGINT, SIG_DFL);
118 case CTRL_BREAK_EVENT:
125 void signal_handler_init(void)
127 SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
137 // Default to RUN_IN_PLACE style relative paths
138 std::string path_share = "..";
139 std::string path_user = "..";
140 std::string path_locale = path_share + DIR_DELIM + "locale";
141 std::string path_cache = path_user + DIR_DELIM + "cache";
144 std::string getDataPath(const char *subpath)
146 return path_share + DIR_DELIM + subpath;
149 void pathRemoveFile(char *path, char delim)
151 // Remove filename and path delimiter
153 for(i = strlen(path)-1; i>=0; i--)
161 bool detectMSVCBuildDir(const std::string &path)
163 const char *ends[] = {
166 "bin\\RelWithDebInfo",
171 return (!removeStringEnd(path, ends).empty());
174 std::string get_sysinfo()
178 std::ostringstream oss;
179 LPSTR filePath = new char[MAX_PATH];
181 VS_FIXEDFILEINFO *fixedFileInfo;
183 GetSystemDirectoryA(filePath, MAX_PATH);
184 PathAppendA(filePath, "kernel32.dll");
186 DWORD dwVersionSize = GetFileVersionInfoSizeA(filePath, NULL);
187 LPBYTE lpVersionInfo = new BYTE[dwVersionSize];
189 GetFileVersionInfoA(filePath, 0, dwVersionSize, lpVersionInfo);
190 VerQueryValueA(lpVersionInfo, "\\", (LPVOID *)&fixedFileInfo, &blockSize);
193 << HIWORD(fixedFileInfo->dwProductVersionMS) << '.' // Major
194 << LOWORD(fixedFileInfo->dwProductVersionMS) << '.' // Minor
195 << HIWORD(fixedFileInfo->dwProductVersionLS) << ' '; // Build
201 if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
202 oss << "x86_64"; // 32-bit app on 64-bit OS
207 delete[] lpVersionInfo;
212 struct utsname osinfo;
214 return std::string(osinfo.sysname) + "/"
215 + osinfo.release + " " + osinfo.machine;
220 bool getCurrentWorkingDir(char *buf, size_t len)
223 DWORD ret = GetCurrentDirectory(len, buf);
224 return (ret != 0) && (ret <= len);
226 return getcwd(buf, len);
231 bool getExecPathFromProcfs(char *buf, size_t buflen)
237 if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
238 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
239 (len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
252 bool getCurrentExecPath(char *buf, size_t len)
254 DWORD written = GetModuleFileNameA(NULL, buf, len);
255 if (written == 0 || written == len)
263 #elif defined(__linux__)
265 bool getCurrentExecPath(char *buf, size_t len)
267 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)
287 //// FreeBSD, NetBSD, DragonFlyBSD
288 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
290 bool getCurrentExecPath(char *buf, size_t len)
292 // Try getting path from procfs first, since valgrind
293 // doesn't work with the latter
294 if (getExecPathFromProcfs(buf, len))
301 mib[2] = KERN_PROC_PATHNAME;
304 if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
312 #elif defined(__sun) || defined(sun)
314 bool getCurrentExecPath(char *buf, size_t len)
316 const char *exec = getexecname();
320 if (strlcpy(buf, exec, len) >= len)
328 #elif defined(__hpux)
330 bool getCurrentExecPath(char *buf, size_t len)
332 struct pst_status psts;
334 if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
337 if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
346 bool getCurrentExecPath(char *buf, size_t len)
357 bool setSystemPaths()
361 // Find path of executable and set path_share relative to it
362 FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
363 "Failed to get current executable path");
364 pathRemoveFile(buf, '\\');
367 path_share = std::string(buf) + "\\..";
369 // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
370 DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
371 FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
373 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
379 #elif defined(__linux__)
381 bool setSystemPaths()
385 if (!getCurrentExecPath(buf, sizeof(buf))) {
387 errorstream << "Unable to read bindir "<< std::endl;
389 FATAL_ERROR("Unable to read bindir");
394 pathRemoveFile(buf, '/');
395 std::string bindir(buf);
397 // Find share directory from these.
398 // It is identified by containing the subdirectory "builtin".
399 std::list<std::string> trylist;
400 std::string static_sharedir = STATIC_SHAREDIR;
401 if (!static_sharedir.empty() && static_sharedir != ".")
402 trylist.push_back(static_sharedir);
404 trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
405 DIR_DELIM + PROJECT_NAME);
406 trylist.push_back(bindir + DIR_DELIM "..");
409 trylist.push_back(path_user);
412 for (std::list<std::string>::const_iterator
413 i = trylist.begin(); i != trylist.end(); ++i) {
414 const std::string &trypath = *i;
415 if (!fs::PathExists(trypath) ||
416 !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
417 warningstream << "system-wide share not found at \""
418 << trypath << "\""<< std::endl;
422 // Warn if was not the first alternative
423 if (i != trylist.begin()) {
424 warningstream << "system-wide share found at \""
425 << trypath << "\"" << std::endl;
428 path_share = trypath;
433 path_user = std::string(getenv("HOME")) + DIR_DELIM "."
442 #elif defined(__APPLE__)
444 bool setSystemPaths()
446 CFBundleRef main_bundle = CFBundleGetMainBundle();
447 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
449 if (CFURLGetFileSystemRepresentation(resources_url,
450 TRUE, (UInt8 *)path, PATH_MAX)) {
451 path_share = std::string(path);
453 warningstream << "Could not determine bundle resource path" << std::endl;
455 CFRelease(resources_url);
457 path_user = std::string(getenv("HOME"))
458 + "/Library/Application Support/"
466 bool setSystemPaths()
468 path_share = STATIC_SHAREDIR;
469 path_user = std::string(getenv("HOME")) + DIR_DELIM "."
470 + lowercase(PROJECT_NAME);
477 void migrateCachePath()
479 const std::string local_cache_path = path_user + DIR_DELIM + "cache";
481 // Delete tmp folder if it exists (it only ever contained
482 // a temporary ogg file, which is no longer used).
483 if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
484 fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
486 // Bail if migration impossible
487 if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
488 || fs::PathExists(path_cache)) {
491 if (!fs::Rename(local_cache_path, path_cache)) {
492 errorstream << "Failed to migrate local cache path "
493 "to system path!" << std::endl;
497 void initializePaths()
502 infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
505 getCurrentExecPath(buf, sizeof(buf)) ||
506 getExecPathFromProcfs(buf, sizeof(buf));
509 pathRemoveFile(buf, DIR_DELIM_CHAR);
510 std::string execpath(buf);
512 path_share = execpath + DIR_DELIM "..";
513 path_user = execpath + DIR_DELIM "..";
515 if (detectMSVCBuildDir(execpath)) {
516 path_share += DIR_DELIM "..";
517 path_user += DIR_DELIM "..";
520 errorstream << "Failed to get paths by executable location, "
521 "trying cwd" << std::endl;
523 if (!getCurrentWorkingDir(buf, sizeof(buf)))
524 FATAL_ERROR("Ran out of methods to get paths");
526 size_t cwdlen = strlen(buf);
527 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
532 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
533 pathRemoveFile(buf, DIR_DELIM_CHAR);
535 std::string execpath(buf);
537 path_share = execpath;
538 path_user = execpath;
540 path_cache = path_user + DIR_DELIM + "cache";
542 infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
544 if (!setSystemPaths())
545 errorstream << "Failed to get one or more system-wide path" << std::endl;
547 // Initialize path_cache
548 // First try $XDG_CACHE_HOME/PROJECT_NAME
549 const char *cache_dir = getenv("XDG_CACHE_HOME");
550 const char *home_dir = getenv("HOME");
552 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
553 } else if (home_dir) {
554 // Then try $HOME/.cache/PROJECT_NAME
555 path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
556 + DIR_DELIM + PROJECT_NAME;
558 // If neither works, use $PATH_USER/cache
559 path_cache = path_user + DIR_DELIM + "cache";
561 // Migrate cache folder to new location if possible
565 infostream << "Detected share path: " << path_share << std::endl;
566 infostream << "Detected user path: " << path_user << std::endl;
567 infostream << "Detected cache path: " << path_cache << std::endl;
570 bool found_localedir = false;
571 # ifdef STATIC_LOCALEDIR
572 if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
573 found_localedir = true;
574 path_locale = STATIC_LOCALEDIR;
575 infostream << "Using locale directory " << STATIC_LOCALEDIR << std::endl;
577 path_locale = getDataPath("locale");
578 if (fs::PathExists(path_locale)) {
579 found_localedir = true;
580 infostream << "Using in-place locale directory " << path_locale
581 << " even though a static one was provided "
582 << "(RUN_IN_PLACE or CUSTOM_LOCALEDIR)." << std::endl;
586 path_locale = getDataPath("locale");
587 if (fs::PathExists(path_locale)) {
588 found_localedir = true;
591 if (!found_localedir) {
592 warningstream << "Couldn't find a locale directory!" << std::endl;
594 #endif // USE_GETTEXT
598 //// OS-specific Secure Random
603 bool secure_rand_fill_buf(void *buf, size_t len)
607 if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
610 CryptGenRandom(wctx, len, (BYTE *)buf);
611 CryptReleaseContext(wctx, 0);
617 bool secure_rand_fill_buf(void *buf, size_t len)
619 // N.B. This function checks *only* for /dev/urandom, because on most
620 // common OSes it is non-blocking, whereas /dev/random is blocking, and it
621 // is exceptionally uncommon for there to be a situation where /dev/random
622 // exists but /dev/urandom does not. This guesswork is necessary since
623 // random devices are not covered by any POSIX standard...
624 FILE *fp = fopen("/dev/urandom", "rb");
628 bool success = fread(buf, len, 1, fp) == 1;
636 void attachOrCreateConsole()
639 static bool consoleAllocated = false;
640 const bool redirected = (_fileno(stdout) == -2 || _fileno(stdout) == -1); // If output is redirected to e.g a file
641 if (!consoleAllocated && redirected && (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())) {
642 freopen("CONOUT$", "w", stdout);
643 freopen("CONOUT$", "w", stderr);
644 consoleAllocated = true;
649 // Load performance counter frequency only once at startup
652 inline double get_perf_freq()
655 QueryPerformanceFrequency(&freq);
656 return freq.QuadPart;
659 double perf_freq = get_perf_freq();
663 } //namespace porting