示例#1
0
void SystemEngine::SetLanguage(const std::string& lang)
{
    Reinitl10n();

    _language = lang;
    setlocale(LC_MESSAGES, _language.c_str());
    setlocale(LC_ALL, "");

#ifdef _WIN32
    std::string lang_var = "LANGUAGE=" + _language;
    putenv(lang_var.c_str());
    SetEnvironmentVariableA("LANGUAGE", _language.c_str());
    SetEnvironmentVariableA("LANG", _language.c_str());
#else
    setenv("LANGUAGE", _language.c_str(), 1);
    setenv("LANG", _language.c_str(), 1);
#endif
}
示例#2
0
// TODO unicode support
int pyi_setenv(const char *variable, const char *value){
    int rc;
#ifdef WIN32
    rc = SetEnvironmentVariableA(variable, value);
#else
    rc = setenv(variable, value, true);
#endif
    return rc;
}
示例#3
0
void EnvironmentImpl::setImpl(const std::string& name, const std::string& value)
{
	if (SetEnvironmentVariableA(name.c_str(), value.c_str()) == 0)
	{
		std::string msg = "cannot set environment variable: ";
		msg.append(name);
		throw SystemException(msg);
	}
}
示例#4
0
文件: Stdlib.cpp 项目: Orvid/folly
int setenv(const char* name, const char* value, int overwrite) {
  if (overwrite == 0 && getenv(name) != nullptr) {
    return 0;
  }

  if (*value != '\0') {
    auto e = _putenv_s(name, value);
    if (e != 0) {
      errno = e;
      return -1;
    }
    return 0;
  }

  // We are trying to set the value to an empty string, but
  // _putenv_s deletes entries if the value is an empty string,
  // and just calling SetEnvironmentVariableA doesn't update
  // _environ, so we have to do these terrible things.
  if (_putenv_s(name, "  ") != 0) {
    errno = EINVAL;
    return -1;
  }

  // Here lies the documentation we blatently ignore to make
  // this work >_>...
  *getenv(name) = '\0';
  // This would result in a double null termination, which
  // normally signifies the end of the environment variable
  // list, so we stick a completely empty environment variable
  // into the list instead.
  *(getenv(name) + 1) = '=';

  // If _wenviron is null, the wide environment has not been initialized
  // yet, and we don't need to try to update it.
  // We have to do this otherwise we'd be forcing the initialization and
  // maintenance of the wide environment even though it's never actually
  // used in most programs.
  if (_wenviron != nullptr) {
    wchar_t buf[_MAX_ENV + 1];
    size_t len;
    if (mbstowcs_s(&len, buf, _MAX_ENV + 1, name, _MAX_ENV) != 0) {
      errno = EINVAL;
      return -1;
    }
    *_wgetenv(buf) = u'\0';
    *(_wgetenv(buf) + 1) = u'=';
  }

  // And now, we have to update the outer environment to have
  // a proper empty value.
  if (!SetEnvironmentVariableA(name, value)) {
    errno = EINVAL;
    return -1;
  }
  return 0;
}
示例#5
0
// TODO unicode support
int pyi_unsetenv(const char *variable)
{
    int rc;
#ifdef WIN32
    rc = SetEnvironmentVariableA(variable, NULL);
#else
    rc = unsetenv(variable);
#endif
    return rc;
}
示例#6
0
文件: time.c 项目: DeltaYang/wine
static void test_FileTimeToLocalFileTime(void)
{
    FILETIME ft, lft;
    SYSTEMTIME st;
    TIME_ZONE_INFORMATION tzinfo;
    DWORD res =  GetTimeZoneInformation(&tzinfo);
    ULONGLONG time = (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1970 +
        (LONGLONG)(tzinfo.Bias + 
            ( res == TIME_ZONE_ID_STANDARD ? tzinfo.StandardBias :
            ( res == TIME_ZONE_ID_DAYLIGHT ? tzinfo.DaylightBias : 0 ))) *
             SECSPERMIN *TICKSPERSEC;
    BOOL ret;

    ok( res != TIME_ZONE_ID_INVALID , "GetTimeZoneInformation failed\n");
    ft.dwHighDateTime = (UINT)(time >> 32);
    ft.dwLowDateTime  = (UINT)time;
    ret = FileTimeToLocalFileTime(&ft, &lft);
    ok( ret,
       "FileTimeToLocalFileTime() failed with Error %d\n",GetLastError());
    FileTimeToSystemTime(&lft, &st);
    ok(((st.wYear == 1970) && (st.wMonth == 1) && (st.wDay == 1) &&
	(st.wHour ==    0) && (st.wMinute == 0) && (st.wSecond == 1) &&
	(st.wMilliseconds == 0)),
       "Got Year %4d Month %2d Day %2d Hour %2d Min %2d Sec %2d mSec %3d\n",
       st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond,
       st.wMilliseconds);

    ok(SetEnvironmentVariableA("TZ","GMT") != 0,
       "SetEnvironmentVariableA failed\n");
    ok(res != TIME_ZONE_ID_INVALID, "GetTimeZoneInformation failed\n");
    ret = FileTimeToLocalFileTime(&ft, &lft);
    ok( ret,
       "FileTimeToLocalFileTime() failed with Error %d\n",GetLastError());
    FileTimeToSystemTime(&lft, &st);
    ok(((st.wYear == 1970) && (st.wMonth == 1) && (st.wDay == 1) &&
	(st.wHour ==    0) && (st.wMinute == 0) && (st.wSecond == 1) &&
	(st.wMilliseconds == 0)),
       "Got Year %4d Month %2d Day %2d Hour %2d Min %2d Sec %2d mSec %3d\n",
       st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond,
       st.wMilliseconds);
    ok(SetEnvironmentVariableA("TZ",NULL) != 0,
       "SetEnvironmentVariableA failed\n");
}
示例#7
0
文件: action.cpp 项目: ArildF/masters
int
putEnvStr(
    char *name,
    char *value
    )
{
    BOOL b = SetEnvironmentVariableA(name, value);

    return (b) ? 0 : -1;
}
示例#8
0
void talon_setenv(char name[], char val[])
{
#if defined(HAS_GETENVIRONMENTVARIABLE)
	SetEnvironmentVariableA(name,val); 
#elif defined(HAS_GETENV)
	setenv(name,val, 1);
#else
#	error "Need a function for setting environment variables"
#endif
}
示例#9
0
// Change value of environment variable name
bool FXSystem::setEnvironment(const FXString& name,const FXString& value){
  if(!name.empty()){
#ifndef WIN32
#ifdef __GNU_LIBRARY__
    if(!value.empty()){
      return setenv(name.text(),value.text(),TRUE)==0;
      }
    unsetenv(name.text());
    return true;
#endif
#else
    if(!value.empty()){
      return SetEnvironmentVariableA(name.text(),value.text())!=0;
      }
    return SetEnvironmentVariableA(name.text(),NULL)!=0;
#endif
    }
  return false;
  }
示例#10
0
runner::env_vars_list_t runner::set_environment_for_process() const
{
    auto curr_vars = read_environment(GetEnvironmentStringsW());

    if (options.environmentMode == "user-default")
    {
        LPVOID envBlock = NULL;

        CreateEnvironmentBlock(&envBlock, NULL, FALSE);

        auto default_vars = read_environment((WCHAR*)envBlock);

        DestroyEnvironmentBlock(envBlock);

        for (auto i = default_vars.cbegin(); i != default_vars.cend(); ++i)
        {
            SetEnvironmentVariableA(i->first.c_str(), i->second.c_str());
        }

        for (auto i = curr_vars.cbegin(); i != curr_vars.cend(); ++i)
        {
            if (std::find(default_vars.cbegin(), default_vars.cend(), *i) == default_vars.cend())
            {
                SetEnvironmentVariableA(i->first.c_str(), NULL);
            }
        }
    }
    else if (options.environmentMode == "clear")
    {
        for (auto i = curr_vars.cbegin(); i != curr_vars.cend(); ++i)
        {
            SetEnvironmentVariableA(i->first.c_str(), NULL);
        }
    }

    for (auto i = options.environmentVars.cbegin(); i != options.environmentVars.cend(); ++i) {
        SetEnvironmentVariableA(i->first.c_str(), i->second.c_str());
    }

    return curr_vars;
}
示例#11
0
//初始化CGI程序环境变量
void initEnvironmentVariables(HttpTask *task){
	//SERVER_NAME
	SetEnvironmentVariableA("SERVER_NAME", task->hostName.c_str());
	//SERVER_PORT
	SetEnvironmentVariableA("SERVER_PORT", int2str(task->serverPort).c_str());

	HttpRequest *request = &(task->request);
	std::string uri = request->getRequestURI();
	//...解码

	//取得params
	std::string params;
	if (fetchParams(uri, &params)){
		SetEnvironmentVariableA("QUERY_NAME", params.c_str());
	}
	
	//REQUEST_METHOD
	if (request->getRequestMethod() == GET)
		SetEnvironmentVariableA("REQUEST_METHOD", "GET");
	else
	{
		SetEnvironmentVariableA("CONTENT_LENGTH", int2str(task->request.getContentLength()).c_str());
		SetEnvironmentVariableA("REQUEST_METHOD", "POST");
	}
}
bool SetEnvironmentVariable( const char *pchVarName, const char *pchVarValue )
{
#if defined(_WIN32)
	return 0 != SetEnvironmentVariableA( pchVarName, pchVarValue );
#elif defined(POSIX)
	if( pchVarValue == NULL )
		return 0 == unsetenv( pchVarName );
	else
		return 0 == setenv( pchVarName, pchVarValue, 1 );
#else
#error "Unsupported Platform"
#endif
}
示例#13
0
文件: stdlib.c 项目: bobylive/libnfc
int setenv(const char *name, const char *value, int overwrite)
{
  int exists = GetEnvironmentVariableA(name, NULL, 0);
  if ((exists && overwrite) || (!exists)) {
    if (!SetEnvironmentVariableA(name, value)) {
      // Set errno here correctly
      return -1;
    }
    return 0;
  }
  // Exists and overwrite is 0.
  return -1;
}
示例#14
0
BOOL __lib_SetEnvironmentVariableW( LPCWSTR lpName, LPCWSTR lpValue )
/*******************************************************************/
{
    if( WIN32_IS_NT ) {                                 /* NT */
        return( SetEnvironmentVariableW( lpName, lpValue ) );
    } else {                                            /* Win95 or Win32s */
        char *          mbName;
        char *          mbValue;
        BOOL            osrc;
        size_t          cvt;
        size_t          len;

        /*** Allocate some memory ***/
        len = wcslen( lpName ) * MB_CUR_MAX + 1;
        mbName = lib_malloc( len );
        if( mbName == NULL ) {
            return( FALSE );
        }
        if( lpValue == NULL ) {
            mbValue = NULL;
        } else {
            len = wcslen( lpValue ) * MB_CUR_MAX + 1;
            mbValue = lib_malloc( len );
            if( mbValue == NULL ) {
                lib_free( mbName );
                return( FALSE );
            }
        }

        /*** Prepare to call the OS ***/
        cvt = wcstombs( mbName, lpName, len );
        if( cvt == (size_t)-1 ) {
            lib_free( mbName );
            if( mbValue != NULL )  lib_free( mbValue );
            return( FALSE );
        }
        if( mbValue != NULL ) {
            cvt = wcstombs( mbValue, lpValue, len );
            if( cvt == (size_t)-1 ) {
                lib_free( mbValue );
                return( FALSE );
            }
        }

        /*** Call the OS ***/
        osrc = SetEnvironmentVariableA( mbName, mbValue );
        lib_free( mbName );
        if( mbValue != NULL )  lib_free( mbValue );
        return( osrc );
    }
}
示例#15
0
文件: shreg.c 项目: Kelimion/wine
static HKEY create_test_entries(void)
{
	HKEY hKey;
        DWORD ret;
        DWORD nExpectedLen1, nExpectedLen2;

        SetEnvironmentVariableA("LONGSYSTEMVAR", sEnvvar1);
        SetEnvironmentVariableA("FOO", sEnvvar2);

        ret = RegCreateKeyA(HKEY_CURRENT_USER, REG_TEST_KEY, &hKey);
	ok( ERROR_SUCCESS == ret, "RegCreateKeyA failed, ret=%u\n", ret);

	if (hKey)
	{
           ok(!RegSetValueExA(hKey,"Test1",0,REG_EXPAND_SZ, (LPBYTE) sTestpath1, strlen(sTestpath1)+1), "RegSetValueExA failed\n");
           ok(!RegSetValueExA(hKey,"Test2",0,REG_SZ, (LPBYTE) sTestpath1, strlen(sTestpath1)+1), "RegSetValueExA failed\n");
           ok(!RegSetValueExA(hKey,"Test3",0,REG_EXPAND_SZ, (LPBYTE) sTestpath2, strlen(sTestpath2)+1), "RegSetValueExA failed\n");
	}

	nExpLen1 = ExpandEnvironmentStringsA(sTestpath1, sExpTestpath1, sizeof(sExpTestpath1));
	nExpLen2 = ExpandEnvironmentStringsA(sTestpath2, sExpTestpath2, sizeof(sExpTestpath2));

	nExpectedLen1 = strlen(sTestpath1) - strlen("%LONGSYSTEMVAR%") + strlen(sEnvvar1) + 1;
	nExpectedLen2 = strlen(sTestpath2) - strlen("%FOO%") + strlen(sEnvvar2) + 1;
	/* ExpandEnvironmentStringsA on NT4 returns 2x the correct result */
	trace("sExplen1 = (%d)\n", nExpLen1);
	if (nExpectedLen1 != nExpLen1)
            trace( "Expanding %s failed (expected %d) - known bug in NT4\n", sTestpath1, nExpectedLen1 );

        trace("sExplen2 = (%d)\n", nExpLen2);
	if (nExpectedLen2 != nExpLen2)
            trace( "Expanding %s failed (expected %d) - known bug in NT4\n", sTestpath2, nExpectedLen2 );	

	/* Make sure we carry on with correct values */
	nExpLen1 = nExpectedLen1; 
	nExpLen2 = nExpectedLen2;
	return hKey;
}
示例#16
0
bool SystemEngine::SetLanguageLocale(const std::string& lang)
{
    // Test whether the file is existing.
    // The function called also reinit the i10n paths
    // so we don't have to do it here.
    if (!IsLanguageLocaleAvailable(lang))
        return false;

    _current_language_locale = lang;
    setlocale(LC_MESSAGES, _current_language_locale.c_str());
    setlocale(LC_ALL, "");

#ifdef _WIN32
    std::string lang_var = "LANGUAGE=" + _current_language_locale;
    putenv(lang_var.c_str());
    SetEnvironmentVariableA("LANGUAGE", _current_language_locale.c_str());
    SetEnvironmentVariableA("LANG", _current_language_locale.c_str());
#else
    setenv("LANGUAGE", _current_language_locale.c_str(), 1);
    setenv("LANG", _current_language_locale.c_str(), 1);
#endif
    return true;
}
示例#17
0
/* Put a variable into the environment */
int
SDL_setenv(const char *name, const char *value, int overwrite)
{
    if (!overwrite) {
        char ch = 0;
        const size_t len = GetEnvironmentVariableA(name, &ch, sizeof (ch));
        if (len > 0) {
            return 0;  /* asked not to overwrite existing value. */
        }
    }
    if (!SetEnvironmentVariableA(name, *value ? value : NULL)) {
        return -1;
    }
    return 0;
}
示例#18
0
ofGstUtils::ofGstUtils() {
	bLoaded 					= false;
	speed 						= 1;
	bPaused						= false;
	bIsMovieDone				= false;
	bPlaying					= false;
	loopMode					= OF_LOOP_NONE;
	bFrameByFrame 				= false;

	gstPipeline					= NULL;
	gstSink						= NULL;

	durationNanos				= 0;

	isAppSink					= false;
	isStream					= false;

	appsink						= NULL;
	closing 					= false;

	busWatchID					= 0;

#if GLIB_MINOR_VERSION<32
	if(!g_thread_supported()){
		g_thread_init(NULL);
	}
#endif

	if(!gst_inited){
#ifdef TARGET_WIN32
		string gst_path = g_getenv("GSTREAMER_1_0_ROOT_X86");
		//putenv(("GST_PLUGIN_PATH_1_0=" + ofFilePath::join(gst_path, "lib\\gstreamer-1.0") + ";.").c_str());
		// to make it compatible with gcc and C++11 standard
		SetEnvironmentVariableA("GST_PLUGIN_PATH_1_0", ofFilePath::join(gst_path, "lib\\gstreamer-1.0").c_str());
#endif
		gst_init (NULL, NULL);
		gst_inited=true;
		ofLogVerbose("ofGstUtils") << "gstreamer inited";
	}
	if(!plugin_registered){
		gst_plugin_register_static(GST_VERSION_MAJOR, GST_VERSION_MINOR,
					"appsink", (char*)"Element application sink",
					appsink_plugin_init, "0.1", "LGPL", "ofVideoPlayer", "openFrameworks",
					"http://openframeworks.cc/");
		plugin_registered=true;
	}

}
示例#19
0
int my_setenv (const char * name, const char * value)
{
   size_t namelen = strlen(name);
   size_t valuelen = (value==NULL ? 0 : strlen(value));

#ifdef WIN32
   /* On Woe32, each process has two copies of the environment variables,
      one managed by the OS and one managed by the C library. We set
      the value in both locations, so that other software that looks in
      one place or the other is guaranteed to see the value. Even if it's
      a bit slow. See also
      <http://article.gmane.org/gmane.comp.gnu.mingw.user/8272>
      <http://article.gmane.org/gmane.comp.gnu.mingw.user/8273>
      <http://www.cygwin.com/ml/cygwin/1999-04/msg00478.html> */

   if (!SetEnvironmentVariableA(name,value))
   {   
     fprintf(stderr, "Warning - SetEnvironmentVariableA(%s, %s) failed.\n",
             name, value);
   }
#endif

#ifdef HAVE_PUTENV
  {
   char* buffer = (char*)malloc(namelen+1+valuelen+1);
   if (!buffer)
     return -1; /* no need to set errno = ENOMEM */
   memcpy(buffer,name,namelen);
   if (value != NULL) {
     buffer[namelen] = '=';
     memcpy(buffer+namelen+1,value,valuelen);
     buffer[namelen+1+valuelen] = 0;
   } else
     buffer[namelen] = 0;
   return putenv(buffer);
  }

#else
#ifdef HAVE_SETENV
   return setenv(name,value,1);
#else
   /* Uh oh, neither putenv() nor setenv() ... */
   fprintf(stderr, "my_setenv() - neither HAVE_PUTENV nor HAVE_SETENV defined\n");
   return -1;
#endif
#endif
}
示例#20
0
/******************************************************************
 *		dbg_attach_debuggee
 *
 * Sets the debuggee to <pid>
 * cofe instructs winedbg what to do when first exception is received
 * (break=FALSE, continue=TRUE)
 * wfe is set to TRUE if dbg_attach_debuggee should also proceed with all debug events
 * until the first exception is received (aka: attach to an already running process)
 */
BOOL dbg_attach_debuggee(DWORD pid, BOOL cofe)
{
    if (!(dbg_curr_process = dbg_add_process(&be_process_active_io, pid, 0))) return FALSE;

    if (!DebugActiveProcess(pid))
    {
        dbg_printf("Can't attach process %04x: error %u\n", pid, GetLastError());
        dbg_del_process(dbg_curr_process);
        return FALSE;
    }
    dbg_curr_process->continue_on_first_exception = cofe;

    SetEnvironmentVariableA("DBGHELP_NOLIVE", NULL);

    dbg_curr_process->active_debuggee = TRUE;
    return TRUE;
}
示例#21
0
文件: path.c 项目: azuwis/mplayer
void set_path_env(void)
{
	/*make our codec dirs available for LoadLibraryA()*/
	char win32path[MAX_PATH];
#ifdef __CYGWIN__
	cygwin_conv_to_full_win32_path(BINARY_CODECS_PATH, win32path);
#else /*__CYGWIN__*/
	/* Expand to absolute path unless it's already absolute */
	if (!strstr(BINARY_CODECS_PATH,":") && BINARY_CODECS_PATH[0] != '\\') {
		GetModuleFileNameA(NULL, win32path, MAX_PATH);
		strcpy(strrchr(win32path, '\\') + 1, BINARY_CODECS_PATH);
	}
	else strcpy(win32path, BINARY_CODECS_PATH);
#endif /*__CYGWIN__*/
	mp_msg(MSGT_WIN32, MSGL_V, "Setting PATH to %s\n", win32path);
	if (!SetEnvironmentVariableA("PATH", win32path))
		mp_msg(MSGT_WIN32, MSGL_WARN, "Cannot set PATH!");
}
示例#22
0
static void update_path(void)
{
  char buff1[MAX_PATH*4], *buff2;
  char *path;
  int size, i;

  path = getenv("PATH");
  GetModuleFileNameA(NULL, buff1, sizeof(buff1));
  for (i = strlen(buff1)-1; i > 0; i--)
    if (buff1[i] == '\\') break;
  buff1[i] = 0;

  size = strlen(path) + strlen(buff1) + 3;
  buff2 = malloc(size);
  if (buff2 == NULL) return;

  snprintf(buff2, size, "%s;%s", path, buff1);
  SetEnvironmentVariableA("PATH", buff2);
  free(buff2);
}
示例#23
0
static void wesnoth_setlocale(int category, std::string const &slocale,
	std::vector<std::string> const *alternates)
{
	std::string locale = slocale;
	// FIXME: ideally we should check LANGUAGE and on first invocation
	// use that value, so someone with es would get the game in Spanish
	// instead of en_US the first time round
	// LANGUAGE overrides other settings, so for now just get rid of it
	// FIXME: add configure check for unsetenv
#ifndef _WIN32
	unsetenv ("LANGUAGE"); // void so no return value to check
#endif

#ifdef __APPLE__
	if (category == LC_MESSAGES && setenv("LANG", locale.c_str(), 1) == -1) {
		ERR_G << "setenv LANG failed: " << strerror(errno);
	}
#endif

#ifdef _WIN32
	std::string win_locale(locale, 0, 2);
	#include "language_win32.ii"
	if(category == LC_MESSAGES) {
		SetEnvironmentVariableA("LANG", win_locale.c_str());
		std::string env = "LANGUAGE=" + locale;
		_putenv(env.c_str());
		return;
	}
	locale = win_locale;
#endif

	char *res = NULL;
	std::vector<std::string>::const_iterator i;
	if (alternates) i = alternates->begin();

	for (;;)
	{
		std::string lang = locale, extra;
		std::string::size_type pos = locale.find('@');
		if (pos != std::string::npos) {
			lang.erase(pos);
			extra = locale.substr(pos);
		}

		/*
		 * The "" is the last item to work-around a problem in glibc picking
		 * the non utf8 locale instead an utf8 version if available.
		 */
		char const *encoding[] = { ".utf-8", ".UTF-8", "" };
		for (int j = 0; j != 3; ++j)
		{
			locale = lang + encoding[j] + extra;
			res = std::setlocale(category, locale.c_str());
			if (res) {
				LOG_G << "Set locale to '" << locale << "' result: '" << res << "'.\n";
				goto done;
			}
		}

		if (!alternates || i == alternates->end()) break;
		locale = *i;
		++i;
	}

	WRN_G << "setlocale() failed for '" << slocale << "'." << std::endl;

	if (category == LC_TIME) {
		time_locale_correct() = false;
	}

#ifndef _WIN32
		if(category == LC_MESSAGES) {
			WRN_G << "Setting LANGUAGE to '" << slocale << "'." << std::endl;
			setenv("LANGUAGE", slocale.c_str(), 1);
			std::setlocale(LC_MESSAGES, "");
		}
#endif

	done:
	DBG_G << "Numeric locale: " << std::setlocale(LC_NUMERIC, NULL) << '\n';
	DBG_G << "Full locale: " << std::setlocale(LC_ALL, NULL) << '\n';
}
示例#24
0
文件: environ.c 项目: mikekap/wine
static void test_ExpandEnvironmentStringsA(void)
{
    const char* value="Long long value";
    const char* not_an_env_var="%NotAnEnvVar%";
    char buf[256], buf1[256], buf2[0x8000];
    DWORD ret_size, ret_size1;

    SetEnvironmentVariableA("EnvVar", value);

    ret_size = ExpandEnvironmentStringsA(NULL, buf1, sizeof(buf1));
    ok(ret_size == 1 || ret_size == 0 /* Win9x */ || ret_size == 2 /* NT4 */,
       "ExpandEnvironmentStrings returned %d\n", ret_size);

    /* Try to get the required buffer size 'the natural way' */
    strcpy(buf, "%EnvVar%");
    ret_size = ExpandEnvironmentStringsA(buf, NULL, 0);
    ok(ret_size == strlen(value)+1 || /* win98 */
       ret_size == (strlen(value)+1)*2 || /* NT4 */
       ret_size == strlen(value)+2 || /* win2k, XP, win2k3 */
       ret_size == 0 /* Win95 */,
       "ExpandEnvironmentStrings returned %d instead of %d, %d or %d\n",
       ret_size, lstrlenA(value)+1, lstrlenA(value)+2, 0);

    /* Again, side-stepping the Win95 bug */
    ret_size = ExpandEnvironmentStringsA(buf, buf1, 0);
    /* v5.1.2600.2945 (XP SP2) returns len + 2 here! */
    ok(ret_size == strlen(value)+1 || ret_size == strlen(value)+2 ||
       ret_size == (strlen(value)+1)*2 /* NT4 */,
       "ExpandEnvironmentStrings returned %d instead of %d\n",
       ret_size, lstrlenA(value)+1);

    /* Try with a buffer that's too small */
    ret_size = ExpandEnvironmentStringsA(buf, buf1, 12);
    /* v5.1.2600.2945 (XP SP2) returns len + 2 here! */
    ok(ret_size == strlen(value)+1 || ret_size == strlen(value)+2 ||
       ret_size == (strlen(value)+1)*2 /* NT4 */,
       "ExpandEnvironmentStrings returned %d instead of %d\n",
       ret_size, lstrlenA(value)+1);

    /* Try with a buffer of just the right size */
    /* v5.1.2600.2945 (XP SP2) needs and returns len + 2 here! */
    ret_size = ExpandEnvironmentStringsA(buf, buf1, ret_size);
    ok(ret_size == strlen(value)+1 || ret_size == strlen(value)+2 ||
       ret_size == (strlen(value)+1)*2 /* NT4 */,
       "ExpandEnvironmentStrings returned %d instead of %d\n",
       ret_size, lstrlenA(value)+1);
    ok(!strcmp(buf1, value), "ExpandEnvironmentStrings returned [%s]\n", buf1);

    /* Try with an unset environment variable */
    strcpy(buf, not_an_env_var);
    ret_size = ExpandEnvironmentStringsA(buf, buf1, sizeof(buf1));
    ok(ret_size == strlen(not_an_env_var)+1 ||
       ret_size == (strlen(not_an_env_var)+1)*2 /* NT4 */,
       "ExpandEnvironmentStrings returned %d instead of %d\n", ret_size, lstrlenA(not_an_env_var)+1);
    ok(!strcmp(buf1, not_an_env_var), "ExpandEnvironmentStrings returned [%s]\n", buf1);

    /* test a large destination size */
    strcpy(buf, "12345");
    ret_size = ExpandEnvironmentStringsA(buf, buf2, sizeof(buf2));
    ok(!strcmp(buf, buf2), "ExpandEnvironmentStrings failed %s vs %s. ret_size = %d\n", buf, buf2, ret_size);

    ret_size1 = GetWindowsDirectoryA(buf1,256);
    ok ((ret_size1 >0) && (ret_size1<256), "GetWindowsDirectory Failed\n");
    ret_size = ExpandEnvironmentStringsA("%SystemRoot%",buf,sizeof(buf));
    if (ERROR_ENVVAR_NOT_FOUND != GetLastError())
    {
        ok(!strcmp(buf, buf1), "ExpandEnvironmentStrings failed %s vs %s. ret_size = %d\n", buf, buf1, ret_size);
    }

    /* Try with a variable that references another */
    SetEnvironmentVariableA("IndirectVar", "Foo%EnvVar%Bar");
    strcpy(buf, "Indirect-%IndirectVar%-Indirect");
    strcpy(buf2, "Indirect-Foo%EnvVar%Bar-Indirect");
    ret_size = ExpandEnvironmentStringsA(buf, buf1, sizeof(buf1));
    ok(ret_size == strlen(buf2)+1 ||
       ret_size == (strlen(buf2)+1)*2 /* NT4 */,
       "ExpandEnvironmentStrings returned %d instead of %d\n", ret_size, lstrlen(buf2)+1);
    ok(!strcmp(buf1, buf2), "ExpandEnvironmentStrings returned [%s]\n", buf1);
    SetEnvironmentVariableA("IndirectVar", NULL);

    SetEnvironmentVariableA("EnvVar", NULL);
}
示例#25
0
文件: environ.c 项目: mikekap/wine
static void test_GetSetEnvironmentVariableA(void)
{
    char buf[256];
    BOOL ret;
    DWORD ret_size;
    static const char name[] = "SomeWildName";
    static const char name_cased[] = "sOMEwILDnAME";
    static const char value[] = "SomeWildValue";

    ret = SetEnvironmentVariableA(name, value);
    ok(ret == TRUE,
       "unexpected error in SetEnvironmentVariableA, GetLastError=%d\n",
       GetLastError());

    /* Try to retrieve the environment variable we just set */
    ret_size = GetEnvironmentVariableA(name, NULL, 0);
    ok(ret_size == strlen(value) + 1,
       "should return length with terminating 0 ret_size=%d\n", ret_size);

    lstrcpyA(buf, "foo");
    ret_size = GetEnvironmentVariableA(name, buf, lstrlenA(value));
    ok(lstrcmpA(buf, "foo") == 0, "should not touch the buffer\n");
    ok(ret_size == strlen(value) + 1,
       "should return length with terminating 0 ret_size=%d\n", ret_size);

    lstrcpyA(buf, "foo");
    ret_size = GetEnvironmentVariableA(name, buf, lstrlenA(value) + 1);
    ok(lstrcmpA(buf, value) == 0, "should touch the buffer\n");
    ok(ret_size == strlen(value),
       "should return length without terminating 0 ret_size=%d\n", ret_size);

    lstrcpyA(buf, "foo");
    ret_size = GetEnvironmentVariableA(name_cased, buf, lstrlenA(value) + 1);
    ok(lstrcmpA(buf, value) == 0, "should touch the buffer\n");
    ok(ret_size == strlen(value),
       "should return length without terminating 0 ret_size=%d\n", ret_size);

    /* Remove that environment variable */
    ret = SetEnvironmentVariableA(name_cased, NULL);
    ok(ret == TRUE, "should erase existing variable\n");

    lstrcpyA(buf, "foo");
    ret_size = GetEnvironmentVariableA(name, buf, lstrlenA(value) + 1);
    ok(lstrcmpA(buf, "foo") == 0, "should not touch the buffer\n");
    ok(ret_size == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND,
       "should not find variable but ret_size=%d GetLastError=%d\n",
       ret_size, GetLastError());

    /* Check behavior of SetEnvironmentVariableA(name, "") */
    ret = SetEnvironmentVariableA(name, value);
    ok(ret == TRUE,
       "unexpected error in SetEnvironmentVariableA, GetLastError=%d\n",
       GetLastError());

    lstrcpyA(buf, "foo");
    ret_size = GetEnvironmentVariableA(name_cased, buf, lstrlenA(value) + 1);
    ok(lstrcmpA(buf, value) == 0, "should touch the buffer\n");
    ok(ret_size == strlen(value),
       "should return length without terminating 0 ret_size=%d\n", ret_size);

    ret = SetEnvironmentVariableA(name_cased, "");
    ok(ret == TRUE,
       "should not fail with empty value but GetLastError=%d\n", GetLastError());

    lstrcpyA(buf, "foo");
    SetLastError(0);
    ret_size = GetEnvironmentVariableA(name, buf, lstrlenA(value) + 1);
    ok(ret_size == 0 &&
       ((GetLastError() == 0 && lstrcmpA(buf, "") == 0) ||
        (GetLastError() == ERROR_ENVVAR_NOT_FOUND)),
       "%s should be set to \"\" (NT) or removed (Win9x) but ret_size=%d GetLastError=%d and buf=%s\n",
       name, ret_size, GetLastError(), buf);

    /* Test the limits */
    ret_size = GetEnvironmentVariableA(NULL, NULL, 0);
    ok(ret_size == 0 && (GetLastError() == ERROR_INVALID_PARAMETER || GetLastError() == ERROR_ENVVAR_NOT_FOUND),
       "should not find variable but ret_size=%d GetLastError=%d\n",
       ret_size, GetLastError());

    ret_size = GetEnvironmentVariableA(NULL, buf, lstrlenA(value) + 1);
    ok(ret_size == 0 && (GetLastError() == ERROR_INVALID_PARAMETER || GetLastError() == ERROR_ENVVAR_NOT_FOUND),
       "should not find variable but ret_size=%d GetLastError=%d\n",
       ret_size, GetLastError());

    ret_size = GetEnvironmentVariableA("", buf, lstrlenA(value) + 1);
    ok(ret_size == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND,
       "should not find variable but ret_size=%d GetLastError=%d\n",
       ret_size, GetLastError());
}
示例#26
0
/**********************************************************************
 *						Functions
 *********************************************************************/
BOOL CALLBACK IH_DlgMain(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch(uMsg)
    {
    case WM_INITDIALOG:
    {
        g_HWND=hwndDlg;
        EnableWindow(GetDlgItem(hwndDlg, IDC_BTN_INLINE), FALSE);
        EnableWindow(GetDlgItem(hwndDlg, IDC_BTN_COPY), FALSE);
    }
    return TRUE;

    case WM_HELP:
    {
        char id[10]="";
        sprintf(id, "%d", IDS_HELPINLINE);
        SetEnvironmentVariableA("HELPID", id);
        SetEnvironmentVariableA("HELPTITLE", "Inline Help");
        DialogBox(hInst, MAKEINTRESOURCE(DLG_HELP), hwndDlg, DlgHelp);
    }
    return TRUE;

    case WM_BROWSE:
    {
        strcpy(g_szFileName, (const char*)wParam);
        //Retrieve the directory of the file.
        int i=strlen(g_szFileName)-1;
        int j=0;
        while(g_szFileName[i]!='\\')
        {
            i--;
            j++;
        }
        strncpy(g_szTargetDir, g_szFileName, strlen(g_szFileName)-j-1);

        //Retrieve stuff.
        EnableWindow(GetDlgItem(g_HWND, IDC_BTN_INLINE), FALSE);
        EnableWindow(GetDlgItem(g_HWND, IDC_BTN_COPY), FALSE);
        SendDlgItemMessageA(g_HWND, IDC_EDT_OEP, EM_SETREADONLY, 0, 0); //Enable change of OEP...
        DragAcceptFiles(g_HWND, FALSE);

        g_FileIsDll=IH_Debugger(g_szFileName, &g_TargetData, IH_DebugEnd_Callback, IH_ErrorMessageCallback);
    }
    return TRUE;

    case WM_DROPFILES:
    {
        //Get the dropped file name.
        DragQueryFileA((HDROP)wParam, 0, g_szFileName, 256);

        //Retrieve the directory of the file.
        int i=strlen(g_szFileName)-1;
        int j=0;
        while(g_szFileName[i]!='\\')
        {
            i--;
            j++;
        }
        strncpy(g_szTargetDir, g_szFileName, strlen(g_szFileName)-j-1);

        //Retrieve stuff.
        EnableWindow(GetDlgItem(g_HWND, IDC_BTN_INLINE), FALSE);
        EnableWindow(GetDlgItem(g_HWND, IDC_BTN_COPY), FALSE);
        SendDlgItemMessageA(g_HWND, IDC_EDT_OEP, EM_SETREADONLY, 0, 0); //Enable change of OEP...
        DragAcceptFiles(g_HWND, FALSE);

        g_FileIsDll=IH_Debugger(g_szFileName, &g_TargetData, IH_DebugEnd_Callback, IH_ErrorMessageCallback);
    }
    return TRUE;

    case WM_COMMAND:
    {
        switch(LOWORD(wParam))
        {
        case IDC_BTN_INLINE:
        {
            NoFocus();
            if(!(g_TargetData.EmptyEntry))
            {
                MessageBoxA(hwndDlg, "You need to specify the place to start the inline...", "N00B!", MB_ICONERROR);
                return TRUE;
            }
            char patch_filename[256]="";
            patch_filename[0]=0;
            OPENFILENAME ofstruct;
            memset(&ofstruct, 0, sizeof(ofstruct));
            ofstruct.lStructSize=sizeof(ofstruct);
            ofstruct.hwndOwner=hwndDlg;
            ofstruct.hInstance=hInst;
            if(!g_FileIsDll)
                ofstruct.lpstrFilter="Executable files (*.exe)\0*.exe\0\0";
            else
                ofstruct.lpstrFilter="Executable files (*.dll)\0*.dll\0\0";
            ofstruct.lpstrFile=patch_filename;
            ofstruct.nMaxFile=256;
            ofstruct.lpstrInitialDir=g_szTargetDir;
            ofstruct.lpstrTitle="Save file";
            if(!g_FileIsDll)
                ofstruct.lpstrDefExt="exe";
            else
                ofstruct.lpstrDefExt="dll";
            ofstruct.Flags=OFN_EXTENSIONDIFFERENT|OFN_HIDEREADONLY|OFN_NONETWORKBUTTON|OFN_OVERWRITEPROMPT;
            GetSaveFileName(&ofstruct);
            if(!patch_filename[0])
            {
                MessageBoxA(hwndDlg, "You must select a file...", "Warning", MB_ICONWARNING);
                return TRUE;
            }

            CopyFileA(g_szFileName, patch_filename, FALSE);
            SetPE32Data(patch_filename, 0, UE_OEP, g_TargetData.EmptyEntry-g_TargetData.ImageBase);
            long newflags=(long)GetPE32Data(patch_filename, g_TargetData.EntrySectionNumber, UE_SECTIONFLAGS);
            SetPE32Data(patch_filename, g_TargetData.EntrySectionNumber, UE_SECTIONFLAGS, (newflags|0x80000000));

            IH_GenerateAsmCode(g_codeText, g_TargetData);
            CopyToClipboard(g_codeText);
            MessageBoxA(hwndDlg, "1) Open the file you just saved with OllyDbg\n2) Open Multimate Assembler v1.5+\n3) Paste the code\n4) Modify the code to do something with the Security DLL\n5) Save the patched file with OllyDbg\n6) Enjoy!", "Instructions", MB_ICONINFORMATION);
        }
        return TRUE;

        case IDC_EDT_FREESPACE:
        {
            char free_temp[10]="";
            GetDlgItemTextA(hwndDlg, IDC_EDT_FREESPACE, free_temp, 10);
            sscanf(FormatTextHex(free_temp), "%X", &(g_TargetData.EmptyEntry));
        }
        return TRUE;

        case IDC_BTN_COPY:
        {
            NoFocus();
            if(g_codeText[0])
            {
                IH_GenerateAsmCode(g_codeText, g_TargetData);
                CopyToClipboard(g_codeText);
                MessageBoxA(hwndDlg, "Code copied to clipboard!", "Yay!", MB_ICONINFORMATION);
            }
            else
                MessageBoxA(hwndDlg, "There is no code to copy, please load a file first...", "Error!", MB_ICONERROR);
        }
        return TRUE;

        case IDC_BTN_PLUGINS:
        {
            NoFocus();
            PLUGFUNC PluginFunction;
            HINSTANCE PLUGIN_INST;
            char total_found_s[5]="";
            char plugin_name[100]="";
            char plugin_dll[100]="";
            char dll_to_load[256]="";
            char temp_str[5]="";
            int total_found=0;
            GetPrivateProfileStringA("Plugins", "total_found", "", total_found_s, 4, sg_szPluginIniFilePath);
            sscanf(total_found_s, "%d", &total_found);
            if(total_found)
            {
                HMENU myMenu=0;
                myMenu=CreatePopupMenu();
                for(int i=1; i!=(total_found+1); i++)
                {
                    sprintf(temp_str, "%d", i);
                    GetPrivateProfileStringA(temp_str, "plugin_name", "", plugin_name, 100, sg_szPluginIniFilePath);
                    AppendMenuA(myMenu, MF_STRING, i, plugin_name);
                }
                POINT cursorPos;
                GetCursorPos(&cursorPos);
                SetForegroundWindow(hwndDlg);
                UINT MenuItemClicked=TrackPopupMenu(myMenu, TPM_RETURNCMD|TPM_NONOTIFY, cursorPos.x, cursorPos.y, 0, hwndDlg, 0);
                SendMessage(hwndDlg, WM_NULL, 0, 0);
                if(!MenuItemClicked)
                    return TRUE;

                sprintf(temp_str, "%d", (int)MenuItemClicked);
                GetPrivateProfileStringA(temp_str, "plugin_dll", "", plugin_dll, 100, sg_szPluginIniFilePath);
                sprintf(dll_to_load, "plugins\\%s", plugin_dll);

                PLUGIN_INST=LoadLibraryA(dll_to_load);
                if(!PLUGIN_INST)
                    MessageBoxA(hwndDlg, "There was an error loading the plugin", plugin_dll, MB_ICONERROR);
                else
                {
                    PluginFunction=(PLUGFUNC)GetProcAddress(PLUGIN_INST, "PluginFunction");
                    if(!PluginFunction)
                        MessageBoxA(hwndDlg, "The export \"PluginFunction\" could not be found, please contact the plugin supplier", plugin_dll, MB_ICONERROR);
                    else
                    {
                        if(!g_TargetData.ImageBase)
                            g_TargetData.ImageBase=0x400000;

                        ShowWindow(GetParent(hwndDlg), 0);
                        PluginFunction(PLUGIN_INST, hwndDlg, g_TargetData.SecurityAddrRegister, sg_szAKTDirectory, g_TargetData.ImageBase);
                        ShowWindow(GetParent(hwndDlg), 1);
                        FreeLibrary(PLUGIN_INST);
                        SetForegroundWindow(hwndDlg);

                    }
                }
            }
            else
            {
                HMENU myMenu=0;
                myMenu=CreatePopupMenu();
                AppendMenuA(myMenu, MF_STRING|MF_GRAYED, 1, "No plugins found :(");
                POINT cursorPos;
                GetCursorPos(&cursorPos);
                SetForegroundWindow(hwndDlg);
                TrackPopupMenu(myMenu, TPM_RETURNCMD|TPM_NONOTIFY, cursorPos.x, cursorPos.y, 0, hwndDlg, 0);
            }
        }
        return TRUE;

        case IDC_EDT_OEP:
        {
            char temp_oep[10]="";
            GetDlgItemTextA(hwndDlg, IDC_EDT_OEP, temp_oep, 10);
            sscanf(temp_oep, "%X", &(g_TargetData.OEP));
        }
        return TRUE;
        }
    }
    return TRUE;
    }
    return FALSE;
}
示例#27
0
void init_gettext(const char *path, const std::string &configured_language, int argc, char** argv) {
#else
void init_gettext(const char *path, const std::string &configured_language) {
#endif
#if USE_GETTEXT
	/** first try to set user override environment **/
	if (configured_language.length() != 0) {
#ifndef _WIN32
		/* add user specified locale to environment */
		setenv("LANGUAGE", configured_language.c_str(), 1);

		/* reload locale with changed environment */
		setlocale(LC_ALL, "");
#elif defined(_MSC_VER)
		std::string current_language_var("");
		if (getenv("LANGUAGE") != 0) {
			current_language_var = std::string(getenv("LANGUAGE"));
		}

		char *lang_str = (char*)calloc(10 + configured_language.length(), sizeof(char));
		strcat(lang_str, "LANGUAGE=");
		strcat(lang_str, configured_language.c_str());
		putenv(lang_str);

		SetEnvironmentVariableA("LANGUAGE",configured_language.c_str());

#ifndef SERVER
		//very very dirty workaround to force gettext to see the right environment
		if (current_language_var != configured_language) {
			STARTUPINFO startupinfo;
			PROCESS_INFORMATION processinfo;
			memset(&startupinfo, 0, sizeof(startupinfo));
			memset(&processinfo, 0, sizeof(processinfo));
			errorstream << "MSVC localization workaround active restating minetest in new environment!" << std::endl;

			std::string parameters = "";

			for (unsigned int i=1;i < argc; i++) {
				if (parameters != "") {
					parameters += " ";
				}
				parameters += argv[i];
			}

			const char* ptr_parameters = 0;

			if (parameters != "") {
				ptr_parameters = parameters.c_str();
			}
			
			/** users may start by short name in commandline without extention **/
			std::string appname = argv[0];
			if (appname.substr(appname.length() - 4) != ".exe") {
				appname += ".exe";
			}

			if (!CreateProcess(appname.c_str(),
					(char*) ptr_parameters,
					NULL,
					NULL,
					false,
					DETACHED_PROCESS | CREATE_UNICODE_ENVIRONMENT,
					NULL,
					NULL,
					&startupinfo,
					&processinfo)) {
				char buffer[1024];		
				FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
					NULL,
					GetLastError(),
					MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),
					buffer,
					sizeof(buffer)-1,
					NULL);
				errorstream << "*******************************************************" << std::endl;
				errorstream << "CMD: " << appname << std::endl;
				errorstream << "Failed to restart with current locale: " << std::endl;
				errorstream << buffer;
				errorstream << "Expect language to be broken!" << std::endl;
				errorstream << "*******************************************************" << std::endl;
			}
			else {
				exit(0);
			}
#else
			errorstream << "*******************************************************" << std::endl;
			errorstream << "Can't apply locale workaround for server!" << std::endl;
			errorstream << "Expect language to be broken!" << std::endl;
			errorstream << "*******************************************************" << std::endl;

#endif
		}

		setlocale(LC_ALL,configured_language.c_str());
#else // Mingw
		char *lang_str = (char*)calloc(10 + configured_language.length(), sizeof(char));
		strcat(lang_str, "LANGUAGE=");
		strcat(lang_str, configured_language.c_str());
		putenv(lang_str);

		setlocale(LC_ALL, "");
#endif // ifndef _WIN32
	}
	else {
		 /* set current system default locale */
		setlocale(LC_ALL, "");
	}

#if defined(_WIN32)
	if (getenv("LANGUAGE") != 0) {
		setlocale(LC_ALL, getenv("LANGUAGE"));
	}
#ifdef _MSC_VER
	else if (getenv("LANG") != 0) {
		setlocale(LC_ALL, getenv("LANG"));
	}
#endif
#endif

	static std::string name = lowercase(PROJECT_NAME);
	bindtextdomain(name.c_str(), path);
	textdomain(name.c_str());

#if defined(_WIN32)
	// Set character encoding for Win32
	char *tdomain = textdomain( (char *) NULL );
	if( tdomain == NULL )
	{
		errorstream << "Warning: domainname parameter is the null pointer" <<
				", default domain is not set" << std::endl;
		tdomain = (char *) "messages";
	}
	/* char *codeset = */bind_textdomain_codeset( tdomain, "UTF-8" );
	//errorstream << "Gettext debug: domainname = " << tdomain << "; codeset = "<< codeset << std::endl;
#endif // defined(_WIN32)

#else
	/* set current system default locale */
	setlocale(LC_ALL, "");
#endif // if USE_GETTEXT

	/* no matter what locale is used we need number format to be "C" */
	/* to ensure formspec parameters are evaluated correct!          */

	setlocale(LC_NUMERIC, "C");
	infostream << "Message locale is now set to: "
			<< setlocale(LC_ALL, 0) << std::endl;
}
示例#28
0
void set_language(const std::string& slocale, const std::vector<std::string>* alternates)
{

	//Code copied from language.cpp::wesnoth_setlocale()
	std::string locale = slocale;
	// FIXME: ideally we should check LANGUAGE and on first invocation
	// use that value, so someone with es would get the game in Spanish
	// instead of en_US the first time round
	// LANGUAGE overrides other settings, so for now just get rid of it
	
#ifdef _WIN32
	(void)alternates;
	std::string win_locale(locale, 0, 2);
	#include "language_win32.ii"
	SetEnvironmentVariableA("LANG", win_locale.c_str());
	std::string env = "LANGUAGE=" + locale;
	_putenv(env.c_str());
	return;
#else
	// FIXME: add configure check for unsetenv
	unsetenv ("LANGUAGE"); // void so no return value to check
#ifdef __APPLE__
	if (setenv("LANG", locale.c_str(), 1) == -1) {
		ERR_G << "setenv LANG failed: " << strerror(errno);
	}
#endif

	char *res = NULL;
	std::vector<std::string>::const_iterator i;
	if (alternates) i = alternates->begin();

	for (;;)
	{
		std::string lang = locale, extra;
		std::string::size_type pos = locale.find('@');
		if (pos != std::string::npos) {
			lang.erase(pos);
			extra = locale.substr(pos);
		}

		/*
		 * The "" is the last item to work-around a problem in glibc picking
		 * the non utf8 locale instead an utf8 version if available.
		 */
		char const *encoding[] = { ".utf-8", ".UTF-8", "" };
		for (int j = 0; j != 3; ++j)
		{
			locale = lang + encoding[j] + extra;
			res = std::setlocale(LC_MESSAGES, locale.c_str());
			if (res) {
				LOG_G << "Set locale to '" << locale << "' result: '" << res << "'.\n";
				return;
			}
		}

		if (!alternates || i == alternates->end()) break;
		locale = *i;
		++i;
	}
	WRN_G << "setlocale() failed for '" << slocale << "'." << std::endl;
#endif //win32
}
示例#29
0
CNetGame::CNetGame ( )
{
	fRestartWaitTime = 0.0f;
	this->allowAdminTeleport = FALSE;
	this->allowInteriorWeapons = FALSE;
	this->worldTime = 12;
	this->weather	= 1;
	this->enableBonusStuntForAll = true;
	this->gravity	= 0.008f;
	this->deathDropAmount = 0;
	this->enableZoneName = false;
	
	this->playerPool = NULL;
	this->vehiclePool = NULL;
	this->gamemodeManager = NULL;
	this->pickupPool = NULL;
	this->objectPool = NULL;
	this->menuPool = NULL;
	this->textDrawPool = NULL;
	this->disableNameTagLineOfSight = true;
	this->gangZonePool = NULL;
	this->text3DLabelsPool = NULL;
	this->bLanMode = FALSE;
	this->byteMod = 0x01;

	this->blimitGlobalChatRadius = false;
	this->dlimitGlobalChatRadius = 10000.0f;
	this->bLimitPlayerMarkerRadius = FALSE;
	this->dlimitPlayerMarkerRadius = 10000.0f;
	this->nameTagDrawDistance = 70.0f;
	this->disableInteriorEnterExit = false;

	this->currentGameModeIndex = 0;
	this->currentGameModeRepeat = 0;
	this->isFirstGameModeLoad = FALSE;
	this->scriptTimerManager = new CScriptTimers;
	this->scriptHttpManager = new CScriptHttp;

	#ifndef WIN32
		this->elapsedTime = 0.0;
	#endif

	if(__Console->GetIntVar("maxplayers") > MAX_PLAYERS)
		__Console->SetIntVar("maxplayers", MAX_PLAYERS);

	char* szBindAddress = __Console->GetStringVar("bind");
	if (szBindAddress && szBindAddress[0] == 0)
		szBindAddress = NULL;

	uint16_t Port = __Console->GetIntVar("port");
	uint16_t MaxPlayers = __Console->GetIntVar("maxplayers");
	BOOL useLanMode = __Console->GetBoolVar("lanmode");

	this->rakServerInterface = RakNetworkFactory::GetRakServerInterface();
	
	//NetGameStartTime = RakNet::GetTime();

	if (!this->rakServerInterface->Start(MaxPlayers, 0, iServerSleepTimer, Port, szBindAddress))
	{
		if (szBindAddress)
			logprintf("Unable to start server on %s:%d. Port in use?",szBindAddress, Port);
		else
			logprintf("Unable to start server on port: %d. Port in use?", Port);
		return;
	}
	
	LoadBanList();

	if(!this->setNextGamemodeFile(NULL)) 
	{
		logprintf("I couldn't load any gamemode scripts. Please verify your server.cfg");
		logprintf("It needs a gamemode0 line at the very least.");
		fcloseall();
		exit(1);
	}
		
	this->rakServerInterface->StartOccasionalPing();

	char* szPass = __Console->GetStringVar("password");
	if ((szPass) && (szPass[0] != 0)) { 
		this->rakServerInterface->SetPassword(szPass);
	}

	RegisterRPCs(this->rakServerInterface);

	char szTime[256];
	sprintf(szTime, "%02d:%02d", this->worldTime, 0);
	__Console->AddStringVar("worldtime", CONSOLE_VARFLAG_RULE, szTime);
	
	if(useLanMode)
		this->bLanMode = true;

	char szScriptFiles[512];
	int len;

	#ifdef WIN32
		GetCurrentDirectoryA(sizeof(szScriptFiles), szScriptFiles);
		len = strlen(szScriptFiles);
		if (szScriptFiles[len-1] != '\\')
		{
			szScriptFiles[len] = '\\';
			szScriptFiles[len+1] = '\0';
		}
		strcat(szScriptFiles, "scriptfiles\\");
		SetEnvironmentVariableA("AMXFILE", szScriptFiles);
	#else
		getcwd(szScriptFiles, sizeof(szScriptFiles));
		len = strlen(szScriptFiles);
		if (szScriptFiles[len-1] != '/')
		{
			szScriptFiles[len] = '/';
			szScriptFiles[len+1] = '\0';
		}
		strcat(szScriptFiles, "scriptfiles/");
		setenv("AMXFILE", szScriptFiles, 1);
	#endif

	this->filterscriptsManager = new CFilterscriptsManager();

	if (szBindAddress) 
	{
		printf( "\nStarted server on %s:%d, with maxplayers: %d lanmode is %s.\n\n",
			szBindAddress, Port, MaxPlayers, useLanMode?"ON":"OFF" );
	}
	else
	{
		printf( "\nStarted server on port: %d, with maxplayers: %d lanmode is %s.\n\n",
			Port, MaxPlayers, useLanMode?"ON":"OFF" );
	}

	this->gameState = 0;
}
示例#30
0
static void test_create_env(void)
{
    BOOL r;
    HANDLE htok;
    WCHAR * env[4];
    char * st;
    int i, j;

    static const struct profile_item common_vars[] = {
        { "ComSpec", { 1, 1, 0, 0 } },
        { "COMPUTERNAME", { 1, 1, 1, 1 } },
        { "NUMBER_OF_PROCESSORS", { 1, 1, 0, 0 } },
        { "OS", { 1, 1, 0, 0 } },
        { "PROCESSOR_ARCHITECTURE", { 1, 1, 0, 0 } },
        { "PROCESSOR_IDENTIFIER", { 1, 1, 0, 0 } },
        { "PROCESSOR_LEVEL", { 1, 1, 0, 0 } },
        { "PROCESSOR_REVISION", { 1, 1, 0, 0 } },
        { "SystemDrive", { 1, 1, 0, 0 } },
        { "SystemRoot", { 1, 1, 0, 0 } },
        { "windir", { 1, 1, 0, 0 } }
    };
    static const struct profile_item common_post_nt4_vars[] = {
        { "ALLUSERSPROFILE", { 1, 1, 0, 0 } },
        { "CommonProgramFiles", { 1, 1, 1, 1 } },
        { "ProgramFiles", { 1, 1, 0, 0 } }
    };
    static const struct profile_item htok_vars[] = {
        { "PATH", { 1, 1, 0, 0 } },
        { "TEMP", { 1, 1, 0, 0 } },
        { "TMP", { 1, 1, 0, 0 } },
        { "USERPROFILE", { 1, 1, 0, 0 } }
    };

    r = SetEnvironmentVariableA("WINE_XYZZY", "ZZYZX");
    expect(TRUE, r);

    if (0)
    {
        /* Crashes on NT4 */
        r = CreateEnvironmentBlock(NULL, NULL, FALSE);
        expect(FALSE, r);
    }

    r = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_DUPLICATE, &htok);
    expect(TRUE, r);

    if (0)
    {
        /* Crashes on NT4 */
        r = CreateEnvironmentBlock(NULL, htok, FALSE);
        expect(FALSE, r);
    }

    r = CreateEnvironmentBlock((LPVOID) &env[0], NULL, FALSE);
    expect(TRUE, r);

    r = CreateEnvironmentBlock((LPVOID) &env[1], htok, FALSE);
    expect(TRUE, r);

    r = CreateEnvironmentBlock((LPVOID) &env[2], NULL, TRUE);
    expect(TRUE, r);

    r = CreateEnvironmentBlock((LPVOID) &env[3], htok, TRUE);
    expect(TRUE, r);

    /* Test for common environment variables (NT4 and higher) */
    for (i = 0; i < sizeof(common_vars)/sizeof(common_vars[0]); i++)
    {
        for (j = 0; j < 4; j++)
        {
            r = get_env(env[j], common_vars[i].name, &st);
            if (common_vars[i].todo[j])
                todo_wine expect_env(TRUE, r, common_vars[i].name);
            else
                expect_env(TRUE, r, common_vars[i].name);
        }
    }

    /* Test for common environment variables (post NT4) */
    if (!GetEnvironmentVariableA("ALLUSERSPROFILE", NULL, 0))
    {
        win_skip("Some environment variables are not present on NT4\n");
    }
    else
    {
        for (i = 0; i < sizeof(common_post_nt4_vars)/sizeof(common_post_nt4_vars[0]); i++)
        {
            for (j = 0; j < 4; j++)
            {
                r = get_env(env[j], common_post_nt4_vars[i].name, &st);
                if (common_post_nt4_vars[i].todo[j])
                    todo_wine expect_env(TRUE, r, common_post_nt4_vars[i].name);
                else
                    expect_env(TRUE, r, common_post_nt4_vars[i].name);
            }
        }
    }

    /* Test for environment variables with values that depends on htok */
    for (i = 0; i < sizeof(htok_vars)/sizeof(htok_vars[0]); i++)
    {
        for (j = 0; j < 4; j++)
        {
            r = get_env(env[j], htok_vars[i].name, &st);
            if (htok_vars[i].todo[j])
                todo_wine expect_env(TRUE, r, htok_vars[i].name);
            else
                expect_env(TRUE, r, htok_vars[i].name);
        }
    }

    r = get_env(env[0], "WINE_XYZZY", &st);
    expect(FALSE, r);
    r = get_env(env[1], "WINE_XYZZY", &st);
    expect(FALSE, r);
    r = get_env(env[2], "WINE_XYZZY", &st);
    expect(TRUE, r);
    r = get_env(env[3], "WINE_XYZZY", &st);
    expect(TRUE, r);
}