ImeModule::ImeModule(HMODULE module):
	Ime::ImeModule(module, g_textServiceClsid),
	config_(windowsVersion()) {
	
	config_.load(); // load configurations

	// override default location of chewing data directories
	std::wstring env;
	wchar_t path[MAX_PATH];

	HRESULT result;

	// get user profile directory
	if(::GetEnvironmentVariableW(L"USERPROFILE", path, MAX_PATH)) {
		userDir_ = path;
		userDir_ += L"\\ChewingTextService";
		// create the user directory if not exists
		// NOTE: this call will fail in Windows 8 store apps
		// We need a way to create the dir in desktop mode and
		// set proper ACL, so later we can access it inside apps.
		DWORD attributes = ::GetFileAttributesW(userDir_.c_str());
		if(attributes == INVALID_FILE_ATTRIBUTES) {
			// create the directory if it does not exist
			if(::GetLastError() == ERROR_FILE_NOT_FOUND) {
				::CreateDirectoryW(userDir_.c_str(), NULL);
				attributes = ::GetFileAttributesW(userDir_.c_str());
			}
		}

		// make the directory hidden
		if(attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_HIDDEN) == 0)
			::SetFileAttributesW(userDir_.c_str(), attributes|FILE_ATTRIBUTE_HIDDEN);

		env = L"CHEWING_USER_PATH=";
		env += userDir_;
		_wputenv(env.c_str());
	}

	// get the program data directory
	// try C:\program files (x86) first
	result = ::SHGetFolderPathW(NULL, CSIDL_PROGRAM_FILESX86, NULL, 0, path);
	if(result != S_OK) // failed, fall back to C:\program files
		result = ::SHGetFolderPathW(NULL, CSIDL_PROGRAM_FILES, NULL, 0, path);
	if(result == S_OK) { // program files folder is found
		programDir_ = path;
		programDir_ += L"\\ChewingTextService";
		env = L"CHEWING_PATH=";
		// prepend user dir path to program path, so user-specific files, if they exist,
		// can take precedence over built-in ones. (for ex: symbols.dat)
		env += userDir_;
		env += ';'; // add ; to separate two dir paths
		// add program dir after user profile dir
		env += programDir_;
		env += L"\\Dictionary";
		_wputenv(env.c_str());
	}

}
Esempio n. 2
0
BOOL apxAddToPathW(APXHANDLE hPool, LPCWSTR szAdd)
{
    LPWSTR wsAdd;
    DWORD  rc;
    DWORD  al;
    
    rc = GetEnvironmentVariableW(L"PATH", NULL, 0);
    if (rc == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)
        return FALSE;
    al = lstrlenW(szAdd) + 6;
    if (!(wsAdd = apxPoolAlloc(hPool, (al + rc + 1) * sizeof(WCHAR))))
        return FALSE;
    lstrcpyW(wsAdd, L"PATH=");        
    lstrcatW(wsAdd, szAdd);        
    lstrcatW(wsAdd, L";");        
    if (!GetEnvironmentVariableW(L"PATH", wsAdd + al, rc - al)) {
        apxLogWrite(APXLOG_MARK_SYSERR);
        apxFree(wsAdd);
        return FALSE;
    }
    SetEnvironmentVariableW(L"PATH", wsAdd + 5);
    _wputenv(wsAdd);
    apxFree(wsAdd);
    return TRUE;
}
	Win32UIBinding::Win32UIBinding(Module *uiModule, Host *host) :
		UIBinding(host),
		menu(0),
		contextMenu(0),
		iconPath("")
	{
		// Initialize common controls so that our Win32 native
		// components look swanky.
		INITCOMMONCONTROLSEX InitCtrlEx;
		InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
		InitCtrlEx.dwICC = 0x00004000; //ICC_STANDARD_CLASSES;
		InitCommonControlsEx(&InitCtrlEx);
		
		// Set the cert path for Curl so that HTTPS works properly.
		// We are using _puetenv here since WebKit uses getenv internally 
		// which is incompatible with the  Win32 envvar API.
		std::wstring pemPath = ::UTF8ToWide(FileUtils::Join(
			uiModule->GetPath().c_str(), "cacert.pem", NULL));
		std::wstring var = L"CURL_CA_BUNDLE_PATH=" + pemPath;
		_wputenv(var.c_str());

		// Hook app:// and ti:// URL support to WebKit
		setNormalizeURLCallback(NormalizeURLCallback);
		setURLToFileURLCallback(URLToFileURLCallback);
		setCanPreprocessCallback(CanPreprocessURLCallback);
		setPreprocessCallback(PreprocessURLCallback);
		setProxyCallback(ProxyForURLCallback);
	}
