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>
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>
63 #include "util/string.h"
72 Signal handler (grabs Ctrl-C on POSIX systems)
75 bool g_killed
= false;
77 bool *signal_handler_killstatus()
82 #if !defined(_WIN32) // POSIX
85 void signal_handler(int sig
)
89 dstream
<< "INFO: signal_handler(): "
90 << "Ctrl-C pressed, shutting down." << std::endl
;
91 } else if (sig
== SIGTERM
) {
92 dstream
<< "INFO: signal_handler(): "
93 << "got SIGTERM, shutting down." << std::endl
;
96 // Comment out for less clutter when testing scripts
97 /*dstream << "INFO: sigint_handler(): "
98 << "Printing debug stacks" << std::endl;
99 debug_stacks_print();*/
103 (void)signal(sig
, SIG_DFL
);
107 void signal_handler_init(void)
109 (void)signal(SIGINT
, signal_handler
);
110 (void)signal(SIGTERM
, signal_handler
);
116 BOOL WINAPI
event_handler(DWORD sig
)
120 case CTRL_CLOSE_EVENT
:
121 case CTRL_LOGOFF_EVENT
:
122 case CTRL_SHUTDOWN_EVENT
:
124 dstream
<< "INFO: event_handler(): "
125 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
126 " shutting down." << std::endl
;
129 (void)signal(SIGINT
, SIG_DFL
);
132 case CTRL_BREAK_EVENT
:
139 void signal_handler_init(void)
141 SetConsoleCtrlHandler((PHANDLER_ROUTINE
)event_handler
, TRUE
);
151 // Default to RUN_IN_PLACE style relative paths
152 std::string path_share
= "..";
153 std::string path_user
= "..";
154 std::string path_locale
= path_share
+ DIR_DELIM
+ "locale";
155 std::string path_cache
= path_user
+ DIR_DELIM
+ "cache";
158 std::string
getDataPath(const char *subpath
)
160 return path_share
+ DIR_DELIM
+ subpath
;
163 void pathRemoveFile(char *path
, char delim
)
165 // Remove filename and path delimiter
167 for(i
= strlen(path
)-1; i
>=0; i
--)
175 bool detectMSVCBuildDir(const std::string
&path
)
177 const char *ends
[] = {
180 "bin\\RelWithDebInfo",
185 return (!removeStringEnd(path
, ends
).empty());
188 std::string
get_sysinfo()
192 std::ostringstream oss
;
193 LPSTR filePath
= new char[MAX_PATH
];
195 VS_FIXEDFILEINFO
*fixedFileInfo
;
197 GetSystemDirectoryA(filePath
, MAX_PATH
);
198 PathAppendA(filePath
, "kernel32.dll");
200 DWORD dwVersionSize
= GetFileVersionInfoSizeA(filePath
, NULL
);
201 LPBYTE lpVersionInfo
= new BYTE
[dwVersionSize
];
203 GetFileVersionInfoA(filePath
, 0, dwVersionSize
, lpVersionInfo
);
204 VerQueryValueA(lpVersionInfo
, "\\", (LPVOID
*)&fixedFileInfo
, &blockSize
);
207 << HIWORD(fixedFileInfo
->dwProductVersionMS
) << '.' // Major
208 << LOWORD(fixedFileInfo
->dwProductVersionMS
) << '.' // Minor
209 << HIWORD(fixedFileInfo
->dwProductVersionLS
) << ' '; // Build
215 if (IsWow64Process(GetCurrentProcess(), &is64
) && is64
)
216 oss
<< "x86_64"; // 32-bit app on 64-bit OS
221 delete[] lpVersionInfo
;
226 struct utsname osinfo
;
228 return std::string(osinfo
.sysname
) + "/"
229 + osinfo
.release
+ " " + osinfo
.machine
;
234 bool getCurrentWorkingDir(char *buf
, size_t len
)
237 DWORD ret
= GetCurrentDirectory(len
, buf
);
238 return (ret
!= 0) && (ret
<= len
);
240 return getcwd(buf
, len
);
245 bool getExecPathFromProcfs(char *buf
, size_t buflen
)
251 if ((len
= readlink("/proc/self/exe", buf
, buflen
)) == -1 &&
252 (len
= readlink("/proc/curproc/file", buf
, buflen
)) == -1 &&
253 (len
= readlink("/proc/curproc/exe", buf
, buflen
)) == -1)
266 bool getCurrentExecPath(char *buf
, size_t len
)
268 DWORD written
= GetModuleFileNameA(NULL
, buf
, len
);
269 if (written
== 0 || written
== len
)
277 #elif defined(__linux__)
279 bool getCurrentExecPath(char *buf
, size_t len
)
281 if (!getExecPathFromProcfs(buf
, len
))
288 //// Mac OS X, Darwin
289 #elif defined(__APPLE__)
291 bool getCurrentExecPath(char *buf
, size_t len
)
293 uint32_t lenb
= (uint32_t)len
;
294 if (_NSGetExecutablePath(buf
, &lenb
) == -1)
301 //// FreeBSD, NetBSD, DragonFlyBSD
302 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
304 bool getCurrentExecPath(char *buf
, size_t len
)
306 // Try getting path from procfs first, since valgrind
307 // doesn't work with the latter
308 if (getExecPathFromProcfs(buf
, len
))
315 mib
[2] = KERN_PROC_PATHNAME
;
318 if (sysctl(mib
, 4, buf
, &len
, NULL
, 0) == -1)
326 #elif defined(__sun) || defined(sun)
328 bool getCurrentExecPath(char *buf
, size_t len
)
330 const char *exec
= getexecname();
334 if (strlcpy(buf
, exec
, len
) >= len
)
342 #elif defined(__hpux)
344 bool getCurrentExecPath(char *buf
, size_t len
)
346 struct pst_status psts
;
348 if (pstat_getproc(&psts
, sizeof(psts
), 0, getpid()) == -1)
351 if (pstat_getpathname(buf
, len
, &psts
.pst_fid_text
) == -1)
360 bool getCurrentExecPath(char *buf
, size_t len
)
371 const char *getHomeOrFail()
373 const char *home
= getenv("HOME");
374 // In rare cases the HOME environment variable may be unset
375 FATAL_ERROR_IF(!home
,
376 "Required environment variable HOME is not set");
386 bool setSystemPaths()
390 // Find path of executable and set path_share relative to it
391 FATAL_ERROR_IF(!getCurrentExecPath(buf
, sizeof(buf
)),
392 "Failed to get current executable path");
393 pathRemoveFile(buf
, '\\');
395 std::string
exepath(buf
);
398 path_share
= exepath
+ "\\..";
399 if (detectMSVCBuildDir(exepath
)) {
400 // The msvc build dir schould normaly not be present if properly installed,
401 // but its usefull for debugging.
402 path_share
+= DIR_DELIM
"..";
405 // Use "C:\Users\<user>\AppData\Roaming\<PROJECT_NAME_C>"
406 DWORD len
= GetEnvironmentVariable("APPDATA", buf
, sizeof(buf
));
407 FATAL_ERROR_IF(len
== 0 || len
> sizeof(buf
), "Failed to get APPDATA");
409 path_user
= std::string(buf
) + DIR_DELIM
+ PROJECT_NAME_C
;
415 #elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
417 bool setSystemPaths()
421 if (!getCurrentExecPath(buf
, sizeof(buf
))) {
423 errorstream
<< "Unable to read bindir "<< std::endl
;
425 FATAL_ERROR("Unable to read bindir");
430 pathRemoveFile(buf
, '/');
431 std::string
bindir(buf
);
433 // Find share directory from these.
434 // It is identified by containing the subdirectory "builtin".
435 std::list
<std::string
> trylist
;
436 std::string static_sharedir
= STATIC_SHAREDIR
;
437 if (!static_sharedir
.empty() && static_sharedir
!= ".")
438 trylist
.push_back(static_sharedir
);
440 trylist
.push_back(bindir
+ DIR_DELIM
".." DIR_DELIM
"share"
441 DIR_DELIM
+ PROJECT_NAME
);
442 trylist
.push_back(bindir
+ DIR_DELIM
"..");
445 trylist
.push_back(path_user
);
448 for (std::list
<std::string
>::const_iterator
449 i
= trylist
.begin(); i
!= trylist
.end(); ++i
) {
450 const std::string
&trypath
= *i
;
451 if (!fs::PathExists(trypath
) ||
452 !fs::PathExists(trypath
+ DIR_DELIM
+ "builtin")) {
453 warningstream
<< "system-wide share not found at \""
454 << trypath
<< "\""<< std::endl
;
458 // Warn if was not the first alternative
459 if (i
!= trylist
.begin()) {
460 warningstream
<< "system-wide share found at \""
461 << trypath
<< "\"" << std::endl
;
464 path_share
= trypath
;
469 path_user
= std::string(getHomeOrFail()) + DIR_DELIM
"."
478 #elif defined(__APPLE__)
480 bool setSystemPaths()
482 CFBundleRef main_bundle
= CFBundleGetMainBundle();
483 CFURLRef resources_url
= CFBundleCopyResourcesDirectoryURL(main_bundle
);
485 if (CFURLGetFileSystemRepresentation(resources_url
,
486 TRUE
, (UInt8
*)path
, PATH_MAX
)) {
487 path_share
= std::string(path
);
489 warningstream
<< "Could not determine bundle resource path" << std::endl
;
491 CFRelease(resources_url
);
493 path_user
= std::string(getHomeOrFail())
494 + "/Library/Application Support/"
502 bool setSystemPaths()
504 path_share
= STATIC_SHAREDIR
;
505 path_user
= std::string(getHomeOrFail()) + DIR_DELIM
"."
506 + lowercase(PROJECT_NAME
);
513 void migrateCachePath()
515 const std::string local_cache_path
= path_user
+ DIR_DELIM
+ "cache";
517 // Delete tmp folder if it exists (it only ever contained
518 // a temporary ogg file, which is no longer used).
519 if (fs::PathExists(local_cache_path
+ DIR_DELIM
+ "tmp"))
520 fs::RecursiveDelete(local_cache_path
+ DIR_DELIM
+ "tmp");
522 // Bail if migration impossible
523 if (path_cache
== local_cache_path
|| !fs::PathExists(local_cache_path
)
524 || fs::PathExists(path_cache
)) {
527 if (!fs::Rename(local_cache_path
, path_cache
)) {
528 errorstream
<< "Failed to migrate local cache path "
529 "to system path!" << std::endl
;
533 void initializePaths()
538 infostream
<< "Using relative paths (RUN_IN_PLACE)" << std::endl
;
541 getCurrentExecPath(buf
, sizeof(buf
)) ||
542 getExecPathFromProcfs(buf
, sizeof(buf
));
545 pathRemoveFile(buf
, DIR_DELIM_CHAR
);
546 std::string
execpath(buf
);
548 path_share
= execpath
+ DIR_DELIM
"..";
549 path_user
= execpath
+ DIR_DELIM
"..";
551 if (detectMSVCBuildDir(execpath
)) {
552 path_share
+= DIR_DELIM
"..";
553 path_user
+= DIR_DELIM
"..";
556 errorstream
<< "Failed to get paths by executable location, "
557 "trying cwd" << std::endl
;
559 if (!getCurrentWorkingDir(buf
, sizeof(buf
)))
560 FATAL_ERROR("Ran out of methods to get paths");
562 size_t cwdlen
= strlen(buf
);
563 if (cwdlen
>= 1 && buf
[cwdlen
- 1] == DIR_DELIM_CHAR
) {
568 if (cwdlen
>= 4 && !strcmp(buf
+ cwdlen
- 4, DIR_DELIM
"bin"))
569 pathRemoveFile(buf
, DIR_DELIM_CHAR
);
571 std::string
execpath(buf
);
573 path_share
= execpath
;
574 path_user
= execpath
;
576 path_cache
= path_user
+ DIR_DELIM
+ "cache";
578 infostream
<< "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl
;
580 if (!setSystemPaths())
581 errorstream
<< "Failed to get one or more system-wide path" << std::endl
;
585 path_cache
= path_user
+ DIR_DELIM
+ "cache";
587 // Initialize path_cache
588 // First try $XDG_CACHE_HOME/PROJECT_NAME
589 const char *cache_dir
= getenv("XDG_CACHE_HOME");
590 const char *home_dir
= getenv("HOME");
592 path_cache
= std::string(cache_dir
) + DIR_DELIM
+ PROJECT_NAME
;
593 } else if (home_dir
) {
594 // Then try $HOME/.cache/PROJECT_NAME
595 path_cache
= std::string(home_dir
) + DIR_DELIM
+ ".cache"
596 + DIR_DELIM
+ PROJECT_NAME
;
598 // If neither works, use $PATH_USER/cache
599 path_cache
= path_user
+ DIR_DELIM
+ "cache";
601 // Migrate cache folder to new location if possible
604 #endif // RUN_IN_PLACE
606 infostream
<< "Detected share path: " << path_share
<< std::endl
;
607 infostream
<< "Detected user path: " << path_user
<< std::endl
;
608 infostream
<< "Detected cache path: " << path_cache
<< std::endl
;
611 bool found_localedir
= false;
612 # ifdef STATIC_LOCALEDIR
613 /* STATIC_LOCALEDIR may be a generalized path such as /usr/share/locale that
614 * doesn't necessarily contain our locale files, so check data path first. */
615 path_locale
= getDataPath("locale");
616 if (fs::PathExists(path_locale
)) {
617 found_localedir
= true;
618 infostream
<< "Using in-place locale directory " << path_locale
619 << " even though a static one was provided." << std::endl
;
620 } else if (STATIC_LOCALEDIR
[0] && fs::PathExists(STATIC_LOCALEDIR
)) {
621 found_localedir
= true;
622 path_locale
= STATIC_LOCALEDIR
;
623 infostream
<< "Using static locale directory " << STATIC_LOCALEDIR
627 path_locale
= getDataPath("locale");
628 if (fs::PathExists(path_locale
)) {
629 found_localedir
= true;
632 if (!found_localedir
) {
633 warningstream
<< "Couldn't find a locale directory!" << std::endl
;
635 #endif // USE_GETTEXT
639 //// OS-specific Secure Random
644 bool secure_rand_fill_buf(void *buf
, size_t len
)
648 if (!CryptAcquireContext(&wctx
, NULL
, NULL
, PROV_RSA_FULL
, CRYPT_VERIFYCONTEXT
))
651 CryptGenRandom(wctx
, len
, (BYTE
*)buf
);
652 CryptReleaseContext(wctx
, 0);
658 bool secure_rand_fill_buf(void *buf
, size_t len
)
660 // N.B. This function checks *only* for /dev/urandom, because on most
661 // common OSes it is non-blocking, whereas /dev/random is blocking, and it
662 // is exceptionally uncommon for there to be a situation where /dev/random
663 // exists but /dev/urandom does not. This guesswork is necessary since
664 // random devices are not covered by any POSIX standard...
665 FILE *fp
= fopen("/dev/urandom", "rb");
669 bool success
= fread(buf
, len
, 1, fp
) == 1;
677 void attachOrCreateConsole()
680 static bool consoleAllocated
= false;
681 const bool redirected
= (_fileno(stdout
) == -2 || _fileno(stdout
) == -1); // If output is redirected to e.g a file
682 if (!consoleAllocated
&& redirected
&& (AttachConsole(ATTACH_PARENT_PROCESS
) || AllocConsole())) {
683 freopen("CONOUT$", "w", stdout
);
684 freopen("CONOUT$", "w", stderr
);
685 consoleAllocated
= true;
690 int mt_snprintf(char *buf
, const size_t buf_size
, const char *fmt
, ...)
692 // https://msdn.microsoft.com/en-us/library/bt7tawza.aspx
693 // Many of the MSVC / Windows printf-style functions do not support positional
694 // arguments (eg. "%1$s"). We just forward the call to vsnprintf for sane
695 // platforms, but defer to _vsprintf_p on MSVC / Windows.
696 // https://github.com/FFmpeg/FFmpeg/blob/5ae9fa13f5ac640bec113120d540f70971aa635d/compat/msvcrt/snprintf.c#L46
697 // _vsprintf_p has to be shimmed with _vscprintf_p on -1 (for an example see
698 // above FFmpeg link).
702 int c
= vsnprintf(buf
, buf_size
, fmt
, args
);
704 int c
= _vsprintf_p(buf
, buf_size
, fmt
, args
);
706 c
= _vscprintf_p(fmt
, args
);
712 bool openURL(const std::string
&url
)
714 if ((url
.substr(0, 7) != "http://" && url
.substr(0, 8) != "https://") ||
715 url
.find_first_of("\r\n") != std::string::npos
) {
716 errorstream
<< "Invalid url: " << url
<< std::endl
;
721 return (intptr_t)ShellExecuteA(NULL
, NULL
, url
.c_str(), NULL
, NULL
, SW_SHOWNORMAL
) > 32;
722 #elif defined(__ANDROID__)
725 #elif defined(__APPLE__)
726 const char *argv
[] = {"open", url
.c_str(), NULL
};
727 return posix_spawnp(NULL
, "open", NULL
, NULL
, (char**)argv
,
728 (*_NSGetEnviron())) == 0;
730 const char *argv
[] = {"xdg-open", url
.c_str(), NULL
};
731 return posix_spawnp(NULL
, "xdg-open", NULL
, NULL
, (char**)argv
, environ
) == 0;
735 // Load performance counter frequency only once at startup
738 inline double get_perf_freq()
741 QueryPerformanceFrequency(&freq
);
742 return freq
.QuadPart
;
745 double perf_freq
= get_perf_freq();
749 } //namespace porting