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 f1a41e4f77
commit 386d695330
3 changed files with 298 additions and 188 deletions

@ -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

@ -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>
@ -101,29 +103,19 @@ void signal_handler_init(void)
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) {
if(g_killed == false)
{
dstream << DTIME << "INFO: event_handler(): " dstream << DTIME << "INFO: event_handler(): "
<<"Ctrl+C, Close Event, Logoff Event or Shutdown Event, shutting down."<<std::endl; << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
// Comment out for less clutter when testing scripts " shutting down." << std::endl;
/*dstream<<DTIME<<"INFO: event_handler(): "
<<"Printing debug stacks"<<std::endl;
debug_stacks_print();*/
g_killed = true; g_killed = true;
} } else {
else
{
(void)signal(SIGINT, SIG_DFL); (void)signal(SIGINT, SIG_DFL);
} }
break; break;
case CTRL_BREAK_EVENT: case CTRL_BREAK_EVENT:
break; break;
@ -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);
@ -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,155 +328,182 @@ 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
buflen--;
ssize_t len;
if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
(len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
(len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
return false;
buf[len] = '\0';
return true;
#else
return false;
#endif
}
//// Windows
#if defined(_WIN32) #if defined(_WIN32)
const DWORD buflen = 1000; bool getCurrentExecPath(char *buf, size_t len)
char buf[buflen]; {
DWORD len; DWORD written = GetModuleFileNameA(NULL, buf, len);
if (written == 0 || written == len)
return false;
// Find path of executable and set path_share relative to it return true;
len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
assert(len < buflen);
pathRemoveFile(buf, '\\');
if(detectMSVCBuildDir(buf)){
infostream<<"MSVC build directory detected"<<std::endl;
path_share = std::string(buf) + "\\..\\..";
path_user = std::string(buf) + "\\..\\..";
}
else{
path_share = std::string(buf) + "\\..";
path_user = std::string(buf) + "\\..";
} }
/*
Linux
*/
#elif defined(linux) || defined(__linux)
char buf[BUFSIZ]; //// Linux
memset(buf, 0, BUFSIZ); #elif defined(linux) || defined(__linux) || defined(__linux__)
// Get path to executable
FATAL_ERROR_IF(readlink("/proc/self/exe", buf, BUFSIZ-1) == -1, "Failed to get cwd");
pathRemoveFile(buf, '/'); bool getCurrentExecPath(char *buf, size_t len)
{
if (!getExecPathFromProcfs(buf, len))
return false;
path_share = std::string(buf) + "/.."; return true;
path_user = std::string(buf) + "/.."; }
/*
OS X //// Mac OS X, Darwin
*/
#elif defined(__APPLE__) #elif defined(__APPLE__)
CFBundleRef main_bundle = CFBundleGetMainBundle(); bool getCurrentExecPath(char *buf, size_t len)
CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle); {
char path[PATH_MAX]; if (_NSGetExecutablePath(buf, &len) == -1)
if (CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX)) { return false;
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);
/* return true;
FreeBSD }
*/
#elif defined(__FreeBSD__)
//// 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;
return true;
}
//// Solaris
#elif defined(__sun) || defined(sun)
bool getCurrentExecPath(char *buf, size_t len)
{
const char *exec = getexecname();
if (exec == NULL)
return false;
if (strlcpy(buf, exec, len) >= len)
return false;
return true;
}
// HP-UX
#elif defined(__hpux)
bool getCurrentExecPath(char *buf, size_t len)
{
struct pst_status psts;
if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
return false;
if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
return false;
return true;
}
path_share = std::string(buf) + "/..";
path_user = std::string(buf) + "/..";
#else #else
//TODO: Get path of executable. This assumes working directory is bin/ bool getCurrentExecPath(char *buf, size_t len)
dstream<<"WARNING: Relative path not properly supported on this platform" {
<<std::endl; return false;
}
/* scriptapi no longer allows paths that start with "..", so assuming that
the current working directory is bin/, strip off the last component. */
char *cwd = getcwd(NULL, 0);
pathRemoveFile(cwd, '/');
path_share = std::string(cwd);
path_user = std::string(cwd);
#endif #endif
#else // RUN_IN_PLACE
/* //// Windows
Use platform-specific paths otherwise
*/
infostream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl;
/*
Windows
*/
#if defined(_WIN32) #if defined(_WIN32)
const DWORD buflen = 1000; // FIXME: Surely there is a better way to do this bool setSystemPaths()
char buf[buflen]; {
DWORD len; 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);
Linux return true;
*/ }
//// Linux
#elif defined(linux) || defined(__linux) #elif defined(linux) || defined(__linux)
// Get path to executable bool setSystemPaths()
std::string bindir = "";
{ {
char buf[BUFSIZ]; char buf[BUFSIZ];
memset(buf, 0, BUFSIZ);
if (readlink("/proc/self/exe", buf, BUFSIZ-1) == -1) { if (!getCurrentExecPath(buf, sizeof(buf))) {
#ifdef __ANDROID__
errorstream << "Unable to read bindir "<< std::endl; errorstream << "Unable to read bindir "<< std::endl;
#ifndef __ANDROID__ #else
FATAL_ERROR("Unable to read bindir"); FATAL_ERROR("Unable to read bindir");
#endif #endif
} else { return false;
}
pathRemoveFile(buf, '/'); pathRemoveFile(buf, '/');
bindir = 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".
@ -489,67 +511,138 @@ void initializePaths()
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) ||
!fs::PathExists(trypath + DIR_DELIM + "builtin")) {
dstream << "WARNING: system-wide share not found at \"" dstream << "WARNING: system-wide share not found at \""
<< trypath << "\""<< std::endl; << 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 }
*/
//// Mac OS X
#elif defined(__APPLE__) #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/"
+ lowercase(PROJECT_NAME);
return true;
}
#else // FreeBSD, and probably many other POSIX-like systems.
#else
bool setSystemPaths()
{
path_share = STATIC_SHAREDIR; path_share = STATIC_SHAREDIR;
path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + lowercase(PROJECT_NAME); path_user = std::string(getenv("HOME")) + DIR_DELIM "."
+ lowercase(PROJECT_NAME);
return true;
}
#endif #endif
#endif // RUN_IN_PLACE
}
static irr::IrrlichtDevice *device; void initializePaths()
void initIrrlicht(irr::IrrlichtDevice *device_)
{ {
device = device_; #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,7 +746,6 @@ 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
@ -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

@ -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)
#if defined(__SVR4)
"Solaris" "Solaris"
#else
"SunOS"
#endif
#elif defined(__CYGWIN__) #elif defined(__CYGWIN__)
"Cygwin" "Cygwin"
#elif defined(__unix__) || defined(__unix) #elif defined(__unix__) || defined(__unix)