예제 #1
0
bool SP_ModuleBag::load(int pid)
{
#ifdef HAVE_LIBBFD
    std::string exe_path = getExePath(pid);
    std::string maps_path = getMapsPath(pid);

    if (d->load(exe_path)) {
        char perm[64], dev[64];
        char path[4096], line[4096];

        FILE *fp = fopen(maps_path.c_str(), "r");

        int ret = 0;

        while (fgets(line, sizeof(line), fp)) {
            uint64_t begin, end, offset, inode;

            path[0] = '\0';

            /* see proc(5) */
            ret = sscanf(line, "%llx-%llx %s %llx %s %llx %s\n",
                             &begin, &end, perm, &offset, dev, &inode, path);

            if (inode && path[0] && strstr(path, "lib") && strstr(path, ".so")) {
                d->loadMapped(begin, end, path);
            }

//            fprintf(stderr, "%lx-%lx %s %lx %s %lx\t%s\n",
//                   begin, end, perm, offset, dev, inode, path);
        }
    }
#endif
    return true;
}
예제 #2
0
//读数据转化文件,生成转换列表
int CGateCmdHandler::init(void)
{
    char fileName[256] = {0};
    char fileDir[256] = {0};
    char processName[256] = {0};
    FILE* p_file = NULL;
    char szExp[1024] = {0};    

    clearList();

    if (getExePath(fileDir, processName, 256))
        return -1;   

    sprintf(fileName, "%s/%s", fileDir, FILE_DATA_TRANS);

    p_file = fopen(fileName, "r");
    if (!p_file)
        return -1;

    while (fgets(szExp, 1024, p_file)) {
        if (addExpression(szExp)) {
            fclose(p_file);
            return -1;
        }
    }

    fclose(p_file);
    
    return 0;
}
예제 #3
0
char *__PHYSFS_platformCalcBaseDir(const char *argv0)
{
    if ((argv0 != NULL) && (strchr(argv0, '\\') != NULL))
        return(NULL); /* default behaviour can handle this. */

    return(getExePath(argv0));
} /* __PHYSFS_platformCalcBaseDir */
예제 #4
0
//---------------------------------------------------------------------------//
  String PathService::convertToAbsPath( const String& szRelPath, bool bInResources /* = true */ )
  {
    if( bInResources )
      return getResourcesPath() + szRelPath;

    else
      return getExePath() + szRelPath;
  }
예제 #5
0
//---------------------------------------------------------------------------//
  void PathService::convertToAbsPath( String& szRelPath, bool bInResources /* = true */ )
  {
    if( bInResources )
      szRelPath = getResourcesPath() + szRelPath;

    else
      szRelPath = getExePath() + szRelPath;
  }
예제 #6
0
int CRDBManager::initDev(void)
{
    clear();

    PTBLOBJ p_result = NULL;

    for (int i = 0; i < sizeof(s_aTblObj) / sizeof(TBLOBJ); i++) {
        p_result = &s_aTblObj[i];
        registerTbl(p_result->szTblName, p_result->p_op);
    }

    //insert table information
    TB001_DEVOBJ devObj = {0};
    CEhJsonReader jsonReader;

    char szFilePath[256] = {0};
    char szFileName[256] = {0};
    char szCfgFilePath[256] = {0};

    if (getExePath(szFilePath, szFileName, 256))
        return -1;

    sprintf(szCfgFilePath, "%s/%s", szFilePath, JSON_FILENAME);
    if (jsonReader.setTbl(szCfgFilePath)) {
        logout(LOG_ALARM, "read json file failed", __FILE__, __LINE__);
        return -1;
    }

    logout(LOG_INFO, "read json file success", __FILE__, __LINE__);
    char szLogOut[2048] = {0};

    int devCount = jsonReader.getDataCount();
    for (int i = 0; i < devCount; i++) {
        if (jsonReader.fetchData(i, &devObj)) {
            logout(LOG_ALARM, "read json data failed", __FILE__, __LINE__);
            return -1;
        }

        sprintf(szLogOut, "id = %d, desc = %s, dataype = %d, protocolID = %d,"
            " groupAddr = %s, status groupAddr = %s, value = %s\n",
            devObj.iID, devObj.szDesc, devObj.iDataType,
            devObj.iProtocolID, devObj.szGroupAddr, devObj.szGroupAddr2,
            devObj.szValue);

        logout(LOG_INFO, szLogOut, __FILE__, __LINE__);

        if (insert(s_aTblObj[0].szTblName, &devObj)) {
            logout(LOG_ALARM, "insert data failed", __FILE__, __LINE__);
            return -1;
        }
    }

    logout(LOG_INFO, "init device successful", __FILE__, __LINE__);
    
    return 0;
}
예제 #7
0
/*
 * Try to make use of GetUserProfileDirectoryW(), which isn't available on
 *  some common variants of Win32. If we can't use this, we just punt and
 *  use the physfs base dir for the user dir, too.
 *
 * On success, module-scope variable (userDir) will have a pointer to
 *  a malloc()'d string of the user's profile dir, and a non-zero value is
 *  returned. If we can't determine the profile dir, (userDir) will
 *  be NULL, and zero is returned.
 */