Esempio n. 4
0
UIWin::UIWin()
    : menu(0)
    , contextMenu(0)
    , iconPath("")
{
    // Initialize common controls so that our Win32 native
    // components look swanky.
    INITCOMMONCONTROLSEX InitCtrlEx;
    InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
    InitCtrlEx.dwICC = 0x00004000; //ICC_STANDARD_CLASSES;
    InitCommonControlsEx(&InitCtrlEx);
    
    // Set the cert path for Curl so that HTTPS works properly.
    // We are using _puetenv here since WebKit uses getenv internally 
    // which is incompatible with the Win32 envvar API.
    std::wstring pemPath = ::UTF8ToWide(FileUtils::Join(
        Host::GetInstance()->GetApplication()->runtime->path.c_str(),
        "rootcert.pem", 0));
    std::wstring var = L"CURL_CA_BUNDLE_PATH=" + pemPath;
    _wputenv(var.c_str());

    // Hook app:// and ti:// URL support to WebKit
    setNormalizeURLCallback(NormalizeURLCallback);
    setURLToFileURLCallback(URLToFileURLCallback);
    //setCanPreprocessCallback(CanPreprocessURLCallback);
    //setPreprocessCallback(PreprocessURLCallback);
    setProxyCallback(ProxyForURLCallback);

    std::string cookieJarFilename(FileUtils::Join(
        Host::GetInstance()->GetApplication()->GetDataPath().c_str(),
        "cookies.dat", 0));
    setCookieJarFilename(cookieJarFilename.c_str());
}
Esempio n. 5
0
RTDECL(int) RTEnvUnsetUtf8(const char *pszVar)
{
    AssertReturn(strchr(pszVar, '=') == NULL, VERR_ENV_INVALID_VAR_NAME);

    size_t cwcVar;
    int rc = RTStrCalcUtf16LenEx(pszVar, RTSTR_MAX, &cwcVar);
    if (RT_SUCCESS(rc))
    {
        PRTUTF16 pwszTmp = (PRTUTF16)RTMemTmpAlloc((cwcVar + 1 + 1) * sizeof(RTUTF16));
        if (pwszTmp)
        {
            rc = RTStrToUtf16Ex(pszVar, RTSTR_MAX, &pwszTmp, cwcVar + 1, NULL);
            if (RT_SUCCESS(rc))
            {
                pwszTmp[cwcVar] = '=';
                pwszTmp[cwcVar + 1] = '\0';
                if (!_wputenv(pwszTmp))
                    rc = VINF_SUCCESS;
                else
                    rc = RTErrConvertFromErrno(errno);
            }
            RTMemTmpFree(pwszTmp);
        }
    }
    return rc;
}
Esempio n. 6
0
SEXP attribute_hidden do_unsetenv(SEXP call, SEXP op, SEXP args, SEXP env)
{
    int i, n;
    SEXP ans, vars;

    checkArity(op, args);

    if (!isString(vars = CAR(args)))
	error(_("wrong type for argument"));
    n = LENGTH(vars);

#if defined(HAVE_UNSETENV) || defined(HAVE_PUTENV_UNSET) || defined(HAVE_PUTENV_UNSET2)
#ifdef HAVE_UNSETENV
    for (i = 0; i < n; i++) unsetenv(translateChar(STRING_ELT(vars, i)));
#elif defined(HAVE_PUTENV_UNSET)
    for (i = 0; i < n; i++) {
	char buf[1000];
	snprintf(buf, 1000, "%s",  translateChar(STRING_ELT(vars, i)));
	putenv(buf);
    }
#elif defined(HAVE_PUTENV_UNSET2)
# ifdef Win32
    for (i = 0; i < n; i++) {
	const wchar_t *w = wtransChar(STRING_ELT(vars, i));
	wchar_t buf[2*wcslen(w)];
	wcscpy(buf, w);
	wcscat(buf, L"=");
	_wputenv(buf);
    }
# else
    for (i = 0; i < n; i++) {
	char buf[1000];
	snprintf(buf, 1000, "%s=", translateChar(STRING_ELT(vars, i)));
	putenv(buf);
    }
# endif
#endif

#elif defined(HAVE_PUTENV) || defined(HAVE_SETENV)
    warning(_("this system cannot unset environment variables: setting to \"\""));
    n = LENGTH(vars);
    for (i = 0; i < n; i++) {
#ifdef HAVE_SETENV
	setenv(translateChar(STRING_ELT(vars, i)), "", 1);
#else
	Rputenv(translateChar(STRING_ELT(vars, i)), "");
#endif
    }

#else
    warning(_("'Sys.unsetenv' is not available on this system"));
#endif

    PROTECT(ans = allocVector(LGLSXP, n));
    for (i = 0; i < n; i++)
	LOGICAL(ans)[i] = !getenv(translateChar(STRING_ELT(vars, i)));
    UNPROTECT(1);
    return ans;
}
Esempio n. 7
0
static void winpidgin_set_locale() {
	const wchar_t *locale;
	wchar_t envstr[25];

	locale = winpidgin_get_locale();

	_snwprintf(envstr, sizeof(envstr) / sizeof(wchar_t), L"LANG=%s", locale);
	wprintf(L"Setting locale: %s\n", envstr);
	_wputenv(envstr);
}
Esempio n. 8
0
static int Rwputenv(const wchar_t *nm, const wchar_t *val)
{
    wchar_t *buf;
    buf = (wchar_t *) malloc((wcslen(nm) + wcslen(val) + 2) * sizeof(wchar_t));
    if(!buf) return 1;
    /* previously wsprintfW, which had a limit of 1024 chars */
    wcscpy(buf, nm); wcscat(buf, L"="); wcscat(buf, val);
    if(_wputenv(buf)) return 1;
    /* no free here: storage remains in use */
    return 0;
}
Esempio n. 9
0
static void portable_mode_dll_prep(const wchar_t *pidgin_dir) {
	/* need to be able to fit MAX_PATH + "PURPLEHOME=" in path2 */
	wchar_t path[MAX_PATH + 1];
	wchar_t path2[MAX_PATH + 12];
	const wchar_t *prev = NULL;

	/* We assume that GTK+ is installed under \\path\to\Pidgin\..\GTK
	 * First we find \\path\to
	 */
	if (*pidgin_dir)
		/* pidgin_dir points to \\path\to\Pidgin */
		prev = wcsrchr(pidgin_dir, L'\\');

	if (prev) {
		int cnt = (prev - pidgin_dir);
		wcsncpy(path, pidgin_dir, cnt);
		path[cnt] = L'\0';
	} else {
		printf("Unable to determine current executable path. \n"
			"This will prevent the settings dir from being set.\n"
			"Assuming GTK+ is in the PATH.\n");
		return;
	}

	/* Set $HOME so that the GTK+ settings get stored in the right place */
	_snwprintf(path2, sizeof(path2) / sizeof(wchar_t), L"HOME=%s", path);
	_wputenv(path2);

	/* Set up the settings dir base to be \\path\to
	 * The actual settings dir will be \\path\to\.purple */
	_snwprintf(path2, sizeof(path2) / sizeof(wchar_t), L"PURPLEHOME=%s", path);
	wprintf(L"Setting settings dir: %s\n", path2);
	_wputenv(path2);

	if (!dll_prep(pidgin_dir)) {
		/* set the GTK+ path to be \\path\to\GTK\bin */
		wcscat(path, L"\\GTK\\bin");
		common_dll_prep(path);
	}
}
Esempio n. 10
0
*/	int OS_Set_Env(REBCHR *expr, int mode)
/*
**		Set a value from the environment.
**		Returns 0 for success and <0 for errors.
**
***********************************************************************/
{
#ifdef UNICODE
	return _wputenv(expr);
#else
	return putenv(expr);
#endif
}
Esempio n. 11
0
RTDECL(int) RTEnvPutUtf8(const char *pszVarEqualValue)
{
    PRTUTF16 pwszVarEqualValue;
    int rc = RTStrToUtf16(pszVarEqualValue, &pwszVarEqualValue);
    if (RT_SUCCESS(rc))
    {
        if (!_wputenv(pwszVarEqualValue))
            rc = VINF_SUCCESS;
        else
            rc = RTErrConvertFromErrno(errno);
        RTUtf16Free(pwszVarEqualValue);
    }
    return rc;
}
TEST(sysdeps_win32, adb_getenv) {
    // Insert all test env vars before first call to adb_getenv() which will
    // read the env var block only once.
    ASSERT_EQ(0, _putenv("SYSDEPS_WIN32_TEST_UPPERCASE=1"));
    ASSERT_EQ(0, _putenv("sysdeps_win32_test_lowercase=2"));
    ASSERT_EQ(0, _putenv("Sysdeps_Win32_Test_MixedCase=3"));

    // UTF-16 value
    ASSERT_EQ(0, _wputenv(L"SYSDEPS_WIN32_TEST_UNICODE=\u00a1\u0048\u006f\u006c"
                          L"\u0061\u0021\u03b1\u03b2\u03b3\u0061\u006d\u0062"
                          L"\u0075\u006c\u014d\u043f\u0440\u0438\u0432\u0435"
                          L"\u0442"));

    // Search for non-existant env vars.
    EXPECT_STREQ(nullptr, adb_getenv("SYSDEPS_WIN32_TEST_NONEXISTANT"));

    // Search for existing env vars.

    // There is no test for an env var with a value of a zero-length string
    // because _putenv() does not support inserting such an env var.

    // Search for env var that is uppercase.
    EXPECT_STREQ("1", adb_getenv("SYSDEPS_WIN32_TEST_UPPERCASE"));
    EXPECT_STREQ("1", adb_getenv("sysdeps_win32_test_uppercase"));
    EXPECT_STREQ("1", adb_getenv("Sysdeps_Win32_Test_Uppercase"));

    // Search for env var that is lowercase.
    EXPECT_STREQ("2", adb_getenv("SYSDEPS_WIN32_TEST_LOWERCASE"));
    EXPECT_STREQ("2", adb_getenv("sysdeps_win32_test_lowercase"));
    EXPECT_STREQ("2", adb_getenv("Sysdeps_Win32_Test_Lowercase"));

    // Search for env var that is mixed-case.
    EXPECT_STREQ("3", adb_getenv("SYSDEPS_WIN32_TEST_MIXEDCASE"));
    EXPECT_STREQ("3", adb_getenv("sysdeps_win32_test_mixedcase"));
    EXPECT_STREQ("3", adb_getenv("Sysdeps_Win32_Test_MixedCase"));

    // Check that UTF-16 was converted to UTF-8.
    EXPECT_STREQ("\xc2\xa1\x48\x6f\x6c\x61\x21\xce\xb1\xce\xb2\xce\xb3\x61\x6d"
                 "\x62\x75\x6c\xc5\x8d\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5"
                 "\xd1\x82",
                 adb_getenv("SYSDEPS_WIN32_TEST_UNICODE"));

    // Check an env var that should always be set.
    const char* path_val = adb_getenv("PATH");
    EXPECT_NE(nullptr, path_val);
    if (path_val != nullptr) {
        EXPECT_GT(strlen(path_val), 0);
    }
}
Esempio n. 13
0
int main()
{
    LPWSTR *szArglist;
    int nArgs;
    wchar_t wszPath[10240];
    wchar_t wszCmd[10240];
    wchar_t *p;
    char* szCmd;

    GetModuleFileNameW(NULL, wszPath, sizeof(wszPath));
    p = wcsrchr(wszPath, L'\\');
    if (p == NULL) {
            printf("Get module file name error!\n");
            return -1;
    }
    *p = 0;

    szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);

    swprintf(wszCmd, L"PATH=%s\\DLLs;%%PATH%%", wszPath);
    _wputenv(wszCmd);

    Py_NoSiteFlag = 1;
    Py_SetPythonHome(wszPath);
    swprintf(wszCmd, L"%s\\Lib", wszPath);
    Py_SetPath(wszCmd);
    Py_Initialize();
    PySys_SetArgv(nArgs-1, szArglist+1);

    swprintf(wszCmd,
            L"import sys\n"
            L"cur = r'%s'\n"
            L"join = lambda *args: '\\\\'.join(args)\n"
            L"sys.path = [join(cur, f) for f in ['', 'Lib', 'Lib/libstdpy.zip', 'site-packages', 'DLLs']]\n"
            L"import os; join = os.path.join\n"
            L"sys.path += [join(cur, 'Lib', f) for f in os.listdir(join(cur, 'Lib')) if f.endswith('.zip') and f != 'libstdpy.zip']\n"
            L"sys.path.insert(1, join(cur, 'src.zip'))\n"
            L"m = r'%s'\n"
            L"sys.path.insert(0, os.path.split(m)[0])\n"
            L"import imp; imp.load_source('__main__', m)\n",
            wszPath, *(szArglist+1));
    /* wprintf(wszCmd); */
    szCmd = to_utf8(wszCmd);
    PyRun_SimpleString(szCmd);
    free(szCmd);
    LocalFree(szArglist);
    return 0;
}
Esempio n. 14
0
static int setenv16_with_putenv16(const wchar *name, const wchar *value)
{
    if(NULL != VMPI_strchr16(name, L'='))
    {
        errno = EINVAL;
        return -1;
    }
    else
    {
        size_t  nameLen     =   VMPI_strlen16(name);
        size_t  valueLen    =   VMPI_strlen16(value);
        size_t  required    =   1 + nameLen + 1 + valueLen;
        wchar   buffer_[101];
        wchar   *buffer     =   (ARRAY_SIZE(buffer_) < required)
                                    ? (wchar*)malloc(required * sizeof(wchar))
                                    : &buffer_[0];

        if(NULL == buffer)
        {
            errno = ENOMEM;
            return -1;
        }
        else
        {
            int r;
            (void)VMPI_strncpy16(&buffer[0], name, nameLen);
            buffer[nameLen] = L'=';
            buffer[nameLen + 1] = '\0';
            (void)VMPI_strncpy16(&buffer[nameLen + 1], value, valueLen);
            buffer[nameLen + 1 + valueLen] = '\0';

            r = _wputenv(&buffer[0]);

            if(buffer != &buffer_[0])
            {
                VMPI_free(buffer);
            }

            return r;
        }
    }
}
Esempio n. 15
0
int look_paths()
{
	HKEY hKey;
	DWORD bufLen = 1024 * sizeof(wchar_t);
	wchar_t buf[1100];
	int i;

	if (RegOpenKeyW(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\xcircuit-dev-win32.exe", &hKey))
		return -1;
	if (RegQueryValueExW(
				hKey,
				L"WishExe",
				NULL,
				NULL,
				(LPBYTE)wish_exe,
				&bufLen)) {
		RegCloseKey(hKey);
		return -1;
	}
	bufLen = 1024 * sizeof(wchar_t);
	if (RegQueryValueExW(
				hKey,
				L"LibPath",
				NULL,
				NULL,
				(LPBYTE)lib_path,
				&bufLen)) {
		RegCloseKey(hKey);
		return -1;
	}
	for (i=0; lib_path[i] != 0; i++)
		if (lib_path[i] == L'\\')
			lib_path[i] = L'/';
	_snwprintf(buf, 1100, L"XCIRCUIT_LIB_DIR=%ws", lib_path);
	_wputenv(buf);
	RegCloseKey(hKey);
	return 0;
}
	/*static*/
	void Win32UIBinding::SetProxyForURL(std::string& url)
	{
		SharedPtr<Proxy> proxy(ProxyConfig::GetProxyForURL(url));
		if (!proxy.isNull())
		{
			std::stringstream proxyEnv;
			if (proxy->type == HTTP)
				proxyEnv << "http_proxy=http://";
			else if (proxy->type = HTTPS)
				proxyEnv << "HTTPS_PROXY=https://";

			if (!proxy->username.empty() || !proxy->password.empty())
				proxyEnv << proxy->username << ":" << proxy->password << "@";

			proxyEnv << proxy->host;

			if (proxy->port != 0)
				proxyEnv << ":" << proxy->port;

			std::wstring proxyEnvStr(::UTF8ToWide(proxyEnv.str()));
			_wputenv(proxyEnvStr.c_str());
		}
	}
Esempio n. 17
0
RTDECL(int) RTEnvSetUtf8(const char *pszVar, const char *pszValue)
{
    AssertReturn(strchr(pszVar, '=') == NULL, VERR_ENV_INVALID_VAR_NAME);

    size_t cwcVar;
    int rc = RTStrCalcUtf16LenEx(pszVar, RTSTR_MAX, &cwcVar);
    if (RT_SUCCESS(rc))
    {
        size_t cwcValue;
        rc = RTStrCalcUtf16LenEx(pszVar, RTSTR_MAX, &cwcValue);
        if (RT_SUCCESS(rc))
        {
            PRTUTF16 pwszTmp = (PRTUTF16)RTMemTmpAlloc((cwcVar + 1 + cwcValue + 1) * sizeof(RTUTF16));
            if (pwszTmp)
            {
                rc = RTStrToUtf16Ex(pszVar, RTSTR_MAX, &pwszTmp, cwcVar + 1, NULL);
                if (RT_SUCCESS(rc))
                {
                    PRTUTF16 pwszTmpValue = &pwszTmp[cwcVar];
                    *pwszTmpValue++ = '=';
                    rc = RTStrToUtf16Ex(pszValue, RTSTR_MAX, &pwszTmpValue, cwcValue + 1, NULL);
                    if (RT_SUCCESS(rc))
                    {
                        if (!_wputenv(pwszTmp))
                            rc = VINF_SUCCESS;
                        else
                            rc = RTErrConvertFromErrno(errno);
                    }
                }
                RTMemTmpFree(pwszTmp);
            }
            else
                rc = VERR_NO_TMP_MEMORY;
        }
    }
    return rc;
}
Esempio n. 18
0
void native_set_env(const NativeString& key, const NativeString& value) {
    MutexLock lock(env_mutex);
    auto key_value = key + L'=' + value;
    if (_wputenv(key_value.data()) == -1)
        throw std::system_error(errno, std::generic_category(), "_wputenv()");
}
/*
 * The main function implements a loader for applications which use UNO.
 *
 * <p>This code runs on the Windows platform only.</p>
 *
 * <p>The main function detects a UNO installation on the system and adds the
 * program directory of the UNO installation to the PATH environment variable.
 * After that, the application process is loaded and started, whereby the
 * new process inherits the environment of the calling process, including
 * the modified PATH environment variable. The application's executable name
 * must be the same as the name of this executable, prefixed by '_'.</p>
 *
 * <p>A UNO installation can be specified by the user by setting the UNO_PATH
 * environment variable to the program directory of the UNO installation.
 * If no installation is specified by the user, the default installation on
 * the system will be taken. The default installation is read from the
 * default value of the key "Software\LibreOffice\UNO\InstallPath" from the
 * root key HKEY_CURRENT_USER in the Windows Registry. If this key is missing,
 * the key is read from the root key HKEY_LOCAL_MACHINE.</p>
 */
int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    LPWSTR lpCmdLine, int nCmdShow )
{
    (void) hInstance; /* unused */
    (void) hPrevInstance; /* unused */
    (void) nCmdShow; /* unused */

    /* get the path of the UNO installation */
    wchar_t* path = getPath();

    if ( path != NULL )
    {
        wchar_t cmd[
            MY_LENGTH(L"\"") + MAX_PATH +
            MY_LENGTH(L"\\unoinfo.exe\" c++")];
            /* hopefully does not overflow */
        cmd[0] = L'"';
        wcscpy(cmd + 1, path);
        if (wcschr(cmd + 1, L'"') != NULL) {
            free(path);
            writeError("Error: bad characters in UNO installation path!\n");
            closeErrorFile();
            return 1;
        }
        size_t pathsize = wcslen(cmd);
        wcscpy(
            cmd + pathsize,
            &L"\\unoinfo.exe\" c++"[
                pathsize == 1 || cmd[pathsize - 1] != L'\\' ? 0 : 1]);
        SECURITY_ATTRIBUTES sec;
        sec.nLength = sizeof (SECURITY_ATTRIBUTES);
        sec.lpSecurityDescriptor = NULL;
        sec.bInheritHandle = TRUE;
        HANDLE stdoutRead;
        HANDLE stdoutWrite;
        HANDLE temp;
        if (CreatePipe(&temp, &stdoutWrite, &sec, 0) == 0 ||
            DuplicateHandle(
                GetCurrentProcess(), temp, GetCurrentProcess(), &stdoutRead, 0,
                FALSE, DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS) == 0)
        {
            free(path);
            writeError("Error: CreatePipe/DuplicateHandle failed!\n");
            closeErrorFile();
            return 1;
        }
        STARTUPINFOW startinfo;
        PROCESS_INFORMATION procinfo;
        memset(&startinfo, 0, sizeof(startinfo));
        startinfo.cb = sizeof(startinfo);
        startinfo.lpDesktop = L"";
        startinfo.dwFlags = STARTF_USESTDHANDLES;
        startinfo.hStdOutput = stdoutWrite;
        BOOL ret = CreateProcessW(
            NULL, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &startinfo, &procinfo);
        if (ret != FALSE) {
            // Release result of GetPath()
            free(path);

            char * buf = NULL;
            char * tmp;
            DWORD n = 1000;
            DWORD k = 0;
            DWORD exitcode;
            CloseHandle(stdoutWrite);
            CloseHandle(procinfo.hThread);
            for (;;) {
                DWORD m;
                tmp = realloc(buf, n);
                if (tmp == NULL) {
                    free(buf);
                    writeError(
                        "Error: out of memory reading unoinfo output!\n");
                    closeErrorFile();
                    return 1;
                }
                buf = tmp;
                if (!ReadFile(stdoutRead, buf + k, n - k, &m, NULL))
                {
                    DWORD err = GetLastError();
                    if (err == ERROR_HANDLE_EOF || err == ERROR_BROKEN_PIPE) {
                        break;
                    }
                    writeError("Error: cannot read unoinfo output!\n");
                    closeErrorFile();
                    return 1;
                }
                if (m == 0) {
                    break;
                }
                k += m;
                if (k >= n) {
                    if (n >= MAXDWORD / 2) {
                        writeError(
                            "Error: out of memory reading unoinfo output!\n");
                        closeErrorFile();
                        return 1;
                    }
                    n *= 2;
                }
            }
            if ((k & 1) == 1) {
                writeError("Error: bad unoinfo output!\n");
                closeErrorFile();
                return 1;
            }
            CloseHandle(stdoutRead);
            if (!GetExitCodeProcess(procinfo.hProcess, &exitcode) ||
                exitcode != 0)
            {
                writeError("Error: executing unoinfo failed!\n");
                closeErrorFile();
                return 1;
            }
            path = (wchar_t*)realloc(buf, k + sizeof(wchar_t));
            if (path == NULL)
            {
                free(buf);
                writeError(
                    "Error: out of memory zero-terminating unoinfo output!\n");
                closeErrorFile();
                return 1;
            }
            path[k / 2] = L'\0';
        } else {
            if (GetLastError() != ERROR_FILE_NOT_FOUND) {
                free(path);
                writeError("Error: calling unoinfo failed!\n");
                closeErrorFile();
                return 1;
            }
            CloseHandle(stdoutRead);
            CloseHandle(stdoutWrite);
        }

        /* get the value of the PATH environment variable */
        const wchar_t* ENVVARNAME = L"PATH";
        const wchar_t* PATHSEPARATOR = L";";
        wchar_t* value = _wgetenv( ENVVARNAME );

        /*
         * add the UNO installation path to the PATH environment variable;
         * note that this only affects the environment variable of the current
         * process, the command processor's environment is not changed
         */
        size_t size = wcslen( ENVVARNAME ) + wcslen( L"=" ) + wcslen( path ) + 1;
        if ( value != NULL )
            size += wcslen( PATHSEPARATOR ) + wcslen( value );
        wchar_t* envstr = (wchar_t*) malloc( size*sizeof(wchar_t) );
        wcscpy( envstr, ENVVARNAME );
        wcscat( envstr, L"=" );
        wcscat( envstr, path );
        if ( value != NULL )
        {
            wcscat( envstr, PATHSEPARATOR );
            wcscat( envstr, value );
        }
        _wputenv( envstr );
        free( envstr );
        free( path );
    }
    else
    {
        writeError( "Warning: no UNO installation found!\n" );
    }

    /* create the command line for the application process */
    wchar_t* cmdline = createCommandLine( lpCmdLine );
    if ( cmdline == NULL )
    {
        writeError( "Error: cannot create command line!\n" );
        closeErrorFile();
        return 1;
    }

    /* create the application process */
    STARTUPINFOW startup_info;
    PROCESS_INFORMATION process_info;
    memset( &startup_info, 0, sizeof(startup_info) );
    startup_info.cb = sizeof(startup_info);
    BOOL bCreate = CreateProcessW( NULL, cmdline, NULL,  NULL, FALSE, 0, NULL, NULL,
        &startup_info, &process_info );
    free( cmdline );
    if ( !bCreate )
    {
        writeError( "Error: cannot create process!\n" );
        closeErrorFile();
        return 1;
    }

    /* close the error file */
    closeErrorFile();

    return 0;
}
Esempio n. 20
0
//windows : find main DLL and extract path
//linux and macos : scilab script fill SCI env variable
char* computeTMPDIR()
{
#ifdef _MSC_VER
    wchar_t wcTmpDirDefault[PATH_MAX];

    if (!GetTempPathW(PATH_MAX, wcTmpDirDefault))
    {
        MessageBoxA(NULL, _("Cannot find Windows temporary directory (1)."), _("Error"), MB_ICONERROR);
        exit(1);
    }
    else
    {
        wchar_t wctmp_dir[PATH_MAX + FILENAME_MAX + 1];
        static wchar_t bufenv[PATH_MAX + 16];
        char *TmpDir = NULL;
        os_swprintf(wctmp_dir, PATH_MAX + FILENAME_MAX + 1, L"%lsSCI_TMP_%d_", wcTmpDirDefault, _getpid());
        if (CreateDirectoryW(wctmp_dir, NULL) == FALSE)
        {
            DWORD attribs = GetFileAttributesW(wctmp_dir);
            if (attribs & FILE_ATTRIBUTE_DIRECTORY)
            {
                /* Repertoire existant */
            }
            else
            {
#ifdef _DEBUG
                {
                    char MsgErr[1024];
                    wsprintfA(MsgErr, _("Impossible to create : %s"), wctmp_dir);
                    MessageBoxA(NULL, MsgErr, _("Error"), MB_ICONERROR);
                    exit(1);
                }
#else
                {
                    GetTempPathW(PATH_MAX, wcTmpDirDefault);
                    wcscpy(wctmp_dir, wcTmpDirDefault);
                    wctmp_dir[wcslen(wctmp_dir) - 1] = '\0'; /* Remove last \ */
                }
#endif
            }
        }

        os_swprintf(bufenv, PATH_MAX + 16, L"TMPDIR=%ls", wctmp_dir);
        _wputenv(bufenv);

        TmpDir = wide_string_to_UTF8(wctmp_dir);
        if (TmpDir)
        {
            return TmpDir;
        }
        else
        {
            return NULL;
        }
    }
    return NULL;
#else
    char *tmpdir;

    char* env_dir = (char*)MALLOC(sizeof(char) * (PATH_MAX + 16));
    /* If the env variable TMPDIR is set, honor this preference */
    tmpdir = getenv("TMPDIR");
    if (tmpdir != NULL && strlen(tmpdir) < (PATH_MAX) && strstr(tmpdir, "SCI_TMP_") == NULL)
    {
        strcpy(env_dir, tmpdir);
    }
    else
    {
        strcpy(env_dir, "/tmp");
    }

    /* XXXXXX will be randomized by mkdtemp */
    char *env_dir_strdup = os_strdup(env_dir); /* Copy to avoid to have the same buffer as input and output for sprintf */
    sprintf(env_dir, "%s/SCI_TMP_%d_XXXXXX", env_dir_strdup, (int)getpid());
    free(env_dir_strdup);

    if (mkdtemp(env_dir) == NULL)
    {
        fprintf(stderr, _("Error: Could not create %s: %s\n"), env_dir, strerror(errno));
    }

    setenvc("TMPDIR", env_dir);
    return env_dir;
#endif
}
Esempio n. 21
0
void setLocalTZ()
{
    _wputenv(localTZ);
    _tzset();
}
Esempio n. 22
0
void setUtcTZ()
{
    _wputenv(L"TZ=UTC0UTC");
    _tzset();
}
Esempio n. 23
0
/*
read the .editrc file
*/
void source_editrc()
{
  wchar_t *appdata = NULL;
  wchar_t *editrc = NULL;
  wchar_t string[_EL_ENV_BUF_LEN];
  char line[_EL_ENV_BUF_LEN];
  char s1[_EL_ENV_BUF_LEN];
  char s2[_EL_ENV_BUF_LEN];
  int d1 = -1;
  size_t n;
  FILE *handle = NULL;
  
  
  _wgetenv_s(&n, NULL, 0, _T("EDITRC"));
  if (n) {
    if (!(editrc = malloc((n + 1) * sizeof(wchar_t)))) {
      return;
    }
    _wgetenv_s(&n, editrc, n, _T("EDITRC"));
    if (!n) {
      free(editrc);
    }
  }
  if (!n) {
    /*
    if the EDITRC environment variable is not set
    look for %APPDATA%\.editrc
    */
    _wgetenv_s(&n, NULL, 0, _T("APPDATA"));
    if (n) {
      if (!(appdata = malloc((n + 1) * sizeof(wchar_t)))) {
        return;
      }
      _wgetenv_s(&n, appdata, n, _T("APPDATA"));
    }
    if (!n) {
      return;
    }
    n = wcslen(appdata) + _EL_ENV_BUF_LEN;
    if (!(editrc = malloc(n * sizeof(wchar_t)))) {
      return;
    }
    swprintf_s(editrc, n, _T("%s\\.editrc"), appdata);
    free(appdata);
  }
  if (_wfopen_s(&handle, editrc, _T("rb"))) {
    free(editrc);
    return;
  }
  /*
  if .editrc could be opened,
  look for the "history size" line and
  read the value
  */
  while (fgets(line, _EL_ENV_BUF_LEN, handle)) {
    line[_EL_ENV_BUF_LEN - 1] = '\0';
    if (line[0]) {
      sscanf_s(line, "%16s %16s %d",
        s1, _EL_ENV_BUF_LEN, s2, _EL_ENV_BUF_LEN, &d1);
      if ((!_stricmp(s1, "history"))
        && (!_stricmp(s2, "size"))) {
        if (d1 < _EL_MIN_HIST_SIZE) {
          d1 = _EL_MIN_HIST_SIZE;
        }
      }
    }
  }
  fclose(handle);
  /*
  if a valid value has been found, set the
  MINGWEDITLINE_HISTORY_SIZE environment variable
  to this value
  */
  if (d1 != -1) {
    swprintf_s(string, _EL_ENV_BUF_LEN, _T("MINGWEDITLINE_HISTORY_SIZE=%d"), d1);
    _wputenv(string);
  }
  free(editrc);
}
Esempio n. 24
0
static void winpidgin_add_stuff_to_path() {
	wchar_t perl_path[MAX_PATH + 1];
	wchar_t *ppath = NULL;
	wchar_t mit_kerberos_path[MAX_PATH + 1];
	wchar_t *mpath = NULL;
	DWORD plen;

	printf("%s", "Looking for Perl... ");

	plen = sizeof(perl_path) / sizeof(wchar_t);
	if (read_reg_string(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Perl", L"",
			    (LPBYTE) &perl_path, &plen)) {
		/* We *could* check for perl510.dll, but it seems unnecessary. */
		wprintf(L"found in '%s'.\n", perl_path);

		if (perl_path[wcslen(perl_path) - 1] != L'\\')
			wcscat(perl_path, L"\\");
		wcscat(perl_path, L"bin");

		ppath = perl_path;
	} else
		printf("%s", "not found.\n");

	printf("%s", "Looking for MIT Kerberos... ");

	plen = sizeof(mit_kerberos_path) / sizeof(wchar_t);
	if (read_reg_string(HKEY_LOCAL_MACHINE, L"SOFTWARE\\MIT\\Kerberos", L"InstallDir",
			    (LPBYTE) &mit_kerberos_path, &plen)) {
		/* We *could* check for gssapi32.dll */
		wprintf(L"found in '%s'.\n", mit_kerberos_path);

		if (mit_kerberos_path[wcslen(mit_kerberos_path) - 1] != L'\\')
			wcscat(mit_kerberos_path, L"\\");
		wcscat(mit_kerberos_path, L"bin");

		mpath = mit_kerberos_path;
	} else
		printf("%s", "not found.\n");

	if (ppath != NULL || mpath != NULL) {
		const wchar_t *path = _wgetenv(L"PATH");
		BOOL add_ppath = ppath != NULL && (path == NULL || !wcsstr(path, ppath));
		BOOL add_mpath = mpath != NULL && (path == NULL || !wcsstr(path, mpath));
		wchar_t *newpath;
		int newlen;

		if (add_ppath || add_mpath) {
			/* Enough to add "PATH=" + path + ";"  + ppath + ";" + mpath + \0 */
			newlen = 6 + (path ? wcslen(path) + 1 : 0);
			if (add_ppath)
				newlen += wcslen(ppath) + 1;
			if (add_mpath)
				newlen += wcslen(mpath) + 1;
			newpath = malloc(newlen * sizeof(wchar_t));

			_snwprintf(newpath, newlen, L"PATH=%s%s%s%s%s%s",
				  path ? path : L"",
				  path ? L";" : L"",
				  add_ppath ? ppath : L"",
				  add_ppath ? L";" : L"",
				  add_mpath ? mpath : L"",
				  add_mpath ? L";" : L"");

			wprintf(L"New PATH: %s\n", newpath);

			_wputenv(newpath);
			free(newpath);
		}
	}
}
Esempio n. 25
0
 inline int putenv(char* string) { return _wputenv(nall::utf16_t(string)); }
Esempio n. 26
0
// Annotate the crash report with a Unique User ID and time
// since install.  Also do some prep work for recording
// time since last crash, which must be calculated at
// crash time.
// If any piece of data doesn't exist, initialize it first.
nsresult SetupExtraData(nsILocalFile* aAppDataDirectory,
                        const nsACString& aBuildID)
{
  nsCOMPtr<nsIFile> dataDirectory;
  nsresult rv = aAppDataDirectory->Clone(getter_AddRefs(dataDirectory));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = dataDirectory->AppendNative(NS_LITERAL_CSTRING("Crash Reports"));
  NS_ENSURE_SUCCESS(rv, rv);

  PRBool exists;
  rv = dataDirectory->Exists(&exists);
  NS_ENSURE_SUCCESS(rv, rv);

  if (!exists) {
    rv = dataDirectory->Create(nsIFile::DIRECTORY_TYPE, 0700);
    NS_ENSURE_SUCCESS(rv, rv);
  }

#if defined(XP_WIN32)
  nsAutoString dataDirEnv(NS_LITERAL_STRING("MOZ_CRASHREPORTER_DATA_DIRECTORY="));

  nsAutoString dataDirectoryPath;
  rv = dataDirectory->GetPath(dataDirectoryPath);
  NS_ENSURE_SUCCESS(rv, rv);

  dataDirEnv.Append(dataDirectoryPath);

  _wputenv(dataDirEnv.get());
#else
  // Save this path in the environment for the crash reporter application.
  nsCAutoString dataDirEnv("MOZ_CRASHREPORTER_DATA_DIRECTORY=");

  nsCAutoString dataDirectoryPath;
  rv = dataDirectory->GetNativePath(dataDirectoryPath);
  NS_ENSURE_SUCCESS(rv, rv);

  dataDirEnv.Append(dataDirectoryPath);

  char* env = ToNewCString(dataDirEnv);
  NS_ENSURE_TRUE(env, NS_ERROR_OUT_OF_MEMORY);

  PR_SetEnv(env);
#endif

  nsCAutoString data;
  if(NS_SUCCEEDED(GetOrInit(dataDirectory, NS_LITERAL_CSTRING("UserID"),
                            data, InitUserID)))
    AnnotateCrashReport(NS_LITERAL_CSTRING("UserID"), data);

  if(NS_SUCCEEDED(GetOrInit(dataDirectory,
                            NS_LITERAL_CSTRING("InstallTime") + aBuildID,
                            data, InitInstallTime)))
    AnnotateCrashReport(NS_LITERAL_CSTRING("InstallTime"), data);

  // this is a little different, since we can't init it with anything,
  // since it's stored at crash time, and we can't annotate the
  // crash report with the stored value, since we really want
  // (now - LastCrash), so we just get a value if it exists,
  // and store it in a time_t value.
  if(NS_SUCCEEDED(GetOrInit(dataDirectory, NS_LITERAL_CSTRING("LastCrash"),
                            data, NULL))) {
    lastCrashTime = (time_t)atol(data.get());
  }

  // not really the best place to init this, but I have the path I need here
  nsCOMPtr<nsIFile> lastCrashFile;
  rv = dataDirectory->Clone(getter_AddRefs(lastCrashFile));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = lastCrashFile->AppendNative(NS_LITERAL_CSTRING("LastCrash"));
  NS_ENSURE_SUCCESS(rv, rv);
  memset(lastCrashTimeFilename, 0, sizeof(lastCrashTimeFilename));

#if defined(XP_WIN32)
  nsAutoString filename;
  rv = lastCrashFile->GetPath(filename);
  NS_ENSURE_SUCCESS(rv, rv);

  if (filename.Length() < XP_PATH_MAX)
    wcsncpy(lastCrashTimeFilename, filename.get(), filename.Length());
#else
  nsCAutoString filename;
  rv = lastCrashFile->GetNativePath(filename);
  NS_ENSURE_SUCCESS(rv, rv);

  if (filename.Length() < XP_PATH_MAX)
    strncpy(lastCrashTimeFilename, filename.get(), filename.Length());
#endif

  return NS_OK;
}
Esempio n. 27
0
PSTEPlugin STEPluginLoadFile(LPCWSTR strPluginFile) {
	HINSTANCE hLib;
	CString strPluginFolder;
	{
		wchar_t   drive[_MAX_DRIVE];
		wchar_t   dir[_MAX_DIR];
		wchar_t   buff[_MAX_PATH] = {'\0'};
		wchar_t   full[_MAX_PATH] = {'\0'};

		_tsplitpath(strPluginFile, drive, dir, NULL, NULL);
		_tmakepath_s(buff,_MAX_PATH, drive, dir, NULL, NULL);
		if (drive[0] == '\0') {
			CSuperTagEditorApp	*pApp = (CSuperTagEditorApp *)AfxGetApp();
			CString strEXE;
			{
				wchar_t*	szName = pApp->MakeFileName(L"");
				wchar_t   drive[_MAX_DRIVE];
				wchar_t   dir[_MAX_DIR];
				wchar_t   buff[_MAX_PATH] = {'\0'};
				_tsplitpath(szName, drive, dir, NULL, NULL);
				_tmakepath_s(buff,_MAX_PATH, drive, dir, L"", L"");
				strEXE = buff;
				delete szName;
			}

			wcscpy_s(full,_MAX_PATH, strEXE);
			wcscat_s(full,_MAX_PATH, dir);
			_wfullpath(buff, full, _MAX_PATH);
		}
		strPluginFolder = buff;
		wchar_t* pathvar = _wgetenv(L"PATH");
		CString strPath = L"PATH=";
		strPath = strPath + strPluginFolder + ";" + pathvar;
		_wputenv(strPath);
		hLib = LoadLibrary(strPluginFile);
		strPath = L"PATH=";
		strPath = strPath + pathvar;
		_wputenv(strPath);
		if (hLib == NULL) return NULL;
	}

	UINT (WINAPI *STEPGetAPIVersion)(void);
	bool (WINAPI *STEPInit)(UINT, LPCWSTR);
	LPCWSTR (WINAPI *STEPGetPluginName)(void);

	(FARPROC&)STEPInit = GetProcAddress(hLib, "_STEPInit@8");
	(FARPROC&)STEPGetAPIVersion = GetProcAddress(hLib, "_STEPGetAPIVersion@0");
	(FARPROC&)STEPGetPluginName = GetProcAddress(hLib, "_STEPGetPluginName@0");
	if (STEPInit == NULL || STEPGetAPIVersion == NULL || STEPGetPluginName == NULL)	return  NULL;
	if ((STEPGetAPIVersion() & 0xFFFF00) > (STEP_API_VERSION & 0xFFFF00))	return NULL; /* STEP 029 */
	PSTEPlugin pPlugin = new STEPlugin;
	pPlugin->hLib = hLib;
	pPlugin->sFileName = strPluginFile;
	pPlugin->sPluginName = STEPGetPluginName();
	(FARPROC&)pPlugin->STEPGetToolTipText = GetProcAddress(hLib, "_STEPGetToolTipText@4");
	(FARPROC&)pPlugin->STEPGetStatusMessage = GetProcAddress(hLib, "_STEPGetStatusMessage@4");
	(FARPROC&)pPlugin->STEPOnUpdateCommand = GetProcAddress(hLib, "_STEPOnUpdateCommand@4");
	(FARPROC&)pPlugin->STEPOnCommand = GetProcAddress(hLib, "_STEPOnCommand@8");
	(FARPROC&)pPlugin->STEPSupportSIF = GetProcAddress(hLib, "_STEPSupportSIF@4");
	(FARPROC&)pPlugin->STEPSupportTrackNumberSIF = GetProcAddress(hLib, "_STEPSupportTrackNumberSIF@4");
	(FARPROC&)pPlugin->STEPSupportGenreSIF = GetProcAddress(hLib, "_STEPSupportGenreSIF@4");
	(FARPROC&)pPlugin->STEPGetControlType = GetProcAddress(hLib, "_STEPGetControlType@12");
	(FARPROC&)pPlugin->STEPGetColumnMax = GetProcAddress(hLib, "_STEPGetColumnMax@12");
	(FARPROC&)pPlugin->STEPGetColumnName = GetProcAddress(hLib, "_STEPGetColumnName@8");
	(FARPROC&)pPlugin->STEPHasSpecificColumnName = GetProcAddress(hLib, "_STEPHasSpecificColumnName@4");
	(FARPROC&)pPlugin->STEPLoad = GetProcAddress(hLib, "_STEPLoad@8");
	(FARPROC&)pPlugin->STEPSave = GetProcAddress(hLib, "_STEPSave@4");
	(FARPROC&)pPlugin->STEPShowOptionDialog = GetProcAddress(hLib, "_STEPShowOptionDialog@4");
	(FARPROC&)pPlugin->STEPOnLoadMenu = GetProcAddress(hLib, "_STEPOnLoadMenu@8");
	(FARPROC&)pPlugin->STEPOnLoadMainMenu = GetProcAddress(hLib, "_STEPOnLoadMainMenu@0");
	(FARPROC&)pPlugin->STEPGetPluginInfo = GetProcAddress(hLib, "_STEPGetPluginInfo@0");
	(FARPROC&)pPlugin->STEPInitFileSpecificInfo = GetProcAddress(hLib, "_STEPInitFileSpecificInfo@4");
	(FARPROC&)pPlugin->STEPOnConvSiFieldToId3tag = GetProcAddress(hLib, "_STEPOnConvSiFieldToId3tag@4");

	plugins.arPlugins.Add(pPlugin);

	if ((*STEPInit)(plugins.arPlugins.GetSize(), strPluginFolder) == false) {
		return NULL;
	}

	return pPlugin;
}
Esempio n. 28
0
static void test__wenviron(void)
{
    static const WCHAR cat_eq_dogW[] = {'c','a','t','=','d','o','g',0};
    static const WCHAR cat_eqW[] = {'c','a','t','=',0};

    int argc;
    char **argv, **envp = NULL;
    WCHAR **wargv, **wenvp = NULL;
    int i, mode = 0;

    ok( p_wenviron != NULL, "Expected the pointer to _wenviron to be non-NULL\n" );
    if (p_wenviron)
        ok( *p_wenviron == NULL, "Expected _wenviron to be NULL, got %p\n", *p_wenviron );
    else
    {
        win_skip( "Pointer to _wenviron is not valid\n" );
        return;
    }

    /* Examine the returned pointer from __p__wenviron(), if available. */
    if (p__p__wenviron)
    {
        ok( *p__p__wenviron() == NULL,
            "Expected _wenviron pointers to be NULL\n" );
    }
    else
        win_skip( "__p__wenviron() is not available\n" );

    /* __getmainargs doesn't initialize _wenviron. */
    __getmainargs(&argc, &argv, &envp, 0, &mode);

    ok( *p_wenviron == NULL, "Expected _wenviron to be NULL, got %p\n", *p_wenviron);
    ok( envp != NULL, "Expected initial environment block pointer to be non-NULL\n" );
    if (!envp)
    {
        skip( "Initial environment block pointer is not valid\n" );
        return;
    }

    /* Neither does calling the non-Unicode environment manipulation functions. */
    ok( _putenv("cat=dog") == 0, "failed setting cat=dog\n" );
    ok( *p_wenviron == NULL, "Expected _wenviron to be NULL, got %p\n", *p_wenviron);
    ok( _putenv("cat=") == 0, "failed deleting cat\n" );

    /* _wenviron isn't initialized until __wgetmainargs is called or
     * one of the Unicode environment manipulation functions is called. */
    ok( _wputenv(cat_eq_dogW) == 0, "failed setting cat=dog\n" );
    ok( *p_wenviron != NULL, "Expected _wenviron to be non-NULL\n" );
    ok( _wputenv(cat_eqW) == 0, "failed deleting cat\n" );

    __wgetmainargs(&argc, &wargv, &wenvp, 0, &mode);

    ok( *p_wenviron != NULL, "Expected _wenviron to be non-NULL\n" );
    ok( wenvp != NULL, "Expected initial environment block pointer to be non-NULL\n" );
    if (!wenvp)
    {
        skip( "Initial environment block pointer is not valid\n" );
        return;
    }

    /* Examine the returned pointer from __p__wenviron(),
     * if available, after _wenviron is initialized. */
    if (p__p__wenviron)
    {
        ok( *p__p__wenviron() == *p_wenviron,
            "Expected _wenviron pointers to be identical\n" );
    }

    for (i = 0; ; i++)
    {
        if ((*p_wenviron)[i])
        {
            ok( wenvp[i] != NULL, "Expected environment block pointer element to be non-NULL\n" );
            ok( !winetest_strcmpW((*p_wenviron)[i], wenvp[i]),
                "Expected _wenviron and environment block pointer strings (%s vs. %s) to match\n",
                wine_dbgstr_w((*p_wenviron)[i]), wine_dbgstr_w(wenvp[i]) );
        }
        else
        {
            ok( !wenvp[i], "Expected environment block pointer element to be NULL, got %p\n", wenvp[i] );
            break;
        }
    }
}
Esempio n. 29
0
int VMPI_putenv16(wchar *name)
{
    return _wputenv( name );
}
Esempio n. 30
0
void FormatTime(ScriptValue &s, ScriptValue *args) {
	unsigned char *c = args[0].stringVal->value;
	if (!AllocateStringValue(s, (int)(3 * strlen(c) + 14))) return;
	static bool settz = 0;
	if (args[0].stringVal->value[0] == 'S') {
		args[0].stringVal->value[0] = args[0].stringVal->value[0];
	}
	// Nasty layout, but boils down to:  If a tz is specified, try to set it.
	// If either couldn't set it or not specified and was set previously, unset it.
	while (1) {
		if (args[2].stringVal->len >= 1 && args[2].stringVal->len <= 20) {
			if (args[2].stringVal->len < 4 || (args[2].stringVal->len == 4 && !IsNumber(args[2].stringVal->value[3]))) {
				for (int i=0; i<sizeof(tzlist)/sizeof(tzlist[0]); i++) {
					if (!stricmp(tzlist[i][0], (char*)args[2].stringVal->value)) {
						char temp[60] = "TZ=";
						sprintf(temp+3, tzlist[i][1]);
						if (!_putenv(temp)) {
							_tzset();
							settz = 1;
							break;
						}
					}
				}
			}
			else {
				wchar_t temp[60] = L"TZ=";
				if (UTF8toUTF16(temp+3, args[2].stringVal->value, args[2].stringVal->len) > 0) {
					if (!_wputenv(temp)) {
						_tzset();
						settz = 1;
						break;
					}
				}
			}
		}
		if (settz) {
			if (!_putenv("TZ=")) {
				_tzset();
				settz = 0;
			}
		}
		break;
	}
	static LCID locale = 0;
	if (!locale) {
		locale = GetThreadLocale();
	}
	__int64 x = args[1].intVal;
	if (!x) x = time64i();
	tm *date = _localtime64(&x);
	SYSTEMTIME st;

	st.wYear = date->tm_year+1900;
	st.wMonth = date->tm_mon+1;
	st.wDayOfWeek = date->tm_wday;
	st.wDay = date->tm_mday;
	st.wHour = date->tm_hour;
	st.wMinute = date->tm_min;
	st.wSecond = date->tm_sec;
	st.wMilliseconds = 0;
	char *out = (char*) s.stringVal->value;
	char * start = (char*) c;
	//static const char *wday[7] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
	//static const char *wday2[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
	//static const char *months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
	//static const char *months2[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
	while (*start) {
		if (LCASE(start[0]) == 'h') {
			int h = date->tm_hour;
			if (*start == 'h') {
				if (h >12) h -= 12;
				else if (!h) h = 12;
			}
			GenericDisplay(start, out, h);
		}
		else if (LCASE(start[0]) == 'n')
			GenericDisplay(start, out, date->tm_min);
		else if (LCASE(start[0]) == 's')
			GenericDisplay(start, out, date->tm_sec);
		else if (LCASE(start[0]) == 't') {
			char letter = 'A';
			if (date->tm_hour >= 12) letter = 'P';
			if (start[0] == 't')
				out++[0]  = LCASE(letter);
			else
				out++[0]  = letter;
			start ++;
			if (start[0] == 't') {
				out++[0]  = 'm';
				start ++;
			}
			else if (start[0] == 'T') {
				out++[0]  = 'M';
				start ++;
			}
		}
		else if (LCASE(start[0]) == 'd') {
			if (LCASE(start[1]) == 'd' && LCASE(start[2]) == 'd') {
				start += 2;
				int incr = 1;
				wchar_t day[100];
				int len;
				if (LCASE(start[1]) == 'd') {
					len = GetDateFormat(locale, 0, &st, L"dddd", day, sizeof(day)/sizeof(wchar_t));
					//day = wday2[date->tm_wday];
					incr = 2;
				}
				else {
					len = GetDateFormat(locale, 0, &st, L"ddd", day, sizeof(day)/sizeof(wchar_t));
				}
				if (len < 0) len = 0;
				else if (len > 99) len = 99;
				day[len] = 0;
				int e = GetLastError();
				wchar_t *p = day;
				int i;
				for (i=0; i<len && i <99; i++) {
					p[i] = towupper(p[i]);
					if (start[0] != 'D') break;
				}
				UTF16toUTF8(out, day);
				out += strlen(out);
				start += incr;
			}
			else
				GenericDisplay(start, out, date->tm_mday);
		}
		else if (LCASE(start[0]) == 'm') {
			if (LCASE(start[1]) == 'm' && LCASE(start[2]) == 'm') {
				start += 2;
				int incr = 1;
				wchar_t day[100];
				int len;
				if (LCASE(start[1]) == 'm') {
					len = GetDateFormat(locale, 0, &st, L"MMMM", day, sizeof(day)/sizeof(wchar_t));
					//day = wday2[date->tm_wday];
					incr = 2;
				}
				else {
					len = GetDateFormat(locale, 0, &st, L"MMM", day, sizeof(day)/sizeof(wchar_t));
				}
				if (len < 0) len = 0;
				else if (len > 99) len = 99;
				day[len] = 0;
				int e = GetLastError();
				wchar_t *p = day;
				int i;
				for (i=0; i<len && i <99; i++) {
					p[i] = towupper(p[i]);
					if (start[0] != 'M') break;
				}
				UTF16toUTF8(out, day);
				out += strlen(out);
				start += incr;
			}
			else
				GenericDisplay(start, out, 1+date->tm_mon);
		}
		else if (LCASE(start[0]) == 'y') {
			int year = date->tm_year%100;
			if (LCASE(start[1]) == 'y') {
				start++;
				if (LCASE(start[1]) == 'y') {
					start ++;
					year = 1900 + date->tm_year;
					if (LCASE(start[1]) == 'y') start++;
				}
			}
			sprintf(out, "%02i", year);
			out+=strlen(out);
			start++;
		}
		else {
			out ++[0] = start++[0];
		}
		if ((out-(char*)s.stringVal->value) + 20 > s.stringVal->len) {
			size_t d = out - (char*)s.stringVal->value;
			ResizeStringValue(s, s.stringVal->len+50);
			out = (char*)s.stringVal->value + d;
		}
	}
	ResizeStringValue(s, (int)(out-(char*)s.stringVal->value));
}