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__) || defined(__OpenBSD__)
29 #include <sys/types.h>
30 #include <sys/sysctl.h>
31 extern char **environ
;
41 #include <sys/utsname.h>
42 #if !defined(__ANDROID__)
48 #include <sys/pstat.h>
50 #if defined(__ANDROID__)
51 #include "porting_android.h"
53 #if defined(__APPLE__)
54 // For _NSGetEnviron()
55 // Related: https://gitlab.haskell.org/ghc/ghc/issues/2458
56 #include <crt_externs.h>
59 #if defined(__HAIKU__)
60 #include <FindDirectory.h>
67 #include "util/string.h"
76 Signal handler (grabs Ctrl-C on POSIX systems)
79 bool g_killed
= false;
81 bool *signal_handler_killstatus()
86 #if !defined(_WIN32) // POSIX
89 void signal_handler(int sig
)
93 dstream
<< "INFO: signal_handler(): "
94 << "Ctrl-C pressed, shutting down." << std::endl
;
95 } else if (sig
== SIGTERM
) {
96 dstream
<< "INFO: signal_handler(): "
97 << "got SIGTERM, shutting down." << std::endl
;
100 // Comment out for less clutter when testing scripts
101 /*dstream << "INFO: sigint_handler(): "
102 << "Printing debug stacks" << std::endl;
103 debug_stacks_print();*/
107 (void)signal(sig
, SIG_DFL
);
111 void signal_handler_init(void)
113 (void)signal(SIGINT
, signal_handler
);
114 (void)signal(SIGTERM
, signal_handler
);
120 BOOL WINAPI
event_handler(DWORD sig
)
124 case CTRL_CLOSE_EVENT
:
125 case CTRL_LOGOFF_EVENT
:
126 case CTRL_SHUTDOWN_EVENT
:
128 dstream
<< "INFO: event_handler(): "
129 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
130 " shutting down." << std::endl
;
133 (void)signal(SIGINT
, SIG_DFL
);
136 case CTRL_BREAK_EVENT
:
143 void signal_handler_init(void)
145 SetConsoleCtrlHandler((PHANDLER_ROUTINE
)event_handler
, TRUE
);
155 // Default to RUN_IN_PLACE style relative paths
156 std::string path_share
= "..";
157 std::string path_user
= "..";
158 std::string path_locale
= path_share
+ DIR_DELIM
+ "locale";
159 std::string path_cache
= path_user
+ DIR_DELIM
+ "cache";
162 std::string
getDataPath(const char *subpath
)
164 return path_share
+ DIR_DELIM
+ subpath
;
167 void pathRemoveFile(char *path
, char delim
)
169 // Remove filename and path delimiter
171 for(i
= strlen(path
)-1; i
>=0; i
--)
179 bool detectMSVCBuildDir(const std::string
&path
)
181 const char *ends
[] = {
184 "bin\\RelWithDebInfo",
189 return (!removeStringEnd(path
, ends
).empty());
192 std::string
get_sysinfo()
196 std::ostringstream oss
;
197 LPSTR filePath
= new char[MAX_PATH
];
199 VS_FIXEDFILEINFO
*fixedFileInfo
;
201 GetSystemDirectoryA(filePath
, MAX_PATH
);
202 PathAppendA(filePath
, "kernel32.dll");
204 DWORD dwVersionSize
= GetFileVersionInfoSizeA(filePath
, NULL
);
205 LPBYTE lpVersionInfo
= new BYTE
[dwVersionSize
];
207 GetFileVersionInfoA(filePath
, 0, dwVersionSize
, lpVersionInfo
);
208 VerQueryValueA(lpVersionInfo
, "\\", (LPVOID
*)&fixedFileInfo
, &blockSize
);
211 << HIWORD(fixedFileInfo
->dwProductVersionMS
) << '.' // Major
212 << LOWORD(fixedFileInfo
->dwProductVersionMS
) << '.' // Minor
213 << HIWORD(fixedFileInfo
->dwProductVersionLS
) << ' '; // Build
219 if (IsWow64Process(GetCurrentProcess(), &is64
) && is64
)
220 oss
<< "x86_64"; // 32-bit app on 64-bit OS
225 delete[] lpVersionInfo
;
230 struct utsname osinfo
;
232 return std::string(osinfo
.sysname
) + "/"
233 + osinfo
.release
+ " " + osinfo
.machine
;
238 bool getCurrentWorkingDir(char *buf
, size_t len
)
241 DWORD ret
= GetCurrentDirectory(len
, buf
);
242 return (ret
!= 0) && (ret
<= len
);
244 return getcwd(buf
, len
);
249 bool getExecPathFromProcfs(char *buf
, size_t buflen
)
255 if ((len
= readlink("/proc/self/exe", buf
, buflen
)) == -1 &&
256 (len
= readlink("/proc/curproc/file", buf
, buflen
)) == -1 &&
257 (len
= readlink("/proc/curproc/exe", buf
, buflen
)) == -1)
270 bool getCurrentExecPath(char *buf
, size_t len
)
272 DWORD written
= GetModuleFileNameA(NULL
, buf
, len
);
273 if (written
== 0 || written
== len
)
281 #elif defined(__linux__)
283 bool getCurrentExecPath(char *buf
, size_t len
)
285 if (!getExecPathFromProcfs(buf
, len
))
292 //// Mac OS X, Darwin
293 #elif defined(__APPLE__)
295 bool getCurrentExecPath(char *buf
, size_t len
)
297 uint32_t lenb
= (uint32_t)len
;
298 if (_NSGetExecutablePath(buf
, &lenb
) == -1)
305 //// FreeBSD, NetBSD, DragonFlyBSD
306 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
308 bool getCurrentExecPath(char *buf
, size_t len
)
310 // Try getting path from procfs first, since valgrind
311 // doesn't work with the latter
312 if (getExecPathFromProcfs(buf
, len
))
319 mib
[2] = KERN_PROC_PATHNAME
;
322 if (sysctl(mib
, 4, buf
, &len
, NULL
, 0) == -1)
328 #elif defined(__HAIKU__)
330 bool getCurrentExecPath(char *buf
, size_t len
)
332 return find_path(B_APP_IMAGE_SYMBOL
, B_FIND_PATH_IMAGE_PATH
, NULL
, buf
, len
) == B_OK
;
336 #elif defined(__sun) || defined(sun)
338 bool getCurrentExecPath(char *buf
, size_t len
)
340 const char *exec
= getexecname();
344 if (strlcpy(buf
, exec
, len
) >= len
)
352 #elif defined(__hpux)
354 bool getCurrentExecPath(char *buf
, size_t len
)
356 struct pst_status psts
;
358 if (pstat_getproc(&psts
, sizeof(psts
), 0, getpid()) == -1)
361 if (pstat_getpathname(buf
, len
, &psts
.pst_fid_text
) == -1)
370 bool getCurrentExecPath(char *buf
, size_t len
)
381 const char *getHomeOrFail()
383 const char *home
= getenv("HOME");
384 // In rare cases the HOME environment variable may be unset
385 FATAL_ERROR_IF(!home
,
386 "Required environment variable HOME is not set");
396 bool setSystemPaths()
400 // Find path of executable and set path_share relative to it
401 FATAL_ERROR_IF(!getCurrentExecPath(buf
, sizeof(buf
)),
402 "Failed to get current executable path");
403 pathRemoveFile(buf
, '\\');
405 std::string
exepath(buf
);
408 path_share
= exepath
+ "\\..";
409 if (detectMSVCBuildDir(exepath
)) {
410 // The msvc build dir schould normaly not be present if properly installed,
411 // but its usefull for debugging.
412 path_share
+= DIR_DELIM
"..";
415 // Use "C:\Users\<user>\AppData\Roaming\<PROJECT_NAME_C>"
416 DWORD len
= GetEnvironmentVariable("APPDATA", buf
, sizeof(buf
));
417 FATAL_ERROR_IF(len
== 0 || len
> sizeof(buf
), "Failed to get APPDATA");
419 path_user
= std::string(buf
) + DIR_DELIM
+ PROJECT_NAME_C
;
425 #elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
427 bool setSystemPaths()
431 if (!getCurrentExecPath(buf
, sizeof(buf
))) {
433 errorstream
<< "Unable to read bindir "<< std::endl
;
435 FATAL_ERROR("Unable to read bindir");
440 pathRemoveFile(buf
, '/');
441 std::string
bindir(buf
);
443 // Find share directory from these.
444 // It is identified by containing the subdirectory "builtin".
445 std::list
<std::string
> trylist
;
446 std::string static_sharedir
= STATIC_SHAREDIR
;
447 if (!static_sharedir
.empty() && static_sharedir
!= ".")
448 trylist
.push_back(static_sharedir
);
450 trylist
.push_back(bindir
+ DIR_DELIM
".." DIR_DELIM
"share"
451 DIR_DELIM
+ PROJECT_NAME
);
452 trylist
.push_back(bindir
+ DIR_DELIM
"..");
455 trylist
.push_back(path_user
);
458 for (std::list
<std::string
>::const_iterator
459 i
= trylist
.begin(); i
!= trylist
.end(); ++i
) {
460 const std::string
&trypath
= *i
;
461 if (!fs::PathExists(trypath
) ||
462 !fs::PathExists(trypath
+ DIR_DELIM
+ "builtin")) {
463 warningstream
<< "system-wide share not found at \""
464 << trypath
<< "\""<< std::endl
;
468 // Warn if was not the first alternative
469 if (i
!= trylist
.begin()) {
470 warningstream
<< "system-wide share found at \""
471 << trypath
<< "\"" << std::endl
;
474 path_share
= trypath
;
479 path_user
= std::string(getHomeOrFail()) + DIR_DELIM
"."
488 #elif defined(__APPLE__)
490 bool setSystemPaths()
492 CFBundleRef main_bundle
= CFBundleGetMainBundle();
493 CFURLRef resources_url
= CFBundleCopyResourcesDirectoryURL(main_bundle
);
495 if (CFURLGetFileSystemRepresentation(resources_url
,
496 TRUE
, (UInt8
*)path
, PATH_MAX
)) {
497 path_share
= std::string(path
);
499 warningstream
<< "Could not determine bundle resource path" << std::endl
;
501 CFRelease(resources_url
);
503 path_user
= std::string(getHomeOrFail())
504 + "/Library/Application Support/"
512 bool setSystemPaths()
514 path_share
= STATIC_SHAREDIR
;
515 path_user
= std::string(getHomeOrFail()) + DIR_DELIM
"."
516 + lowercase(PROJECT_NAME
);
523 void migrateCachePath()
525 const std::string local_cache_path
= path_user
+ DIR_DELIM
+ "cache";
527 // Delete tmp folder if it exists (it only ever contained
528 // a temporary ogg file, which is no longer used).
529 if (fs::PathExists(local_cache_path
+ DIR_DELIM
+ "tmp"))
530 fs::RecursiveDelete(local_cache_path
+ DIR_DELIM
+ "tmp");
532 // Bail if migration impossible
533 if (path_cache
== local_cache_path
|| !fs::PathExists(local_cache_path
)
534 || fs::PathExists(path_cache
)) {
537 if (!fs::Rename(local_cache_path
, path_cache
)) {
538 errorstream
<< "Failed to migrate local cache path "
539 "to system path!" << std::endl
;
543 void initializePaths()
548 infostream
<< "Using relative paths (RUN_IN_PLACE)" << std::endl
;
551 getCurrentExecPath(buf
, sizeof(buf
)) ||
552 getExecPathFromProcfs(buf
, sizeof(buf
));
555 pathRemoveFile(buf
, DIR_DELIM_CHAR
);
556 std::string
execpath(buf
);
558 path_share
= execpath
+ DIR_DELIM
"..";
559 path_user
= execpath
+ DIR_DELIM
"..";
561 if (detectMSVCBuildDir(execpath
)) {
562 path_share
+= DIR_DELIM
"..";
563 path_user
+= DIR_DELIM
"..";
566 errorstream
<< "Failed to get paths by executable location, "
567 "trying cwd" << std::endl
;
569 if (!getCurrentWorkingDir(buf
, sizeof(buf
)))
570 FATAL_ERROR("Ran out of methods to get paths");
572 size_t cwdlen
= strlen(buf
);
573 if (cwdlen
>= 1 && buf
[cwdlen
- 1] == DIR_DELIM_CHAR
) {
578 if (cwdlen
>= 4 && !strcmp(buf
+ cwdlen
- 4, DIR_DELIM
"bin"))
579 pathRemoveFile(buf
, DIR_DELIM_CHAR
);
581 std::string
execpath(buf
);
583 path_share
= execpath
;
584 path_user
= execpath
;
586 path_cache
= path_user
+ DIR_DELIM
+ "cache";
588 infostream
<< "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl
;
590 if (!setSystemPaths())
591 errorstream
<< "Failed to get one or more system-wide path" << std::endl
;
595 path_cache
= path_user
+ DIR_DELIM
+ "cache";
597 // Initialize path_cache
598 // First try $XDG_CACHE_HOME/PROJECT_NAME
599 const char *cache_dir
= getenv("XDG_CACHE_HOME");
600 const char *home_dir
= getenv("HOME");
602 path_cache
= std::string(cache_dir
) + DIR_DELIM
+ PROJECT_NAME
;
603 } else if (home_dir
) {
604 // Then try $HOME/.cache/PROJECT_NAME
605 path_cache
= std::string(home_dir
) + DIR_DELIM
+ ".cache"
606 + DIR_DELIM
+ PROJECT_NAME
;
608 // If neither works, use $PATH_USER/cache
609 path_cache
= path_user
+ DIR_DELIM
+ "cache";
611 // Migrate cache folder to new location if possible
614 #endif // RUN_IN_PLACE
616 infostream
<< "Detected share path: " << path_share
<< std::endl
;
617 infostream
<< "Detected user path: " << path_user
<< std::endl
;
618 infostream
<< "Detected cache path: " << path_cache
<< std::endl
;
621 bool found_localedir
= false;
622 # ifdef STATIC_LOCALEDIR
623 /* STATIC_LOCALEDIR may be a generalized path such as /usr/share/locale that
624 * doesn't necessarily contain our locale files, so check data path first. */
625 path_locale
= getDataPath("locale");
626 if (fs::PathExists(path_locale
)) {
627 found_localedir
= true;
628 infostream
<< "Using in-place locale directory " << path_locale
629 << " even though a static one was provided." << std::endl
;
630 } else if (STATIC_LOCALEDIR
[0] && fs::PathExists(STATIC_LOCALEDIR
)) {
631 found_localedir
= true;
632 path_locale
= STATIC_LOCALEDIR
;
633 infostream
<< "Using static locale directory " << STATIC_LOCALEDIR
637 path_locale
= getDataPath("locale");
638 if (fs::PathExists(path_locale
)) {
639 found_localedir
= true;
642 if (!found_localedir
) {
643 warningstream
<< "Couldn't find a locale directory!" << std::endl
;
645 #endif // USE_GETTEXT
649 //// OS-specific Secure Random
654 bool secure_rand_fill_buf(void *buf
, size_t len
)
658 if (!CryptAcquireContext(&wctx
, NULL
, NULL
, PROV_RSA_FULL
, CRYPT_VERIFYCONTEXT
))
661 CryptGenRandom(wctx
, len
, (BYTE
*)buf
);
662 CryptReleaseContext(wctx
, 0);
668 bool secure_rand_fill_buf(void *buf
, size_t len
)
670 // N.B. This function checks *only* for /dev/urandom, because on most
671 // common OSes it is non-blocking, whereas /dev/random is blocking, and it
672 // is exceptionally uncommon for there to be a situation where /dev/random
673 // exists but /dev/urandom does not. This guesswork is necessary since
674 // random devices are not covered by any POSIX standard...
675 FILE *fp
= fopen("/dev/urandom", "rb");
679 bool success
= fread(buf
, len
, 1, fp
) == 1;
687 void attachOrCreateConsole()
690 static bool consoleAllocated
= false;
691 const bool redirected
= (_fileno(stdout
) == -2 || _fileno(stdout
) == -1); // If output is redirected to e.g a file
692 if (!consoleAllocated
&& redirected
&& (AttachConsole(ATTACH_PARENT_PROCESS
) || AllocConsole())) {
693 freopen("CONOUT$", "w", stdout
);
694 freopen("CONOUT$", "w", stderr
);
695 consoleAllocated
= true;
700 int mt_snprintf(char *buf
, const size_t buf_size
, const char *fmt
, ...)
702 // https://msdn.microsoft.com/en-us/library/bt7tawza.aspx
703 // Many of the MSVC / Windows printf-style functions do not support positional
704 // arguments (eg. "%1$s"). We just forward the call to vsnprintf for sane
705 // platforms, but defer to _vsprintf_p on MSVC / Windows.
706 // https://github.com/FFmpeg/FFmpeg/blob/5ae9fa13f5ac640bec113120d540f70971aa635d/compat/msvcrt/snprintf.c#L46
707 // _vsprintf_p has to be shimmed with _vscprintf_p on -1 (for an example see
708 // above FFmpeg link).
712 int c
= vsnprintf(buf
, buf_size
, fmt
, args
);
714 int c
= _vsprintf_p(buf
, buf_size
, fmt
, args
);
716 c
= _vscprintf_p(fmt
, args
);
722 bool openURL(const std::string
&url
)
724 if ((url
.substr(0, 7) != "http://" && url
.substr(0, 8) != "https://") ||
725 url
.find_first_of("\r\n") != std::string::npos
) {
726 errorstream
<< "Invalid url: " << url
<< std::endl
;
731 return (intptr_t)ShellExecuteA(NULL
, NULL
, url
.c_str(), NULL
, NULL
, SW_SHOWNORMAL
) > 32;
732 #elif defined(__ANDROID__)
735 #elif defined(__APPLE__)
736 const char *argv
[] = {"open", url
.c_str(), NULL
};
737 return posix_spawnp(NULL
, "open", NULL
, NULL
, (char**)argv
,
738 (*_NSGetEnviron())) == 0;
740 const char *argv
[] = {"xdg-open", url
.c_str(), NULL
};
741 return posix_spawnp(NULL
, "xdg-open", NULL
, NULL
, (char**)argv
, environ
) == 0;
745 // Load performance counter frequency only once at startup
748 inline double get_perf_freq()
751 QueryPerformanceFrequency(&freq
);
752 return freq
.QuadPart
;
755 double perf_freq
= get_perf_freq();
759 } //namespace porting