static int determineUserDir(void)
{
    if (userDir != NULL)
        return(1);  /* already good to go. */

    /*
     * GetUserProfileDirectoryW() is only available on NT 4.0 and later.
     *  This means Win95/98/ME (and CE?) users have to do without, so for
     *  them, we'll default to the base directory when we can't get the
     *  function pointer. Since this is originally an NT API, we don't
	 *  offer a non-Unicode fallback.
     */
    if (pGetUserProfileDirectoryW != NULL)
    {
        HANDLE accessToken = NULL;       /* Security handle to process */
        HANDLE processHandle = GetCurrentProcess();
        if (OpenProcessToken(processHandle, TOKEN_QUERY, &accessToken))
        {
            DWORD psize = 0;
            WCHAR dummy = 0;
            LPWSTR wstr = NULL;
            BOOL rc = 0;

            /*
             * Should fail. Will write the size of the profile path in
             *  psize. Also note that the second parameter can't be
             *  NULL or the function fails.
             */	
    		rc = pGetUserProfileDirectoryW(accessToken, &dummy, &psize);
            assert(!rc);  /* !!! FIXME: handle this gracefully. */
            (void)rc;

            /* Allocate memory for the profile directory */
            wstr = (LPWSTR) __PHYSFS_smallAlloc(psize * sizeof (WCHAR));
            if (wstr != NULL)
            {
                if (pGetUserProfileDirectoryW(accessToken, wstr, &psize))
                    userDir = unicodeToUtf8Heap(wstr);
                __PHYSFS_smallFree(wstr);
            } /* else */
        } /* if */

        CloseHandle(accessToken);
    } /* if */

    if (userDir == NULL)  /* couldn't get profile for some reason. */
    {
        /* Might just be a non-NT system; resort to the basedir. */
        userDir = getExePath();
        BAIL_IF_MACRO(userDir == NULL, NULL, 0); /* STILL failed?! */
    } /* if */

    return(1);  /* We made it: hit the showers. */
} /* determineUserDir */
예제 #8
0
// getLocalPath will try looking for a file in the same directory as where
// the executable is located and return the filepath in variable path and 
// true if a valid file is found
bool getLocalPath(char path[])
{
	if (getExePath(path)) {
		if (strlen(path) + strlen(ITEMFILENAME) < PATHSIZE) {
			strcat(path, ITEMFILENAME);
			return true;
		} else {
			pathToLong();
		}
	}

	return false;
}
예제 #9
0
//---------------------------------------------------------------------------//
  String PathService::toRelPath(const String& _anAbsPath, bool _isInResources)
  {
    const String theAbsPart = _isInResources ? getResourcesPath() : getExePath();

    std::size_t thePosOfAbsPart = _anAbsPath.find(theAbsPart);

    if (thePosOfAbsPart != String::npos)
    {
      return _anAbsPath.substr(thePosOfAbsPart + theAbsPart.length());
    }

    return _anAbsPath;
  }
예제 #10
0
int init_obj(void)
{    
    if (initSocket())
        return -1;

    char szFilePath[256] = {0};
    char szFileName[256] = {0};
    char szLogFilePath[256] = {0};    
    if (getExePath(szFilePath, szFileName, 256))
        return -1;

    sprintf(szLogFilePath, "%s/%s", szFilePath, "log.dat");

#ifdef _MYDEBUG
    if (loginit(szLogFilePath, LOG_INFO))
        return -1;
#else
    if (loginit(szLogFilePath, LOG_WARNING))
        return -1;
#endif

    if (rdb_init()) {
        logout(LOG_EMERGENCY, "Failed to init protocol", 
           __FILE__, __LINE__);

        return -1;
    }

    if (pushOut_init()) {
        logout(LOG_ERR, "Failed to init push out", 
           __FILE__, __LINE__);

        return -1;
    }

    if (ptl_init()) {
        logout(LOG_EMERGENCY, "Failed to init protocol", 
           __FILE__, __LINE__);

        return -1;
    }
    
    return 0;
}
예제 #11
0
  /*
  * Try to make use of GetUserProfileDirectoryW(), which isn't available on
  *  some common variants of Win32. If we can't use this, we just punt and
  *  use the physfs base dir for the user dir, too.
  *
  * On success, module-scope variable (userDir) will have a pointer to
  *  a malloc()'d string of the user's profile dir, and a non-zero value is
  *  returned. If we can't determine the profile dir, (userDir) will
  *  be NULL, and zero is returned.
  */
static int determineUserDir(void)
{
	if (userDir != NULL)
		return(1);  /* already good to go. */

	const wchar_t* path = Windows::Storage::ApplicationData::Current->LocalFolder->Path->Data();
	wchar_t path2[1024];
	wcscpy_s(path2, path);
	wcscat_s(path2, L"\\");

	userDir = unicodeToUtf8Heap(path2);

	if (userDir == NULL)  /* couldn't get profile for some reason. */
	{
		/* Might just be a non-NT system; resort to the basedir. */
		userDir = getExePath();
		BAIL_IF_MACRO(userDir == NULL, NULL, 0); /* STILL failed?! */
	} /* if */

	return(1);  /* We made it: hit the showers. */
} /* determineUserDir */
예제 #12
0
/*-------------------------------------------------------------------
 Function: init()
 Purpose: initial, create socket, connect device
 Parameters: 
 return: 0 --  success
         -1 -- failed
-------------------------------------------------------------------*/
int CIpKnxPtl::init(void)
{
    FILE *pFile = NULL;
    char szFilePath[256] = {0};
    char szFileName[256] = {0};
    char szCfgFilePath[256] = {0};
    char szIp[64] = {0};
    int  iPort = 0;

    if (getExePath(szFilePath, szFileName, 256))
        return -1;

    sprintf(szCfgFilePath, "%s/%s", szFilePath, IPKNXFILE);

    pFile = fopen(szCfgFilePath, "rb");
    if (pFile) {
        fscanf(pFile, "%[^:]%*c%d", szIp, &iPort);
        fclose(pFile);
        pFile = NULL;
    }

    return m_ipKnxApp.init(szIp, iPort);
}
예제 #13
0
//---------------------------------------------------------------------------//
  String PathService::getResourcesPath()
  {
    static String szPath = "";

    if( szPath != "" )
    {
      return szPath;
    }

    szPath = getExePath();

    if( m_szRelativeResourcePath.empty() )
    {
      szPath += "/Resources/";
    }
    else
    {
      szPath += m_szRelativeResourcePath;
    }

    removeFolderUpMarkers(szPath);

    return szPath;
  }
