Porting: Refactor initalizePaths()

Add support for Solaris and HP-UX
Search additional potential procfs locations for current executable
This commit is contained in:
kwolekr 2015-04-18 20:12:14 -04:00
parent 0c792db05c
commit cd986191f1
3 changed files with 298 additions and 188 deletions

View File

@ -26,9 +26,11 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#ifdef _WIN32 // WINDOWS #ifdef _WIN32 // WINDOWS
#define DIR_DELIM "\\" #define DIR_DELIM "\\"
#define DIR_DELIM_CHAR '\\'
#define FILESYS_CASE_INSENSITIVE 1 #define FILESYS_CASE_INSENSITIVE 1
#else // POSIX #else // POSIX
#define DIR_DELIM "/" #define DIR_DELIM "/"
#define DIR_DELIM_CHAR '/'
#define FILESYS_CASE_INSENSITIVE 0 #define FILESYS_CASE_INSENSITIVE 0
#endif #endif

View File

@ -35,12 +35,14 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include <unistd.h> #include <unistd.h>
#include <sys/utsname.h> #include <sys/utsname.h>
#endif #endif
#if defined(__hpux)
#define _PSTAT64
#include <sys/pstat.h>
#endif
#if !defined(_WIN32) && !defined(__APPLE__) && \ #if !defined(_WIN32) && !defined(__APPLE__) && \
!defined(__ANDROID__) && !defined(SERVER) !defined(__ANDROID__) && !defined(SERVER)
#define XORG_USED #define XORG_USED
#endif #endif
#ifdef XORG_USED #ifdef XORG_USED
#include <X11/Xlib.h> #include <X11/Xlib.h>
#include <X11/Xutil.h> #include <X11/Xutil.h>
@ -99,39 +101,29 @@ void signal_handler_init(void)
#else // _WIN32 #else // _WIN32
#include <signal.h> #include <signal.h>
BOOL WINAPI event_handler(DWORD sig) BOOL WINAPI event_handler(DWORD sig)
{ {
switch(sig) switch (sig) {
{ case CTRL_C_EVENT:
case CTRL_C_EVENT: case CTRL_CLOSE_EVENT:
case CTRL_CLOSE_EVENT: case CTRL_LOGOFF_EVENT:
case CTRL_LOGOFF_EVENT: case CTRL_SHUTDOWN_EVENT:
case CTRL_SHUTDOWN_EVENT: if (g_killed == false) {
dstream << DTIME << "INFO: event_handler(): "
if(g_killed == false) << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
{ " shutting down." << std::endl;
dstream<<DTIME<<"INFO: event_handler(): " g_killed = true;
<<"Ctrl+C, Close Event, Logoff Event or Shutdown Event, shutting down."<<std::endl; } else {
// Comment out for less clutter when testing scripts (void)signal(SIGINT, SIG_DFL);
/*dstream<<DTIME<<"INFO: event_handler(): "
<<"Printing debug stacks"<<std::endl;
debug_stacks_print();*/
g_killed = true;
}
else
{
(void)signal(SIGINT, SIG_DFL);
}
break;
case CTRL_BREAK_EVENT:
break;
} }
break;
return TRUE; case CTRL_BREAK_EVENT:
break;
} }
return TRUE;
}
void signal_handler_init(void) void signal_handler_init(void)
{ {
SetConsoleCtrlHandler( (PHANDLER_ROUTINE)event_handler,TRUE); SetConsoleCtrlHandler( (PHANDLER_ROUTINE)event_handler,TRUE);
@ -143,7 +135,8 @@ void signal_handler_init(void)
/* /*
Multithreading support Multithreading support
*/ */
int getNumberOfProcessors() { int getNumberOfProcessors()
{
#if defined(_SC_NPROCESSORS_ONLN) #if defined(_SC_NPROCESSORS_ONLN)
return sysconf(_SC_NPROCESSORS_ONLN); return sysconf(_SC_NPROCESSORS_ONLN);
@ -177,7 +170,8 @@ int getNumberOfProcessors() {
#ifndef __ANDROID__ #ifndef __ANDROID__
bool threadBindToProcessor(threadid_t tid, int pnumber) { bool threadBindToProcessor(threadid_t tid, int pnumber)
{
#if defined(_WIN32) #if defined(_WIN32)
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid); HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
@ -201,7 +195,7 @@ bool threadBindToProcessor(threadid_t tid, int pnumber) {
#elif defined(__sun) || defined(sun) #elif defined(__sun) || defined(sun)
return processor_bind(P_LWPID, MAKE_LWPID_PTHREAD(tid), return processor_bind(P_LWPID, MAKE_LWPID_PTHREAD(tid),
pnumber, NULL) == 0; pnumber, NULL) == 0;
#elif defined(_AIX) #elif defined(_AIX)
@ -212,7 +206,7 @@ bool threadBindToProcessor(threadid_t tid, int pnumber) {
pthread_spu_t answer; pthread_spu_t answer;
return pthread_processor_bind_np(PTHREAD_BIND_ADVISORY_NP, return pthread_processor_bind_np(PTHREAD_BIND_ADVISORY_NP,
&answer, pnumber, tid) == 0; &answer, pnumber, tid) == 0;
#elif defined(__APPLE__) #elif defined(__APPLE__)
@ -221,7 +215,7 @@ bool threadBindToProcessor(threadid_t tid, int pnumber) {
thread_port_t threadport = pthread_mach_thread_np(tid); thread_port_t threadport = pthread_mach_thread_np(tid);
tapol.affinity_tag = pnumber + 1; tapol.affinity_tag = pnumber + 1;
return thread_policy_set(threadport, THREAD_AFFINITY_POLICY, return thread_policy_set(threadport, THREAD_AFFINITY_POLICY,
(thread_policy_t)&tapol, THREAD_AFFINITY_POLICY_COUNT) == KERN_SUCCESS; (thread_policy_t)&tapol, THREAD_AFFINITY_POLICY_COUNT) == KERN_SUCCESS;
#else #else
@ -231,7 +225,8 @@ bool threadBindToProcessor(threadid_t tid, int pnumber) {
} }
#endif #endif
bool threadSetPriority(threadid_t tid, int prio) { bool threadSetPriority(threadid_t tid, int prio)
{
#if defined(_WIN32) #if defined(_WIN32)
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid); HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
@ -286,14 +281,14 @@ void pathRemoveFile(char *path, char delim)
path[i] = 0; path[i] = 0;
} }
bool detectMSVCBuildDir(char *c_path) bool detectMSVCBuildDir(const std::string &path)
{ {
std::string path(c_path);
const char *ends[] = { const char *ends[] = {
"bin\\Release", "bin\\Release",
"bin\\Debug", "bin\\Debug",
"bin\\Build", "bin\\Build",
NULL}; NULL
};
return (removeStringEnd(path, ends) != ""); return (removeStringEnd(path, ends) != "");
} }
@ -333,224 +328,322 @@ std::string get_sysinfo()
#endif #endif
} }
void initializePaths()
bool getCurrentWorkingDir(char *buf, size_t len)
{ {
#if RUN_IN_PLACE #ifdef _WIN32
/* DWORD ret = GetCurrentDirectory(len, buf);
Use relative paths if RUN_IN_PLACE return (ret != 0) && (ret <= len);
*/ #else
return getcwd(buf, len);
#endif
}
infostream<<"Using relative paths (RUN_IN_PLACE)"<<std::endl;
/* bool getExecPathFromProcfs(char *buf, size_t buflen)
Windows {
*/ #ifndef _WIN32
#if defined(_WIN32) buflen--;
const DWORD buflen = 1000; ssize_t len;
char buf[buflen]; if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
DWORD len; (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
(len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
return false;
// Find path of executable and set path_share relative to it buf[len] = '\0';
len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen); return true;
assert(len < buflen); #else
pathRemoveFile(buf, '\\'); return false;
#endif
}
if(detectMSVCBuildDir(buf)){ //// Windows
infostream<<"MSVC build directory detected"<<std::endl; #if defined(_WIN32)
path_share = std::string(buf) + "\\..\\..";
path_user = std::string(buf) + "\\..\\..";
}
else{
path_share = std::string(buf) + "\\..";
path_user = std::string(buf) + "\\..";
}
/* bool getCurrentExecPath(char *buf, size_t len)
Linux {
*/ DWORD written = GetModuleFileNameA(NULL, buf, len);
#elif defined(linux) || defined(__linux) if (written == 0 || written == len)
return false;
char buf[BUFSIZ]; return true;
memset(buf, 0, BUFSIZ); }
// Get path to executable
FATAL_ERROR_IF(readlink("/proc/self/exe", buf, BUFSIZ-1) == -1, "Failed to get cwd");
pathRemoveFile(buf, '/');
path_share = std::string(buf) + "/.."; //// Linux
path_user = std::string(buf) + "/.."; #elif defined(linux) || defined(__linux) || defined(__linux__)
/* bool getCurrentExecPath(char *buf, size_t len)
OS X {
*/ if (!getExecPathFromProcfs(buf, len))
#elif defined(__APPLE__) return false;
CFBundleRef main_bundle = CFBundleGetMainBundle(); return true;
CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle); }
char path[PATH_MAX];
if (CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX)) {
path_share = std::string(path);
path_user = std::string(path) + "/../User";
} else {
dstream << "WARNING: Could not determine bundle resource path" << std::endl;
}
CFRelease(resources_url);
/*
FreeBSD //// Mac OS X, Darwin
*/ #elif defined(__APPLE__)
#elif defined(__FreeBSD__)
bool getCurrentExecPath(char *buf, size_t len)
{
if (_NSGetExecutablePath(buf, &len) == -1)
return false;
return true;
}
//// FreeBSD, NetBSD, DragonFlyBSD
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
bool getCurrentExecPath(char *buf, size_t len)
{
// Try getting path from procfs first, since valgrind
// doesn't work with the latter
if (getExecPathFromProcfs(buf, len))
return true;
int mib[4]; int mib[4];
char buf[BUFSIZ];
size_t len = sizeof(buf);
mib[0] = CTL_KERN; mib[0] = CTL_KERN;
mib[1] = KERN_PROC; mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PATHNAME; mib[2] = KERN_PROC_PATHNAME;
mib[3] = -1; mib[3] = -1;
FATAL_ERROR_IF(sysctl(mib, 4, buf, &len, NULL, 0) == -1, "");
pathRemoveFile(buf, '/'); if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
return false;
path_share = std::string(buf) + "/.."; return true;
path_user = std::string(buf) + "/.."; }
#else
//TODO: Get path of executable. This assumes working directory is bin/ //// Solaris
dstream<<"WARNING: Relative path not properly supported on this platform" #elif defined(__sun) || defined(sun)
<<std::endl;
/* scriptapi no longer allows paths that start with "..", so assuming that bool getCurrentExecPath(char *buf, size_t len)
the current working directory is bin/, strip off the last component. */ {
char *cwd = getcwd(NULL, 0); const char *exec = getexecname();
pathRemoveFile(cwd, '/'); if (exec == NULL)
path_share = std::string(cwd); return false;
path_user = std::string(cwd);
#endif if (strlcpy(buf, exec, len) >= len)
return false;
#else // RUN_IN_PLACE return true;
}
/*
Use platform-specific paths otherwise
*/
infostream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl; // HP-UX
#elif defined(__hpux)
/* bool getCurrentExecPath(char *buf, size_t len)
Windows {
*/ struct pst_status psts;
#if defined(_WIN32)
const DWORD buflen = 1000; // FIXME: Surely there is a better way to do this if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
char buf[buflen]; return false;
DWORD len;
if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
return false;
return true;
}
#else
bool getCurrentExecPath(char *buf, size_t len)
{
return false;
}
#endif
//// Windows
#if defined(_WIN32)
bool setSystemPaths()
{
char buf[BUFSIZ];
// Find path of executable and set path_share relative to it // Find path of executable and set path_share relative to it
len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen); FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
FATAL_ERROR_IF(len >= buflen, "Overlow"); "Failed to get current executable path");
pathRemoveFile(buf, '\\'); pathRemoveFile(buf, '\\');
// Use ".\bin\.." // Use ".\bin\.."
path_share = std::string(buf) + "\\.."; path_share = std::string(buf) + "\\..";
// Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>" // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
len = GetEnvironmentVariable("APPDATA", buf, buflen); DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
FATAL_ERROR_IF(len >= buflen, "Overlow"); FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
path_user = std::string(buf) + DIR_DELIM + lowercase(PROJECT_NAME); path_user = std::string(buf) + DIR_DELIM + lowercase(PROJECT_NAME);
return true;
}
/*
Linux
*/
#elif defined(linux) || defined(__linux)
// Get path to executable //// Linux
std::string bindir = ""; #elif defined(linux) || defined(__linux)
{
char buf[BUFSIZ]; bool setSystemPaths()
memset(buf, 0, BUFSIZ); {
if (readlink("/proc/self/exe", buf, BUFSIZ-1) == -1) { char buf[BUFSIZ];
errorstream << "Unable to read bindir "<< std::endl;
#ifndef __ANDROID__ if (!getCurrentExecPath(buf, sizeof(buf))) {
FATAL_ERROR("Unable to read bindir"); #ifdef __ANDROID__
errorstream << "Unable to read bindir "<< std::endl;
#else
FATAL_ERROR("Unable to read bindir");
#endif #endif
} else { return false;
pathRemoveFile(buf, '/');
bindir = buf;
}
} }
pathRemoveFile(buf, '/');
std::string bindir(buf);
// Find share directory from these. // Find share directory from these.
// It is identified by containing the subdirectory "builtin". // It is identified by containing the subdirectory "builtin".
std::list<std::string> trylist; std::list<std::string> trylist;
std::string static_sharedir = STATIC_SHAREDIR; std::string static_sharedir = STATIC_SHAREDIR;
if(static_sharedir != "" && static_sharedir != ".") if (static_sharedir != "" && static_sharedir != ".")
trylist.push_back(static_sharedir); trylist.push_back(static_sharedir);
trylist.push_back(
bindir + DIR_DELIM + ".." + DIR_DELIM + "share" + DIR_DELIM + lowercase(PROJECT_NAME)); trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
trylist.push_back(bindir + DIR_DELIM + ".."); DIR_DELIM + lowercase(PROJECT_NAME));
trylist.push_back(bindir + DIR_DELIM "..");
#ifdef __ANDROID__ #ifdef __ANDROID__
trylist.push_back(path_user); trylist.push_back(path_user);
#endif #endif
for(std::list<std::string>::const_iterator i = trylist.begin(); for (std::list<std::string>::const_iterator
i != trylist.end(); i++) i = trylist.begin(); i != trylist.end(); i++) {
{
const std::string &trypath = *i; const std::string &trypath = *i;
if(!fs::PathExists(trypath) || !fs::PathExists(trypath + DIR_DELIM + "builtin")){ if (!fs::PathExists(trypath) ||
dstream<<"WARNING: system-wide share not found at \"" !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
<<trypath<<"\""<<std::endl; dstream << "WARNING: system-wide share not found at \""
<< trypath << "\""<< std::endl;
continue; continue;
} }
// Warn if was not the first alternative // Warn if was not the first alternative
if(i != trylist.begin()){ if (i != trylist.begin()) {
dstream<<"WARNING: system-wide share found at \"" dstream << "WARNING: system-wide share found at \""
<<trypath<<"\""<<std::endl; << trypath << "\"" << std::endl;
} }
path_share = trypath; path_share = trypath;
break; break;
} }
#ifndef __ANDROID__ #ifndef __ANDROID__
path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + lowercase(PROJECT_NAME); path_user = std::string(getenv("HOME")) + DIR_DELIM "."
+ lowercase(PROJECT_NAME);
#endif #endif
/* return true;
OS X }
*/
#elif defined(__APPLE__)
//// Mac OS X
#elif defined(__APPLE__)
bool setSystemPaths()
{
CFBundleRef main_bundle = CFBundleGetMainBundle(); CFBundleRef main_bundle = CFBundleGetMainBundle();
CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle); CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
char path[PATH_MAX]; char path[PATH_MAX];
if (CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX)) { if (CFURLGetFileSystemRepresentation(resources_url,
TRUE, (UInt8 *)path, PATH_MAX)) {
path_share = std::string(path); path_share = std::string(path);
} else { } else {
dstream << "WARNING: Could not determine bundle resource path" << std::endl; dstream << "WARNING: Could not determine bundle resource path" << std::endl;
} }
CFRelease(resources_url); CFRelease(resources_url);
path_user = std::string(getenv("HOME")) + "/Library/Application Support/" + lowercase(PROJECT_NAME); path_user = std::string(getenv("HOME"))
+ "/Library/Application Support/"
#else // FreeBSD, and probably many other POSIX-like systems. + lowercase(PROJECT_NAME);
return true;
path_share = STATIC_SHAREDIR;
path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + lowercase(PROJECT_NAME);
#endif
#endif // RUN_IN_PLACE
} }
static irr::IrrlichtDevice *device;
void initIrrlicht(irr::IrrlichtDevice *device_) #else
bool setSystemPaths()
{ {
device = device_; path_share = STATIC_SHAREDIR;
path_user = std::string(getenv("HOME")) + DIR_DELIM "."
+ lowercase(PROJECT_NAME);
return true;
} }
#endif
void initializePaths()
{
#if RUN_IN_PLACE
char buf[BUFSIZ];
infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
bool success =
getCurrentExecPath(buf, sizeof(buf)) ||
getExecPathFromProcfs(buf, sizeof(buf));
if (success) {
pathRemoveFile(buf, '/');
std::string execpath(buf);
path_share = execpath + DIR_DELIM "..";
path_user = execpath + DIR_DELIM "..";
if (detectMSVCBuildDir(execpath)) {
path_share += DIR_DELIM "..";
path_user += DIR_DELIM "..";
}
} else {
errorstream << "Failed to get paths by executable location, "
"trying cwd" << std::endl;
if (!getCurrentWorkingDir(buf, sizeof(buf)))
FATAL_ERROR("Ran out of methods to get paths");
size_t cwdlen = strlen(buf);
if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
cwdlen--;
buf[cwdlen] = '\0';
}
if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
pathRemoveFile(buf, DIR_DELIM_CHAR);
std::string execpath(buf);
path_share = execpath;
path_user = execpath;
}
#else
infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
if (!setSystemPaths())
errorstream << "Failed to get one or more system-wide path" << std::endl;
#endif
infostream << "Detected share path: " << path_share << std::endl;
infostream << "Detected user path: " << path_user << std::endl;
}
void setXorgClassHint(const video::SExposedVideoData &video_data, void setXorgClassHint(const video::SExposedVideoData &video_data,
const std::string &name) const std::string &name)
{ {
@ -568,8 +661,20 @@ void setXorgClassHint(const video::SExposedVideoData &video_data,
#endif #endif
} }
////
//// Video/Display Information (Client-only)
////
#ifndef SERVER #ifndef SERVER
static irr::IrrlichtDevice *device;
void initIrrlicht(irr::IrrlichtDevice *device_)
{
device = device_;
}
v2u32 getWindowSize() v2u32 getWindowSize()
{ {
return device->getVideoDriver()->getScreenSize(); return device->getVideoDriver()->getScreenSize();
@ -641,9 +746,8 @@ const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
return driver_names[type]; return driver_names[type];
} }
# ifndef __ANDROID__
#ifndef __ANDROID__ # ifdef XORG_USED
#ifdef XORG_USED
static float calcDisplayDensity() static float calcDisplayDensity()
{ {
@ -679,12 +783,12 @@ float getDisplayDensity()
} }
#else # else // XORG_USED
float getDisplayDensity() float getDisplayDensity()
{ {
return g_settings->getFloat("screen_dpi")/96.0; return g_settings->getFloat("screen_dpi")/96.0;
} }
#endif # endif // XORG_USED
v2u32 getDisplaySize() v2u32 getDisplaySize()
{ {
@ -695,8 +799,8 @@ v2u32 getDisplaySize()
return deskres; return deskres;
} }
#endif # endif // __ANDROID__
#endif #endif // SERVER
} //namespace porting } //namespace porting

View File

@ -377,7 +377,7 @@ const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type);
const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type); const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type);
#endif #endif
inline const char * getPlatformName() inline const char *getPlatformName()
{ {
return return
#if defined(ANDROID) #if defined(ANDROID)
@ -401,8 +401,12 @@ inline const char * getPlatformName()
"AIX" "AIX"
#elif defined(__hpux) #elif defined(__hpux)
"HP-UX" "HP-UX"
#elif defined(__sun) && defined(__SVR4) #elif defined(__sun) || defined(sun)
"Solaris" #if defined(__SVR4)
"Solaris"
#else
"SunOS"
#endif
#elif defined(__CYGWIN__) #elif defined(__CYGWIN__)
"Cygwin" "Cygwin"
#elif defined(__unix__) || defined(__unix) #elif defined(__unix__) || defined(__unix)