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>
38 #include <sys/utsname.h>
42 #include <sys/pstat.h>
49 #include "util/string.h"
57 Signal handler (grabs Ctrl-C on POSIX systems)
60 bool g_killed = false;
62 bool * signal_handler_killstatus(void)
67 #if !defined(_WIN32) // POSIX
70 void signal_handler(int sig)
74 dstream << "INFO: signal_handler(): "
75 << "Ctrl-C pressed, shutting down." << std::endl;
76 } else if (sig == SIGTERM) {
77 dstream << "INFO: signal_handler(): "
78 << "got SIGTERM, shutting down." << std::endl;
81 // Comment out for less clutter when testing scripts
82 /*dstream << "INFO: sigint_handler(): "
83 << "Printing debug stacks" << std::endl;
84 debug_stacks_print();*/
88 (void)signal(sig, SIG_DFL);
92 void signal_handler_init(void)
94 (void)signal(SIGINT, signal_handler);
95 (void)signal(SIGTERM, signal_handler);
101 BOOL WINAPI event_handler(DWORD sig)
105 case CTRL_CLOSE_EVENT:
106 case CTRL_LOGOFF_EVENT:
107 case CTRL_SHUTDOWN_EVENT:
109 dstream << "INFO: event_handler(): "
110 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
111 " shutting down." << std::endl;
114 (void)signal(SIGINT, SIG_DFL);
117 case CTRL_BREAK_EVENT:
124 void signal_handler_init(void)
126 SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
136 // Default to RUN_IN_PLACE style relative paths
137 std::string path_share = "..";
138 std::string path_user = "..";
139 std::string path_locale = path_share + DIR_DELIM + "locale";
140 std::string path_cache = path_user + DIR_DELIM + "cache";
143 std::string getDataPath(const char *subpath)
145 return path_share + DIR_DELIM + subpath;
148 void pathRemoveFile(char *path, char delim)
150 // Remove filename and path delimiter
152 for(i = strlen(path)-1; i>=0; i--)
160 bool detectMSVCBuildDir(const std::string &path)
162 const char *ends[] = {
165 "bin\\RelWithDebInfo",
170 return (removeStringEnd(path, ends) != "");
173 std::string get_sysinfo()
177 std::ostringstream oss;
179 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
180 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
182 tmp = osvi.szCSDVersion;
183 std::replace(tmp.begin(), tmp.end(), ' ', '_');
185 oss << "Windows/" << osvi.dwMajorVersion << "."
186 << osvi.dwMinorVersion;
187 if (osvi.szCSDVersion[0])
194 if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
195 oss << "x86_64"; // 32-bit app on 64-bit OS
202 struct utsname osinfo;
204 return std::string(osinfo.sysname) + "/"
205 + osinfo.release + " " + osinfo.machine;
210 bool getCurrentWorkingDir(char *buf, size_t len)
213 DWORD ret = GetCurrentDirectory(len, buf);
214 return (ret != 0) && (ret <= len);
216 return getcwd(buf, len);
221 bool getExecPathFromProcfs(char *buf, size_t buflen)
227 if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
228 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
229 (len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
242 bool getCurrentExecPath(char *buf, size_t len)
244 DWORD written = GetModuleFileNameA(NULL, buf, len);
245 if (written == 0 || written == len)
253 #elif defined(__linux__)
255 bool getCurrentExecPath(char *buf, size_t len)
257 if (!getExecPathFromProcfs(buf, len))
264 //// Mac OS X, Darwin
265 #elif defined(__APPLE__)
267 bool getCurrentExecPath(char *buf, size_t len)
269 uint32_t lenb = (uint32_t)len;
270 if (_NSGetExecutablePath(buf, &lenb) == -1)
277 //// FreeBSD, NetBSD, DragonFlyBSD
278 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
280 bool getCurrentExecPath(char *buf, size_t len)
282 // Try getting path from procfs first, since valgrind
283 // doesn't work with the latter
284 if (getExecPathFromProcfs(buf, len))
291 mib[2] = KERN_PROC_PATHNAME;
294 if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
302 #elif defined(__sun) || defined(sun)
304 bool getCurrentExecPath(char *buf, size_t len)
306 const char *exec = getexecname();
310 if (strlcpy(buf, exec, len) >= len)
318 #elif defined(__hpux)
320 bool getCurrentExecPath(char *buf, size_t len)
322 struct pst_status psts;
324 if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
327 if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
336 bool getCurrentExecPath(char *buf, size_t len)
347 bool setSystemPaths()
351 // Find path of executable and set path_share relative to it
352 FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
353 "Failed to get current executable path");
354 pathRemoveFile(buf, '\\');
357 path_share = std::string(buf) + "\\..";
359 // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
360 DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
361 FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
363 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
369 #elif defined(__linux__)
371 bool setSystemPaths()
375 if (!getCurrentExecPath(buf, sizeof(buf))) {
377 errorstream << "Unable to read bindir "<< std::endl;
379 FATAL_ERROR("Unable to read bindir");
384 pathRemoveFile(buf, '/');
385 std::string bindir(buf);
387 // Find share directory from these.
388 // It is identified by containing the subdirectory "builtin".
389 std::list<std::string> trylist;
390 std::string static_sharedir = STATIC_SHAREDIR;
391 if (static_sharedir != "" && static_sharedir != ".")
392 trylist.push_back(static_sharedir);
394 trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
395 DIR_DELIM + PROJECT_NAME);
396 trylist.push_back(bindir + DIR_DELIM "..");
399 trylist.push_back(path_user);
402 for (std::list<std::string>::const_iterator
403 i = trylist.begin(); i != trylist.end(); ++i) {
404 const std::string &trypath = *i;
405 if (!fs::PathExists(trypath) ||
406 !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
407 warningstream << "system-wide share not found at \""
408 << trypath << "\""<< std::endl;
412 // Warn if was not the first alternative
413 if (i != trylist.begin()) {
414 warningstream << "system-wide share found at \""
415 << trypath << "\"" << std::endl;
418 path_share = trypath;
423 path_user = std::string(getenv("HOME")) + DIR_DELIM "."
432 #elif defined(__APPLE__)
434 bool setSystemPaths()
436 CFBundleRef main_bundle = CFBundleGetMainBundle();
437 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
439 if (CFURLGetFileSystemRepresentation(resources_url,
440 TRUE, (UInt8 *)path, PATH_MAX)) {
441 path_share = std::string(path);
443 warningstream << "Could not determine bundle resource path" << std::endl;
445 CFRelease(resources_url);
447 path_user = std::string(getenv("HOME"))
448 + "/Library/Application Support/"
456 bool setSystemPaths()
458 path_share = STATIC_SHAREDIR;
459 path_user = std::string(getenv("HOME")) + DIR_DELIM "."
460 + lowercase(PROJECT_NAME);
467 void migrateCachePath()
469 const std::string local_cache_path = path_user + DIR_DELIM + "cache";
471 // Delete tmp folder if it exists (it only ever contained
472 // a temporary ogg file, which is no longer used).
473 if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
474 fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
476 // Bail if migration impossible
477 if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
478 || fs::PathExists(path_cache)) {
481 if (!fs::Rename(local_cache_path, path_cache)) {
482 errorstream << "Failed to migrate local cache path "
483 "to system path!" << std::endl;
487 void initializePaths()
492 infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
495 getCurrentExecPath(buf, sizeof(buf)) ||
496 getExecPathFromProcfs(buf, sizeof(buf));
499 pathRemoveFile(buf, DIR_DELIM_CHAR);
500 std::string execpath(buf);
502 path_share = execpath + DIR_DELIM "..";
503 path_user = execpath + DIR_DELIM "..";
505 if (detectMSVCBuildDir(execpath)) {
506 path_share += DIR_DELIM "..";
507 path_user += DIR_DELIM "..";
510 errorstream << "Failed to get paths by executable location, "
511 "trying cwd" << std::endl;
513 if (!getCurrentWorkingDir(buf, sizeof(buf)))
514 FATAL_ERROR("Ran out of methods to get paths");
516 size_t cwdlen = strlen(buf);
517 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
522 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
523 pathRemoveFile(buf, DIR_DELIM_CHAR);
525 std::string execpath(buf);
527 path_share = execpath;
528 path_user = execpath;
530 path_cache = path_user + DIR_DELIM + "cache";
532 infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
534 if (!setSystemPaths())
535 errorstream << "Failed to get one or more system-wide path" << std::endl;
537 // Initialize path_cache
538 // First try $XDG_CACHE_HOME/PROJECT_NAME
539 const char *cache_dir = getenv("XDG_CACHE_HOME");
540 const char *home_dir = getenv("HOME");
542 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
543 } else if (home_dir) {
544 // Then try $HOME/.cache/PROJECT_NAME
545 path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
546 + DIR_DELIM + PROJECT_NAME;
548 // If neither works, use $PATH_USER/cache
549 path_cache = path_user + DIR_DELIM + "cache";
551 // Migrate cache folder to new location if possible
555 infostream << "Detected share path: " << path_share << std::endl;
556 infostream << "Detected user path: " << path_user << std::endl;
557 infostream << "Detected cache path: " << path_cache << std::endl;
560 bool found_localedir = false;
561 # ifdef STATIC_LOCALEDIR
562 if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
563 found_localedir = true;
564 path_locale = STATIC_LOCALEDIR;
565 infostream << "Using locale directory " << STATIC_LOCALEDIR << std::endl;
567 path_locale = getDataPath("locale");
568 if (fs::PathExists(path_locale)) {
569 found_localedir = true;
570 infostream << "Using in-place locale directory " << path_locale
571 << " even though a static one was provided "
572 << "(RUN_IN_PLACE or CUSTOM_LOCALEDIR)." << std::endl;
576 path_locale = getDataPath("locale");
577 if (fs::PathExists(path_locale)) {
578 found_localedir = true;
581 if (!found_localedir) {
582 warningstream << "Couldn't find a locale directory!" << std::endl;
584 #endif // USE_GETTEXT
588 //// OS-specific Secure Random
593 bool secure_rand_fill_buf(void *buf, size_t len)
597 if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
600 CryptGenRandom(wctx, len, (BYTE *)buf);
601 CryptReleaseContext(wctx, 0);
607 bool secure_rand_fill_buf(void *buf, size_t len)
609 // N.B. This function checks *only* for /dev/urandom, because on most
610 // common OSes it is non-blocking, whereas /dev/random is blocking, and it
611 // is exceptionally uncommon for there to be a situation where /dev/random
612 // exists but /dev/urandom does not. This guesswork is necessary since
613 // random devices are not covered by any POSIX standard...
614 FILE *fp = fopen("/dev/urandom", "rb");
618 bool success = fread(buf, len, 1, fp) == 1;
626 void attachOrCreateConsole(void)
629 static bool consoleAllocated = false;
630 const bool redirected = (_fileno(stdout) == -2 || _fileno(stdout) == -1); // If output is redirected to e.g a file
631 if (!consoleAllocated && redirected && (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())) {
632 freopen("CONOUT$", "w", stdout);
633 freopen("CONOUT$", "w", stderr);
634 consoleAllocated = true;
639 // Load performance counter frequency only once at startup
642 inline double get_perf_freq()
645 QueryPerformanceFrequency(&freq);
646 return freq.QuadPart;
649 double perf_freq = get_perf_freq();
653 } //namespace porting