예제 #14
0
void readcfg()
{
	string filepath;
	string path = getExePath();
	filepath = path;
	filepath.append(string("\\SysConfig.ini"));
	
	char str[20];
	memset(str,0,sizeof(str));
	//本地IP
	GetPrivateProfileString("CGISERVER", "IP", "127.0.0.1",str,19, filepath.c_str());
	g_cfg.local_ip = "";
	g_cfg.local_ip.append(str);
	
	g_cfg.local_port = GetPrivateProfileInt("CGISERVER", "PORT", 8080, filepath.c_str());
	
	g_cfg.max_works_num = GetPrivateProfileInt("CGISERVER", "workers", 3, filepath.c_str());
	
	g_cfg.max_clients_num = GetPrivateProfileInt("CGISERVER", "max_client", 100000, filepath.c_str());
	
	////DB 
	GetPrivateProfileString("DBSERVER", "dbname", "test",str,19, filepath.c_str());
	g_cfg.db_name = str;
	GetPrivateProfileString("DBSERVER", "user", "root",str,19, filepath.c_str());
	g_cfg.db_user = str;
	GetPrivateProfileString("DBSERVER", "psw", "123456",str,19, filepath.c_str());
	g_cfg.db_psw  = str;
	GetPrivateProfileString("DBSERVER", "IP", "127.0.0.1",str,19, filepath.c_str());
	g_cfg.db_ip="";
	g_cfg.db_ip.append(str);
	g_cfg.db_port = GetPrivateProfileInt("DBSERVER", "PORT", 3306, filepath.c_str());
	//“恶意”连接多久关闭,单位秒
	g_cfg.outtime = GetPrivateProfileInt("LINK", "outtime", 10, filepath.c_str());
	
	writelogimmediatly("[log][readcfg]ok.\n");
}
예제 #15
0
int prepare(const char *lpCmdLine)
{
    char tmp[MAX_ARGS] = {0};
    hModule = GetModuleHandle(NULL);
    if (hModule == NULL)
    {
        return FALSE;
    }

    // Get executable path
    char exePath[_MAX_PATH] = {0};
    int pathLen = getExePath(exePath);
    if (pathLen == -1)
    {
        return FALSE;
    }

    if (!initializeLogging(lpCmdLine, exePath, pathLen))
    {
        return FALSE;
    }

    debug("\n\nVersion:\t%s\n", VERSION);
    debug("CmdLine:\t%s %s\n", exePath, lpCmdLine);
    setWow64Flag();

    // Set default error message, title and optional support web site url.
    loadString(SUPPORT_URL, errUrl);
    loadString(ERR_TITLE, errTitle);
    if (!loadString(STARTUP_ERR, errMsg))
    {
        debug(ERROR_FORMAT, "Startup error message not defined.");
        return FALSE;
    }

    // Single instance
    loadString(MUTEX_NAME, mutexName);
    if (*mutexName)
    {
        SECURITY_ATTRIBUTES security;
        security.nLength = sizeof(SECURITY_ATTRIBUTES);
        security.bInheritHandle = TRUE;
        security.lpSecurityDescriptor = NULL;
        CreateMutexA(&security, FALSE, mutexName);
        if (GetLastError() == ERROR_ALREADY_EXISTS)
        {
            debug(ERROR_FORMAT, "Instance already exists.");
            return ERROR_ALREADY_EXISTS;
        }
    }

    // Working dir
    char tmp_path[_MAX_PATH] = {0};
    GetCurrentDirectory(_MAX_PATH, oldPwd);
    if (loadString(CHDIR, tmp_path))
    {
        strncpy(workingDir, exePath, pathLen);
        appendPath(workingDir, tmp_path);
        _chdir(workingDir);
        debug("Working dir:\t%s\n", workingDir);
    }

    // Use bundled jre or find java
    if (loadString(JRE_PATH, tmp_path))
    {
        char jrePath[MAX_ARGS] = {0};
        expandVars(jrePath, tmp_path, exePath, pathLen);
        debug("Bundled JRE:\t%s\n", jrePath);
        if (jrePath[0] == '\\' || jrePath[1] == ':')
        {
            // Absolute
            strcpy(cmd, jrePath);
        }
        else
        {
            // Relative
            strncpy(cmd, exePath, pathLen);
            appendPath(cmd, jrePath);
        }

        if (isLauncherPathValid(cmd))
        {
            foundJava = (wow64 && loadBool(BUNDLED_JRE_64_BIT))
                        ? FOUND_BUNDLED | KEY_WOW64_64KEY
                        : FOUND_BUNDLED;
        }
    }

    if (foundJava == NO_JAVA_FOUND)
    {
        if (!loadString(JAVA_MIN_VER, javaMinVer))
        {
            loadString(BUNDLED_JRE_ERR, errMsg);
            return FALSE;
        }

        loadString(JAVA_MAX_VER, javaMaxVer);
        if (!findJavaHome(cmd, loadInt(JDK_PREFERENCE)))
        {
            loadString(JRE_VERSION_ERR, errMsg);
            strcat(errMsg, " ");
            strcat(errMsg, javaMinVer);

            if (*javaMaxVer)
            {
                strcat(errMsg, " - ");
                strcat(errMsg, javaMaxVer);
            }

            if (runtimeBits == USE_64_BIT_RUNTIME
                    || runtimeBits == USE_32_BIT_RUNTIME)
            {
                strcat(errMsg, " (");
                strcat(errMsg, runtimeBits == USE_64_BIT_RUNTIME ? "64" : "32");
                strcat(errMsg, "-bit)");
            }

            if (corruptedJreFound)
            {
                char launcherErrMsg[BIG_STR] = {0};

                if (loadString(LAUNCHER_ERR, launcherErrMsg))
                {
                    strcat(errMsg, "\n");
                    strcat(errMsg, launcherErrMsg);
                }
            }

            loadString(DOWNLOAD_URL, errUrl);
            return FALSE;
        }
    }

    // Store the JRE Home Dir
    strcpy(jreHomeDir, cmd);

    // Append a path to the Path environment variable
    char jreBinPath[_MAX_PATH] = {0};
    strcpy(jreBinPath, cmd);
    strcat(jreBinPath, "\\bin");
    if (!appendToPathVar(jreBinPath))
    {
        debug(ERROR_FORMAT, "appendToPathVar failed.");
        return FALSE;
    }

    // Set environment variables
    char envVars[MAX_VAR_SIZE] = {0};
    loadString(ENV_VARIABLES, envVars);
    char *var = strtok(envVars, "\t");
    while (var != NULL)
    {
        char *varValue = strchr(var, '=');
        *varValue++ = 0;
        *tmp = 0;
        expandVars(tmp, varValue, exePath, pathLen);
        debug("Set var:\t%s = %s\n", var, tmp);
        SetEnvironmentVariable(var, tmp);
        var = strtok(NULL, "\t");
    }
    *tmp = 0;

    // Process priority
    priority = loadInt(PRIORITY_CLASS);

    // Launcher
    appendJavaw(cmd);

    // Heap sizes
    appendHeapSizes(args);

    // JVM options
    char jvmOptions[MAX_ARGS] = {0};
    setJvmOptions(jvmOptions, exePath);

    // Expand environment %variables%
    expandVars(args, jvmOptions, exePath, pathLen);

    // MainClass + Classpath or Jar
    char mainClass[STR] = {0};
    char jar[_MAX_PATH] = {0};

    const BOOL wrapper = loadBool(WRAPPER);
    loadString(JAR, jar);

    if (loadString(MAIN_CLASS, mainClass))
    {
        if (!loadString(CLASSPATH, tmp))
        {
            debug("Info:\t\tClasspath not defined.\n");
        }
        char exp[MAX_ARGS] = {0};
        expandVars(exp, tmp, exePath, pathLen);
        strcat(args, "-classpath \"");
        if (wrapper)
        {
            appendAppClasspath(args, exePath);
        }
        else if (*jar)
        {
            appendAppClasspath(args, jar);
        }

        // Deal with wildcards or >> strcat(args, exp); <<
        char* cp = strtok(exp, ";");
        while(cp != NULL)
        {
            debug("Add classpath:\t%s\n", cp);
            if (strpbrk(cp, "*?") != NULL)
            {
                int len = strrchr(cp, '\\') - cp + 1;
                strncpy(tmp_path, cp, len);
                char* filename = tmp_path + len;
                *filename = 0;
                struct _finddata_t c_file;
                long hFile;
                if ((hFile = _findfirst(cp, &c_file)) != -1L)
                {
                    do
                    {
                        strcpy(filename, c_file.name);
                        appendAppClasspath(args, tmp_path);
                        debug("      \"      :\t%s\n", tmp_path);
                    } while (_findnext(hFile, &c_file) == 0);
                }
                _findclose(hFile);
            }
            else
            {
                appendAppClasspath(args, cp);
            }
            cp = strtok(NULL, ";");
        }
        *(args + strlen(args) - 1) = 0;

        strcat(args, "\" ");
        strcat(args, mainClass);
    }
    else if (wrapper)
    {
        strcat(args, "-jar \"");
        strcat(args, exePath);
        strcat(args, "\"");
    }
    else
    {
        strcat(args, "-jar \"");
        strncat(args, exePath, pathLen);
        appendPath(args, jar);
        strcat(args, "\"");
    }

    // Constant command line args
    if (loadString(CMD_LINE, tmp))
    {
        strcat(args, " ");
        strcat(args, tmp);
    }

    // Command line args
    if (*lpCmdLine)
    {
        strcpy(tmp, lpCmdLine);
        char* dst;
        while ((dst = strstr(tmp, "--l4j-")) != NULL)
        {
            char* src = strchr(dst, ' ');
            if (src == NULL || *(src + 1) == 0)
            {
                *dst = 0;
            }
            else
            {
                strcpy(dst, src + 1);
            }
        }
        if (*tmp)
        {
            strcat(args, " ");
            strcat(args, tmp);
        }
    }

    debug("Launcher:\t%s\n", cmd);
    debug("Launcher args:\t%s\n", args);
    debug("Args length:\t%d/32768 chars\n", strlen(args));
    return TRUE;
}
예제 #16
0
/*
 * Try to make use of GetUserProfileDirectory(), which isn't available on
 *  some common variants of Win32. If we can't use this, we just punt and
 *  use the physfs base dir for the user dir, too.
 *
 * On success, module-scope variable (userDir) will have a pointer to
 *  a malloc()'d string of the user's profile dir, and a non-zero value is
 *  returned. If we can't determine the profile dir, (userDir) will
 *  be NULL, and zero is returned.
 */
