wxString CodeBlocksApp::GetAppPath() const { wxString base; #ifdef __WXMSW__ wxChar name[MAX_PATH] = {0}; GetModuleFileName(0L, name, MAX_PATH); wxFileName fname(name); base = fname.GetPath(wxPATH_GET_VOLUME); #else if (!m_Prefix.IsEmpty()) return m_Prefix; #ifdef SELFPATH // SELFPATH is a macro from prefix.h (binreloc) // it returns the absolute filename of us // similar to win32 GetModuleFileName()... base = wxString(SELFPATH,wxConvUTF8); base = wxFileName(base).GetPath(); #endif #if defined(sun) || defined(__sun) base = wxString(getexecname(),wxConvCurrent); base = wxFileName(base).GetPath(); #endif #if defined(__APPLE__) && defined(__MACH__) char path[MAXPATHLEN+1]; uint32_t path_len = MAXPATHLEN; // SPI first appeared in Mac OS X 10.2 _NSGetExecutablePath(path, &path_len); base = wxString(path, wxConvUTF8); base = wxFileName(base).GetPath(); #endif if (base.IsEmpty()) base = _T("."); #endif return base; }
string GetExecutableDirectory() { char dir[512]; #if defined __APPLE__ uint32_t bufsize = 512; _NSGetExecutablePath(dir, &bufsize); #elif defined WIN32 HMODULE module = GetModuleHandleA(NULL); GetModuleFileNameA(module, dir, 512); #else #error "GetExecutableDirectory not implemented on this platform" #endif int idx = strlen(dir); while (idx >= 0) { if (dir[idx] == '/' || dir[idx] == '\\') { dir[idx] = 0; break; } idx--; } return string(dir); }
boost::filesystem::path Paths::getExecutablePath() { #if defined(SWIFTEN_PLATFORM_MACOSX) ByteArray path; uint32_t size = 4096; path.resize(size); if (_NSGetExecutablePath(const_cast<char*>(reinterpret_cast<const char*>(vecptr(path))), &size) == 0) { return boost::filesystem::path(std::string(reinterpret_cast<const char*>(vecptr(path)), path.size()).c_str()).parent_path(); } #elif defined(SWIFTEN_PLATFORM_LINUX) ByteArray path; path.resize(4096); ssize_t size = readlink("/proc/self/exe", reinterpret_cast<char*>(vecptr(path)), path.size()); if (size > 0) { path.resize(size); return boost::filesystem::path(std::string(reinterpret_cast<const char*>(vecptr(path)), path.size()).c_str()).parent_path(); } #elif defined(SWIFTEN_PLATFORM_WINDOWS) ByteArray data; data.resize(2048); GetModuleFileName(NULL, reinterpret_cast<char*>(vecptr(data)), data.size()); return boost::filesystem::path(std::string(reinterpret_cast<const char*>(vecptr(data)), data.size()).c_str()).parent_path(); #endif return boost::filesystem::path(); }
String getProcessName(void) { String path; size_t size = PATH_MAX; char *buf = path.buf(size); // http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe #ifdef __APPLE__ uint32_t len = size; if (_NSGetExecutablePath(buf, &len) != 0) { *buf = 0; return path; } len = strlen(buf); #else ssize_t len; len = readlink("/proc/self/exe", buf, size - 1); if (len == -1) { // /proc/self/exe is not available on setuid processes, so fallback to // /proc/self/cmdline. int fd = open("/proc/self/cmdline", O_RDONLY); if (fd >= 0) { len = read(fd, buf, size - 1); close(fd); } } if (len <= 0) { snprintf(buf, size, "%i", (int)getpid()); return path; } #endif path.truncate(len); return path; }
void ScriptFunctionsRegister(struct lua_State* L) { #if LUAPLUS_EXTENSIONS LuaState* state = lua_State_To_LuaState(L); LuaObject globalsObj = state->GetGlobals(); globalsObj.Register("GetTickCount", LS_GetTickCount); #if defined(_MSC_VER) && defined(WIN32) && !defined(_XBOX) && !defined(_XBOX_VER) && !defined(PLATFORM_PS3) #elif defined(__APPLE__) char modulePath[MAXPATHLEN + 1]; unsigned int path_len = MAXPATHLEN; _NSGetExecutablePath(modulePath, &path_len); char* slashPtr = strrchr(modulePath, '/'); slashPtr++; *slashPtr = 0; #endif // _MSC_VER #endif // LUAPLUS_EXTENSIONS #if LUAPLUS_DUMPOBJECT state->GetGlobals().Register("LuaDumpGlobals", LS_LuaDumpGlobals); state->GetGlobals().Register("LuaDumpObject", LS_LuaDumpObject); state->GetGlobals().Register("LuaDumpFile", LS_LuaDumpFile); #endif // LUAPLUS_DUMPOBJECT }
std::string self_exec_filename() { // nice overview of crossplatform methods: // http://stackoverflow.com/questions/5919996 #ifdef __linux return read_symlink("/proc/self/exe"); #elif __APPLE__ uint32_t bufsize = 1024; while (true) { std::unique_ptr<char[]> buf{new char[bufsize]}; if (_NSGetExecutablePath(buf.get(), &bufsize) < 0) { continue; } return std::string{buf.get()}; } #elif WIN32 static_assert(false, "subprocess::self_filename is not yet implemented for WIN32"); #else static_assert(false, "subprocess::self_filename is not yet implemented for... whatever platform you're using right now."); #endif }
static char *executable_path() { #if defined(NEKO_WINDOWS) static char path[MAX_PATH]; if( GetModuleFileName(NULL,path,MAX_PATH) == 0 ) return NULL; return path; #elif defined(NEKO_MAC) static char path[MAXPATHLEN+1]; uint32_t path_len = MAXPATHLEN; if ( _NSGetExecutablePath(path, &path_len) ) return NULL; return path; #elif defined(NEKO_BSD) int mib[4]; mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PATHNAME; mib[3] = -1; static char path[MAXPATHLEN]; size_t cb = sizeof(path); sysctl(mib, 4, path, &cb, NULL, 0); if (!cb) return NULL; return path; #else static char path[200]; int length = readlink("/proc/self/exe", path, sizeof(path)); if( length < 0 || length >= 200 ) { char *p = getenv(" "); // for upx if( p == NULL ) p = getenv("_"); return p; } path[length] = '\0'; return path; #endif }
void NativeInit(int argc, const char *argv[], const char *savegame_directory, const char *external_directory, const char *installID) { EnableFZ(); setlocale( LC_ALL, "C" ); std::string user_data_path = savegame_directory; isMessagePending = false; // We want this to be FIRST. #ifndef USING_QT_UI #ifdef BLACKBERRY // Packed assets are included in app/native/ dir VFSRegister("", new DirectoryAssetReader("app/native/assets/")); #elif defined(IOS) VFSRegister("", new DirectoryAssetReader(external_directory)); user_data_path += "/"; #elif defined(__APPLE__) char program_path[4090]; uint32_t program_path_size = sizeof(program_path); _NSGetExecutablePath(program_path,&program_path_size); *(strrchr(program_path, '/')+1) = '\0'; char assets_path[4096]; sprintf(assets_path,"%sassets/",program_path); VFSRegister("", new DirectoryAssetReader(assets_path)); VFSRegister("", new DirectoryAssetReader("assets/")); #else VFSRegister("", new DirectoryAssetReader("assets/")); #endif #endif VFSRegister("", new DirectoryAssetReader(user_data_path.c_str())); host = new NativeHost(); #ifndef _WIN32 logger = new AndroidLogger(); LogManager::Init(); LogManager *logman = LogManager::GetInstance(); ILOG("Logman: %p", logman); config_filename = user_data_path + "/ppsspp.ini"; g_Config.Load(config_filename.c_str()); #endif const char *fileToLog = 0; const char *stateToLoad = 0; bool gfxLog = false; // Parse command line LogTypes::LOG_LEVELS logLevel = LogTypes::LINFO; for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { switch (argv[i][1]) { case 'd': // Enable debug logging // Note that you must also change the max log level in Log.h. logLevel = LogTypes::LDEBUG; break; case 'g': gfxLog = true; break; case 'j': g_Config.bJit = true; g_Config.bSaveSettings = false; break; case 'i': g_Config.bJit = false; g_Config.bSaveSettings = false; break; case '-': if (!strncmp(argv[i], "--log=", strlen("--log=")) && strlen(argv[i]) > strlen("--log=")) fileToLog = argv[i] + strlen("--log="); if (!strncmp(argv[i], "--state=", strlen("--state=")) && strlen(argv[i]) > strlen("--state=")) stateToLoad = argv[i] + strlen("--state="); break; } } else { if (boot_filename.empty()) { boot_filename = argv[i]; if (!File::Exists(boot_filename)) { fprintf(stderr, "File not found: %s\n", boot_filename.c_str()); exit(1); } } else { fprintf(stderr, "Can only boot one file"); exit(1); } } } if (fileToLog != NULL) LogManager::GetInstance()->ChangeFileLog(fileToLog); #ifndef _WIN32 if (g_Config.currentDirectory == "") { #if defined(ANDROID) g_Config.currentDirectory = external_directory; #elif defined(BLACKBERRY) || defined(__SYMBIAN32__) || defined(MEEGO_EDITION_HARMATTAN) || defined(IOS) || defined(_WIN32) g_Config.currentDirectory = savegame_directory; #else g_Config.currentDirectory = getenv("HOME"); #endif } #if defined(ANDROID) g_Config.internalDataDirectory = savegame_directory; // Maybe there should be an option to use internal memory instead, but I think // that for most people, using external memory (SDCard/USB Storage) makes the // most sense. g_Config.memCardDirectory = std::string(external_directory) + "/"; g_Config.flashDirectory = std::string(external_directory)+"/flash/"; #elif defined(BLACKBERRY) || defined(__SYMBIAN32__) || defined(MEEGO_EDITION_HARMATTAN) || defined(IOS) || defined(_WIN32) g_Config.memCardDirectory = user_data_path; #ifdef BLACKBERRY g_Config.flashDirectory = "app/native/assets/flash/"; #elif defined(IOS) g_Config.flashDirectory = std::string(external_directory) + "flash0/"; #elif defined(MEEGO_EDITION_HARMATTAN) g_Config.flashDirectory = "/opt/PPSSPP/flash/"; #else g_Config.flashDirectory = user_data_path+"/flash/"; #endif #else g_Config.memCardDirectory = std::string(getenv("HOME"))+"/.ppsspp/"; g_Config.flashDirectory = g_Config.memCardDirectory+"/flash/"; #endif for (int i = 0; i < LogTypes::NUMBER_OF_LOGS; i++) { LogTypes::LOG_TYPE type = (LogTypes::LOG_TYPE)i; logman->SetEnable(type, true); logman->SetLogLevel(type, gfxLog && i == LogTypes::G3D ? LogTypes::LDEBUG : logLevel); #ifdef ANDROID logman->AddListener(type, logger); #endif } #ifdef __SYMBIAN32__ g_Config.bHardwareTransform = true; g_Config.bUseVBO = false; #endif // Special hack for G3D as it's very spammy. Need to make a flag for this. if (!gfxLog) logman->SetLogLevel(LogTypes::G3D, LogTypes::LERROR); INFO_LOG(BOOT, "Logger inited."); #endif i18nrepo.LoadIni(g_Config.languageIni); if (!boot_filename.empty() && stateToLoad != NULL) SaveState::Load(stateToLoad); g_gameInfoCache.Init(); }
int main(int argc, char **argv) { #if defined(__APPLE__) && defined(__MACH__) char path[2049]; _NSGetExecutablePath(path, 2048); String basePath = path; vector<String> cpts = basePath.split("/"); String installPath = ""; for(int i=0; i < cpts.size() - 2; i++) { installPath = installPath + cpts[i]; installPath += String("/"); } #else char path[2049]; TCHAR tpath[2049]; GetModuleFileName(NULL, (LPWSTR)tpath, 2048); wtoc(path, tpath, 2048); String basePath = path; vector<String> cpts = basePath.split("\\"); String installPath = ""; for(int i=0; i < cpts.size() - 2; i++) { installPath = installPath + cpts[i]; installPath += String("\\"); } #endif printf("Polycode build tool v0.1.1\n"); for(int i=0; i < argc; i++) { String argString = String(argv[i]); vector<String> bits = argString.split("="); if(bits.size() == 2) { BuildArg arg; arg.name = bits[0]; arg.value = bits[1]; args.push_back(arg); } } if(getArg("--config") == "") { printf("\n\nInput config XML missing. Use --config=path to specify.\n\n"); return 1; } if(getArg("--out") == "") { printf("\n\nOutput file not specified. Use --out=outfile.polyapp to specify.\n\n"); return 1; } char dirPath[4099]; #if defined(__APPLE__) && defined(__MACH__) _getcwd(dirPath, sizeof(dirPath)); #else TCHAR tdirpath[4099]; GetCurrentDirectory(4098, (LPWSTR)tdirpath); wtoc(dirPath, tdirpath, 4098); #endif String currentPath = String(dirPath); String configPath = getArg("--config"); String finalPath = configPath; if(configPath[0] != '/') { #ifdef _WINDOWS finalPath = currentPath+"\\"+configPath; #else finalPath = currentPath+"/"+configPath; #endif } finalPath = finalPath.replace(":", ""); finalPath = finalPath.replace("\\", "/"); finalPath = finalPath.substr(1, finalPath.length() - 1); printf("Reading config file from %s\n", finalPath.c_str()); Object configFile; if(!configFile.loadFromXML(finalPath)) { printf("Specified config file doesn't exist!\n"); return 1; } printf("OK!\n"); // start required params String entryPoint; int defaultWidth; int defaultHeight; int frameRate = 60; int antiAliasingLevel = 0; bool fullScreen = false; float backgroundColorR = 0.2; float backgroundColorG = 0.2; float backgroundColorB = 0.2; if(configFile.root["entryPoint"]) { printf("Entry point: %s\n", configFile.root["entryPoint"]->stringVal.c_str()); entryPoint = configFile.root["entryPoint"]->stringVal; } else { printf("Required parameter: \"entryPoint\" is missing from config file!\n"); return 1; } if(configFile.root["defaultWidth"]) { printf("Width: %d\n", configFile.root["defaultWidth"]->intVal); defaultWidth = configFile.root["defaultWidth"]->intVal; } else { printf("Required parameter: \"defaultWidth\" is missing from config file!\n"); return 1; } if(configFile.root["defaultHeight"]) { printf("Height: %d\n", configFile.root["defaultHeight"]->intVal); defaultHeight = configFile.root["defaultHeight"]->intVal; } else { printf("Required parameter: \"defaultHeight\" is missing from config file!\n"); return 1; } // start optional params if(configFile.root["frameRate"]) { printf("Frame rate: %d\n", configFile.root["frameRate"]->intVal); frameRate = configFile.root["frameRate"]->intVal; } if(configFile.root["antiAliasingLevel"]) { printf("Anti-aliasing level: %d\n", configFile.root["antiAliasingLevel"]->intVal); antiAliasingLevel = configFile.root["antiAliasingLevel"]->intVal; } if(configFile.root["fullScreen"]) { fullScreen = configFile.root["fullScreen"]->boolVal; if(fullScreen) { printf("Full-screen: true\n"); } else { printf("Full-screen: false\n"); } } if(configFile.root["backgroundColor"]) { ObjectEntry *color = configFile.root["backgroundColor"]; if((*color)["red"] && (*color)["green"] && (*color)["blue"]) { backgroundColorR = (*color)["red"]->NumberVal; backgroundColorG = (*color)["green"]->NumberVal; backgroundColorB = (*color)["blue"]->NumberVal; printf("Background color: %f %f %f\n", backgroundColorR, backgroundColorG, backgroundColorB); } else { printf("backgroundColor node specified, but missing all three color attributes (red,green,blue). Ignoring.\n"); } } zipFile z = zipOpen(getArg("--out").c_str(), 0); Object runInfo; runInfo.root.name = "PolycodeApp"; runInfo.root.addChild("entryPoint", entryPoint); runInfo.root.addChild("defaultHeight", defaultHeight); runInfo.root.addChild("defaultWidth", defaultWidth); runInfo.root.addChild("frameRate", frameRate); runInfo.root.addChild("antiAliasingLevel", antiAliasingLevel); runInfo.root.addChild("fullScreen", fullScreen); ObjectEntry *color = runInfo.root.addChild("backgroundColor"); color->addChild("red", backgroundColorR); color->addChild("green", backgroundColorG); color->addChild("blue", backgroundColorB); addFileToZip(z, entryPoint, entryPoint, false); if(configFile.root["modules"]) { #ifdef _WINDOWS String modulesPath = installPath + "Modules\\"; #else String modulesPath = installPath + "Modules/"; #endif ObjectEntry *modules = configFile.root["modules"]; if(modules) { for(int i=0; i < modules->length; i++) { printf("Adding module: %s\n", (*modules)[i]->stringVal.c_str()); String modulePath = modulesPath + (*modules)[i]->stringVal; #ifdef _WINDOWS String moduleAPIPath = modulePath + "\\API"; String moduleLibPath = modulePath + "\\Lib"; moduleAPIPath = moduleAPIPath.replace("\\", "/"); moduleAPIPath = moduleAPIPath.substr(2, moduleAPIPath.length() - 2); moduleLibPath = moduleLibPath.replace("\\", "/"); moduleLibPath = moduleLibPath.substr(2, moduleLibPath.length() - 2); #else String moduleAPIPath = modulePath + "/API"; String moduleLibPath = modulePath + "/Lib"; #endif printf("Path:%s\n", moduleAPIPath.c_str()); addFolderToZip(z, moduleAPIPath, "", false); addFolderToZip(z, moduleLibPath, "__lib", false); //String module = configFile.root["entryPoint"]->stringVal; } runInfo.root.addChild(configFile.root["modules"]); } } if(configFile.root["packedItems"]) { ObjectEntry *packed = configFile.root["packedItems"]; if(packed) { for(int i=0; i < packed->length; i++) { ObjectEntry *entryPath = (*(*packed)[i])["path"]; ObjectEntry *entryType = (*(*packed)[i])["type"]; if(entryPath && entryType) { if(entryType->stringVal == "folder") { addFolderToZip(z, entryPath->stringVal, entryPath->stringVal, false); } else { addFileToZip(z, entryPath->stringVal, entryPath->stringVal, false); } } } runInfo.root.addChild(configFile.root["packedItems"]); } } runInfo.saveToXML("runinfo_tmp_zzzz.polyrun"); addFileToZip(z, "runinfo_tmp_zzzz.polyrun", "runinfo.polyrun", true); //addFolderToZip(z, getArg("--project"), ""); zipClose(z, ""); OSBasics::removeItem("runinfo_tmp_zzzz.polyrun"); return 0; }
static void spawn_via_launchd(void) { char watchman_path[WATCHMAN_NAME_MAX]; uint32_t size = sizeof(watchman_path); char plist_path[WATCHMAN_NAME_MAX]; FILE *fp; struct passwd *pw; uid_t uid; char *argv[MAX_DAEMON_ARGS] = { "/bin/launchctl", "load", "-F", NULL }; posix_spawnattr_t attr; pid_t pid; int res; close_random_fds(); if (_NSGetExecutablePath(watchman_path, &size) == -1) { w_log(W_LOG_ERR, "_NSGetExecutablePath: path too long; size %u\n", size); abort(); } uid = getuid(); pw = getpwuid(uid); if (!pw) { w_log(W_LOG_ERR, "getpwuid(%d) failed: %s. I don't know who you are\n", uid, strerror(errno)); abort(); } snprintf(plist_path, sizeof(plist_path), "%s/Library/LaunchAgents", pw->pw_dir); // Best effort attempt to ensure that the agents dir exists. We'll detect // and report the failure in the fopen call below. mkdir(plist_path, 0755); snprintf(plist_path, sizeof(plist_path), "%s/Library/LaunchAgents/com.github.facebook.watchman.plist", pw->pw_dir); if (access(plist_path, R_OK) == 0) { // Unload any that may already exist, as it is likely wrong char *unload_argv[MAX_DAEMON_ARGS] = { "/bin/launchctl", "unload", NULL }; append_argv(unload_argv, plist_path); errno = posix_spawnattr_init(&attr); if (errno != 0) { w_log(W_LOG_FATAL, "posix_spawnattr_init: %s\n", strerror(errno)); } res = posix_spawnp(&pid, unload_argv[0], NULL, &attr, unload_argv, environ); if (res == 0) { waitpid(pid, &res, 0); } posix_spawnattr_destroy(&attr); // Forcibly remove the plist. In some cases it may have some attributes // set that prevent launchd from loading it. This can happen where // the system was re-imaged or restored from a backup unlink(plist_path); } fp = fopen(plist_path, "w"); if (!fp) { w_log(W_LOG_ERR, "Failed to open %s for write: %s\n", plist_path, strerror(errno)); abort(); } compute_file_name(&pid_file, compute_user_name(), "pid", "pidfile"); fprintf(fp, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" " "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" "<plist version=\"1.0\">\n" "<dict>\n" " <key>Label</key>\n" " <string>com.github.facebook.watchman</string>\n" " <key>Disabled</key>\n" " <false/>\n" " <key>ProgramArguments</key>\n" " <array>\n" " <string>%s</string>\n" " <string>--foreground</string>\n" " <string>--logfile=%s</string>\n" " <string>--log-level=%d</string>\n" " <string>--sockname=%s</string>\n" " <string>--statefile=%s</string>\n" " <string>--pidfile=%s</string>\n" " </array>\n" " <key>Sockets</key>\n" " <dict>\n" " <key>sock</key>\n" // coupled with get_listener_socket_from_launchd " <dict>\n" " <key>SockPathName</key>\n" " <string>%s</string>\n" " <key>SockPathMode</key>\n" " <integer>%d</integer>\n" " </dict>\n" " </dict>\n" " <key>KeepAlive</key>\n" " <dict>\n" " <key>Crashed</key>\n" " <true/>\n" " </dict>\n" " <key>RunAtLoad</key>\n" " <true/>\n" " <key>EnvironmentVariables</key>\n" " <dict>\n" " <key>PATH</key>\n" " <string><![CDATA[%s]]></string>\n" " </dict>\n" " <key>ProcessType</key>\n" " <string>Interactive</string>\n" " <key>Nice</key>\n" " <integer>-5</integer>\n" "</dict>\n" "</plist>\n", watchman_path, log_name, log_level, sock_name, watchman_state_file, pid_file, sock_name, 0600, getenv("PATH")); fclose(fp); // Don't rely on umask, ensure we have the correct perms chmod(plist_path, 0644); append_argv(argv, plist_path); errno = posix_spawnattr_init(&attr); if (errno != 0) { w_log(W_LOG_FATAL, "posix_spawnattr_init: %s\n", strerror(errno)); } res = posix_spawnp(&pid, argv[0], NULL, &attr, argv, environ); if (res) { w_log(W_LOG_FATAL, "Failed to spawn watchman via launchd: %s\n", strerror(errno)); } posix_spawnattr_destroy(&attr); if (waitpid(pid, &res, 0) == -1) { w_log(W_LOG_FATAL, "Failed waiting for launchctl load: %s\n", strerror(errno)); } if (WIFEXITED(res) && WEXITSTATUS(res) == 0) { return; } // Most likely cause is "headless" operation with no GUI context if (WIFEXITED(res)) { w_log(W_LOG_ERR, "launchctl: exited with status %d\n", WEXITSTATUS(res)); } else if (WIFSIGNALED(res)) { w_log(W_LOG_ERR, "launchctl: signaled with %d\n", WTERMSIG(res)); } w_log(W_LOG_ERR, "Falling back to daemonize\n"); daemonize(); }
static void calculate_path(void) { extern wchar_t *Py_GetProgramName(void); static wchar_t delimiter[2] = {DELIM, '\0'}; static wchar_t separator[2] = {SEP, '\0'}; char *_rtpypath = Py_GETENV("PYTHONPATH"); /* XXX use wide version on Windows */ wchar_t rtpypath[MAXPATHLEN+1]; wchar_t *home = Py_GetPythonHome(); char *_path = getenv("PATH"); wchar_t *path_buffer = NULL; wchar_t *path = NULL; wchar_t *prog = Py_GetProgramName(); wchar_t argv0_path[MAXPATHLEN+1]; wchar_t zip_path[MAXPATHLEN+1]; int pfound, efound; /* 1 if found; -1 if found build directory */ wchar_t *buf; size_t bufsz; size_t prefixsz; wchar_t *defpath; #ifdef WITH_NEXT_FRAMEWORK NSModule pythonModule; #endif #ifdef __APPLE__ #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 uint32_t nsexeclength = MAXPATHLEN; #else unsigned long nsexeclength = MAXPATHLEN; #endif char execpath[MAXPATHLEN+1]; #endif wchar_t *_pythonpath, *_prefix, *_exec_prefix; _pythonpath = _Py_char2wchar(PYTHONPATH, NULL); _prefix = _Py_char2wchar(PREFIX, NULL); _exec_prefix = _Py_char2wchar(EXEC_PREFIX, NULL); if (!_pythonpath || !_prefix || !_exec_prefix) { Py_FatalError( "Unable to decode path variables in getpath.c: " "memory error"); } if (_path) { path_buffer = _Py_char2wchar(_path, NULL); path = path_buffer; } /* If there is no slash in the argv0 path, then we have to * assume python is on the user's $PATH, since there's no * other way to find a directory to start the search from. If * $PATH isn't exported, you lose. */ if (wcschr(prog, SEP)) wcsncpy(progpath, prog, MAXPATHLEN); #ifdef __APPLE__ /* On Mac OS X, if a script uses an interpreter of the form * "#!/opt/python2.3/bin/python", the kernel only passes "python" * as argv[0], which falls through to the $PATH search below. * If /opt/python2.3/bin isn't in your path, or is near the end, * this algorithm may incorrectly find /usr/bin/python. To work * around this, we can use _NSGetExecutablePath to get a better * hint of what the intended interpreter was, although this * will fail if a relative path was used. but in that case, * absolutize() should help us out below */ else if(0 == _NSGetExecutablePath(execpath, &nsexeclength) && execpath[0] == SEP) { size_t r = mbstowcs(progpath, execpath, MAXPATHLEN+1); if (r == (size_t)-1 || r > MAXPATHLEN) { /* Could not convert execpath, or it's too long. */ progpath[0] = '\0'; } } #endif /* __APPLE__ */ else if (path) { while (1) { wchar_t *delim = wcschr(path, DELIM); if (delim) { size_t len = delim - path; if (len > MAXPATHLEN) len = MAXPATHLEN; wcsncpy(progpath, path, len); *(progpath + len) = '\0'; } else wcsncpy(progpath, path, MAXPATHLEN); joinpath(progpath, prog); if (isxfile(progpath)) break; if (!delim) { progpath[0] = L'\0'; break; } path = delim + 1; } } else progpath[0] = '\0'; if (path_buffer != NULL) PyMem_Free(path_buffer); if (progpath[0] != SEP && progpath[0] != '\0') absolutize(progpath); wcsncpy(argv0_path, progpath, MAXPATHLEN); argv0_path[MAXPATHLEN] = '\0'; #ifdef WITH_NEXT_FRAMEWORK /* On Mac OS X we have a special case if we're running from a framework. ** This is because the python home should be set relative to the library, ** which is in the framework, not relative to the executable, which may ** be outside of the framework. Except when we're in the build directory... */ pythonModule = NSModuleForSymbol(NSLookupAndBindSymbol("_Py_Initialize")); /* Use dylib functions to find out where the framework was loaded from */ buf = (wchar_t *)NSLibraryNameForModule(pythonModule); if (buf != NULL) { /* We're in a framework. */ /* See if we might be in the build directory. The framework in the ** build directory is incomplete, it only has the .dylib and a few ** needed symlinks, it doesn't have the Lib directories and such. ** If we're running with the framework from the build directory we must ** be running the interpreter in the build directory, so we use the ** build-directory-specific logic to find Lib and such. */ wcsncpy(argv0_path, buf, MAXPATHLEN); reduce(argv0_path); joinpath(argv0_path, lib_python); joinpath(argv0_path, LANDMARK); if (!ismodule(argv0_path)) { /* We are in the build directory so use the name of the executable - we know that the absolute path is passed */ wcsncpy(argv0_path, progpath, MAXPATHLEN); } else { /* Use the location of the library as the progpath */ wcsncpy(argv0_path, buf, MAXPATHLEN); } } #endif #if HAVE_READLINK { wchar_t tmpbuffer[MAXPATHLEN+1]; int linklen = _Py_wreadlink(progpath, tmpbuffer, MAXPATHLEN); while (linklen != -1) { if (tmpbuffer[0] == SEP) /* tmpbuffer should never be longer than MAXPATHLEN, but extra check does not hurt */ wcsncpy(argv0_path, tmpbuffer, MAXPATHLEN); else { /* Interpret relative to progpath */ reduce(argv0_path); joinpath(argv0_path, tmpbuffer); } linklen = _Py_wreadlink(argv0_path, tmpbuffer, MAXPATHLEN); } } #endif /* HAVE_READLINK */ reduce(argv0_path); /* At this point, argv0_path is guaranteed to be less than MAXPATHLEN bytes long. */ if (!(pfound = search_for_prefix(argv0_path, home, _prefix))) { if (!Py_FrozenFlag) fprintf(stderr, "Could not find platform independent libraries <prefix>\n"); wcsncpy(prefix, _prefix, MAXPATHLEN); joinpath(prefix, lib_python); } else reduce(prefix); wcsncpy(zip_path, prefix, MAXPATHLEN); zip_path[MAXPATHLEN] = L'\0'; if (pfound > 0) { /* Use the reduced prefix returned by Py_GetPrefix() */ reduce(zip_path); reduce(zip_path); } else wcsncpy(zip_path, _prefix, MAXPATHLEN); joinpath(zip_path, L"lib/python00.zip"); bufsz = wcslen(zip_path); /* Replace "00" with version */ zip_path[bufsz - 6] = VERSION[0]; zip_path[bufsz - 5] = VERSION[2]; if (!(efound = search_for_exec_prefix(argv0_path, home, _exec_prefix))) { if (!Py_FrozenFlag) fprintf(stderr, "Could not find platform dependent libraries <exec_prefix>\n"); wcsncpy(exec_prefix, _exec_prefix, MAXPATHLEN); joinpath(exec_prefix, L"lib/lib-dynload"); } /* If we found EXEC_PREFIX do *not* reduce it! (Yet.) */ if ((!pfound || !efound) && !Py_FrozenFlag) fprintf(stderr, "Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]\n"); /* Calculate size of return buffer. */ bufsz = 0; if (_rtpypath) { size_t s = mbstowcs(rtpypath, _rtpypath, sizeof(rtpypath)/sizeof(wchar_t)); if (s == (size_t)-1 || s >=sizeof(rtpypath)) /* XXX deal with errors more gracefully */ _rtpypath = NULL; if (_rtpypath) bufsz += wcslen(rtpypath) + 1; } defpath = _pythonpath; prefixsz = wcslen(prefix) + 1; while (1) { wchar_t *delim = wcschr(defpath, DELIM); if (defpath[0] != SEP) /* Paths are relative to prefix */ bufsz += prefixsz; if (delim) bufsz += delim - defpath + 1; else { bufsz += wcslen(defpath) + 1; break; } defpath = delim + 1; } bufsz += wcslen(zip_path) + 1; bufsz += wcslen(exec_prefix) + 1; /* This is the only malloc call in this file */ buf = (wchar_t *)PyMem_Malloc(bufsz*sizeof(wchar_t)); if (buf == NULL) { /* We can't exit, so print a warning and limp along */ fprintf(stderr, "Not enough memory for dynamic PYTHONPATH.\n"); fprintf(stderr, "Using default static PYTHONPATH.\n"); module_search_path = L"" PYTHONPATH; } else { /* Run-time value of $PYTHONPATH goes first */ if (_rtpypath) { wcscpy(buf, rtpypath); wcscat(buf, delimiter); } else buf[0] = '\0'; /* Next is the default zip path */ wcscat(buf, zip_path); wcscat(buf, delimiter); /* Next goes merge of compile-time $PYTHONPATH with * dynamically located prefix. */ defpath = _pythonpath; while (1) { wchar_t *delim = wcschr(defpath, DELIM); if (defpath[0] != SEP) { wcscat(buf, prefix); wcscat(buf, separator); } if (delim) { size_t len = delim - defpath + 1; size_t end = wcslen(buf) + len; wcsncat(buf, defpath, len); *(buf + end) = '\0'; } else { wcscat(buf, defpath); break; } defpath = delim + 1; } wcscat(buf, delimiter); /* Finally, on goes the directory for dynamic-load modules */ wcscat(buf, exec_prefix); /* And publish the results */ module_search_path = buf; } /* Reduce prefix and exec_prefix to their essence, * e.g. /usr/local/lib/python1.5 is reduced to /usr/local. * If we're loading relative to the build directory, * return the compiled-in defaults instead. */ if (pfound > 0) { reduce(prefix); reduce(prefix); /* The prefix is the root directory, but reduce() chopped * off the "/". */ if (!prefix[0]) wcscpy(prefix, separator); } else wcsncpy(prefix, _prefix, MAXPATHLEN); if (efound > 0) { reduce(exec_prefix); reduce(exec_prefix); reduce(exec_prefix); if (!exec_prefix[0]) wcscpy(exec_prefix, separator); } else wcsncpy(exec_prefix, _exec_prefix, MAXPATHLEN); PyMem_Free(_pythonpath); PyMem_Free(_prefix); PyMem_Free(_exec_prefix); }
static void SetExecutablePath(char* exePath) { // !!! this assumes that exePath can hold PATH_MAX chars !!! #ifdef _WIN32 DWORD len = GetModuleFileNameA(NULL, exePath, PATH_MAX); if(len <= 0 || len == PATH_MAX) { // an error occured, clear exe path exePath[0] = '\0'; } #elif defined(__linux) || defined(__NetBSD__) || defined(__OpenBSD__) // all the platforms that have /proc/$pid/exe or similar that symlink the // real executable - basiscally Linux and the BSDs except for FreeBSD which // doesn't enable proc by default and has a sysctl() for this char buf[PATH_MAX] = {0}; #ifdef __linux snprintf(buf, sizeof(buf), "/proc/%d/exe", getpid()); #else // the BSDs snprintf(buf, sizeof(buf), "/proc/%d/file", getpid()); #endif // readlink() doesn't null-terminate! int len = readlink(buf, exePath, PATH_MAX-1); if (len <= 0) { // an error occured, clear exe path exePath[0] = '\0'; } else { exePath[len] = '\0'; } #elif defined(__FreeBSD__) // the sysctl should also work when /proc/ is not mounted (which seems to // be common on FreeBSD), so use it.. int name[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1}; size_t len = PATH_MAX-1; int ret = sysctl(name, sizeof(name)/sizeof(name[0]), exePath, &len, NULL, 0); if(ret != 0) { // an error occured, clear exe path exePath[0] = '\0'; } #elif defined(__APPLE__) uint32_t bufSize = PATH_MAX; if(_NSGetExecutablePath(exePath, &bufSize) != 0) { // WTF, PATH_MAX is not enough to hold the path? // an error occured, clear exe path exePath[0] = '\0'; } // TODO: realpath() ? // TODO: no idea what this is if the executable is in an app bundle #else #error "Unsupported Platform!" // feel free to add implementation for your platform and send me a patch #endif }
static Bool get_default_install_path(char *file_path, u32 path_type) { char app_path[GF_MAX_PATH]; char *sep; u32 size = GF_MAX_PATH; /*on OSX, Linux & co, user home is where we store the cfg file*/ if (path_type==GF_PATH_CFG) { char *user_home = getenv("HOME"); #ifdef GPAC_IPHONE char buf[PATH_MAX]; char *res; #endif if (!user_home) return 0; #ifdef GPAC_IPHONE res = realpath(user_home, buf); if (res) { strcpy(file_path, buf); strcat(file_path, "/Documents"); } else #endif strcpy(file_path, user_home); if (file_path[strlen(file_path)-1] == '/') file_path[strlen(file_path)-1] = 0; //cleanup of old install in .gpacrc if (check_file_exists(".gpacrc", file_path, file_path)) { strcpy(app_path, file_path); strcat(app_path, "/.gpacrc"); gf_delete_file(app_path); } strcat(file_path, "/.gpac"); if (!gf_dir_exists(file_path)) { gf_mkdir(file_path); } return 1; } if (path_type==GF_PATH_APP) { #if (defined(__DARWIN__) || defined(__APPLE__) ) if (_NSGetExecutablePath(app_path, &size) ==0) { realpath(app_path, file_path); char *sep = strrchr(file_path, '/'); if (sep) sep[0] = 0; return 1; } #elif defined(GPAC_CONFIG_LINUX) size = readlink("/proc/self/exe", file_path, GF_MAX_PATH); if (size>0) { char *sep = strrchr(file_path, '/'); if (sep) sep[0] = 0; return 1; } #endif return 0; } /*locate the app*/ if (!get_default_install_path(app_path, GF_PATH_APP)) return 0; /*installed or symlink on system, user user home directory*/ if (!strnicmp(app_path, "/usr/", 5) || !strnicmp(app_path, "/opt/", 5)) { if (path_type==GF_PATH_GUI) { /*look in possible install dirs ...*/ if (check_file_exists("gui.bt", "/usr/share/gpac/gui", file_path)) return 1; if (check_file_exists("gui.bt", "/usr/local/share/gpac/gui", file_path)) return 1; if (check_file_exists("gui.bt", "/opt/share/gpac/gui", file_path)) return 1; if (check_file_exists("gui.bt", "/opt/local/share/gpac/gui", file_path)) return 1; } else if (path_type==GF_PATH_MODULES) { /*look in possible install dirs ...*/ if (check_file_exists(TEST_MODULE, "/usr/lib/gpac", file_path)) return 1; if (check_file_exists(TEST_MODULE, "/usr/local/lib/gpac", file_path)) return 1; if (check_file_exists(TEST_MODULE, "/opt/lib/gpac", file_path)) return 1; if (check_file_exists(TEST_MODULE, "/opt/local/lib/gpac", file_path)) return 1; if (check_file_exists(TEST_MODULE, "/usr/lib/x86_64-linux-gnu/gpac", file_path)) return 1; if (check_file_exists(TEST_MODULE, "/usr/lib/i386-linux-gnu/gpac", file_path)) return 1; } } if (path_type==GF_PATH_GUI) { if (get_default_install_path(app_path, GF_PATH_CFG)) { /*GUI not found, look in ~/.gpac/gui/ */ strcat(app_path, "/.gpac/gui"); if (check_file_exists("gui.bt", app_path, file_path)) return 1; } /*GUI not found, look in gpac distribution if any */ if (get_default_install_path(app_path, GF_PATH_APP)) { char *sep = strstr(app_path, "/bin/gcc"); if (!sep) sep = strstr(app_path, "/bin/osx"); if (sep) { sep[0] = 0; strcat(app_path, "/gui"); if (check_file_exists("gui.bt", app_path, file_path)) return 1; } } /*GUI not found, look in .app for OSX case*/ } if (path_type==GF_PATH_MODULES) { /*look in gpac compilation tree (modules are output in the same folder as apps) */ if (get_default_install_path(app_path, GF_PATH_APP)) { if (check_file_exists(TEST_MODULE, app_path, file_path)) return 1; /*on OSX check modules subdirectory */ strcat(app_path, "/modules"); if (check_file_exists(TEST_MODULE, app_path, file_path)) return 1; } /*modules not found, look in ~/.gpac/modules/ */ if (get_default_install_path(app_path, GF_PATH_CFG)) { strcpy(app_path, file_path); strcat(app_path, "/.gpac/modules"); if (check_file_exists(TEST_MODULE, app_path, file_path)) return 1; } /*modules not found, failure*/ return 0; } /*OSX way vs iPhone*/ sep = strstr(app_path, ".app/"); if (sep) sep[4] = 0; /*we are looking for .app install path, or GUI */ if (path_type==GF_PATH_GUI) { #ifndef GPAC_IPHONE strcat(app_path, "/Contents/MacOS/gui"); if (check_file_exists("gui.bt", app_path, file_path)) return 1; #else /*iOS: for now, everything is set flat within the package*/ /*iOS app is distributed with embedded GUI*/ get_default_install_path(app_path, GF_PATH_APP); strcat(app_path, "/gui"); if (check_file_exists("gui.bt", app_path, file_path)) return 1; #endif } else { // (path_type==GF_PATH_MODULES) strcat(app_path, "/Contents/MacOS/modules"); if (check_file_exists(TEST_MODULE, app_path, file_path)) return 1; } /*not found ...*/ return 0; }
bool Instance_LocateModule(const char * name, char * fileName) { #if defined(__WIN32__) HMODULE hModule = null; if(name && name[0]) { uint16 _wmoduleName[MAX_LOCATION]; UTF8toUTF16Buffer(name, _wmoduleName, MAX_LOCATION); hModule = GetModuleHandle(_wmoduleName); if(!hModule) { wcscat(_wmoduleName, L".exe"); hModule = GetModuleHandle(_wmoduleName); } if(hModule) { uint16 _wfileName[MAX_LOCATION]; GetModuleFileNameW(hModule, _wfileName, MAX_LOCATION); UTF16toUTF8Buffer(_wfileName, fileName, MAX_LOCATION); return true; } } else { uint16 _wfileName[MAX_LOCATION]; GetModuleFileNameW(null, _wfileName, MAX_LOCATION); UTF16toUTF8Buffer(_wfileName, fileName, MAX_LOCATION); return true; } #elif defined(__APPLE__) if(name && name[0]) { int imageCount = _dyld_image_count(); int c; int nameLen = strlen(name); for(c = 0; c<imageCount; c++) { struct mach_header * header = _dyld_get_image_header(c); char * path = _dyld_get_image_name(c); int pathLen = strlen(path); char * subStr = RSearchString(path, name, pathLen, false, false); if(subStr) { if(( *(subStr-1) == '/' || !strncmp(subStr - 4, "/lib", 4)) && (!subStr[nameLen] || !strncmp(subStr + nameLen, ".dylib", 6))) { strcpy(fileName, path); return true; } } } } else { int size = MAX_LOCATION; _NSGetExecutablePath(fileName, &size); return true; } #elif defined(__unix__) //File f = FileOpen("/proc/self/maps", read); FILE * f = null; char exeName[MAX_FILENAME]; exeName[0] = 0; #if defined(__linux__) f = fopen("/proc/self/status", "r"); #else f = fopen("/proc/curproc/status", "r"); #endif if(f) { char line[1025]; while(fgets(line, sizeof(line), f)) { char * name = strstr(line, "Name:\t"); if(name) { int nameLen; name += 6; nameLen = strlen(name); name[--nameLen] = 0; strcpy(exeName, name); break; } } fclose(f); } #if defined(__linux__) f = fopen("/proc/self/maps", "r"); #else f = fopen("/proc/curproc/map", "r"); #endif if(f) { char line[1025]; //while(f.GetLine(line, sizeof(line))) while(fgets(line, sizeof(line), f)) { char * path = strstr(line, "/"); if(path) { int pathLen = strlen(path); path[--pathLen] = 0; if(name && name[0]) { int nameLen = strlen(name); char * subStr; subStr = RSearchString(path, name, pathLen, false, false); if(subStr) { if(( *(subStr-1) == '/' || !strncmp(subStr - 4, "/lib", 4)) && (!subStr[nameLen] || !strncmp(subStr + nameLen, ".so", 3))) { char * space = strchr(path, ' '); if(space) *space = 0; strcpy(fileName, path); fclose(f); return true; } } } else { char name[MAX_FILENAME]; GetLastDirectory(path, name); if(!exeName[0] || !strcmp(name, exeName)) { char * space = strchr(path, ' '); if(space) *space = 0; strcpy(fileName, path); fclose(f); return true; } } } } fclose(f); } #if !defined(ECERE_NOFILE) && !defined(__linux__) && !defined(__EMSCRIPTEN__) if(name && name[0]) { // Couldn't locate libraries with /proc/curmap/map, attempt with ldd FILE * in = null, * out = null; _DualPipe * p; char command[MAX_LOCATION]; snprintf(command, sizeof(command), "ldd /proc/%d/file", (int)getpid()); p = _DualPipeOpen(1, command, null, &in, &out); if(p) { bool result = false; char line[1025]; int nameLen = strlen(name); while(DualPipe_GetLine(in, line, sizeof(line))) { char * path = strstr(line, "/"); if(path) { int pathLen = strlen(path); char * subStr; path[--pathLen] = 0; subStr = RSearchString(path, name, pathLen, false, false); if(subStr) { if(( *(subStr-1) == '/' || !strncmp(subStr - 4, "/lib", 4)) && (!subStr[nameLen] || !strncmp(subStr + nameLen, ".so", 3))) { char * space = strchr(path, ' '); if(space) *space = 0; strcpy(fileName, path); result = true; } } } } DualPipe_Wait(p); fclose(in); DualPipe_Destructor(p); return result; } } #endif if(!name || !name[0]) { #if defined(__FreeBSD__) { int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 }; size_t cb = MAX_LOCATION; fileName[0] = 0; sysctl(mib, 4, fileName, &cb, null, 0); if(fileName[0]) return true; } #endif #if !defined(__linux__) { char * env; if(!access("/proc/curproc/file", F_OK)) { strcpy(fileName, "/proc/curproc/file"); return true; } if((env = getenv("_"))) { strcpy(fileName, env); return true; } } #endif strcpy(fileName, exeLocation); return true; } #endif return false; }
/* * is_llvm_bitcode_from_memory() is passed a pointer and size of a memory * buffer, a pointer to an arch_flag struct and an pointer to return the lto * module if not NULL. If it the memory is an llvm bit code it returns 1 and * sets the fields in the arch flag. If pmod is not NULL it stores the lto * module in their, if not it frees the lto module. If the memory buffer is * not an llvm bit code it returns 0. */ __private_extern__ int is_llvm_bitcode_from_memory( char *addr, uint32_t size, struct arch_flag *arch_flag, void **pmod) /* maybe NULL */ { uint32_t bufsize; char *p, *prefix, *lto_path, buf[MAXPATHLEN], resolved_name[PATH_MAX]; int i; void *mod; /* * The libLTO API's can't handle empty files. So return 0 to indicate * this is not a bitcode file if it has a zero size. */ if(size == 0) return(0); if(tried_to_load_lto == 0){ tried_to_load_lto = 1; /* * Construct the prefix to this executable assuming it is in a bin * directory relative to a lib directory of the matching lto library * and first try to load that. If not then fall back to trying * "/Applications/Xcode.app/Contents/Developer/Toolchains/ * XcodeDefault.xctoolchain/usr/lib/libLTO.dylib". */ bufsize = MAXPATHLEN; p = buf; i = _NSGetExecutablePath(p, &bufsize); if(i == -1){ p = allocate(bufsize); _NSGetExecutablePath(p, &bufsize); } prefix = realpath(p, resolved_name); p = rindex(prefix, '/'); if(p != NULL) p[1] = '\0'; lto_path = makestr(prefix, "../lib/libLTO.dylib", NULL); lto_handle = dlopen(lto_path, RTLD_NOW); if(lto_handle == NULL){ free(lto_path); lto_path = NULL; lto_handle = dlopen("/Applications/Xcode.app/Contents/" "Developer/Toolchains/XcodeDefault." "xctoolchain/usr/lib/libLTO.dylib", RTLD_NOW); } if(lto_handle == NULL) return(0); lto_is_object = dlsym(lto_handle, "lto_module_is_object_file_in_memory"); lto_create = dlsym(lto_handle, "lto_module_create_from_memory"); lto_create_local = dlsym(lto_handle, "lto_module_create_in_local_context"); lto_dispose = dlsym(lto_handle, "lto_module_dispose"); lto_get_target = dlsym(lto_handle, "lto_module_get_target_triple"); lto_get_num_symbols = dlsym(lto_handle, "lto_module_get_num_symbols"); lto_get_sym_attr = dlsym(lto_handle, "lto_module_get_symbol_attribute"); lto_get_sym_name = dlsym(lto_handle, "lto_module_get_symbol_name"); if(lto_is_object == NULL || lto_create == NULL || lto_dispose == NULL || lto_get_target == NULL || lto_get_num_symbols == NULL || lto_get_sym_attr == NULL || lto_get_sym_name == NULL){ dlclose(lto_handle); if(lto_path != NULL) free(lto_path); return(0); } } if(lto_handle == NULL) return(0); if(!lto_is_object(addr, size)) return(0); if(lto_create_local) mod = lto_create_local(addr, size, "is_llvm_bitcode_from_memory"); else mod = lto_create(addr, size); if(mod == NULL) return(0); /* * It is possible for new targets to be added to lto that are not yet * known to this code. So we will try to get lucky and let them pass * through with the cputype set to 0. This should work for things * like libtool(1) as long as we don't get two different unknown * targets. But we'll hope that just doesn't happen. */ arch_flag->cputype = 0; arch_flag->cpusubtype = 0; arch_flag->name = NULL; (void)get_lto_cputype(arch_flag, lto_get_target(mod)); if(pmod != NULL) *pmod = mod; else lto_free(mod); return(1); }
// set path and pathdll (wpath also set for win) // WIN arg is 0, Unix arg is argv[0] void jepath(char* arg) { #ifdef _WIN32 WCHAR wpath[PLEN]; GetModuleFileNameW(0,wpath,_MAX_PATH); *(wcsrchr(wpath, '\\')) = 0; WideCharToMultiByte(CP_UTF8,0,wpath,1+(int)wcslen(wpath),path,PLEN,0,0); #else #define sz 4000 char arg2[sz],arg3[sz]; char* src,*snk;int n,len=sz; // fprintf(stderr,"arg0 %s\n",arg); // try host dependent way to get path to executable // use arg if they fail (arg command in PATH won't work) #ifdef __MACH__ n=_NSGetExecutablePath(arg2,&len); if(0!=n) strcat(arg2,arg); #else n=readlink("/proc/self/exe",arg2,sizeof(arg2)); if(-1==n) strcpy(arg2,arg); else arg2[n]=0; #endif // fprintf(stderr,"arg2 %s\n",arg2); // arg2 is path (abs or relative) to executable or soft link n=readlink(arg2,arg3,sz); if(-1==n) strcpy(arg3,arg2); else arg3[n]=0; // fprintf(stderr,"arg3 %s\n",arg3); if('/'==*arg3) strcpy(path,arg3); else { getcwd(path,sizeof(path)); strcat(path,"/"); strcat(path,arg3); } *(1+strrchr(path,'/'))=0; // remove ./ and backoff ../ snk=src=path; while(*src) { if('/'==*src&&'.'==*(1+src)&&'.'==*(2+src)&&'/'==*(3+src)) { *snk=0; snk=strrchr(path,'/'); snk=0==snk?path:snk; src+=3; } else if('/'==*src&&'.'==*(1+src)&&'/'==*(2+src)) src+=2; else *snk++=*src++; } *snk=0; snk=path+strlen(path)-1; if('/'==*snk) *snk=0; #endif strcpy(pathdll,path); strcat(pathdll,filesepx); strcat(pathdll,JDLLNAME); // fprintf(stderr,"arg4 %s\n",path); }
void initializePaths() { #if RUN_IN_PLACE /* Use relative paths if RUN_IN_PLACE */ infostream<<"Using relative paths (RUN_IN_PLACE)"<<std::endl; /* Windows */ #if defined(_WIN32) const DWORD buflen = 1000; char buf[buflen]; DWORD len; // Find path of executable and set path_share relative to it 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{ #if STATIC_BUILD path_share = std::string(buf) + "\\."; path_user = std::string(buf) + "\\."; #else path_share = std::string(buf) + "\\.."; path_user = std::string(buf) + "\\.."; #endif } /* Linux */ #elif defined(linux) || defined(__linux) char buf[BUFSIZ]; memset(buf, 0, BUFSIZ); // Get path to executable assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1); pathRemoveFile(buf, '/'); path_share = std::string(buf) + "/.."; path_user = std::string(buf) + "/.."; /* OS X */ #elif defined(__APPLE__) //https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dyld.3.html //TODO: Test this code char buf[BUFSIZ]; uint32_t len = sizeof(buf); assert(_NSGetExecutablePath(buf, &len) != -1); pathRemoveFile(buf, '/'); path_share = std::string(buf) + "/.."; path_user = std::string(buf) + "/.."; /* FreeBSD */ #elif defined(__FreeBSD__) int mib[4]; char buf[BUFSIZ]; size_t len = sizeof(buf); mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PATHNAME; mib[3] = -1; assert(sysctl(mib, 4, buf, &len, NULL, 0) != -1); pathRemoveFile(buf, '/'); path_share = std::string(buf) + "/.."; path_user = std::string(buf) + "/.."; #else //TODO: Get path of executable. This assumes working directory is bin/ dstream<<"WARNING: Relative path not properly supported on this platform" <<std::endl; /* 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 #else // RUN_IN_PLACE /* Use platform-specific paths otherwise */ infostream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl; /* Windows */ #if defined(_WIN32) const DWORD buflen = 1000; char buf[buflen]; DWORD len; // Find path of executable and set path_share relative to it len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen); assert(len < buflen); pathRemoveFile(buf, '\\'); // Use ".\bin\.." path_share = std::string(buf) + "\\.."; // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>" len = GetEnvironmentVariable("APPDATA", buf, buflen); assert(len < buflen); path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME; /* Linux */ #elif defined(linux) || defined(__linux) // Get path to executable std::string bindir = ""; { char buf[BUFSIZ]; memset(buf, 0, BUFSIZ); if (readlink("/proc/self/exe", buf, BUFSIZ-1) == -1) { errorstream << "Unable to read bindir "<< std::endl; #ifndef __ANDROID__ assert("Unable to read bindir" == 0); #endif } else { pathRemoveFile(buf, '/'); bindir = buf; } } // Find share directory from these. // It is identified by containing the subdirectory "builtin". std::list<std::string> trylist; std::string static_sharedir = STATIC_SHAREDIR; if(static_sharedir != "" && static_sharedir != ".") trylist.push_back(static_sharedir); trylist.push_back( bindir + DIR_DELIM + ".." + DIR_DELIM + "share" + DIR_DELIM + PROJECT_NAME); trylist.push_back(bindir + DIR_DELIM + ".."); #ifdef __ANDROID__ trylist.push_back(DIR_DELIM "sdcard" DIR_DELIM PROJECT_NAME); #endif for(std::list<std::string>::const_iterator i = trylist.begin(); i != trylist.end(); i++) { const std::string &trypath = *i; if(!fs::PathExists(trypath) || !fs::PathExists(trypath + DIR_DELIM + "builtin")){ dstream<<"WARNING: system-wide share not found at \"" <<trypath<<"\""<<std::endl; continue; } // Warn if was not the first alternative if(i != trylist.begin()){ dstream<<"WARNING: system-wide share found at \"" <<trypath<<"\""<<std::endl; } path_share = trypath; break; } #ifndef __ANDROID__ path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME; #else path_user = std::string(DIR_DELIM "sdcard" DIR_DELIM PROJECT_NAME DIR_DELIM); #endif /* OS X */ #elif defined(__APPLE__) // Code based on // http://stackoverflow.com/questions/516200/relative-paths-not-working-in-xcode-c CFBundleRef main_bundle = CFBundleGetMainBundle(); CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle); char path[PATH_MAX]; if(CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX)) { dstream<<"Bundle resource path: "<<path<<std::endl; //chdir(path); path_share = std::string(path) + DIR_DELIM + "share"; } else { // error! dstream<<"WARNING: Could not determine bundle resource path"<<std::endl; } CFRelease(resources_url); path_user = std::string(getenv("HOME")) + "/Library/Application Support/" + PROJECT_NAME; #else // FreeBSD, and probably many other POSIX-like systems. path_share = STATIC_SHAREDIR; path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME; #endif #endif // RUN_IN_PLACE }
static void get_executable_path() { uint32_t bufsize = sizeof(executable_path); _NSGetExecutablePath(executable_path, &bufsize); }
char *get_executable_path(char *epath, size_t buflen) { char *p; #ifdef __APPLE__ unsigned int l = buflen; if (_NSGetExecutablePath(epath, &l) != 0) return NULL; #elif defined(__FreeBSD__) || defined(__DragonFly__) int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 }; size_t l = buflen; if (sysctl(mib, 4, epath, &l, NULL, 0) != 0) return NULL; #elif defined(__OpenBSD__) int mib[4]; char **argv; size_t len; size_t l; const char *comm; int ok = 0; mib[0] = CTL_KERN; mib[1] = KERN_PROC_ARGS; mib[2] = getpid(); mib[3] = KERN_PROC_ARGV; if (sysctl(mib, 4, NULL, &len, NULL, 0) < 0) abort(); if (!(argv = malloc(len))) abort(); if (sysctl(mib, 4, argv, &len, NULL, 0) < 0) abort(); comm = argv[0]; if (*comm == '/' || *comm == '.') { char *rpath; if ((rpath = realpath(comm, NULL))) { strlcpy(epath, rpath, buflen); free(rpath); ok = 1; } } else { char *sp; char *xpath = strdup(getenv("PATH")); char *path = strtok_r(xpath, ":", &sp); struct stat st; if (!xpath) abort(); while (path) { snprintf(epath, buflen, "%s/%s", path, comm); if (!stat(epath, &st) && (st.st_mode & S_IXUSR)) { ok = 1; break; } path = strtok_r(NULL, ":", &sp); } free(xpath); } free(argv); if (!ok) return NULL; l = strlen(epath); #else ssize_t l = readlink("/proc/self/exe", epath, buflen); #endif if (l <= 0) return NULL; epath[buflen - 1] = '\0'; p = strrchr(epath, '/'); if (p) *p = '\0'; return epath; }
kim_error kim_os_library_get_application_path (kim_string *out_path) { kim_error err = KIM_NO_ERROR; kim_string path = NULL; CFBundleRef bundle = CFBundleGetMainBundle (); if (!err && !out_path) { err = check_error (KIM_NULL_PARAMETER_ERR); } /* Check if the caller is a bundle */ if (!err && bundle) { CFURLRef bundle_url = CFBundleCopyBundleURL (bundle); CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL (bundle); CFURLRef executable_url = CFBundleCopyExecutableURL (bundle); CFURLRef absolute_url = NULL; CFStringRef cfpath = NULL; if (bundle_url && resources_url && !CFEqual (bundle_url, resources_url)) { absolute_url = CFURLCopyAbsoluteURL (bundle_url); } else if (executable_url) { absolute_url = CFURLCopyAbsoluteURL (executable_url); } if (absolute_url) { cfpath = CFURLCopyFileSystemPath (absolute_url, kCFURLPOSIXPathStyle); if (!cfpath) { err = check_error (KIM_OUT_OF_MEMORY_ERR); } } if (!err && cfpath) { err = kim_os_string_create_from_cfstring (&path, cfpath); } if (cfpath ) { CFRelease (cfpath); } if (absolute_url ) { CFRelease (absolute_url); } if (bundle_url ) { CFRelease (bundle_url); } if (resources_url ) { CFRelease (resources_url); } if (executable_url) { CFRelease (executable_url); } } /* Caller is not a bundle, try _NSGetExecutablePath */ /* Note: this does not work on CFM applications */ if (!err && !path) { char *buffer = NULL; uint32_t len = 0; /* Tiny stupid buffer to get the length of the path */ if (!err) { buffer = malloc (1); if (!buffer) { err = check_error (KIM_OUT_OF_MEMORY_ERR); } } /* Get the length of the path */ if (!err) { if (_NSGetExecutablePath (buffer, &len) != 0) { char *temp = realloc (buffer, len + 1); if (!temp) { err = check_error (KIM_OUT_OF_MEMORY_ERR); } else { buffer = temp; } } } /* Get the path */ if (!err) { if (_NSGetExecutablePath (buffer, &len) != 0) { err = check_error (KIM_OUT_OF_MEMORY_ERR); } else { err = kim_string_copy (&path, buffer); } } if (buffer) { free (buffer); } } if (!err) { *out_path = path; path = NULL; } kim_string_free (&path); return check_error (err); }
std::string getExecutablePath() { #if ARX_PLATFORM == ARX_PLATFORM_MACOSX uint32_t bufsize = 0; // Obtain required size _NSGetExecutablePath(NULL, &bufsize); std::vector<char> exepath(bufsize); if(_NSGetExecutablePath(&exepath.front(), &bufsize) == 0) { char exerealpath[MAXPATHLEN]; if(realpath(&exepath.front(), exerealpath)) { return exerealpath; } } #elif defined(ARX_HAVE_WINAPI) std::vector<char> buffer; buffer.resize(MAX_PATH); if(GetModuleFileNameA(NULL, buffer.data(), buffer.size()) > 0) { return std::string(buffer.data(), buffer.size()); } #else // Try to get the path from OS-specific procfs entries #ifdef ARX_HAVE_READLINK std::vector<char> buffer(1024); // Linux if(try_readlink(buffer, "/proc/self/exe")) { return std::string(buffer.begin(), buffer.end()); } // BSD if(try_readlink(buffer, "/proc/curproc/file")) { return std::string(buffer.begin(), buffer.end()); } // Solaris if(try_readlink(buffer, "/proc/self/path/a.out")) { return std::string(buffer.begin(), buffer.end()); } #endif // FreeBSD #if defined(ARX_HAVE_SYSCTL) && defined(CTL_KERN) && defined(KERN_PROC) \ && defined(KERN_PROC_PATHNAME) && ARX_PLATFORM == ARX_PLATFORM_BSD \ && defined(PATH_MAX) int mib[4]; mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PATHNAME; mib[3] = -1; char pathname[PATH_MAX]; size_t size = sizeof(pathname); int error = sysctl(mib, 4, pathname, &size, NULL, 0); if(error != -1 && size > 0 && size < sizeof(pathname)) { return util::loadString(pathname, size); } #endif // Solaris #ifdef ARX_HAVE_GETEXECNAME const char * execname = getexecname(); if(execname != NULL) { return execname; } #endif // Fall back to argv[0] if possible if(executablePath != NULL) { std::string path(executablePath); if(path.find('/') != std::string::npos) { return path; } } #endif // Give up - we couldn't determine the exe path. return std::string(); }
const char *_CFProcessPath(void) { #if !defined(__LINUX__) CFAllocatorRef alloc = NULL; char *thePath = NULL; int execIndex = 0; if (__CFProcessPath) return __CFProcessPath; if (!__CFProcessPath) { thePath = getenv("CFProcessPath"); alloc = CFRetain(__CFGetDefaultAllocator()); if (thePath) { int len = strlen(thePath); __CFProcessPath = CFAllocatorAllocate(alloc, len+1, 0); if (__CFOASafe) __CFSetLastAllocationEventName((void *)__CFProcessPath, "CFUtilities (process-path)"); memmove((char *)__CFProcessPath, thePath, len + 1); } } #if defined(__MACH__) { struct stat exec, lcfm; unsigned long size = CFMaxPathSize; char buffer[CFMaxPathSize]; if (0 == _NSGetExecutablePath(buffer, &size) && strcasestr(buffer, "LaunchCFMApp") != NULL && 0 == stat("/System/Library/Frameworks/Carbon.framework/Versions/Current/Support/LaunchCFMApp", &lcfm) && 0 == stat(buffer, &exec) && (lcfm.st_dev == exec.st_dev) && (lcfm.st_ino == exec.st_ino)) { // Executable is LaunchCFMApp, take special action execIndex = 1; __CFIsCFM = true; } } #endif if (!__CFProcessPath && NULL != (*_NSGetArgv())[execIndex]) { char buf[CFMaxPathSize] = {0}; #if defined(__WIN32__) HINSTANCE hinst = GetModuleHandle(NULL); DWORD rlen = hinst ? GetModuleFileName(hinst, buf, 1028) : 0; thePath = rlen ? buf : NULL; #else struct stat statbuf; const char *arg0 = (*_NSGetArgv())[execIndex]; if (arg0[0] == '/') { // We've got an absolute path; look no further; thePath = (char *)arg0; } else { char *theList = getenv("PATH"); if (NULL != theList && NULL == strrchr(arg0, '/')) { thePath = _CFSearchForNameInPath(alloc, arg0, theList); if (thePath) { // User could have "." or "../bin" or other relative path in $PATH if (('/' != thePath[0]) && _CFGetCurrentDirectory(buf, CFMaxPathSize)) { strlcat(buf, "/", CFMaxPathSize); strlcat(buf, thePath, CFMaxPathSize); if (0 == stat(buf, &statbuf)) { CFAllocatorDeallocate(alloc, (void *)thePath); thePath = buf; } } if (thePath != buf) { strlcpy(buf, thePath, CFMaxPathSize); CFAllocatorDeallocate(alloc, (void *)thePath); thePath = buf; } } } } // After attempting a search through $PATH, if existant, // try prepending the current directory to argv[0]. if (!thePath && _CFGetCurrentDirectory(buf, CFMaxPathSize)) { if (buf[strlen(buf)-1] != '/') { strlcat(buf, "/", CFMaxPathSize); } strlcat(buf, arg0, CFMaxPathSize); if (0 == stat(buf, &statbuf)) { thePath = buf; } } if (thePath) { // We are going to process the buffer replacing all "/./" with "/" CFIndex srcIndex = 0, dstIndex = 0; CFIndex len = strlen(thePath); for (srcIndex=0; srcIndex<len; srcIndex++) { thePath[dstIndex] = thePath[srcIndex]; dstIndex++; if ((srcIndex < len-2) && (thePath[srcIndex] == '/') && (thePath[srcIndex+1] == '.') && (thePath[srcIndex+2] == '/')) { // We are at the first slash of a "/./" Skip the "./" srcIndex+=2; } } thePath[dstIndex] = 0; } #endif if (!thePath) { thePath = (*_NSGetArgv())[execIndex]; } if (thePath) { int len = strlen(thePath); __CFProcessPath = CFAllocatorAllocate(alloc, len + 1, 0); if (__CFOASafe) __CFSetLastAllocationEventName((void *)__CFProcessPath, "CFUtilities (process-path)"); memmove((char *)__CFProcessPath, thePath, len + 1); } if (__CFProcessPath) { const char *p = 0; int i; for (i = 0; __CFProcessPath[i] != 0; i++){ if (__CFProcessPath[i] == '/') p = __CFProcessPath + i; } if (p != 0) __CFprogname = p + 1; else __CFprogname = __CFProcessPath; } } #endif if (!__CFProcessPath) { __CFProcessPath = ""; } return __CFProcessPath; }
int main(int argc, char *argv[]) { // install debug message handler qInstallMsgHandler(myMessageOutput); // Gain admin privileges on the Mac #ifdef Q_WS_MAC char myPath[PATH_MAX]; uint32_t pathSize=sizeof(myPath); if(geteuid() != 0) { AuthorizationItem adminPriv; AuthorizationRights adminRights; AuthorizationRef adminRightsRef; OSStatus result; char myPath[MAXPATHLEN]; uint32_t pathSize = MAXPATHLEN; int childStatus; adminPriv.name = kAuthorizationRightExecute; adminPriv.valueLength = 0; adminPriv.value = NULL; adminPriv.flags = 0; adminRights.count = 1; adminRights.items = &adminPriv; result = AuthorizationCreate(&adminRights, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults | kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed, &adminRightsRef); if(result != errAuthorizationSuccess) { fprintf(stderr, "Couldn't Authenticate: %d\n", result); exit(1); } _NSGetExecutablePath(myPath, &pathSize); result = AuthorizationExecuteWithPrivileges(adminRightsRef, myPath, kAuthorizationFlagDefaults, NULL, NULL); if(result != errAuthorizationSuccess) { fprintf(stderr, "Couldn't execute self: %d\n", result); } waitpid(-1, &childStatus, NULL); exit(0); } _NSGetExecutablePath(myPath,&pathSize); char* slash = strrchr(myPath, '/'); if(slash!=NULL) { *slash = '\0'; } #endif // Q_WS_MAC QApplication a(argc, argv); MainWindow w; #ifdef Q_WS_MAC w.setPath(myPath); #endif w.show(); return a.exec(); }
EXPORT int run(const char **ENV_VARS, const char **ENV_VAR_VALS, char *PROGRAM, const char *MODULE, const char *FUNCTION, const char *PYVER, int IS_GUI, int argc, const char **argv, const char **envp) { char *pathPtr = NULL, *t = NULL; char buf[3*PATH_MAX]; int ret = 0, i; PyObject *site, *mainf, *res; uint32_t buf_size = PATH_MAX+1; char *ebuf = calloc(buf_size, sizeof(char)); ret = _NSGetExecutablePath(ebuf, &buf_size); if (ret == -1) { free(ebuf); ebuf = calloc(buf_size, sizeof(char)); if (_NSGetExecutablePath(ebuf, &buf_size) != 0) return report_error("Failed to find real path of executable."); } pathPtr = realpath(ebuf, buf); if (pathPtr == NULL) { return report_error(strerror(errno)); } for (i = 0; i < 3; i++) { t = rindex(pathPtr, '/'); if (t == NULL) return report_error("Failed to determine bundle path."); *t = '\0'; } if (strstr(pathPtr, "/calibre.app/Contents/") != NULL) { // We are one of the duplicate executables created to workaround codesign's limitations for (i = 0; i < 2; i++) { t = rindex(pathPtr, '/'); if (t == NULL) return report_error("Failed to resolve bundle path in dummy executable"); *t = '\0'; } } char rpath[PATH_MAX+1], exe_path[PATH_MAX+1]; snprintf(exe_path, PATH_MAX+1, "%s/Contents", pathPtr); snprintf(rpath, PATH_MAX+1, "%s/Resources", exe_path); initialize_interpreter(ENV_VARS, ENV_VAR_VALS, PROGRAM, MODULE, FUNCTION, PYVER, IS_GUI, exe_path, rpath, argc, argv); site = PyImport_ImportModule("site"); if (site == NULL) ret = calibre_show_python_error("Failed to import site module", -1); else { Py_XINCREF(site); mainf = PyObject_GetAttrString(site, "main"); if (mainf == NULL || !PyCallable_Check(mainf)) ret = calibre_show_python_error("site module has no main function", -1); else { Py_XINCREF(mainf); res = PyObject_CallObject(mainf, NULL); if (res == NULL) ret = calibre_show_python_error("Python function terminated unexpectedly", -1); else { } } } PyErr_Clear(); Py_Finalize(); //printf("11111 Returning: %d\r\n", ret); return ret; }
char *exe_name(void) { #if defined(WIN) char *name= (char *)malloc(64); DWORD max=64, res; while ((res = GetModuleFileName(NULL, name, max)) >= max) { #elif defined MACOSX char *fn=(char*)malloc(64),*name=(char*)malloc(PATH_MAX); uint32_t max=64, res; if (_NSGetExecutablePath(fn, &max) != 0) { fn = (char*)realloc(fn, max); _NSGetExecutablePath(fn, &max); } if (realpath(fn, name) == NULL) { free(fn); free(name); return NULL; } res = 1; #else char fn[64], *name=(char *)malloc(64); size_t max=64, res; sprintf(fn, "/proc/self/exe"); memset(name, 0, max); while ((res = readlink(fn, name, max)) >= max-1) { #endif #ifndef MACOSX max *= 2; name = (char *)realloc(name, max); memset(name, 0, max); } #endif if (res <= 0) { free(name); return NULL; } return name; } //Signum function int isign(float i) //TODO: INline or macro { if (i<0) return -1; if (i>0) return 1; return 0; } unsigned clamp_flt(float f, float min, float max) //TODO: Also inline/macro { if (f<min) return 0; if (f>max) return 255; return (int)(255.0f*(f-min)/(max-min)); } float restrict_flt(float f, float min, float max) //TODO Inline or macro or something { if (f<min) return min; if (f>max) return max; return f; } char *mystrdup(const char *s) { char *x; if (s) { x = (char*)malloc(strlen(s)+1); strcpy(x, s); return x; } return NULL; }
static void spawn_via_launchd(void) { char watchman_path[WATCHMAN_NAME_MAX]; uint32_t size = sizeof(watchman_path); char plist_path[WATCHMAN_NAME_MAX]; FILE *fp; struct passwd *pw; uid_t uid; char *argv[MAX_DAEMON_ARGS] = { "/bin/launchctl", "load", "-F", NULL }; posix_spawnattr_t attr; pid_t pid; int res; if (_NSGetExecutablePath(watchman_path, &size) == -1) { w_log(W_LOG_ERR, "_NSGetExecutablePath: path too long; size %u\n", size); abort(); } uid = getuid(); pw = getpwuid(uid); if (!pw) { w_log(W_LOG_ERR, "getpwuid(%d) failed: %s. I don't know who you are\n", uid, strerror(errno)); abort(); } snprintf(plist_path, sizeof(plist_path), "%s/Library/LaunchAgents", pw->pw_dir); // Best effort attempt to ensure that the agents dir exists. We'll detect // and report the failure in the fopen call below. mkdir(plist_path, 0755); snprintf(plist_path, sizeof(plist_path), "%s/Library/LaunchAgents/com.github.facebook.watchman.plist", pw->pw_dir); fp = fopen(plist_path, "w"); if (!fp) { w_log(W_LOG_ERR, "Failed to open %s for write: %s\n", plist_path, strerror(errno)); abort(); } fprintf(fp, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" " "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" "<plist version=\"1.0\">\n" "<dict>\n" " <key>Label</key>\n" " <string>com.github.facebook.watchman</string>\n" " <key>Disabled</key>\n" " <false/>\n" " <key>ProgramArguments</key>\n" " <array>\n" " <string>%s</string>\n" " <string>--foreground</string>\n" " <string>--logfile=%s</string>\n" " <string>--sockname=%s</string>\n" " <string>--statefile=%s</string>\n" " </array>\n" " <key>Sockets</key>\n" " <dict>\n" " <key>sock</key>\n" // coupled with get_listener_socket_from_launchd " <dict>\n" " <key>SockPathName</key>\n" " <string>%s</string>\n" " </dict>\n" " </dict>\n" " <key>KeepAlive</key>\n" " <dict>\n" " <key>Crashed</key>\n" " <true/>\n" " </dict>\n" " <key>RunAtLoad</key>\n" " <false/>\n" "</dict>\n" "</plist>\n", watchman_path, log_name, sock_name, watchman_state_file, sock_name); fclose(fp); append_argv(argv, plist_path); errno = posix_spawnattr_init(&attr); if (errno != 0) { w_log(W_LOG_FATAL, "posix_spawnattr_init: %s\n", strerror(errno)); } res = posix_spawnp(&pid, argv[0], NULL, &attr, argv, environ); if (res) { w_log(W_LOG_FATAL, "Failed to spawn watchman via launchd: %s\n", strerror(errno)); } posix_spawnattr_destroy(&attr); if (waitpid(pid, &res, 0) == -1) { w_log(W_LOG_FATAL, "Failed waiting for launchctl load: %s\n", strerror(errno)); } if (WIFEXITED(res) && WEXITSTATUS(res) == 0) { return; } // Most likely cause is "headless" operation with no GUI context if (WIFEXITED(res)) { w_log(W_LOG_ERR, "launchctl: exited with status %d\n", WEXITSTATUS(res)); } else if (WIFSIGNALED(res)) { w_log(W_LOG_ERR, "launchctl: signalled with %d\n", WTERMSIG(res)); } w_log(W_LOG_ERR, "Falling back to daemonize\n"); daemonize(); }
// Determine the absolute path of the directory the current executable is in // and add it to our search path static void add_exec_dir() { char path[FILENAME_MAX]; bool success; #ifdef PLATFORM_IS_WINDOWS // Specified size *includes* nul terminator GetModuleFileName(NULL, path, FILENAME_MAX); success = (GetLastError() == ERROR_SUCCESS); #elif defined PLATFORM_IS_LINUX // Specified size *excludes* nul terminator ssize_t r = readlink("/proc/self/exe", path, FILENAME_MAX - 1); success = (r >= 0); if(success) path[r] = '\0'; #elif defined PLATFORM_IS_FREEBSD int mib[4]; mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PATHNAME; mib[3] = -1; size_t len = FILENAME_MAX; int r = sysctl(mib, 4, path, &len, NULL, 0); success = (r == 0); #elif defined PLATFORM_IS_MACOSX char exec_path[FILENAME_MAX]; uint32_t size = sizeof(exec_path); int r = _NSGetExecutablePath(exec_path, &size); success = (r == 0); if(success) { pony_realpath(exec_path, path); } #else # error Unsupported platform for exec_path() #endif if(!success) { errorf(NULL, "Error determining executable path"); return; } // We only need the directory char *p = strrchr(path, PATH_SLASH); if(p == NULL) { errorf(NULL, "Error determining executable path (%s)", path); return; } p++; *p = '\0'; add_path(path); // Allow ponyc to find the packages directory when it is installed. #ifdef PLATFORM_IS_WINDOWS strcpy(p, "..\\packages"); #else strcpy(p, "../packages"); #endif add_path(path); // Check two levels up. This allows ponyc to find the packages directory // when it is built from source. #ifdef PLATFORM_IS_WINDOWS strcpy(p, "..\\..\\packages"); #else strcpy(p, "../../packages"); #endif add_path(path); }
/* * Return full path to the current executable. * Executable is the .exe created by pyinstaller: path/myappname.exe * Because the calling process can set argv[0] to whatever it wants, * we use a few alternate methods to get the executable path. * * execfile - buffer where to put path to executable. * appname - usually the item argv[0]. */ int pyi_path_executable(char *execfile, const char *appname) { char buffer[PATH_MAX]; size_t result = -1; #ifdef _WIN32 wchar_t modulename_w[PATH_MAX]; /* GetModuleFileNameW returns an absolute, fully qualified path */ if (!GetModuleFileNameW(NULL, modulename_w, PATH_MAX)) { FATALERROR("Failed to get executable path. \nGetModuleFileNameW: %s", GetWinErrorString()); return -1; } if (!pyi_win32_utils_to_utf8(execfile, modulename_w, PATH_MAX)) { FATALERROR("Failed to convert executable path to UTF-8.", GetWinErrorString()); return -1; } #elif __APPLE__ uint32_t length = sizeof(buffer); /* Mac OS X has special function to obtain path to executable. * This may return a symlink. */ if (_NSGetExecutablePath(buffer, &length) != 0) { FATALERROR("System error - unable to load!"); return -1; } if (pyi_path_fullpath(execfile, PATH_MAX, buffer) == false) { VS("LOADER: Cannot get fullpath for %s\n", execfile); return -1; } #else /* ifdef _WIN32 */ result = -1; /* On Linux, FreeBSD, and Solaris, we try these /proc paths first */ #if defined(__linux__) result = readlink("/proc/self/exe", execfile, PATH_MAX); /* Linux */ #elif defined(__FreeBSD__) result = readlink("/proc/curproc/file", execfile, PATH_MAX); /* FreeBSD */ #elif defined(__sun) result = readlink("/proc/self/path/a.out", execfile, PATH_MAX); /* Solaris */ #endif if (-1 != result) { /* execfile is not yet zero-terminated. result is the byte count. */ *(execfile + result) = '\0'; } else { /* No /proc path found or provided */ if (appname[0] == PYI_SEP || strchr(appname, PYI_SEP)) { /* Absolute or relative path. * Convert to absolute and resolve symlinks. */ if (pyi_path_fullpath(execfile, PATH_MAX, appname) == false) { VS("LOADER: Cannot get fullpath for %s\n", execfile); return -1; } } else { /* Not absolute or relative path, just program name. Search $PATH */ result = pyi_search_path(buffer, appname); if (-1 == result) { /* Searching $PATH failed, user is crazy. */ VS("LOADER: Searching $PATH failed for %s", appname); strcpy(buffer, appname); } if (pyi_path_fullpath(execfile, PATH_MAX, buffer) == false) { VS("LOADER: Cannot get fullpath for %s\n", execfile); return -1; } } } #endif /* ifdef _WIN32 */ VS("LOADER: executable is %s\n", execfile); return 0; }
void XBMCHelper::Configure() { int oldMode = m_mode; int oldDelay = m_sequenceDelay; int oldAlwaysOn = m_alwaysOn; int oldPort = m_port; // Read the new configuration. m_errorStarting = false; m_mode = g_guiSettings.GetInt("input.appleremotemode"); m_sequenceDelay = g_guiSettings.GetInt("input.appleremotesequencetime"); m_alwaysOn = g_guiSettings.GetBool("input.appleremotealwayson"); CStdString port_string = g_guiSettings.GetString("services.esport"); m_port = atoi(port_string.c_str()); // Don't let it enable if sofa control or remote buddy is around. if (IsRemoteBuddyInstalled() || IsSofaControlRunning()) { // If we were starting then remember error. if (oldMode == APPLE_REMOTE_DISABLED && m_mode != APPLE_REMOTE_DISABLED) m_errorStarting = true; m_mode = APPLE_REMOTE_DISABLED; g_guiSettings.SetInt("input.appleremotemode", APPLE_REMOTE_DISABLED); } // New configuration. if (oldMode != m_mode || oldDelay != m_sequenceDelay || oldPort != m_port) { // Build a new config string. std::string strConfig; switch (m_mode) { case APPLE_REMOTE_UNIVERSAL: strConfig = "--universal "; break; case APPLE_REMOTE_MULTIREMOTE: strConfig = "--multiremote "; break; default: break; } std::stringstream strPort; strPort << "--port " << m_port; strConfig += strPort.str(); #ifdef _DEBUG strConfig += "--verbose "; #endif char strDelay[64]; sprintf(strDelay, "--timeout %d ", m_sequenceDelay); strConfig += strDelay; // Find out where we're running from. char real_path[2*MAXPATHLEN]; char given_path[2*MAXPATHLEN]; uint32_t path_size = 2*MAXPATHLEN; if (_NSGetExecutablePath(given_path, &path_size) == 0) { if (realpath(given_path, real_path) != NULL) { strConfig += "--appPath \""; strConfig += real_path; strConfig += "\" "; strConfig += "--appHome \""; strConfig += m_homepath; strConfig += "\" "; } } // Write the new configuration. strConfig + "\n"; WriteFile(m_configFile.c_str(), strConfig); // If process is running, kill -HUP to have it reload settings. int pid = GetProcessPid(XBMC_HELPER_PROGRAM); if (pid != -1) kill(pid, SIGHUP); } // Turning off? if (oldMode != APPLE_REMOTE_DISABLED && m_mode == APPLE_REMOTE_DISABLED) { Stop(); Uninstall(); } // Turning on. if (oldMode == APPLE_REMOTE_DISABLED && m_mode != APPLE_REMOTE_DISABLED) Start(); // Installation/uninstallation. if (oldAlwaysOn == false && m_alwaysOn == true) Install(); if (oldAlwaysOn == true && m_alwaysOn == false) Uninstall(); }
void QueryAgent::make_discoverable() { // Create a tmp file containing the information to be used // by console to find us. const char* tmpdir = 0; if(shared_.config.qa_tmpdir.value.size() > 0) { tmpdir = shared_.config.qa_tmpdir.value.c_str(); } else { tmpdir = getenv("TMPDIR"); } if(tmpdir) { std::ostringstream ss; pid_t pid = getpid(); ss << tmpdir << "/rubinius-agent." << pid; strncpy(tmp_path, ss.str().c_str(), ss.str().size()); std::ofstream stream(tmp_path); // Couldn't open the path, for whatever reason. if(!stream) return; int argc = shared_.env()->argc(); char** argv = shared_.env()->argv(); if(stream) { stream << pid << "\n"; stream << port() << "\n"; for(int i = 0; i < argc; i++) { stream << argv[i] << " "; } stream << "\n"; char buf[PATH_MAX]; #ifdef __APPLE__ uint32_t size = PATH_MAX; if(_NSGetExecutablePath(buf, &size) == 0) { stream << buf << "\n"; } else if(realpath(argv[0], buf)) { stream << buf << "\n"; } else { stream << argv[0] << "\n"; } #elif defined(__linux__) { std::ifstream exe("/proc/self/exe"); if(exe) { char buf[PATH_MAX]; exe.get(buf, PATH_MAX); stream << buf << "\n"; } else if(realpath(argv[0], buf)) { stream << buf << "\n"; } else { stream << argv[0] << "\n"; } } #else if(realpath(argv[0], buf)) { stream << buf << "\n"; } else { stream << argv[0] << "\n"; } #endif stream.close(); atexit(remove_tmp_path); } } }