Beispiel #1
0
/*static*/ OsPath Paths::RootData(const OsPath& argv0)
{

#ifdef INSTALLED_DATADIR
	UNUSED2(argv0);
	return OsPath(STRINGIZE(INSTALLED_DATADIR))/"";
#else

# if OS_MACOSX
	if (osx_IsAppBundleValid())
	{
		debug_printf(L"Valid app bundle detected\n");

		std::string resourcesPath = osx_GetBundleResourcesPath();
		// Ensure we have a valid resources path
		ENSURE(!resourcesPath.empty());

		return OsPath(resourcesPath)/"data"/"";
	}
# endif // OS_MACOSX

	return Root(argv0)/"data"/"";

#endif // INSTALLED_DATADIR
}
Beispiel #2
0
OsPath sys_ExecutablePathname()
{
	OsPath path;

	// On OS X we might be a bundle, return the bundle path as the executable name,
	//	i.e. /path/to/0ad.app instead of /path/to/0ad.app/Contents/MacOS/pyrogenesis
	if (osx_IsAppBundleValid())
	{
		path = osx_GetBundlePath();
		ENSURE(!path.empty());
	}
	else
	{
		char temp[PATH_MAX];
		u32 size = PATH_MAX;
		if (_NSGetExecutablePath(temp, &size) == 0)
		{
			char name[PATH_MAX];
			realpath(temp, name);
			path = OsPath(name);
		}
	}

	return path;
}
Beispiel #3
0
int
AccessFile(const char *path, int mode)
{ char tmp[MAXPATHLEN];
#ifdef HAVE_ACCESS
  int m = 0;

  if ( mode == ACCESS_EXIST )
    m = F_OK;
  else
  { if ( mode & ACCESS_READ    ) m |= R_OK;
    if ( mode & ACCESS_WRITE   ) m |= W_OK;
#ifdef X_OK
    if ( mode & ACCESS_EXECUTE ) m |= X_OK;
#endif
  }

#ifdef __ANDROID__
  if (Yap_isAsset(path)) {
    return  !(mode & ACCESS_WRITE ) && Yap_AccessAsset(path, m);
  }
#endif
  return access(OsPath(path, tmp), m) == 0 ? TRUE : FALSE;
#else
# error "No implementation for AccessFile()"
#endif
}
Beispiel #4
0
void CNetTurnManager::DisplayOOSError(u32 turn, const std::string& hash, const std::string& expectedHash, bool isReplay, OsPath* path = NULL)
{
	m_HasSyncError = true;

	std::stringstream msg;
	msg << "Out of sync on turn " << turn << ": expected hash " << expectedHash << "\n";

	if (expectedHash != hash || m_CurrentTurn != turn)
		msg << "\nCurrent state: turn " << m_CurrentTurn << ", hash " << hash << "\n\n";

	if (isReplay)
		msg << "\nThe current game state is different from the original game state.\n\n";
	else
	{
		if (expectedHash == hash)
			msg << "Your game state is identical to the hosts game state.\n\n";
		else
			msg << "Your game state is different from the hosts game state.\n\n";
	}

	if (path)
		msg << "Dumping current state to " << utf8_from_wstring(OsPath(*path).string());

	LOGERROR("%s", msg.str());

	if (g_GUI)
		g_GUI->DisplayMessageBox(600, 350, L"Sync error", wstring_from_utf8(msg.str()));
}
Beispiel #5
0
/*static*/ OsPath Paths::Root(const OsPath& argv0)
{
#if OS_ANDROID
	return OsPath("/sdcard/0ad"); // TODO: this is kind of bogus
#else

	// get full path to executable
	OsPath pathname = sys_ExecutablePathname();	// safe, but requires OS-specific implementation
	if(pathname.empty())	// failed, use argv[0] instead
	{
		errno = 0;
		pathname = wrealpath(argv0);
		if(pathname.empty())
			WARN_IF_ERR(StatusFromErrno());
	}

	// make sure it's valid
	if(!FileExists(pathname))
	{
		LOGERROR(L"Cannot find executable (expected at '%ls')", pathname.string().c_str());
		WARN_IF_ERR(StatusFromErrno());
	}

	for(size_t i = 0; i < 2; i++)	// remove "system/name.exe"
		pathname = pathname.Parent();
	return pathname;

#endif
}
Beispiel #6
0
int
LastModifiedFile(const char *name, double *tp)
{
#ifdef __WINDOWS__
  HANDLE hFile;
  wchar_t wfile[MAXPATHLEN];

#define nano * 0.000000001
#define ntick 100.0
#define SEC_TO_UNIX_EPOCH 11644473600.0

  if ( !_xos_os_filenameW(name, wfile, MAXPATHLEN) )
    return FALSE;

  if ( (hFile=CreateFileW(wfile,
			  0,
			  FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE,
			  NULL,
			  OPEN_EXISTING,
			  FILE_FLAG_BACKUP_SEMANTICS,
			  NULL)) != INVALID_HANDLE_VALUE )
  { FILETIME wt;
    int rc;

    rc = GetFileTime(hFile, NULL, NULL, &wt);
    CloseHandle(hFile);

    if ( rc )
    { double t;

      t  = (double)wt.dwHighDateTime * (4294967296.0 * ntick nano);
      t += (double)wt.dwLowDateTime  * (ntick nano);
      t -= SEC_TO_UNIX_EPOCH;

      *tp = t;

      return TRUE;
    }
  }

  set_posix_error(GetLastError());

  return FALSE;
#else
  char tmp[MAXPATHLEN];
  statstruct buf;

  if ( statfunc(OsPath(name, tmp), &buf) < 0 )
    return FALSE;

#ifdef HAVE_STRUCT_STAT_ST_MTIM
  *tp = (double)buf.st_mtim.tv_sec + (double)buf.st_mtim.tv_nsec/1.0e9;
#else
  *tp = (double)buf.st_mtime;
#endif

  return TRUE;
#endif
}
Beispiel #7
0
struct wdirent* wreaddir(WDIR* wd)
{
	dirent* ent = readdir(wd->d);
	if(!ent)
		return 0;
	wcscpy_s(wd->name, ARRAY_SIZE(wd->name), OsPath(ent->d_name).string().c_str());
	return &wd->ent;
}
Beispiel #8
0
OsPath wrealpath(const OsPath& pathname)
{
	char resolvedBuf[PATH_MAX];
	const char* resolved = realpath(OsString(pathname).c_str(), resolvedBuf);
	if(!resolved)
		return OsPath();
	return resolved;
}
Beispiel #9
0
int
AccessFile(const char *path, int mode)
{ char tmp[MAXPATHLEN];
#ifdef HAVE_ACCESS
  return access(OsPath(path, tmp), access_mode(mode)) == 0 ? TRUE : FALSE;
#else
#error "No implementation for AccessFile()"
#endif
}
Beispiel #10
0
static int64_t
SizeFile(const char *path)
{ char tmp[MAXPATHLEN];
  statstruct buf;

  if ( statfunc(OsPath(path, tmp), &buf) < 0 )
    return -1;

  return buf.st_size;
}
Beispiel #11
0
int
AccessDirectory(const char *path, int mode)
{
#if O_XOS
  char tmp[MAXPATHLEN];
  return _xos_access_dir(OsPath(path, tmp), access_mode(mode)) == 0 ? TRUE : FALSE;
#else
  return AccessFile(path, mode);
#endif
}
Beispiel #12
0
/*static*/ OsPath Paths::XDG_Path(const char* envname, const OsPath& home, const OsPath& defaultPath)
{
	const char* path = getenv(envname);
	if(path)
	{
		if(path[0] != '/')	// relative to $HOME
			return home / path/"";
		return OsPath(path)/"";
	}
	return defaultPath/"";
}
Beispiel #13
0
static int64_t
SizeFile(const char *path)
{ char tmp[MAXPATHLEN];
  statstruct buf;

#ifdef __ANDROID__
  if (Yap_isAsset(path)) {
    return Yap_AssetSize( path );
  }
#endif
  if ( statfunc(OsPath(path, tmp), &buf) < 0 )
    return -1;

  return buf.st_size;
}
Beispiel #14
0
int
ExistsFile(const char *path)
{
#ifdef O_XOS
  return _xos_exists(path, _XOS_FILE);
#else
  char tmp[MAXPATHLEN];
  statstruct buf;

  if ( statfunc(OsPath(path, tmp), &buf) == -1 || !S_ISREG(buf.st_mode) )
  { DEBUG(2, perror(tmp));
    return FALSE;
  }
  return TRUE;
#endif
}
Beispiel #15
0
int
ExistsDirectory(const char *path)
{
#ifdef O_XOS
  return _xos_exists(path, _XOS_DIR);
#else
  char tmp[MAXPATHLEN];
  char *ospath = OsPath(path, tmp);
  statstruct buf;

  if ( statfunc(ospath, &buf) < 0 )
    return FALSE;

  if ( S_ISDIR(buf.st_mode) )
    return TRUE;

  return FALSE;
#endif /*O_XOS*/
}
Beispiel #16
0
static void fsevent_callback(
    ConstFSEventStreamRef UNUSED(streamRef),
    void * UNUSED(clientCallBackInfo),
    size_t numEvents,
    void *eventPaths,
    const FSEventStreamEventFlags eventFlags[],
    const FSEventStreamEventId UNUSED(eventIds)[] )
{
    unsigned long i;
    char **paths = (char **)eventPaths;
 
    for (i=0; i<numEvents; i++)
    {
      bool    isWatched = false;
      OsPath eventPath  = OsPath(paths[i]);
      unsigned long eventType = eventFlags[i];

      if ( eventPath.Filename().string().c_str()[0] != '.' )
      {
        for ( DirWatchMap::iterator it = g_Paths.begin() ; it != g_Paths.end(); ++it)
          if ( path_is_subpath( it->path.string().c_str(), eventPath.string().c_str() ) )
            isWatched = true;
      }

      if ( ! isWatched )
        return;

      OsPath filename = Path( eventPath.string().c_str() );

      if ( eventType & kFSEventStreamEventFlagItemIsFile)
      {
        if ( eventType & kFSEventStreamEventFlagItemRemoved )
          g_QueuedDirs.push_back(DirWatchNotification( filename.string().c_str(), DirWatchNotification::Deleted ));
        else if ( eventType & kFSEventStreamEventFlagItemRenamed )
          g_QueuedDirs.push_back(DirWatchNotification( filename.string().c_str(), DirWatchNotification::Deleted ));
        else if ( eventType & kFSEventStreamEventFlagItemCreated )
          g_QueuedDirs.push_back(DirWatchNotification( filename.string().c_str(), DirWatchNotification::Created ));
        else if ( eventType & kFSEventStreamEventFlagItemModified )
          g_QueuedDirs.push_back(DirWatchNotification( filename.string().c_str(), DirWatchNotification::Changed ));
      }
    }

}
Beispiel #17
0
Paths::Paths(const CmdLineArgs& args)
{
	m_root = Root(args.GetArg0());

#ifdef INSTALLED_DATADIR
	m_rdata = OsPath(STRINGIZE(INSTALLED_DATADIR))/"";
#else
	m_rdata = m_root/"data"/"";
#endif

	const char* subdirectoryName = args.Has("writableRoot")? 0 : "0ad";

	// everything is a subdirectory of the root
	if(!subdirectoryName)
	{
		m_data = m_rdata;
		m_config = m_data/"config"/"";
		m_cache = m_data/"cache"/"";
		m_logs = m_root/"logs"/"";
	}
	else
	{
#if OS_WIN
		const OsPath appdata = wutil_AppdataPath() / subdirectoryName/"";
		m_data = appdata/"data"/"";
		m_config = appdata/"config"/"";
		m_cache = appdata/"cache"/"";
		m_logs = appdata/"logs"/"";
#else
		const char* envHome = getenv("HOME");
		ENSURE(envHome);
		const OsPath home(envHome);
		const OsPath xdgData   = XDG_Path("XDG_DATA_HOME",   home, home/".local/share/") / subdirectoryName;
		const OsPath xdgConfig = XDG_Path("XDG_CONFIG_HOME", home, home/".config/"     ) / subdirectoryName;
		const OsPath xdgCache  = XDG_Path("XDG_CACHE_HOME",  home, home/".cache/"      ) / subdirectoryName;
		m_data   = xdgData/"";
		m_cache  = xdgCache/"";
		m_config = xdgConfig/"config"/"";
		m_logs   = xdgConfig/"logs"/"";
#endif
	}
}
Beispiel #18
0
int
ExistsDirectory(const char *path)
{
#ifdef O_XOS
  return _xos_exists(path, _XOS_DIR);
#else
  char tmp[MAXPATHLEN];
  char *ospath = OsPath(path, tmp);
  statstruct buf;

#ifdef __ANDROID__
  if (Yap_isAsset(ospath)) {
    return   Yap_AssetIsDir(ospath);
  }
#endif
  if ( statfunc(ospath, &buf) < 0 )
    return FALSE;

  if ( S_ISDIR(buf.st_mode) )
    return TRUE;

  return FALSE;
#endif /*O_XOS*/
}
OsPath unix_ExecutablePathname()
{
    // Find the executable's filename
    Dl_info dl_info;
    memset(&dl_info, 0, sizeof(dl_info));
    if (!T::dladdr((void *)sys_ExecutablePathname, &dl_info) || !dl_info.dli_fname)
        return OsPath();
    const char* path = dl_info.dli_fname;

    // If this looks like an absolute path, use realpath to get the normalized
    // path (with no '.' or '..')
    if (path[0] == '/')
    {
        char resolved[PATH_MAX];
        if (!realpath(path, resolved))
            return OsPath();
        return resolved;
    }

    // If this looks like a relative path, resolve against cwd and use realpath
    if (strchr(path, '/'))
    {
        char cwd[PATH_MAX];
        if (!T::getcwd(cwd, PATH_MAX))
            return OsPath();

        char absolute[PATH_MAX];
        int ret = snprintf(absolute, PATH_MAX, "%s/%s", cwd, path);
        if (ret < 0 || ret >= PATH_MAX)
            return OsPath(); // path too long, or other error
        char resolved[PATH_MAX];
        if (!realpath(absolute, resolved))
            return OsPath();
        return resolved;
    }

    // If it's not a path at all, i.e. it's just a filename, we'd
    // probably have to search through PATH to find it.
    // That's complex and should be uncommon, so don't bother.
    return OsPath();
}
Beispiel #20
0
// moved into a helper function to ensure args is destroyed before
// exit(), which may result in a memory leak.
static void RunGameOrAtlas(int argc, const char* argv[])
{
	CmdLineArgs args(argc, argv);

	g_args = args;

	// We need to initialise libxml2 in the main thread before
	// any thread uses it. So initialise it here before we
	// might run Atlas.
	CXeromyces::Startup();

	// run Atlas (if requested via args)
	bool ran_atlas = ATLAS_RunIfOnCmdLine(args, false);
	// Atlas handles the whole init/shutdown/etc sequence by itself;
	// when we get here, it has exited and we're done.
	if(ran_atlas)
		return;

	// run non-visual simulation replay if requested
	if (args.Has("replay"))
	{
		std::string replayFile = args.Get("replay");
		if (!FileExists(OsPath(replayFile)))
		{
			debug_printf("ERROR: The requested replay file '%s' does not exist!\n", replayFile.c_str());
			return;
		}
		Paths paths(args);
		g_VFS = CreateVfs(20 * MiB);
		g_VFS->Mount(L"cache/", paths.Cache(), VFS_MOUNT_ARCHIVABLE);
		MountMods(paths, GetMods(args, INIT_MODS));

		{
			CReplayPlayer replay;
			replay.Load(replayFile);
			replay.Replay(args.Has("serializationtest"), args.Has("ooslog"));
		}

		g_VFS.reset();

		CXeromyces::Terminate();
		return;
	}

	// If visual replay file does not exist, quit before starting the renderer
	if (args.Has("replay-visual"))
	{
		std::string replayFile = args.Get("replay-visual");
		if (!FileExists(OsPath(replayFile)))
		{
			debug_printf("ERROR: The requested replay file '%s' does not exist!\n", replayFile.c_str());
			return;
		}
	}

	// run in archive-building mode if requested
	if (args.Has("archivebuild"))
	{
		Paths paths(args);

		OsPath mod(args.Get("archivebuild"));
		OsPath zip;
		if (args.Has("archivebuild-output"))
			zip = args.Get("archivebuild-output");
		else
			zip = mod.Filename().ChangeExtension(L".zip");

		CArchiveBuilder builder(mod, paths.Cache());

		// Add mods provided on the command line
		// NOTE: We do not handle mods in the user mod path here
		std::vector<CStr> mods = args.GetMultiple("mod");
		for (size_t i = 0; i < mods.size(); ++i)
			builder.AddBaseMod(paths.RData()/"mods"/mods[i]);

		builder.Build(zip, args.Has("archivebuild-compress"));

		CXeromyces::Terminate();
		return;
	}

	const double res = timer_Resolution();
	g_frequencyFilter = CreateFrequencyFilter(res, 30.0);

	// run the game
	int flags = INIT_MODS;
	do
	{
		restart = false;
		quit = false;
		if (!Init(args, flags))
		{
			flags &= ~INIT_MODS;
			Shutdown(SHUTDOWN_FROM_CONFIG);
			continue;
		}
		InitGraphics(args, 0);
		MainControllerInit();
		while (!quit)
			Frame();
		Shutdown(0);
		MainControllerShutdown();
		flags &= ~INIT_MODS;
	} while (restart);

	if (restart_in_atlas)
	{
		ATLAS_RunIfOnCmdLine(args, true);
		return;
	}

	// Shut down libxml2 (done here to match the Startup call)
	CXeromyces::Terminate();
}
Beispiel #21
0
Paths::Paths(const CmdLineArgs& args)
{
	m_root = Root(args.GetArg0());

	m_rdata = RootData(args.GetArg0());

	const char* subdirectoryName = args.Has("writableRoot")? 0 : "0ad";

	if(!subdirectoryName)
	{
		// Note: if writableRoot option is passed to the game, then
		//	all the data is a subdirectory of the root
		m_gameData = m_rdata;
		m_userData = m_gameData;
		m_config = m_gameData / "config"/"";
		m_cache = m_gameData / "cache"/"";
		m_logs = m_root / "logs"/"";
	}
	else // OS-specific path handling
	{

#if OS_ANDROID

		const OsPath appdata = OsPath("/sdcard/0ad/appdata");

		// We don't make the game vs. user data distinction on Android
		m_gameData = appdata/"data"/"";
		m_userData = m_gameData;
		m_config = appdata/"config"/"";
		m_cache = appdata/"cache"/"";
		m_logs = appdata/"logs"/"";

#elif OS_WIN

		/* For reasoning behind our Windows paths, see the discussion here:
		 * http://www.wildfiregames.com/forum/index.php?showtopic=14759
		 * 
		 * Summary:
		 *	1. Local appdata: for bulky unfriendly data like the cache,
		 *      which can be recreated if deleted; doesn't need backing up.
		 *  2. Roaming appdata: for slightly less unfriendly data like config
		 *      files that might theoretically be shared between different
		 *      machines on a domain.
		 *  3. Personal / My Documents: for data explicitly created by the user,
		 *      and which should be visible and easily accessed. We use a non-
		 *      localized My Games subfolder for improved organization.
		 */

		// %localappdata%/0ad/
		const OsPath localAppdata = wutil_LocalAppdataPath() / subdirectoryName/"";
		// %appdata%/0ad/
		const OsPath roamingAppData = wutil_RoamingAppdataPath() / subdirectoryName/"";
		// My Documents/My Games/0ad/
		const OsPath personalData = wutil_PersonalPath() / "My Games" / subdirectoryName/"";

		m_cache = localAppdata / "cache"/"";
		m_gameData = roamingAppData / "data"/"";
		m_userData = personalData/"";
		m_config = roamingAppData / "config"/"";
		m_logs = localAppdata / "logs"/"";

#elif OS_MACOSX

		/* For reasoning behind our OS X paths, see the discussion here:
		 * http://www.wildfiregames.com/forum/index.php?showtopic=15511
		 *
		 * Summary:
		 *  1. Application Support: most data associated with the app
		 *		should be stored here, with few exceptions (e.g. temporary
		 *		data, cached data, and managed media files).
		 *  2. Caches: used for non-critial app data that can be easily
		 *		regenerated if this directory is deleted. It is not
		 *		included in backups by default.
		 *
		 * Note: the paths returned by osx_Get*Path are not guaranteed to exist,
		 *     but that's OK since we always create them on demand.
		 */

		// We probably want to use the same subdirectoryName regardless
		//	of whether running a bundle or from SVN. Apple recommends using
		//	company name, bundle name or bundle identifier.
		OsPath appSupportPath;  // ~/Library/Application Support/0ad
		OsPath cachePath;       // ~/Library/Caches/0ad

		{
			std::string path = osx_GetAppSupportPath();
			ENSURE(!path.empty());
			appSupportPath = OsPath(path) / subdirectoryName;
		}
		{
			std::string path = osx_GetCachesPath();
			ENSURE(!path.empty());
			cachePath = OsPath(path) / subdirectoryName;
		}

		// We don't make the game vs. user data distinction on OS X
		m_gameData = appSupportPath /"";
		m_userData = m_gameData;
		m_cache = cachePath/"";
		m_config = appSupportPath / "config"/"";
		m_logs = appSupportPath / "logs"/"";

#else // OS_UNIX

		const char* envHome = getenv("HOME");
		ENSURE(envHome);
		const OsPath home(envHome);
		const OsPath xdgData   = XDG_Path("XDG_DATA_HOME",   home, home/".local/share/") / subdirectoryName;
		const OsPath xdgConfig = XDG_Path("XDG_CONFIG_HOME", home, home/".config/"     ) / subdirectoryName;
		const OsPath xdgCache  = XDG_Path("XDG_CACHE_HOME",  home, home/".cache/"      ) / subdirectoryName;

		// We don't make the game vs. user data distinction on Unix
		m_gameData = xdgData/"";
		m_userData = m_gameData;
		m_cache  = xdgCache/"";
		m_config = xdgConfig / "config"/"";
		m_logs   = xdgConfig / "logs"/"";

#endif
	}
}
Beispiel #22
0
// moved into a helper function to ensure args is destroyed before
// exit(), which may result in a memory leak.
static void RunGameOrAtlas(int argc, const char* argv[])
{
	CmdLineArgs args(argc, argv);

	g_args = args;

	if (args.Has("version") || args.Has("-version"))
	{
		debug_printf("Pyrogenesis %s\n", engine_version);
		return;
	}

	const bool isVisualReplay = args.Has("replay-visual");
	const bool isNonVisualReplay = args.Has("replay");

	const CStr replayFile =
		isVisualReplay ? args.Get("replay-visual") :
		isNonVisualReplay ? args.Get("replay") : "";

	if (isVisualReplay || isNonVisualReplay)
	{
		if (!FileExists(OsPath(replayFile)))
		{
			debug_printf("ERROR: The requested replay file '%s' does not exist!\n", replayFile.c_str());
			return;
		}
		if (DirectoryExists(OsPath(replayFile)))
		{
			debug_printf("ERROR: The requested replay file '%s' is a directory!\n", replayFile.c_str());
			return;
		}
	}

	// We need to initialize SpiderMonkey and libxml2 in the main thread before
	// any thread uses them. So initialize them here before we might run Atlas.
	ScriptEngine scriptEngine;
	CXeromyces::Startup();

	if (ATLAS_RunIfOnCmdLine(args, false))
	{
		CXeromyces::Terminate();
		return;
	}

	if (isNonVisualReplay)
	{
		if (!args.Has("mod"))
		{
			LOGERROR("At least one mod should be specified! Did you mean to add the argument '-mod=public'?");
			CXeromyces::Terminate();
			return;
		}

		Paths paths(args);
		g_VFS = CreateVfs(20 * MiB);
		g_VFS->Mount(L"cache/", paths.Cache(), VFS_MOUNT_ARCHIVABLE);
		MountMods(paths, GetMods(args, INIT_MODS));

		{
			CReplayPlayer replay;
			replay.Load(replayFile);
			replay.Replay(
				args.Has("serializationtest"),
				args.Has("rejointest") ? args.Get("rejointest").ToInt() : -1,
				args.Has("ooslog"));
		}

		g_VFS.reset();

		CXeromyces::Terminate();
		return;
	}

	// run in archive-building mode if requested
	if (args.Has("archivebuild"))
	{
		Paths paths(args);

		OsPath mod(args.Get("archivebuild"));
		OsPath zip;
		if (args.Has("archivebuild-output"))
			zip = args.Get("archivebuild-output");
		else
			zip = mod.Filename().ChangeExtension(L".zip");

		CArchiveBuilder builder(mod, paths.Cache());

		// Add mods provided on the command line
		// NOTE: We do not handle mods in the user mod path here
		std::vector<CStr> mods = args.GetMultiple("mod");
		for (size_t i = 0; i < mods.size(); ++i)
			builder.AddBaseMod(paths.RData()/"mods"/mods[i]);

		builder.Build(zip, args.Has("archivebuild-compress"));

		CXeromyces::Terminate();
		return;
	}

	const double res = timer_Resolution();
	g_frequencyFilter = CreateFrequencyFilter(res, 30.0);

	// run the game
	int flags = INIT_MODS;
	do
	{
		restart = false;
		quit = false;
		if (!Init(args, flags))
		{
			flags &= ~INIT_MODS;
			Shutdown(SHUTDOWN_FROM_CONFIG);
			continue;
		}
		InitGraphics(args, 0);
		MainControllerInit();
		while (!quit)
			Frame();
		Shutdown(0);
		MainControllerShutdown();
		flags &= ~INIT_MODS;
	} while (restart);

	if (restart_in_atlas)
		ATLAS_RunIfOnCmdLine(args, true);

	CXeromyces::Terminate();
}
Beispiel #23
0
bool SwAdminRpcSnapshot::execute(const HttpRequestContext& requestContext,
                                 UtlSList&                 params,
                                 void*                     userData,
                                 XmlRpcResponse&           response,
                                 ExecutionStatus&          status)
{

   bool result = false;
   status = XmlRpcMethod::FAILED;

   if (2 != params.entries())
   {
      handleExtraExecuteParam(name(), response, status);
   }
   else
   {
      if (!params.at(0) || !params.at(0)->isInstanceOf(UtlString::TYPE))
      {
         handleMissingExecuteParam(name(), PARAM_NAME_CALLING_HOST, response, status);
      }
      else
      {
         UtlString* pCallingHostname = dynamic_cast<UtlString*>(params.at(0));
         SipxRpc* pSipxRpcImpl = ((SipxRpc *)userData);

         if (!params.at(1) || !params.at(1)->isInstanceOf(UtlSList::TYPE))
         {
            handleMissingExecuteParam(name(), PARAM_NAME_COMMAND, response, status);
         }
         else
         {
            if (validCaller(requestContext, *pCallingHostname, response, *pSipxRpcImpl, name()))
            {
               UtlSList* pArgsList = dynamic_cast<UtlSList*>(params.at(1));
               UtlSListIterator argsListIterator( *pArgsList );
               UtlString * pArg;

               // Make sure that there is no other instance running.
               if (! duplicateProcess(SwAdminSnapshot, response, status))
               {
                  UtlBool   method_result(true);
                  UtlString arguments[pArgsList->entries()+2];
                  UtlString subCommand;
                  OsPath    mWorkingDirectory = ".";
                  OsPath    mExec = SipXecsService::Path(SipXecsService::BinDirType, SwAdminSnapshot);

                  UtlString mStdOutFile(SwAdminSnapshot_cmd);
                  UtlString mStdErrFile(SwAdminSnapshot_cmd);

                  mStdOutFile.append(SwAdminStdOut_filetype);
                  mStdErrFile.append(SwAdminStdErr_filetype);

                  // Construct and set the response.
                  OsPath mStdOutPath = OsPath(SipXecsService::Path(SipXecsService::LogDirType, mStdOutFile.data()));
                  OsPath mStdErrPath = OsPath(SipXecsService::Path(SipXecsService::LogDirType, mStdErrFile.data()));
                  OsPath processOutPath = OsPath(SipXecsService::Path(SipXecsService::TmpDirType, OUTPUT_FILENAME));

                  for (int i = 0; (pArg = dynamic_cast<UtlString*>(argsListIterator())); i++)
                  {
                     XmlUnEscape(arguments[i], *pArg);
                  }

                  arguments[pArgsList->entries()] = processOutPath.data();
                  arguments[pArgsList->entries()+1] = NULL;

                  // execute the command and return whether or not the launch was successful.
                  OsProcess* swCheck = new OsProcess();

                  // Setup the Standard Output and Standard Error files.
                  OsPath mStdInFile;   // Blank
                  int rc;
                  rc = swCheck->setIORedirect(mStdInFile, mStdOutPath, mStdErrPath);

                  // Launch the process but tell the parent to ignore the child's signals (especially on shutdown).
                  // It will let the system handle it to avoid a defunct process.
                  if ( (rc=swCheck->launch(mExec, &arguments[0], mWorkingDirectory,
                                   swCheck->NormalPriorityClass, FALSE,
                                   TRUE)) // Parent to ignore child signals.
                           == OS_SUCCESS )
                  {
                     // Add the file resources to Supervisor Process so they can be retrieved
                     FileResource::logFileResource( mStdOutPath, SipxProcessManager::getInstance()->findProcess(SUPERVISOR_PROCESS_NAME));
                     FileResource::logFileResource( mStdErrPath, SipxProcessManager::getInstance()->findProcess(SUPERVISOR_PROCESS_NAME));
                     FileResource::logFileResource( processOutPath, SipxProcessManager::getInstance()->findProcess(SUPERVISOR_PROCESS_NAME));

                     UtlString outputFilename = processOutPath;

                     // Construct and set the response.
                     UtlSList outputPaths;
                     outputPaths.insert(&outputFilename);
                     outputPaths.insert(&mStdOutPath);
                     outputPaths.insert(&mStdErrPath);

                     response.setResponse(&outputPaths);
                     status = XmlRpcMethod::OK;
                     result = true;
                  } // launch
                  else
                  {
                     // Failed to launch the command, send a fault.
                     response.setFault(SwAdminRpcMethod::FailureToLaunch, "Failure to launch command");
                     status = XmlRpcMethod::FAILED;
                  }

                  delete swCheck;
               }  // duplicateProcess
            }  // validcaller
            else
            {
               status = XmlRpcMethod::FAILED;
            }
         }  // param 1 okay
      }  // param 0 okay
   } //number of parms check

   return result;
}
Beispiel #24
0
static int
LastModifiedFile64(const char *name, int64_t *tp)
{
#ifdef __WINDOWS__
  HANDLE hFile;
  wchar_t wfile[MAXPATHLEN];

#define nano * 0.000000001
#define ntick 100.0
#define SEC_TO_UNIX_EPOCH 11644473600.0

  if ( !_xos_os_filenameW(name, wfile, MAXPATHLEN) )
    return FALSE;

  if ( (hFile=CreateFileW(wfile,
			  0,
			  FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE,
			  NULL,
			  OPEN_EXISTING,
			  FILE_FLAG_BACKUP_SEMANTICS,
			  NULL)) != INVALID_HANDLE_VALUE )
  { FILETIME wt;
    int rc;

    rc = GetFileTime(hFile, NULL, NULL, (FILETIME *)&wt);
    CloseHandle(hFile);

    if ( rc )
    {
      LARGE_INTEGER date, adjust;
      date.HighPart = wt.dwHighDateTime;
      date.LowPart = wt.dwLowDateTime;

      adjust.QuadPart = 11644473600000 * 10000;
      date.QuadPart -= adjust.QuadPart;
      date.QuadPart /= 10000000;

      *tp = date.QuadPart;
      return TRUE;
    }
  }

  set_posix_error(GetLastError());

  return FALSE;
#else
  char tmp[MAXPATHLEN];
  statstruct buf;
#ifdef __ANDROID__
  if (Yap_isAsset(name)) {
    if ( statfunc(OsPath("/", tmp), &buf) < 0 ) {
            return FALSE;
    }
      *tp = (int64_t)buf.st_mtime;
      return Yap_AccessAsset(name, R_OK);
     }

#endif

  if ( statfunc(OsPath(name, tmp), &buf) < 0 ){
      return FALSE;
    }

  *tp = (int64_t)buf.st_mtime;
  return TRUE;
#endif
}