static int determineUserDir(void)
{
    DWORD psize = 0;
    char dummy[1];
    BOOL rc = 0;
    HANDLE processHandle;            /* Current process handle */
    HANDLE accessToken = NULL;       /* Security handle to process */
    LPFNGETUSERPROFILEDIR GetUserProfileDirectory;
    HMODULE lib;

    assert(userDir == NULL);

    /*
     * GetUserProfileDirectory() is only available on NT 4.0 and later.
     *  This means Win95/98/ME (and CE?) users have to do without, so for
     *  them, we'll default to the base directory when we can't get the
     *  function pointer.
     */

    lib = LoadLibrary("userenv.dll");
    if (lib)
    {
        /* !!! FIXME: Handle Unicode? */
        GetUserProfileDirectory = (LPFNGETUSERPROFILEDIR)
                                  GetProcAddress(lib, "GetUserProfileDirectoryA");
        if (GetUserProfileDirectory)
        {
            processHandle = GetCurrentProcess();
            if (OpenProcessToken(processHandle, TOKEN_QUERY, &accessToken))
            {
                /*
                 * Should fail. Will write the size of the profile path in
                 *  psize. Also note that the second parameter can't be
                 *  NULL or the function fails.
                 */
                rc = GetUserProfileDirectory(accessToken, dummy, &psize);
                assert(!rc);  /* success?! */

                /* Allocate memory for the profile directory */
                userDir = (char *) malloc(psize);
                if (userDir != NULL)
                {
                    if (!GetUserProfileDirectory(accessToken, userDir, &psize))
                    {
                        free(userDir);
                        userDir = NULL;
                    } /* if */
                } /* else */
            } /* if */

            CloseHandle(accessToken);
        } /* if */

        FreeLibrary(lib);
    } /* if */

    if (userDir == NULL)  /* couldn't get profile for some reason. */
    {
        /* Might just be a non-NT system; resort to the basedir. */
        userDir = getExePath(NULL);
        BAIL_IF_MACRO(userDir == NULL, NULL, 0); /* STILL failed?! */
    } /* if */

    return(1);  /* We made it: hit the showers. */
} /* determineUserDir */
예제 #17
0
int main(int argc, char** argv)
{
	mq::MapSite::StrVec args(argv + 1, argv + argc);	// "+ 1" to skip first arg. It's the name of the program

	if(args.size() < 1)
	{
		std::cout << "[ERROR]: Not enough arguments. Type at least something to search for after the exe name.\n";
		return 3;
	}

	std::string searchStr = args[0];

	for(auto i = 1u; i < args.size(); i++)
		searchStr.append(" " + args[i]);

	mq::BattlezoneOneCom bz1server;

	if(!bz1server.isServerGood())
	{
		std::cout << "[ERROR]: Cannot contact server. Exiting.\n";
		return 1;
	}

	mq::MapSite::StrMap results = bz1server.getMaps(searchStr);

	if(results.empty())
	{
		std::cout << "No results found for \"" << searchStr << "\"!\n";
		return 0;
	}

	for(auto it = results.begin(); it != results.end(); it++)
	{
		std::cout << std::distance(results.begin(), it) << ") " << it->first << " : " << it->second << '\n';
	}

	bool badInput = true;
	std::string input;
	std::vector<unsigned int> choices(1);

	while(badInput)
	{
		std::cout << "\nEnter the number(s) of the map to download (\"-1\" to cancel): ";
		std::getline(std::cin, input);

		if(input == "-1")
			return 0;

		std::stringstream ss(input);

		badInput = false;
		try
		{
			while(ss >> choices.back())
				choices.emplace_back();

			choices.erase(--choices.end());	// get rid of extra item

			for(auto& c : choices)
				if(c >= results.size())
					throw 0;
		}
		catch(...)
		{
			badInput = true;
			choices.resize(1);
			std::cout << "[ERROR]: Bad input. Try again!\n";
		}
	}

	std::string installLocation = getBZinstallDir();

	if(installLocation.empty())
		installLocation = getExePath();

	installLocation += "addon/";

	for(auto& c : choices)
	{
		auto choiceIter = std::next(results.begin(), c);

		std::string resFileName = bz1server.downloadMap(choiceIter->second, installLocation);

		if(resFileName.empty())
		{
			std::cout << "[ERROR]: Download failed for \"" << choiceIter->first << "\". Exiting.\n";
			return 2;
		}

		extractMap(resFileName);
	}

	return 0;
}
예제 #18
0
int prepare(const char *lpCmdLine) {
	char tmp[MAX_ARGS] = {0};
	hModule = GetModuleHandle(NULL);
	if (hModule == NULL) {
		return FALSE;
	}

	// Get executable path
	char exePath[_MAX_PATH] = {0};
	int pathLen = getExePath(exePath);
	if (pathLen == -1) {
		return FALSE;
	}

	// Initialize logging
    if (strstr(lpCmdLine, "--l4j-debug") != NULL) {
		hLog = openLogFile(exePath, pathLen);
		if (hLog == NULL) {
			return FALSE;
		}
		debug("\n\nCmdLine:\t%s %s\n", exePath, lpCmdLine);
	}

    setWow64Flag();

	// Set default error message, title and optional support web site url.
	loadString(SUPPORT_URL, errUrl);
	loadString(ERR_TITLE, errTitle);
	if (!loadString(STARTUP_ERR, errMsg)) {
		return FALSE;
	}

	// Single instance
	loadString(MUTEX_NAME, mutexName);
	if (*mutexName) {
		SECURITY_ATTRIBUTES security;
		security.nLength = sizeof(SECURITY_ATTRIBUTES);
		security.bInheritHandle = TRUE;
		security.lpSecurityDescriptor = NULL;
		CreateMutexA(&security, FALSE, mutexName);
		if (GetLastError() == ERROR_ALREADY_EXISTS) {
			debug("Instance already exists.");
			return ERROR_ALREADY_EXISTS;
		}
	}

	// Working dir
	char tmp_path[_MAX_PATH] = {0};
	GetCurrentDirectory(_MAX_PATH, oldPwd);
	if (loadString(CHDIR, tmp_path)) {
		strncpy(workingDir, exePath, pathLen);
		appendPath(workingDir, tmp_path);
		_chdir(workingDir);
		debug("Working dir:\t%s\n", workingDir);
	}

	// Use bundled jre or find java
	if (loadString(JRE_PATH, tmp_path)) {
		char jrePath[MAX_ARGS] = {0};
		expandVars(jrePath, tmp_path, exePath, pathLen);
		debug("Bundled JRE:\t%s\n", jrePath);
		if (jrePath[0] == '\\' || jrePath[1] == ':') {
			// Absolute
			strcpy(cmd, jrePath);
		} else {
			// Relative
			strncpy(cmd, exePath, pathLen);
			appendPath(cmd, jrePath);
		}
    }
	if (!isJrePathOk(cmd)) {
		if (!loadString(JAVA_MIN_VER, javaMinVer)) {
			loadString(BUNDLED_JRE_ERR, errMsg);
			return FALSE;
		}
		loadString(JAVA_MAX_VER, javaMaxVer);
		if (!findJavaHome(cmd, loadInt(JDK_PREFERENCE))) {
			loadString(JRE_VERSION_ERR, errMsg);
			strcat(errMsg, " ");
			strcat(errMsg, javaMinVer);
			if (*javaMaxVer) {
				strcat(errMsg, " - ");
				strcat(errMsg, javaMaxVer);
			}
			loadString(DOWNLOAD_URL, errUrl);
			return FALSE;
		}
		if (!isJrePathOk(cmd)) {
			loadString(LAUNCHER_ERR, errMsg);
			return FALSE;
		}
	}

    // Append a path to the Path environment variable
	char jreBinPath[_MAX_PATH];
	strcpy(jreBinPath, cmd);
	strcat(jreBinPath, "\\bin");
	if (!appendToPathVar(jreBinPath)) {
		return FALSE;
	}

	// Set environment variables
	char envVars[MAX_VAR_SIZE] = {0};
	loadString(ENV_VARIABLES, envVars);
	char *var = strtok(envVars, "\t");
	while (var != NULL) {
		char *varValue = strchr(var, '=');
		*varValue++ = 0;
		*tmp = 0;
		expandVars(tmp, varValue, exePath, pathLen);
		debug("Set var:\t%s = %s\n", var, tmp);
		SetEnvironmentVariable(var, tmp);
		var = strtok(NULL, "\t");
	}
	*tmp = 0;

	// Process priority
	priority = loadInt(PRIORITY_CLASS);

	// Custom process name
	const BOOL setProcName = loadBool(SET_PROC_NAME)
			&& strstr(lpCmdLine, "--l4j-default-proc") == NULL;
	const BOOL wrapper = loadBool(WRAPPER);

    char jdk_path[_MAX_PATH] = {0};  // fry
    strcpy(jdk_path, cmd);
    //msgBox(jdk_path);

	appendLauncher(setProcName, exePath, pathLen, cmd);

	// Heap sizes
	appendHeapSizes(args);

    // JVM options
	if (loadString(JVM_OPTIONS, tmp)) {
		strcat(tmp, " ");
	} else {
        *tmp = 0;
    }
	/*
	 * Load additional JVM options from .l4j.ini file
	 * Options are separated by spaces or CRLF
	 * # starts an inline comment
	 */
	strncpy(tmp_path, exePath, strlen(exePath) - 3);
	strcat(tmp_path, "l4j.ini");
	long hFile;
	if ((hFile = _open(tmp_path, _O_RDONLY)) != -1) {
		const int jvmOptLen = strlen(tmp);
		char* src = tmp + jvmOptLen;
		char* dst = src;
		const int len = _read(hFile, src, MAX_ARGS - jvmOptLen - BIG_STR);
		BOOL copy = TRUE;
		int i;
		for (i = 0; i < len; i++, src++) {
			if (*src == '#') {
				copy = FALSE;
			} else if (*src == 13 || *src == 10) {
				copy = TRUE;
				if (dst > tmp && *(dst - 1) != ' ') {
					*dst++ = ' ';
				}
			} else if (copy) {
				*dst++ = *src;
			}
		}
		*dst = 0;
		if (len > 0 && *(dst - 1) != ' ') {
			strcat(tmp, " ");
		}
		_close(hFile);
	}

    // Expand environment %variables%
	expandVars(args, tmp, exePath, pathLen);

	// MainClass + Classpath or Jar
	char mainClass[STR] = {0};
	char jar[_MAX_PATH] = {0};
	loadString(JAR, jar);
	if (loadString(MAIN_CLASS, mainClass)) {
		if (!loadString(CLASSPATH, tmp)) {
			return FALSE;
		}
		char exp[MAX_ARGS] = {0};
		expandVars(exp, tmp, exePath, pathLen);
		strcat(args, "-classpath \"");
		if (wrapper) {
			appendAppClasspath(args, exePath, exp);
		} else if (*jar) {
			appendAppClasspath(args, jar, exp);
		}

	// add tools.jar for JDK  [fry]
	char tools[_MAX_PATH] = { 0 };
	sprintf(tools, "%s\\lib\\tools.jar", jdk_path);
	appendAppClasspath(args, tools, exp);

		// Deal with wildcards or >> strcat(args, exp); <<
		char* cp = strtok(exp, ";");
		while(cp != NULL) {
			debug("Add classpath:\t%s\n", cp);
			if (strpbrk(cp, "*?") != NULL) {
				int len = strrchr(cp, '\\') - cp + 1;
				strncpy(tmp_path, cp, len);
				char* filename = tmp_path + len;
				*filename = 0;
				struct _finddata_t c_file;
				long hFile;
				if ((hFile = _findfirst(cp, &c_file)) != -1L) {
					do {
						strcpy(filename, c_file.name);
						strcat(args, tmp_path);
						strcat(args, ";");
						debug("      \"      :\t%s\n", tmp_path);
					} while (_findnext(hFile, &c_file) == 0);
				}
				_findclose(hFile);
			} else {
				strcat(args, cp);
				strcat(args, ";");
			}
			cp = strtok(NULL, ";");
		}
		*(args + strlen(args) - 1) = 0;

		strcat(args, "\" ");
		strcat(args, mainClass);
	} else if (wrapper) {
       	strcat(args, "-jar \"");
		strcat(args, exePath);
   		strcat(args, "\"");
    } else {
       	strcat(args, "-jar \"");
        strncat(args, exePath, pathLen);
        appendPath(args, jar);
       	strcat(args, "\"");
    }

	// Constant command line args
	if (loadString(CMD_LINE, tmp)) {
		strcat(args, " ");
		strcat(args, tmp);
	}

	// Command line args
	if (*lpCmdLine) {
		strcpy(tmp, lpCmdLine);
		char* dst;
		while ((dst = strstr(tmp, "--l4j-")) != NULL) {
			char* src = strchr(dst, ' ');
			if (src == NULL || *(src + 1) == 0) {
				*dst = 0;
			} else {
				strcpy(dst, src + 1);
			}
		}
		if (*tmp) {
			strcat(args, " ");
			strcat(args, tmp);
		}
	}

	debug("Launcher:\t%s\n", cmd);
	debug("Launcher args:\t%s\n", args);
	debug("Args length:\t%d/32768 chars\n", strlen(args));
	return TRUE;
}
예제 #19
0
파일: Util.cpp 프로젝트: iloveghq/GaborPC
//将二进制资源保存为文件
//saveAsFileName:保存文件为该名称,resID:资源ID,folder:文件夹;bSubPathOfExe:是否放在应用程序文件夹下,true:是
BOOL CUtil::saveBinResourceAsFile(CString saveAsFileName,UINT resID,CString folder,BOOL bSubPathOfExe)
{
	//
	HRSRC hsrc=::FindResource(NULL,MAKEINTRESOURCE(resID),TEXT("BIN"));//定位资源
	if(NULL==hsrc)
	{
		return FALSE;
	}//end if

	DWORD dwSize=::SizeofResource(NULL,hsrc);//获取资源大小
	if(0==dwSize)
	{
		return FALSE;
	}//end if

	HGLOBAL hGlobal=::LoadResource(NULL,hsrc);//加载资源
	if(NULL==hGlobal)
	{
		return FALSE;
	}//end if

	LPBYTE p;
	p=(LPBYTE)GlobalAlloc(GPTR,dwSize);//分配内存
	if(NULL==p)
	{
		//AfxMessageBox(_T("内存分配失败"));
		return FALSE;
	}//end if

	::CopyMemory((LPVOID)p,(LPCVOID)::LockResource(hGlobal),dwSize);//复制数据到p
	GlobalUnlock(hGlobal);
	CString path;
	//构造文件路径
	if(bSubPathOfExe)//放在应用程序文件夹下
	{
		if(""==folder)//直接放在应用程序文件夹下
		{
			path.Format(_T("%s\\%s"),getExePath(),saveAsFileName);
		}
		else
		{
			path.Format(_T("%s\\%s\\%s"),getExePath(),folder,saveAsFileName);
		}//end if
	}
	else//放在自己选择的文件夹下
	{
		if(""==folder)
		{
			path.Format(_T("%s"),saveAsFileName);//此时包含文件夹和文件名
		}
		else
		{
			path.Format(_T("%s\\%s"),folder,saveAsFileName);
		}//end if
	}//end if
	CFile file(path,CFile::modeCreate|CFile::modeWrite);
	file.Write(p,dwSize);//写入
	file.Close();//关闭
	//释放资源
	UnlockResource(hGlobal);
	FreeResource(hGlobal);
	::GlobalFree((HGLOBAL)p);
	return TRUE;
}
/**
 * Attempt to find and load a jvm.dll file.  Find the createVM()
 * function's address and return it
 */
static CreateVMFunc getCreateVMFunc()
{
    bool found = false;
    String libname;

    /**
     * First, look for an embedded jre in the .exe's dir.
     * This allows us to package our own JRE if we want to.
     */
    String inkscapeHome = getExePath();
    inkscapeHome.append("\\jre");
    msg("INKSCAPE_HOME='%s'", inkscapeHome.c_str());
    String path = checkPathUnderRoot(inkscapeHome);
    if (path.size() > 0)
        {
        libname = path;
        found = true;
        }

    /**
     * Next, look for JAVA_HOME.  This will allow the user
     * to override what's in the registry
     */
    if (!found)
        {
        const char *envStr = getenv("JAVA_HOME");
        if (envStr)
            {
            String javaHome = cleanPath(envStr);
            msg("JAVA_HOME='%s'", javaHome.c_str());
            path = checkPathUnderRoot(javaHome);
            if (path.size() > 0)
                {
                libname = path;
                found = true;
                }
            }
        }

    //not at JAVA_HOME.  check the registry
    if (!found)
        {
        char verbuf[16];
        char regpath[80];
        strcpy(regpath, "SOFTWARE\\JavaSoft\\Java Runtime Environment");
        bool ret = getRegistryString(HKEY_LOCAL_MACHINE,
                     regpath, "CurrentVersion", verbuf, 15);
        if (!ret)
            {
            msg("JVM CurrentVersion not found in registry at '%s'", regpath);
            }
        else
            {
            strcat(regpath, "\\");
            strcat(regpath, verbuf);
            //msg("reg path: %s\n", regpath);
            char valbuf[80];
            ret = getRegistryString(HKEY_LOCAL_MACHINE,
                     regpath, "RuntimeLib", valbuf, 79);
            if (ret)
                {
                found = true;
                libname = valbuf;
                }
            else
                {
                msg("JVM RuntimeLib not found in registry at '%s'",
				          regpath);
				}
			}
        }

    if (!found)
        {
        err("JVM not found at JAVA_HOME or in registry");
        return NULL;
        }

    /**
     * If we are here, then we seem to have a valid path for jvm.dll
     * Give it a try
     */	 	     
    msg("getCreateVMFunc: Loading JVM: %s", libname.c_str());
    HMODULE lib = LoadLibrary(libname.c_str());
    if (!lib)
        {
        err("Java VM not found at '%s'", libname.c_str());
        return NULL;
        }
    CreateVMFunc createVM = (CreateVMFunc)GetProcAddress(lib, "JNI_CreateJavaVM");
    if (!createVM)
        {
        err("Could not find 'JNI_CreateJavaVM' in shared library '%s'",
		                   libname.c_str());
        return NULL;
        }
    return createVM;
}
예제 #21
0
파일: osx_stub.cpp 프로젝트: CueMol/cuemol2
int main(int argc, char **argv)
{
  nsresult rv;
  char *lastSlash;

  char iniPath[MAXPATHLEN];
  char greDir[MAXPATHLEN];
  bool greFound = false;

  CFBundleRef appBundle = CFBundleGetMainBundle();
  if (!appBundle)
    return 1;

  CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(appBundle);
  if (!resourcesURL)
    return 1;

  CFURLRef absResourcesURL = CFURLCopyAbsoluteURL(resourcesURL);
  CFRelease(resourcesURL);
  if (!absResourcesURL)
    return 1;

  CFURLRef iniFileURL =
    CFURLCreateCopyAppendingPathComponent(kCFAllocatorDefault,
                                          absResourcesURL,
                                          CFSTR("application.ini"),
                                          false);
  CFRelease(absResourcesURL);
  if (!iniFileURL)
    return 1;

  CFStringRef iniPathStr =
    CFURLCopyFileSystemPath(iniFileURL, kCFURLPOSIXPathStyle);
  CFRelease(iniFileURL);
  if (!iniPathStr)
    return 1;

  CFStringGetCString(iniPathStr, iniPath, sizeof(iniPath),
                     kCFStringEncodingUTF8);
  CFRelease(iniPathStr);

  printf("iniPath = %s\n", iniPath);

  ////////////////////////////////////////

  if (!getExePath(greDir)) {
    return 1;
  }

  /*if (!getFrameworkPath(greDir)) {
    return 1;
    }*/
  /*if (realpath(tmpPath, greDir)) {
    greFound = true;
    }*/

  printf("greDir = %s\n", greDir);
  if (access(greDir, R_OK | X_OK) == 0)
    greFound = true;

  if (!greFound) {
    printf("Could not find the Mozilla runtime.\n");
    return 1;
  }

  rv = XPCOMGlueStartup(greDir);

  if (NS_FAILED(rv)) {
    printf("Couldn't load XPCOM.\n");
    return 1;
  }

  printf("Glue startup OK.\n");

  /////////////////////////////////////////////////////

  static const nsDynamicFunctionLoad kXULFuncs[] = {
    { "XRE_CreateAppData", (NSFuncPtr*) &XRE_CreateAppData },
    { "XRE_FreeAppData", (NSFuncPtr*) &XRE_FreeAppData },
    { "XRE_main", (NSFuncPtr*) &XRE_main },
    { nullptr, nullptr }
  };

  rv = XPCOMGlueLoadXULFunctions(kXULFuncs);
  if (NS_FAILED(rv)) {
    printf("Couldn't load XRE functions.\n");
    return 1;
  }

  NS_LogInit();

  int retval;

  nsXREAppData *pAppData = NULL;
  {
    nsCOMPtr<nsIFile> iniFile;
    // nsIFile *pIniFile;
    rv = NS_NewNativeLocalFile(nsDependentCString(iniPath), PR_FALSE,
			       getter_AddRefs(iniFile));
                               //&pIniFile);
    //NS_ADDREF(pIniFile);
    if (NS_FAILED(rv)) {
      printf("Couldn't find application.ini file.\n");
      return 1;
    }

    rv = XRE_CreateAppData(iniFile, &pAppData);
    //rv = XRE_CreateAppData(pIniFile, &pAppData);
    if (NS_FAILED(rv)) {
      printf("Error: couldn't parse application.ini.\n");
      return 1;
    }
  }

  NS_ASSERTION(pAppData->directory, "Failed to get app directory.");
  {
    nsAutoString path;
    pAppData->directory->GetPath(path);

    nsAutoCString nsstr;
    ::CopyUTF16toUTF8(path, nsstr);

    printf("appData.directory=%s\n", nsstr.get());
  }

  if (!pAppData->xreDirectory) {
    char xreDir[MAXPATHLEN];
    if (!getFrameworkPath(xreDir))
      return 1;

    rv = NS_NewNativeLocalFile(nsDependentCString(xreDir), PR_FALSE,
			       &pAppData->xreDirectory);
  }
  
  printf("### ENTERING XRE_MAIN ###\n");

  retval = XRE_main(argc, argv, pAppData, 0);

  printf("### LEAVING XRE_MAIN ###\n");

  NS_LogTerm();

  return retval;
}