Пример #1
0
static BOOL load_xpcom(PRUnichar *gre_path)
{
    WCHAR path_env[MAX_PATH];
    int len;

    static const WCHAR wszPATH[] = {'P','A','T','H',0};
    static const WCHAR strXPCOM[] = {'x','p','c','o','m','.','d','l','l',0};

    TRACE("(%s)\n", debugstr_w(gre_path));

    /* We have to modify PATH as XPCOM loads other DLLs from this directory. */
    GetEnvironmentVariableW(wszPATH, path_env, sizeof(path_env)/sizeof(WCHAR));
    len = strlenW(path_env);
    path_env[len++] = ';';
    strcpyW(path_env+len, gre_path);
    SetEnvironmentVariableW(wszPATH, path_env);

    hXPCOM = LoadLibraryW(strXPCOM);
    if(!hXPCOM) {
        WARN("Could not load XPCOM: %ld\n", GetLastError());
        return FALSE;
    }

#define NS_DLSYM(func) \
    func = (typeof(func))GetProcAddress(hXPCOM, #func); \
    if(!func) \
        ERR("Could not GetProcAddress(" #func ") failed\n")

    NS_DLSYM(NS_InitXPCOM2);
    NS_DLSYM(NS_ShutdownXPCOM);
    NS_DLSYM(NS_GetComponentRegistrar);
    NS_DLSYM(NS_StringContainerInit);
    NS_DLSYM(NS_CStringContainerInit);
    NS_DLSYM(NS_StringContainerFinish);
    NS_DLSYM(NS_CStringContainerFinish);
    NS_DLSYM(NS_StringSetData);
    NS_DLSYM(NS_CStringSetData);
    NS_DLSYM(NS_NewLocalFile);
    NS_DLSYM(NS_StringGetData);
    NS_DLSYM(NS_CStringGetData);

#undef NS_DLSYM

    return TRUE;
}
Пример #2
0
result_t process_base::chdir(const char *directory)
{
    wstring str = utf8to16String(directory);
    wchar utf16_buffer[MAX_PATH];
    DWORD utf16_len;
    wchar drive_letter;

    if (!SetCurrentDirectoryW(str.c_str()))
        return CHECK_ERROR(LastError());

    utf16_len = GetCurrentDirectoryW(MAX_PATH, utf16_buffer);
    if (utf16_len == 0)
        return CHECK_ERROR(LastError());

    if (utf16_buffer[utf16_len - 1] == L'\\' &&
            !(utf16_len == 3 && utf16_buffer[1] == L':'))
    {
        utf16_len--;
        utf16_buffer[utf16_len] = L'\0';
    }

    if (utf16_len < 2 || utf16_buffer[1] != L':')
        drive_letter = 0;
    else if (utf16_buffer[0] >= L'A' && utf16_buffer[0] <= L'Z')
        drive_letter = utf16_buffer[0];
    else if (utf16_buffer[0] >= L'a' && utf16_buffer[0] <= L'z')
        drive_letter = utf16_buffer[0] - L'a' + L'A';
    else
        drive_letter = 0;

    if (drive_letter != 0)
    {
        wchar env_var[4];

        env_var[0] = L'=';
        env_var[1] = drive_letter;
        env_var[2] = L':';
        env_var[3] = L'\0';

        if (!SetEnvironmentVariableW(env_var, utf16_buffer))
            return CHECK_ERROR(LastError());
    }

    return 0;
}
Пример #3
0
void ApplyExportEnvVar(LPCWSTR asEnvNameVal)
{
	if (!asEnvNameVal)
		return;

	while (*asEnvNameVal)
	{
		LPCWSTR pszName = asEnvNameVal;
		LPCWSTR pszVal = pszName + lstrlen(pszName) + 1;
		LPCWSTR pszNext = pszVal + lstrlen(pszVal) + 1;
		// Skip ConEmu's internals!
		if (IsExportEnvVarAllowed(pszName))
		{
			SetEnvironmentVariableW(pszName, pszVal);
		}
		asEnvNameVal = pszNext;
	}
}
Пример #4
0
BOOL SetEenvironment()
{
	TCHAR *sep = L"\n";
	TCHAR *token = wcstok(szEnvironment, sep);
	while(token!=NULL)
	{
		TCHAR *pos = wcschr(token, L'=');
		if (pos)
		{
			*pos = 0;
			TCHAR* key = token;
			TCHAR* value = pos + 1;
			SetEnvironmentVariableW(key, value);
		}
		token = wcstok(NULL, sep);
	}
	return TRUE;
}
Пример #5
0
void ApplyExportEnvVar(LPCWSTR asEnvNameVal)
{
	if (!asEnvNameVal)
		return;

	while (*asEnvNameVal)
	{
		LPCWSTR pszName = asEnvNameVal;
		LPCWSTR pszVal = pszName + lstrlen(pszName) + 1;
		LPCWSTR pszNext = pszVal + lstrlen(pszVal) + 1;
		// Skip ConEmu's internals!
		if (IsExportEnvVarAllowed(pszName))
		{
			// Doubt that someone really needs to export empty var instead of its deletion
			SetEnvironmentVariableW(pszName, *pszVal ? pszVal : NULL);
		}
		asEnvNameVal = pszNext;
	}
}
Пример #6
0
void
SanitizeEnvironmentVariables()
{
  DWORD bufferSize = GetEnvironmentVariableW(L"PATH", NULL, 0);
  if (bufferSize) {
    wchar_t* originalPath = new wchar_t[bufferSize];
    if (bufferSize - 1 == GetEnvironmentVariableW(L"PATH", originalPath, bufferSize)) {
      bufferSize = ExpandEnvironmentStringsW(originalPath, NULL, 0);
      if (bufferSize) {
        wchar_t* newPath = new wchar_t[bufferSize];
        if (ExpandEnvironmentStringsW(originalPath,
                                      newPath,
                                      bufferSize)) {
          SetEnvironmentVariableW(L"PATH", newPath);
        }
        delete[] newPath;
      }
    }
    delete[] originalPath;
  }
}
Пример #7
0
static void
set_env(char *key, char *value)
{
#ifdef __WIN32__
    WCHAR wkey[MAXPATHLEN];
    WCHAR wvalue[MAXPATHLEN];
    MultiByteToWideChar(CP_UTF8, 0, key, -1, wkey, MAXPATHLEN);
    MultiByteToWideChar(CP_UTF8, 0, value, -1, wvalue, MAXPATHLEN);
    if (!SetEnvironmentVariableW(wkey, wvalue))
        error("SetEnvironmentVariable(\"%s\", \"%s\") failed!", key, value);
#else
    size_t size = strlen(key) + 1 + strlen(value) + 1;
    char *str = emalloc(size);
    sprintf(str, "%s=%s", key, value);
    if (putenv(str) != 0)
        error("putenv(\"%s\") failed!", str);
#ifdef HAVE_COPYING_PUTENV
    efree(str);
#endif
#endif
}
Пример #8
0
bool terminal_try_attach(void)
{
    // mpv.exe is a flagged as a GUI application, but it acts as a console
    // application when started from the console wrapper (see
    // osdep/win32-console-wrapper.c). The console wrapper sets
    // _started_from_console=yes, so check that variable before trying to
    // attach to the console.
    wchar_t console_env[4] = { 0 };
    if (!GetEnvironmentVariableW(L"_started_from_console", console_env, 4))
        return false;
    if (wcsncmp(console_env, L"yes", 4))
        return false;
    SetEnvironmentVariableW(L"_started_from_console", NULL);

    if (!AttachConsole(ATTACH_PARENT_PROCESS))
        return false;

    // We have a console window. Redirect output streams to that console's
    // low-level handles, so things that use printf directly work later on.
    reopen_console_handle(STD_OUTPUT_HANDLE, STDOUT_FILENO, stdout);
    reopen_console_handle(STD_ERROR_HANDLE, STDERR_FILENO, stderr);

    return true;
}
Пример #9
0
//
// Attempt to load libintl.dll.  If it doesn't work, use dummy functions.
// "dir" is the directory where the libintl.dll might be.
// Return 1 for success, 0 for failure.
//
    static int
dyn_libintl_init(char *dir)
{
    int		i;
    static struct
    {
	char	    *name;
	FARPROC	    *ptr;
    } libintl_entry[] =
    {
	{(char *)"gettext",		(FARPROC*)&dyn_libintl_gettext},
	{(char *)"textdomain",		(FARPROC*)&dyn_libintl_textdomain},
	{(char *)"bindtextdomain",	(FARPROC*)&dyn_libintl_bindtextdomain},
	{NULL, NULL}
    };
    DWORD	len, len2;
    LPWSTR	buf = NULL;
    LPWSTR	buf2 = NULL;

    // No need to initialize twice.
    if (hLibintlDLL)
	return 1;

    // Load gettext library from $VIMRUNTIME\GvimExt{64,32} directory.
    // Add the directory to $PATH temporarily.
    len = GetEnvironmentVariableW(L"PATH", NULL, 0);
    len2 = MAX_PATH + 1 + len;
    buf = (LPWSTR)malloc(len * sizeof(WCHAR));
    buf2 = (LPWSTR)malloc(len2 * sizeof(WCHAR));
    if (buf != NULL && buf2 != NULL)
    {
	GetEnvironmentVariableW(L"PATH", buf, len);
#ifdef _WIN64
	_snwprintf(buf2, len2, L"%S\\GvimExt64;%s", dir, buf);
#else
	_snwprintf(buf2, len2, L"%S\\GvimExt32;%s", dir, buf);
#endif
	SetEnvironmentVariableW(L"PATH", buf2);
	hLibintlDLL = LoadLibrary(GETTEXT_DLL);
#ifdef GETTEXT_DLL_ALT
	if (!hLibintlDLL)
	    hLibintlDLL = LoadLibrary(GETTEXT_DLL_ALT);
#endif
	SetEnvironmentVariableW(L"PATH", buf);
    }
    free(buf);
    free(buf2);
    if (!hLibintlDLL)
	return 0;

    // Get the addresses of the functions we need.
    for (i = 0; libintl_entry[i].name != NULL
					 && libintl_entry[i].ptr != NULL; ++i)
    {
	if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
					      libintl_entry[i].name)) == NULL)
	{
	    dyn_libintl_end();
	    return 0;
	}
    }
    return 1;
}
Пример #10
0
EASYHOOK_NT_EXPORT HookCompleteInjection(LPREMOTE_INFO InInfo)
{
/*
Description:

    This method is directly called from assembler code. It will update
    the symbols with the ones of the current process, adjust the PATH
    variable and invoke one of two above injection completions.

*/

    WCHAR*	    	PATH = NULL;
	ULONG		    ErrorCode = 0;
	HMODULE         hMod = GetModuleHandleA("kernel32.dll");
    ULONG           DirSize;
    ULONG           EnvSize;

    /*
		To increase stability we will now update all symbols with the
		real local ones...
	*/
	InInfo->LoadLibraryW = GetProcAddress(hMod, "LoadLibraryW");
	InInfo->FreeLibrary = GetProcAddress(hMod, "FreeLibrary");
	InInfo->GetProcAddress = GetProcAddress(hMod, "GetProcAddress");
	InInfo->VirtualFree = GetProcAddress(hMod, "VirtualFree");
	InInfo->VirtualProtect = GetProcAddress(hMod, "VirtualProtect");
	InInfo->ExitThread = GetProcAddress(hMod, "ExitThread");
	InInfo->GetLastError = GetProcAddress(hMod, "GetLastError");

    

	/* 
        Make directory of user library path available to current process...
	    This is to find dependencies without copying them into a global
	    directory which might cause trouble.
    */

	DirSize = RtlUnicodeLength(InInfo->PATH);
	EnvSize = GetEnvironmentVariableW(L"PATH", NULL, 0) + DirSize;

	if((PATH = (wchar_t*)RtlAllocateMemory(TRUE, EnvSize * 2 + 10)) == NULL)
		UNMANAGED_ERROR(1);

	GetEnvironmentVariableW(L"PATH", PATH, EnvSize);

	// add library path to environment variable
	if(!RtlMoveMemory(PATH + DirSize, PATH, (EnvSize - DirSize) * 2))
        UNMANAGED_ERROR(1);

	RtlCopyMemory(PATH, InInfo->PATH, DirSize * 2);

	if(!SetEnvironmentVariableW(L"PATH", PATH))
		UNMANAGED_ERROR(2);

    if(!RTL_SUCCESS(RhSetWakeUpThreadID(InInfo->WakeUpThreadID)))
        UNMANAGED_ERROR(3);

	// load and execute user library...
	if(InInfo->IsManaged)
        ErrorCode = CompleteManagedInjection(InInfo);
    else
        ErrorCode = CompleteUnmanagedInjection(InInfo);

ABORT_ERROR:

    // release resources
	if(PATH != NULL)
		RtlFreeMemory(PATH);

	if(InInfo->hRemoteSignal != NULL)
		CloseHandle(InInfo->hRemoteSignal);

	return ErrorCode;
}
Пример #11
0
/* Runs a handler process specified by full command line <data> (with arguments).
 * Before running:
 * Replaces environment variables.
 * Replaces special MimeRun variables (see above) with the detected values taken from <mres>.
 * Replaces %* and %N with the appropriate bits of <lpfile> and <einfo>->lpParameters.
 * If <executable> is TRUE, waits until the handler process terminates, otherwise returns
 * (almost) immediately.
 */
int run_handler (wchar_t *logfile, wchar_t *data, MimeResults *mres, LPSHELLEXECUTEINFOW einfo, wchar_t *lpfile, wchar_t *lpdir, int executable, int fix_redir)
{
  BOOL ret = 0;
  PVOID redir;
  HMODULE kernel32 = NULL;
  Wow64DisableWow64FsRedirectionFunction disablewow64 = NULL;
  Wow64RevertWow64FsRedirectionFunction revertwow64 = NULL;
  DWORD err;
  int i;
  int depth = 0;
  size_t dupdatalen;
  wchar_t *exp_data = NULL;
  wchar_t *dupdata = NULL;
  wchar_t *dupparams = NULL;
  wchar_t **old_argv = NULL, **newargv = NULL;
  STARTUPINFOW si;
  PROCESS_INFORMATION pi;
  DWORD applelen, typelen, enclen, namelen;
  wchar_t *store_apple = NULL, *store_type = NULL, *store_enc = NULL, *store_name = NULL;

  logtofilew (logfile, L">run_handler\n");

  if (einfo->lpParameters != NULL)
  {
    i = wcslen (einfo->lpParameters) + 1 + wcslen (lpfile);
    logtofilew (logfile, L"Fake commandline length is %d + 1 + %d == %d\n", wcslen (einfo->lpParameters), wcslen (lpfile), i);
    dupparams = (wchar_t *) malloc (sizeof (wchar_t *) * (i + 1));
    if (dupparams == NULL)
    {
      logtofilew (logfile, L"Failed to allocate %d bytes\n", sizeof (wchar_t *) * (i + 1));
      return 1;
    }
    dupparams[0] = L'\0';
    wcscat (dupparams, lpfile);
    wcscat (dupparams, L" ");
    wcscat (dupparams, einfo->lpParameters);
    logtofilew (logfile, L"Fake commandline is %s\n", dupparams);
    if (make_argv (dupparams, &i, NULL) == 0 && i >= 1)
    {
      old_argv = (wchar_t **) malloc (sizeof (wchar_t *) * (i + 1));
      make_argv (dupparams, NULL, old_argv);
      old_argv[i] = NULL;
      logtofilew (logfile, L"Old arguments:\n");
      for (i = 0; old_argv[i] != NULL; i++)
        logtofilew (logfile, L"%2d: %s\n", i, old_argv[i]);
      logtofilew (logfile, L"\n");
    }
    else
    {
      logtofilew (logfile, L"First call to make_argv() have failed or argc <= 0\n");
      free (dupparams);
      return 2;
    }
  }
  else
  {
    old_argv = (wchar_t **) malloc (sizeof (wchar_t *) * 2);
    old_argv[0] = lpfile;
    old_argv[1] = NULL;
    logtofilew (logfile, L"Old arguments:\n");
    for (i = 0; old_argv[i] != NULL; i++)
      logtofilew (logfile, L"%2d: %s\n", i, old_argv[i]);
    logtofilew (logfile, L"\n");
  }

  store_name = store_var (NAME_VARW, &namelen);
  store_type = store_var (TYPE_VARW, &typelen);
  store_enc = store_var (ENC_VARW, &enclen);
  store_apple = store_var (APPLE_VARW, &applelen);

  logtofilew (logfile, L"Backed up variables: {%s}, {%s}, {%s}, {%s}\n", store_name, store_type, store_enc, store_apple);

  SetEnvironmentVariableW (NAME_VARW, mres->wname == NULL ? L"" : mres->wname);
  SetEnvironmentVariableW (TYPE_VARW, mres->wtype == NULL ? L"" : mres->wtype);
  SetEnvironmentVariableW (ENC_VARW, mres->wenc == NULL ? L"" : mres->wenc);
  SetEnvironmentVariableW (APPLE_VARW, mres->wapple == NULL ? L"" : mres->wapple);
  
  exp_data = expand_vars (data, old_argv);

  logtofilew (logfile, L"Commandline with expanded variables: %s\n", exp_data);
  if (dupparams != NULL)
    free (dupparams);
  if (old_argv != NULL)
    free (old_argv);

  SetEnvironmentVariableW (NAME_VARW, store_name);
  SetEnvironmentVariableW (TYPE_VARW, store_type);
  SetEnvironmentVariableW (ENC_VARW, store_enc);
  SetEnvironmentVariableW (APPLE_VARW, store_apple);

  if (store_apple != NULL)
    free (store_apple);
  if (store_type != NULL)
    free (store_type);
  if (store_enc != NULL)
    free (store_enc);
  if (store_name != NULL)
    free (store_name);

  dupdata = (wchar_t *) wcsdup (exp_data);
  if (make_argv (dupdata, &i, NULL) == 0 && i >= 1)
  {
    newargv = (wchar_t **) malloc (sizeof (wchar_t *) * (i + 1));
    make_argv (dupdata, NULL, newargv);
    newargv[i] = NULL;
  }
  else
  {
    logtofilew (logfile, L"First call to make_argv() have failed or argc <= 0\n");
    free (dupdata);
    return 3;
  }

  memset (&si, 0, sizeof (si));
  si.cb = sizeof (si);
  if (einfo->nShow != SW_SHOWDEFAULT)
  {
    si.dwFlags |= STARTF_USESHOWWINDOW;
    si.wShowWindow = einfo->nShow;
    logtofilew (logfile, L"Using nShow == %d\n", si.wShowWindow);
  }


  if (einfo->fMask & SEE_MASK_NO_CONSOLE)
  {
    logtofilew (logfile, L"We will create new console and will not inherit in/out/err handles\n");
  }
  else
  {
    logtofilew (logfile, L"We will not create new console, child process will inherit in/out/err handles\n");
    si.dwFlags |= STARTF_USESTDHANDLES;
    si.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
    si.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
    si.hStdError = GetStdHandle (STD_ERROR_HANDLE);
  }

  if (fix_redir && iam32on64 ())
  {
    kernel32 = LoadLibraryW (L"kernel32.dll");
    if (kernel32 != NULL)
    {
      disablewow64 = (Wow64DisableWow64FsRedirectionFunction) GetProcAddress (kernel32, "Wow64DisableWow64FsRedirection");
      revertwow64 = (Wow64RevertWow64FsRedirectionFunction) GetProcAddress (kernel32, "Wow64RevertWow64FsRedirection");
      if (disablewow64 == NULL || revertwow64 == NULL)
        fix_redir = 0;
      else
        fix_redir = disablewow64 (&redir);
    }
    else
      fix_redir = 0;
  }
  else
    fix_redir = 0;

  ret = CreateProcessW (newargv[0], exp_data, NULL, NULL, TRUE, einfo->fMask & SEE_MASK_NO_CONSOLE ? CREATE_NEW_CONSOLE : 0, NULL, lpdir, &si, &pi);
  err = GetLastError();
  if (fix_redir != 0)
    revertwow64 (redir);
  if (kernel32 != NULL)
    FreeLibrary (kernel32);

  if (ret != 0)
  {
    logtofilew (logfile, L"CreateProcessW() succeeded\n");
    ret = 0;
    if (executable)
    {
      logtofilew (logfile, L"Waiting until executable process terminates...\n");
      WaitForSingleObject (pi.hProcess, INFINITE);
      logtofilew (logfile, L"Finished waiting until executable process terminates\n");
    }
    else
    {
      if (einfo->fMask & SEE_MASK_NOCLOSEPROCESS)
      {
        einfo->hProcess = pi.hProcess;
        logtofilew (logfile, L"Will return process handle %08X\n", pi.hProcess);
      }
      if (einfo->fMask & SEE_MASK_WAITFORINPUTIDLE)
      {
        logtofilew (logfile, L"Waiting until non-executable process' input idles...\n");
        WaitForInputIdle (pi.hProcess, 60*1000);
        logtofilew (logfile, L"Finished waiting until non-executable process' input idles\n");
      }
    }
    einfo->hInstApp = (HINSTANCE) 33;
  }
  else
  {
    logtofilew (logfile, L"CreateProcessW() have failed with %d\n", err);
    switch (err)
    {
    case ERROR_FILE_NOT_FOUND:
      einfo->hInstApp = (HINSTANCE) SE_ERR_FNF;
      break;
    case ERROR_PATH_NOT_FOUND:
      einfo->hInstApp = (HINSTANCE) SE_ERR_PNF;
      break;
    case ERROR_ACCESS_DENIED:
      einfo->hInstApp = (HINSTANCE) SE_ERR_ACCESSDENIED;
      break;
    case ERROR_NOT_ENOUGH_MEMORY:
      einfo->hInstApp = (HINSTANCE) SE_ERR_OOM;
      break;
    default:
      einfo->hInstApp = (HINSTANCE) 33;
    }
    ret = 1;
  }
  logtofilew (logfile, L"hInstApp is set to %d\n", einfo->hInstApp);
  free (exp_data);
  if (dupdata != NULL)
    free (dupdata);
  if (newargv != NULL)
    free (newargv);
  logtofilew (logfile, L"<run_handler %d\n", ret);
  return ret;
}
Пример #12
0
/** \brief 主函数
 *
 * 主启动函数。负责调用启动DLL的启动函数
 */
INT WINAPI WinMain(HINSTANCE currentInstance, HINSTANCE previousInstance, LPSTR pCommandLine, INT showType)
{
	INT exitCode = -1;

	/* 获得几个要加到Path的文件夹路径 */
	wchar_t binaryPath[MAX_PATH];
	wchar_t pathEnvironmentVariable[32767 /* http://msdn.microsoft.com/en-us/library/windows/desktop/ms683188.aspx */ ];
	std::wstring newPathEnvironmentVariable;

	// 当前exe路径
	GetModuleFileNameW(currentInstance, binaryPath, sizeof(binaryPath) / sizeof(binaryPath[0]));
	PathRemoveBlanksW(binaryPath);
	PathUnquoteSpacesW(binaryPath);
	PathRemoveBackslashW(binaryPath);

	// bin文件夹路径
	PathRemoveFileSpecW(binaryPath);
	PathAppendW(binaryPath, L"bin");

	// 拷贝到待增加路径字符串
	newPathEnvironmentVariable.append(binaryPath);

	// plugin文件夹路径
	PathRemoveFileSpecW(binaryPath);
	PathAppendW(binaryPath, L"plugin");

	// 拷贝到待增加路径字符串
	newPathEnvironmentVariable.append(L";");
	newPathEnvironmentVariable.append(binaryPath);

	/* 设置PATH环境变量 */
	// 获取环境变量
	pathEnvironmentVariable[0] = L'\0';
	DWORD length = GetEnvironmentVariableW(L"PATH", pathEnvironmentVariable, sizeof(pathEnvironmentVariable) / sizeof(pathEnvironmentVariable[0]));

	// 组合新环境变量
	if (length > 0)
		newPathEnvironmentVariable.append(L";");

	newPathEnvironmentVariable.append(pathEnvironmentVariable);

	// 拷贝回去
	wcscpy_s(pathEnvironmentVariable, newPathEnvironmentVariable.c_str());

	// 设置环境变量
	SetEnvironmentVariableW(L"PATH", pathEnvironmentVariable);

	/* 载入CRT的Dll,防止Dll冲突 */

	// 再次得到bin文件夹路径
	PathRemoveFileSpecW(binaryPath);
	PathAppendW(binaryPath, L"bin");

#ifdef _DEBUG
	PathAppendW(binaryPath, L"msvcr100d.dll");
	HMODULE msvcr100 = LoadLibraryW(binaryPath);

	PathRemoveFileSpecW(binaryPath);
	PathAppendW(binaryPath, L"msvcp100d.dll");
	HMODULE msvcp100 = LoadLibraryW(binaryPath);
#else
	PathAppendW(binaryPath, L"msvcr100.dll");
	HMODULE msvcr100 = LoadLibraryW(binaryPath);

	PathRemoveFileSpecW(binaryPath);
	PathAppendW(binaryPath, L"msvcp100.dll");
	HMODULE msvcp100 = LoadLibraryW(binaryPath);
#endif

	// 尝试载入YDWEStartup.dll
	HMODULE startupModule = LoadLibraryW(L"YDWEStartup.dll");
	if (startupModule)
	{
		TPFStartup pfStartup = (TPFStartup)GetProcAddress(startupModule, "YDWEStartup");
		if (pfStartup)
			exitCode = pfStartup(currentInstance, previousInstance, pCommandLine, showType);

		FreeLibrary(startupModule);
	}

	if (msvcp100)
		FreeLibrary(msvcp100);
	if (msvcr100)
		FreeLibrary(msvcr100);

	return exitCode;
}
Пример #13
0
BOOL
WINAPI
InitializeProfiles(VOID)
{
    WCHAR szProfilesPath[MAX_PATH];
    WCHAR szProfilePath[MAX_PATH];
    WCHAR szCommonFilesDirPath[MAX_PATH];
    WCHAR szBuffer[MAX_PATH];
    DWORD dwLength;
    PFOLDERDATA lpFolderData;
    HKEY hKey;
    LONG Error;

    DPRINT("InitializeProfiles()\n");

    /* Load profiles directory path */
    if (!LoadStringW(hInstance,
                     IDS_PROFILEPATH,
                     szBuffer,
                     MAX_PATH))
    {
        DPRINT1("Error: %lu\n", GetLastError());
        return FALSE;
    }

    Error = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
                          L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList",
                          0,
                          KEY_SET_VALUE,
                          &hKey);
    if (Error != ERROR_SUCCESS)
    {
        DPRINT1("Error: %lu\n", Error);
        SetLastError((DWORD)Error);
        return FALSE;
    }

    /* Expand it */
    if (!ExpandEnvironmentStringsW(szBuffer,
                                   szProfilesPath,
                                   MAX_PATH))
    {
        DPRINT1("Error: %lu\n", GetLastError());
        RegCloseKey(hKey);
        return FALSE;
    }

    /* Create profiles directory */
    if (!CreateDirectoryW(szProfilesPath, NULL))
    {
        if (GetLastError() != ERROR_ALREADY_EXISTS)
        {
            DPRINT1("Error: %lu\n", GetLastError());
            RegCloseKey(hKey);
            return FALSE;
        }
    }

    /* Store the profiles directory path in the registry */
    dwLength = (wcslen (szBuffer) + 1) * sizeof(WCHAR);
    Error = RegSetValueExW(hKey,
                           L"ProfilesDirectory",
                           0,
                           REG_EXPAND_SZ,
                           (LPBYTE)szBuffer,
                           dwLength);
    if (Error != ERROR_SUCCESS)
    {
        DPRINT1("Error: %lu\n", Error);
        RegCloseKey(hKey);
        SetLastError((DWORD)Error);
        return FALSE;
    }

    /* Set 'DefaultUserProfile' value */
    wcscpy(szBuffer, L"Default User");

    /* Create Default User profile directory path */
    wcscpy(szProfilePath, szProfilesPath);
    wcscat(szProfilePath, L"\\");
    wcscat(szProfilePath, szBuffer);

    /* Attempt default user directory creation */
    if (!CreateDirectoryW (szProfilePath, NULL))
    {
        if (GetLastError() != ERROR_ALREADY_EXISTS)
        {
            DPRINT1("Error: %lu\n", GetLastError());
            RegCloseKey(hKey);
            return FALSE;
        }

        /* Directory existed, let's try to append the postfix */
        if (!AppendSystemPostfix(szBuffer, MAX_PATH))
        {
            DPRINT1("AppendSystemPostfix() failed\n", GetLastError());
            RegCloseKey(hKey);
            return FALSE;
        }

        /* Create Default User profile directory path again */
        wcscpy(szProfilePath, szProfilesPath);
        wcscat(szProfilePath, L"\\");
        wcscat(szProfilePath, szBuffer);

        /* Attempt creation again with appended postfix */
        if (!CreateDirectoryW(szProfilePath, NULL))
        {
            if (GetLastError() != ERROR_ALREADY_EXISTS)
            {
                DPRINT1("Error: %lu\n", GetLastError());
                RegCloseKey(hKey);
                return FALSE;
            }
        }
    }

    /* Store the default user profile path in the registry */
    dwLength = (wcslen (szBuffer) + 1) * sizeof(WCHAR);
    Error = RegSetValueExW(hKey,
                           L"DefaultUserProfile",
                           0,
                           REG_SZ,
                           (LPBYTE)szBuffer,
                           dwLength);
    if (Error != ERROR_SUCCESS)
    {
        DPRINT1("Error: %lu\n", Error);
        RegCloseKey(hKey);
        SetLastError((DWORD)Error);
        return FALSE;
    }

    RegCloseKey(hKey);

    /* Set current user profile */
    SetEnvironmentVariableW(L"USERPROFILE", szProfilePath);

    /* Create 'Default User' subdirectories */
    /* FIXME: Get these paths from the registry */
    lpFolderData = &UserShellFolders[0];
    while (lpFolderData->lpValueName != NULL)
    {
        wcscpy(szBuffer, szProfilePath);
        wcscat(szBuffer, L"\\");

        /* Append the folder name */
        dwLength = wcslen(szBuffer);
        if (!LoadStringW(hInstance,
                         lpFolderData->uId,
                         &szBuffer[dwLength],
                         MAX_PATH - dwLength))
        {
            /* Use the default name instead */
            wcscat(szBuffer, lpFolderData->lpPath);
        }

        if (!CreateDirectoryW(szBuffer, NULL))
        {
            if (GetLastError() != ERROR_ALREADY_EXISTS)
            {
                DPRINT1("Error: %lu\n", GetLastError());
                return FALSE;
            }
        }

        if (lpFolderData->bHidden == TRUE)
        {
            SetFileAttributesW(szBuffer,
                               FILE_ATTRIBUTE_HIDDEN);
        }

        lpFolderData++;
    }

    /* Set default 'Shell Folders' values */
    Error = RegOpenKeyExW(HKEY_USERS,
                          L".Default\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders",
                          0,
                          KEY_SET_VALUE,
                          &hKey);
    if (Error != ERROR_SUCCESS)
    {
        DPRINT1("Error: %lu\n", Error);
        SetLastError((DWORD)Error);
        return FALSE;
    }

    lpFolderData = &UserShellFolders[0];
    while (lpFolderData->lpValueName != NULL)
    {
        if (lpFolderData->bShellFolder)
        {
            wcscpy(szBuffer, szProfilePath);
            wcscat(szBuffer, L"\\");

            /* Append the folder name */
            dwLength = wcslen(szBuffer);
            if (!LoadStringW(hInstance,
                             lpFolderData->uId,
                             &szBuffer[dwLength],
                             MAX_PATH - dwLength))
            {
                /* Use the default name instead */
                wcscat(szBuffer, lpFolderData->lpPath);
            }

            dwLength = (wcslen(szBuffer) + 1) * sizeof(WCHAR);
            Error = RegSetValueExW(hKey,
                                   lpFolderData->lpValueName,
                                   0,
                                   REG_SZ,
                                   (LPBYTE)szBuffer,
                                   dwLength);
            if (Error != ERROR_SUCCESS)
            {
                DPRINT1("Error: %lu\n", Error);
                RegCloseKey(hKey);
                SetLastError((DWORD)Error);
                return FALSE;
            }
        }

        lpFolderData++;
    }

    /* Set 'Fonts' folder path */
    GetWindowsDirectoryW(szBuffer, MAX_PATH);
    wcscat(szBuffer, L"\\fonts");

    dwLength = (wcslen(szBuffer) + 1) * sizeof(WCHAR);
    Error = RegSetValueExW(hKey,
                           L"Fonts",
                           0,
                           REG_SZ,
                           (LPBYTE)szBuffer,
                           dwLength);
    if (Error != ERROR_SUCCESS)
    {
        DPRINT1("Error: %lu\n", Error);
        RegCloseKey(hKey);
        SetLastError((DWORD)Error);
        return FALSE;
    }

    RegCloseKey(hKey);

    /* Set default 'User Shell Folders' values */
    Error = RegOpenKeyExW(HKEY_USERS,
                          L".Default\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders",
                          0,
                          KEY_SET_VALUE,
                          &hKey);
    if (Error != ERROR_SUCCESS)
    {
        DPRINT1("Error: %lu\n", Error);
        SetLastError((DWORD)Error);
        return FALSE;
    }

    lpFolderData = &UserShellFolders[0];
    while (lpFolderData->lpValueName != NULL)
    {
        if (lpFolderData->bUserShellFolder)
        {
            wcscpy(szBuffer, L"%USERPROFILE%\\");

            /* Append the folder name */
            dwLength = wcslen(szBuffer);
            if (!LoadStringW(hInstance,
                             lpFolderData->uId,
                             &szBuffer[dwLength],
                             MAX_PATH - dwLength))
            {
                /* Use the default name instead */
                wcscat(szBuffer, lpFolderData->lpPath);
            }

            dwLength = (wcslen(szBuffer) + 1) * sizeof(WCHAR);
            Error = RegSetValueExW(hKey,
                                   lpFolderData->lpValueName,
                                   0,
                                   REG_EXPAND_SZ,
                                   (LPBYTE)szBuffer,
                                   dwLength);
            if (Error != ERROR_SUCCESS)
            {
                DPRINT1("Error: %lu\n", Error);
                RegCloseKey(hKey);
                SetLastError((DWORD)Error);
                return FALSE;
            }
        }

        lpFolderData++;
    }

    RegCloseKey(hKey);

    /* Set 'AllUsersProfile' value */
    wcscpy(szBuffer, L"All Users");

    /* Create 'All Users' profile directory path */
    wcscpy(szProfilePath, szProfilesPath);
    wcscat(szProfilePath, L"\\");
    wcscat(szProfilePath, szBuffer);

    /* Attempt 'All Users' directory creation */
    if (!CreateDirectoryW (szProfilePath, NULL))
    {
        if (GetLastError() != ERROR_ALREADY_EXISTS)
        {
            DPRINT1("Error: %lu\n", GetLastError());
            return FALSE;
        }

        /* Directory existed, let's try to append the postfix */
        if (!AppendSystemPostfix(szBuffer, MAX_PATH))
        {
            DPRINT1("AppendSystemPostfix() failed\n", GetLastError());
            return FALSE;
        }

        /* Attempt again creation with appended postfix */
        wcscpy(szProfilePath, szProfilesPath);
        wcscat(szProfilePath, L"\\");
        wcscat(szProfilePath, szBuffer);

        if (!CreateDirectoryW(szProfilePath, NULL))
        {
            if (GetLastError() != ERROR_ALREADY_EXISTS)
            {
                DPRINT1("Error: %lu\n", GetLastError());
                return FALSE;
            }
        }
    }

    Error = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
                          L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList",
                          0,
                          KEY_SET_VALUE,
                          &hKey);
    if (Error != ERROR_SUCCESS)
    {
        DPRINT1("Error: %lu\n", Error);
        SetLastError((DWORD)Error);
        return FALSE;
    }

    dwLength = (wcslen(szBuffer) + 1) * sizeof(WCHAR);
    Error = RegSetValueExW(hKey,
                           L"AllUsersProfile",
                           0,
                           REG_SZ,
                           (LPBYTE)szBuffer,
                           dwLength);

    RegCloseKey(hKey);

    if (Error != ERROR_SUCCESS)
    {
        DPRINT1("Error: %lu\n", Error);
        SetLastError((DWORD)Error);
        return FALSE;
    }

    /* Set 'All Users' profile */
    SetEnvironmentVariableW(L"ALLUSERSPROFILE", szProfilePath);

    /* Create 'All Users' subdirectories */
    /* FIXME: Take these paths from the registry */
    lpFolderData = &CommonShellFolders[0];
    while (lpFolderData->lpValueName != NULL)
    {
        wcscpy(szBuffer, szProfilePath);
        wcscat(szBuffer, L"\\");

        /* Append the folder name */
        dwLength = wcslen(szBuffer);
        if (!LoadStringW(hInstance,
                         lpFolderData->uId,
                         &szBuffer[dwLength],
                         MAX_PATH - dwLength))
        {
            /* Use the default name instead */
            wcscat(szBuffer, lpFolderData->lpPath);
        }

        if (!CreateDirectoryW(szBuffer, NULL))
        {
            if (GetLastError() != ERROR_ALREADY_EXISTS)
            {
                DPRINT1("Error: %lu\n", GetLastError());
                return FALSE;
            }
        }

        if (lpFolderData->bHidden)
        {
            SetFileAttributesW(szBuffer,
                               FILE_ATTRIBUTE_HIDDEN);
        }

        lpFolderData++;
    }

    /* Set common 'Shell Folders' values */
    Error = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
                          L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders",
                          0,
                          KEY_SET_VALUE,
                          &hKey);
    if (Error != ERROR_SUCCESS)
    {
        DPRINT1("Error: %lu\n", Error);
        SetLastError((DWORD)Error);
        return FALSE;
    }

    lpFolderData = &CommonShellFolders[0];
    while (lpFolderData->lpValueName != NULL)
    {
        if (lpFolderData->bShellFolder)
        {
            wcscpy(szBuffer, szProfilePath);
            wcscat(szBuffer, L"\\");

            /* Append the folder name */
            dwLength = wcslen(szBuffer);
            if (!LoadStringW(hInstance,
                             lpFolderData->uId,
                             &szBuffer[dwLength],
                             MAX_PATH - dwLength))
            {
                /* Use the default name instead */
                wcscat(szBuffer, lpFolderData->lpPath);
            }

            dwLength = (wcslen(szBuffer) + 1) * sizeof(WCHAR);
            Error = RegSetValueExW(hKey,
                                   lpFolderData->lpValueName,
                                   0,
                                   REG_SZ,
                                   (LPBYTE)szBuffer,
                                   dwLength);
            if (Error != ERROR_SUCCESS)
            {
                DPRINT1("Error: %lu\n", Error);
                RegCloseKey(hKey);
                SetLastError((DWORD)Error);
                return FALSE;
            }
        }

        lpFolderData++;
    }

    RegCloseKey(hKey);

    /* Set common 'User Shell Folders' values */
    Error = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
                          L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders",
                          0,
                          KEY_SET_VALUE,
                          &hKey);
    if (Error != ERROR_SUCCESS)
    {
        DPRINT1("Error: %lu\n", Error);
        SetLastError((DWORD)Error);
        return FALSE;
    }

    lpFolderData = &CommonShellFolders[0];
    while (lpFolderData->lpValueName != NULL)
    {
        if (lpFolderData->bUserShellFolder)
        {
            wcscpy(szBuffer, L"%ALLUSERSPROFILE%\\");

            /* Append the folder name */
            dwLength = wcslen(szBuffer);
            if (!LoadStringW(hInstance,
                             lpFolderData->uId,
                             &szBuffer[dwLength],
                             MAX_PATH - dwLength))
            {
                /* Use the default name instead */
                wcscat(szBuffer, lpFolderData->lpPath);
            }

            dwLength = (wcslen(szBuffer) + 1) * sizeof(WCHAR);
            Error = RegSetValueExW(hKey,
                                   lpFolderData->lpValueName,
                                   0,
                                   REG_EXPAND_SZ,
                                   (LPBYTE)szBuffer,
                                   dwLength);
            if (Error != ERROR_SUCCESS)
            {
                DPRINT1("Error: %lu\n", Error);
                RegCloseKey(hKey);
                SetLastError((DWORD)Error);
                return FALSE;
            }
        }

        lpFolderData++;
    }

    RegCloseKey(hKey);

    /* Load 'Program Files' location */
    if (!LoadStringW(hInstance,
                     IDS_PROGRAMFILES,
                     szBuffer,
                     MAX_PATH))
    {
        DPRINT1("Error: %lu\n", GetLastError());
        return FALSE;
    }

    if (!LoadStringW(hInstance,
                     IDS_COMMONFILES,
                     szCommonFilesDirPath,
                     MAX_PATH))
    {
        DPRINT1("Warning: %lu\n", GetLastError());
    }

    /* Expand it */
    if (!ExpandEnvironmentStringsW(szBuffer,
                                   szProfilesPath,
                                   MAX_PATH))
    {
        DPRINT1("Error: %lu\n", GetLastError());
        return FALSE;
    }

    wcscpy(szBuffer, szProfilesPath);
    wcscat(szBuffer, L"\\");
    wcscat(szBuffer, szCommonFilesDirPath);

    if (!ExpandEnvironmentStringsW(szBuffer,
                                  szCommonFilesDirPath,
                                  MAX_PATH))
    {
        DPRINT1("Warning: %lu\n", GetLastError());
    }

    /* Store it */
    Error = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
                          L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion",
                          0,
                          KEY_SET_VALUE,
                          &hKey);
    if (Error != ERROR_SUCCESS)
    {
        DPRINT1("Error: %lu\n", Error);
        SetLastError((DWORD)Error);
        return FALSE;
    }

    dwLength = (wcslen (szProfilesPath) + 1) * sizeof(WCHAR);
    Error = RegSetValueExW(hKey,
                           L"ProgramFilesDir",
                           0,
                           REG_SZ,
                           (LPBYTE)szProfilesPath,
                           dwLength);
    if (Error != ERROR_SUCCESS)
    {
        DPRINT1("Error: %lu\n", Error);
        RegCloseKey(hKey);
        SetLastError((DWORD)Error);
        return FALSE;
    }

    dwLength = (wcslen(szCommonFilesDirPath) + 1) * sizeof(WCHAR);
    Error = RegSetValueExW(hKey,
                           L"CommonFilesDir",
                           0,
                           REG_SZ,
                           (LPBYTE)szCommonFilesDirPath,
                           dwLength);
    if (Error != ERROR_SUCCESS)
    {
        DPRINT1("Warning: %lu\n", Error);
    }

    RegCloseKey (hKey);

    /* Create directory */
    if (!CreateDirectoryW(szProfilesPath, NULL))
    {
        if (GetLastError () != ERROR_ALREADY_EXISTS)
        {
            DPRINT1("Error: %lu\n", GetLastError());
            return FALSE;
        }
    }

    /* Create directory */
    if (!CreateDirectoryW(szCommonFilesDirPath, NULL))
    {
        if (GetLastError () != ERROR_ALREADY_EXISTS)
        {
            DPRINT1("Warning: %lu\n", GetLastError());
        }
    }

    DPRINT("Success\n");

    return TRUE;
}
Пример #14
0
static int os_setenv (lua_State *L) {
  const char *name = luaL_checkstring(L, 1);
  const char *value;
  wchar_t *utf16_name;
  wchar_t *utf16_value;
  int error, result;
  
  if(name[0] == 0){
    /* nothing to do */
    lua_pushboolean(L, 1);
    return 1;
  }

  if(lua_isnoneornil(L, 2)){
    value = "";
  } else {
    value = luaL_checkstring(L, 2);
  }
  
  utf16_name = convert_to_utf16(name,&error);
  if(utf16_name == NULL){
    if(error == ERROR_COMMITMENT_LIMIT || error == ERROR_NOT_ENOUGH_MEMORY){
      return luaL_error(L, "not enough memory");
    } else {
      return luaL_error(L, "unable to convert %s to "
        "utf-16: error code = 0x%p", name, (void *)(ULONG_PTR)error);
    }
  }
  utf16_value = convert_to_utf16(value,&error);
  if(utf16_value == NULL){
    free(utf16_name);
    if(error == ERROR_COMMITMENT_LIMIT || error == ERROR_NOT_ENOUGH_MEMORY){
      return luaL_error(L, "not enough memory");
    } else {
      return luaL_error(L, "unable to convert %s to "
        "utf-16: error code = 0x%p", value, (void *)(ULONG_PTR)error);
    }
  }

  /*
  * Being mixed with SetEnvironmentVariable
  * calls _wputenv might cause an application
  * crash (confirmed on XP SP2 x86):
  * _wputenv(L"TEST=Hello");
  * SetEnvironmentVariableW(L"TEST",NULL);
  * _wputenv(L"TEST=");
  */
  if(utf16_value[0] != 0)
    result = SetEnvironmentVariableW(utf16_name,utf16_value);
  else
    result = SetEnvironmentVariableW(utf16_name,NULL);
  error = GetLastError();
  free(utf16_name);
  free(utf16_value);
  if(result == 0 && error != ERROR_ENVVAR_NOT_FOUND){
    return luaL_error(L, "SetEnvironmentVariableW "
      "failed: error code = 0x%p", (void *)(ULONG_PTR)error);
  }
  lua_pushboolean(L, 1);
  return 1;
}
Пример #15
0
bool StartupMiniPosixEnv(LauncherStructure &config)
{
  SetCurrentDirectoryW(config.root.c_str());
  if(config.clearEnvironment){
    ClearEnvironmentVariableW();
  }
  SetEnvironmentVariableW(L"MSYSTEM",config.env.c_str());
  SetEnvironmentVariableW(L"WD",config.wd.c_str());
  SetEnvironmentVariableW(L"MSYSCON",L"mintty.exe");

  if(!config.appendPath.empty()){
    PutPathEnvironmentVariableW(config.appendPath);
  }

  PROCESS_INFORMATION pi;
  STARTUPINFO si;
  ZeroMemory(&si, sizeof(si));
  si.cb = sizeof(si);
  si.dwFlags = STARTF_USESHOWWINDOW;
  si.wShowWindow = SW_SHOW;

  int const ArraySize=8192;
  wchar_t cmdline[ArraySize]={0};
  auto hr=StringCchCatW(cmdline,ArraySize,config.mintty.c_str());
  StringCchCatW(cmdline,ArraySize,L" -i ");
  StringCchCatW(cmdline,ArraySize,config.icon.c_str());
  StringCchCatW(cmdline,ArraySize,L" /usr/bin/");
  if(config.enableZshell){
      StringCchCatW(cmdline,ArraySize,L"zsh --login ");
  }else{
      StringCchCatW(cmdline,ArraySize,config.otherShell.c_str());
      StringCchCatW(cmdline,ArraySize,L" --login ");
  }
//   auto hr=StringCchPrintfW(cmdline,ArraySize,L"%s -i%s /usr/bin/%s --login ",
//   config.mintty.c_str(),
//   config.icon.c_str(),
//   config.enableZshell?L"zsh":config.otherShell.c_str());
  if(hr!=S_OK){
      MessageBoxW(nullptr,L"Please check your profile !",L"Parse commandline failed !",MB_OK|MB_ICONERROR);
      return false;
  }
  if(!config.shellArgs.empty()){
      StringCchCatW(cmdline,ArraySize,config.shellArgs.c_str());  
  }
  ///CreateProcess
  BOOL result = CreateProcessW(
    NULL,
    cmdline,
    NULL,
    NULL,
    TRUE,
    CREATE_NEW_CONSOLE,
    NULL,
    NULL,
    &si,
    &pi
    );
  if(result){
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
  }
  return true;
}
Пример #16
0
UINT __stdcall InstallPythonAPI(MSIHANDLE hModule)
{
    logStringW(hModule, L"InstallPythonAPI: Checking for installed Python environment ...");

    HKEY hkPythonCore = NULL;
    BOOL bFound = FALSE;
    LONG rc = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Python\\PythonCore", 0, KEY_READ, &hkPythonCore);
    if (rc != ERROR_SUCCESS)
    {
        logStringW(hModule, L"InstallPythonAPI: Python seems not to be installed.");
        return ERROR_SUCCESS;
    }

    WCHAR wszPath[MAX_PATH] = { 0 };
    WCHAR wszVal[MAX_PATH] = { 0 };

    for (int i = 0;; ++i)
    {
        WCHAR wszRoot[MAX_PATH] = { 0 };
        DWORD dwLen = sizeof(wszPath);
        DWORD dwKeyType = REG_SZ;

        rc = RegEnumKeyExW(hkPythonCore, i, wszRoot, &dwLen, NULL, NULL, NULL, NULL);
        if (rc != ERROR_SUCCESS || dwLen <= 0)
            break;

        swprintf_s(wszPath, RT_ELEMENTS(wszPath), L"%s\\InstallPath", wszRoot);
        dwLen = sizeof(wszVal);

        HKEY hkPythonInstPath = NULL;
        rc = RegOpenKeyExW(hkPythonCore, wszPath, 0, KEY_READ,  &hkPythonInstPath);
        if (rc != ERROR_SUCCESS)
            continue;

        rc = RegQueryValueExW(hkPythonInstPath, L"", NULL, &dwKeyType, (LPBYTE)wszVal, &dwLen);
        if (rc == ERROR_SUCCESS)
            logStringW(hModule, L"InstallPythonAPI: Path \"%s\" detected.", wszVal);

        RegCloseKey(hkPythonInstPath);
    }
    RegCloseKey(hkPythonCore);

    /* Python path found? */
    WCHAR wszExec[MAX_PATH] = { 0 };
    WCHAR wszCmdLine[MAX_PATH] = { 0 };
    DWORD dwExitCode = 0;
    if (wcslen(wszVal) > 0)
    {
        /* Cool, check for installed Win32 extensions. */
        logStringW(hModule, L"InstallPythonAPI: Python installed. Checking for Win32 extensions ...");
        swprintf_s(wszExec, RT_ELEMENTS(wszExec), L"%s\\python.exe", wszVal);
        swprintf_s(wszCmdLine, RT_ELEMENTS(wszCmdLine), L"%s\\python.exe -c \"import win32api\"", wszVal);

        DWORD dwRetExec = Exec(hModule, wszExec, wszCmdLine, NULL, &dwExitCode);
        if (   (ERROR_SUCCESS == dwRetExec)
            && (            0 == dwExitCode))
        {
            /* Did we get the correct error level (=0)? */
            logStringW(hModule, L"InstallPythonAPI: Win32 extensions installed.");
            bFound = TRUE;
        }
        else
            logStringW(hModule, L"InstallPythonAPI: Win32 extensions not found.");
    }

    BOOL bInstalled = FALSE;
    if (bFound) /* Is Python and all required stuff installed? */
    {
        /* Get the VBoxAPI setup string. */
        WCHAR wszPathTargetDir[MAX_PATH] = {0};
        VBoxGetProperty(hModule, L"CustomActionData", wszPathTargetDir, sizeof(wszPathTargetDir));
        if (wcslen(wszPathTargetDir))
        {
            /* Set final path. */
            swprintf_s(wszPath, RT_ELEMENTS(wszPath), L"%s", wszPathTargetDir);

            /* Install our API module. */
            swprintf_s(wszCmdLine, RT_ELEMENTS(wszCmdLine), L"%s\\python.exe vboxapisetup.py install", wszVal);

            /* Set required environment variables. */
            if (!SetEnvironmentVariableW(L"VBOX_INSTALL_PATH", wszPathTargetDir))
                logStringW(hModule, L"InstallPythonAPI: Could set environment variable VBOX_INSTALL_PATH!");
            else
            {
                DWORD dwRetExec = Exec(hModule, wszExec, wszCmdLine, wszPath, &dwExitCode);
                if (   (ERROR_SUCCESS == dwRetExec)
                    && (            0 == dwExitCode))
                {
                    /* All done! */
                    logStringW(hModule, L"InstallPythonAPI: VBoxAPI for Python successfully installed.");
                    bInstalled = TRUE;
                }
                else
                {
                    if (dwRetExec)
                        logStringW(hModule, L"InstallPythonAPI: Error while executing installation of VBox API: %ld", dwRetExec);
                    else
                        logStringW(hModule, L"InstallPythonAPI: Python reported an error while installing VBox API: %ld", dwExitCode);
                }
            }
        }
        else
            logStringW(hModule, L"InstallPythonAPI: Unable to retrieve VBox installation path!");
    }

    VBoxSetProperty(hModule, L"VBOX_PYTHON_IS_INSTALLED", bInstalled ? L"1" : L"0");

    if (!bInstalled)
        logStringW(hModule, L"InstallPythonAPI: VBox API not installed.");
    return ERROR_SUCCESS; /* Do not fail here. */
}
Пример #17
0
int __cdecl main(int argc, char *argv[]) 
{

#if WIN32

    /* Define some buffers needed for the function */
    WCHAR * pResultBuffer = NULL;

    WCHAR FirstEnvironmentVariable[] = {'P','A','L','T','E','S','T','\0'};
    WCHAR FirstEnvironmentValue[] = {'F','I','R','S','T','\0'};

    WCHAR ModifiedEnvironmentVariable[] = {'p','a','l','t','e','s','t','\0'};

    DWORD  size = 0;
    BOOL bRc = TRUE;

    /*
     * Initialize the PAL and return FAILURE if this fails
     */

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }
  
    /* Set the first environment variable */
    bRc = SetEnvironmentVariableW(FirstEnvironmentVariable,
                            FirstEnvironmentValue);

    if(!bRc)
    {
        Fail("ERROR: SetEnvironmentVariable failed to set a "
            "proper environment variable with error %u.\n",
            GetLastError());
    }

    /* Normal case, PATH should fit into this buffer */
    size = GetEnvironmentVariableW(ModifiedEnvironmentVariable,        
                                  pResultBuffer,    
                                  0);                 

    /* To account for the nul character at the end of the string */
    size = size + 1;
    
    pResultBuffer = malloc(sizeof(WCHAR)*size);
    if ( pResultBuffer == NULL )
    {
        Fail("ERROR: Failed to allocate memory for pResultBuffer pointer.\n");
    }

    /* Try to retrieve the value of the first environment variable */
    GetEnvironmentVariableW(ModifiedEnvironmentVariable,
                           pResultBuffer,
                           size);

    if ( pResultBuffer == NULL )
    {
        Fail("ERROR: GetEnvironmentVariable failed to return a value "
            "from a proper environment variable with error %u.\n",
            GetLastError());
    }

    /* Compare the strings to see that the correct variable was returned */
    if(wcsncmp(pResultBuffer,FirstEnvironmentValue,wcslen(pResultBuffer)) != 0)
    {
        Trace("ERROR: The value in the buffer should have been '%S' but "
             "was really '%S'.\n",FirstEnvironmentValue, pResultBuffer);
        free(pResultBuffer);
        Fail("");
    }

    free(pResultBuffer);
  
    PAL_Terminate();
    return PASS;


#else

    return PASS;
#endif
}
Пример #18
0
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
		    PWSTR szCmdLine, int iCmdShow)
{
    int argc = __argc;
    wchar_t **argv = __wargv;
#else
#define WERL 0
int wmain(int argc, wchar_t **argv)
{
#endif
  HANDLE erlexec_handle; /* Instance */
  ErlexecFunction *win_erlexec;
  wchar_t *path = malloc(100*sizeof(wchar_t));
  wchar_t *npath;
  int pathlen;
  char ** utf8argv;
  int i, len;

  get_parameters();

  if ((pathlen = GetEnvironmentVariableW(L"PATH",path,100)) == 0) {
    error("No PATH variable (!)");
  } else if (pathlen > 100) {
    path = realloc(path,pathlen*sizeof(wchar_t));
    GetEnvironmentVariableW(L"PATH",path,pathlen);
  }
  pathlen = (wcslen(path) + wcslen(erlexec_dir) + 2);
  npath = (wchar_t *) malloc(pathlen*sizeof(wchar_t));
  swprintf(npath,pathlen,L"%s;%s",erlexec_dir,path);
  SetEnvironmentVariableW(L"PATH",npath);

  if ((erlexec_handle = LoadLibraryW(erlexec_name)) == NULL) {
    error("Could not load module %S.",erlexec_name);
  }

  if ((win_erlexec = (ErlexecFunction *) 
       GetProcAddress(erlexec_handle,"win_erlexec")) == NULL) {
    error("Could not find entry point \"win_erlexec\" in %S.", erlexec_name);
  }

  /* Convert argv to utf8 */
  utf8argv = malloc((argc+1) * sizeof(char*));
  for (i=0; i<argc; i++) {
      len = WideCharToMultiByte(CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL);
      utf8argv[i] = malloc(len*sizeof(char));
      WideCharToMultiByte(CP_UTF8, 0, argv[i], -1, utf8argv[i], len, NULL, NULL);
  }
  utf8argv[argc] = NULL;

#ifdef HARDDEBUG
	{
	    wchar_t tempbuf[2048] = L"";
	    wchar_t *sbuf;
	    int i;
	    sbuf=tempbuf;
	    sbuf += swprintf(sbuf, 2048, L"utf16: %d\n", argc);
	    for (i = 0; i < argc; ++i) {
		sbuf += swprintf(sbuf, 2048, L"|%s|", argv[i]);
	    };
	    sbuf += swprintf(sbuf, 2048, L"\nutf8: \n");
	    for (i = 0; i < argc; ++i) {
		sbuf += swprintf(sbuf, 2048, L"|%S|", utf8argv[i]);
	    };
	    MessageBoxW(NULL, tempbuf, L"erl_exec args", MB_OK|MB_ICONERROR);
	}
#endif

  return (*win_erlexec)(argc,utf8argv,erlexec_handle,WERL);
  
} 
Пример #19
0
Файл: util.c Проект: 5y/node
int uv_chdir(const char* dir) {
  WCHAR utf16_buffer[MAX_PATH];
  size_t utf16_len;
  WCHAR drive_letter, env_var[4];

  if (dir == NULL) {
    return UV_EINVAL;
  }

  if (MultiByteToWideChar(CP_UTF8,
                          0,
                          dir,
                          -1,
                          utf16_buffer,
                          MAX_PATH) == 0) {
    DWORD error = GetLastError();
    /* The maximum length of the current working directory is 260 chars, */
    /* including terminating null. If it doesn't fit, the path name must be */
    /* too long. */
    if (error == ERROR_INSUFFICIENT_BUFFER) {
      return UV_ENAMETOOLONG;
    } else {
      return uv_translate_sys_error(error);
    }
  }

  if (!SetCurrentDirectoryW(utf16_buffer)) {
    return uv_translate_sys_error(GetLastError());
  }

  /* Windows stores the drive-local path in an "hidden" environment variable, */
  /* which has the form "=C:=C:\Windows". SetCurrentDirectory does not */
  /* update this, so we'll have to do it. */
  utf16_len = GetCurrentDirectoryW(MAX_PATH, utf16_buffer);
  if (utf16_len == 0) {
    return uv_translate_sys_error(GetLastError());
  } else if (utf16_len > MAX_PATH) {
    return UV_EIO;
  }

  /* The returned directory should not have a trailing slash, unless it */
  /* points at a drive root, like c:\. Remove it if needed. */
  if (utf16_buffer[utf16_len - 1] == L'\\' &&
      !(utf16_len == 3 && utf16_buffer[1] == L':')) {
    utf16_len--;
    utf16_buffer[utf16_len] = L'\0';
  }

  if (utf16_len < 2 || utf16_buffer[1] != L':') {
    /* Doesn't look like a drive letter could be there - probably an UNC */
    /* path. TODO: Need to handle win32 namespaces like \\?\C:\ ? */
    drive_letter = 0;
  } else if (utf16_buffer[0] >= L'A' && utf16_buffer[0] <= L'Z') {
    drive_letter = utf16_buffer[0];
  } else if (utf16_buffer[0] >= L'a' && utf16_buffer[0] <= L'z') {
    /* Convert to uppercase. */
    drive_letter = utf16_buffer[0] - L'a' + L'A';
  } else {
    /* Not valid. */
    drive_letter = 0;
  }

  if (drive_letter != 0) {
    /* Construct the environment variable name and set it. */
    env_var[0] = L'=';
    env_var[1] = drive_letter;
    env_var[2] = L':';
    env_var[3] = L'\0';

    if (!SetEnvironmentVariableW(env_var, utf16_buffer)) {
      return uv_translate_sys_error(GetLastError());
    }
  }

  return 0;
}
Пример #20
0
/**
 * \fn int CEnvironment::win32_setenv(const std::wstring &name, const std::wstring &value = L"",
 *     updateAction action = autoDetect)
 * \brief Internal function used to manipulate with environment variables on win32.
 *
 * This function make all dirty work with setting, deleting and modifying environment variables.
 *
 * \param name   The environment variable name.
 * \param value  (optional) the new value of environment variable.
 * \param action (optional) the action.
 * \return Zero on success, 2 if at least one external runtime update failed, 4 if process
 * 		   environment update failed, 8 if our runtime environment update failed or, in case of
 * 		   several errors, sum of all errors values; non-zero in case of other errors.
 */
int CEnvironment::win32_setenv(const std::string &name, const std::string &value /* = "" */, enum updateAction action /* = autoDetect */)
{
  std::wstring Wname (win32ConvertUtf8ToW(name));
  if (Wname.empty() || name.find('=') != std::wstring::npos)
    return -1;
  if ( (action == addOnly || action == addOrUpdateOnly) && value.empty() )
    return -1;
  if (action == addOnly && !(getenv(name).empty()) )
    return 0;

  bool convIsOK;
  std::wstring Wvalue (win32ConvertUtf8ToW(value,&convIsOK));
  if (!convIsOK)
    return -1;

  int retValue = 0;
  std::wstring EnvString;
  if (action == deleteVariable)
    EnvString = Wname + L"=";
  else
    EnvString = Wname + L"=" + Wvalue;

  static const wchar_t *modulesList[] =
  {
  /*{ L"msvcrt20.dll" }, // Visual C++ 2.0 / 2.1 / 2.2
    { L"msvcrt40.dll" }, // Visual C++ 4.0 / 4.1 */ // too old and no UNICODE support - ignoring
    { L"msvcrt.dll" },   // Visual Studio 6.0 / MinGW[-w64]
    { L"msvcr70.dll" },  // Visual Studio 2002
    { L"msvcr71.dll" },  // Visual Studio 2003
    { L"msvcr80.dll" },  // Visual Studio 2005
    { L"msvcr90.dll" },  // Visual Studio 2008
    { L"msvcr100.dll" }, // Visual Studio 2010
#ifdef _DEBUG
    { L"msvcr100d.dll" },// Visual Studio 2010 (debug)
#endif
    { L"msvcr110.dll" }, // Visual Studio 2012
#ifdef _DEBUG
    { L"msvcr110d.dll" },// Visual Studio 2012 (debug)
#endif
    { L"msvcr120.dll" }, // Visual Studio 2013
#ifdef _DEBUG
    { L"msvcr120d.dll" },// Visual Studio 2013 (debug)
#endif
    { L"vcruntime140.dll" },
    { L"ucrtbase.dll" },
#ifdef _DEBUG
    { L"vcruntime140d.dll" },
    { L"ucrtbased.dll" },
#endif
    { NULL }             // Terminating NULL for list
  };

  // Check all modules each function run, because modules can be loaded/unloaded at runtime
  for (int i = 0; modulesList[i]; i++)
  {
    HMODULE hModule;
    if (!GetModuleHandleExW(0, modulesList[i], &hModule) || hModule == NULL) // Flag 0 ensures that module will be kept loaded until it'll be freed
      continue; // Module not loaded

    wputenvPtr wputenvFunc = (wputenvPtr) GetProcAddress(hModule, "_wputenv");
    if (wputenvFunc != NULL && wputenvFunc(EnvString.c_str()) != 0)
      retValue |= 2; // At lest one external runtime library Environment update failed
    FreeLibrary(hModule);
  }

  // Update process Environment used for current process and for future new child processes
  if (action == deleteVariable || value.empty())
    retValue += SetEnvironmentVariableW(Wname.c_str(), NULL) ? 0 : 4; // 4 if failed
  else
    retValue += SetEnvironmentVariableW(Wname.c_str(), Wvalue.c_str()) ? 0 : 4; // 4 if failed

  // Finally update our runtime Environment
  retValue += (::_wputenv(EnvString.c_str()) == 0) ? 0 : 8; // 8 if failed

  return retValue;
}
Пример #21
0
static void test_GetSetEnvironmentVariableW(void)
{
    WCHAR buf[256];
    BOOL ret;
    DWORD ret_size;
    static const WCHAR name[] = {'S','o','m','e','W','i','l','d','N','a','m','e',0};
    static const WCHAR value[] = {'S','o','m','e','W','i','l','d','V','a','l','u','e',0};
    static const WCHAR name_cased[] = {'s','O','M','E','w','I','L','D','n','A','M','E',0};
    static const WCHAR empty_strW[] = { 0 };
    static const WCHAR fooW[] = {'f','o','o',0};

    ret = SetEnvironmentVariableW(name, value);
    if (ret == FALSE && GetLastError()==ERROR_CALL_NOT_IMPLEMENTED)
    {
        /* Must be Win9x which doesn't support the Unicode functions */
        win_skip("SetEnvironmentVariableW is not implemented\n");
        return;
    }
    ok(ret == TRUE,
       "unexpected error in SetEnvironmentVariableW, GetLastError=%d\n",
       GetLastError());

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

    lstrcpyW(buf, fooW);
    ret_size = GetEnvironmentVariableW(name, buf, lstrlenW(value));
    ok_w(lstrcmpW(buf, fooW) == 0 ||
         lstrlenW(buf) == 0, /* Vista */
         "Expected untouched or empty buffer, got \"%s\"\n", buf);

    ok(ret_size == lstrlenW(value) + 1,
       "should return length with terminating 0 ret_size=%d\n", ret_size);

    lstrcpyW(buf, fooW);
    ret_size = GetEnvironmentVariableW(name, buf, lstrlenW(value) + 1);
    ok(lstrcmpW(buf, value) == 0, "should touch the buffer\n");
    ok(ret_size == lstrlenW(value),
       "should return length without terminating 0 ret_size=%d\n", ret_size);

    lstrcpyW(buf, fooW);
    ret_size = GetEnvironmentVariableW(name_cased, buf, lstrlenW(value) + 1);
    ok(lstrcmpW(buf, value) == 0, "should touch the buffer\n");
    ok(ret_size == lstrlenW(value),
       "should return length without terminating 0 ret_size=%d\n", ret_size);

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

    lstrcpyW(buf, fooW);
    ret_size = GetEnvironmentVariableW(name, buf, lstrlenW(value) + 1);
    ok(lstrcmpW(buf, fooW) == 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 SetEnvironmentVariableW(name, "") */
    ret = SetEnvironmentVariableW(name, value);
    ok(ret == TRUE,
       "unexpected error in SetEnvironmentVariableW, GetLastError=%d\n",
       GetLastError());

    lstrcpyW(buf, fooW);
    ret_size = GetEnvironmentVariableW(name, buf, lstrlenW(value) + 1);
    ok(lstrcmpW(buf, value) == 0, "should touch the buffer\n");
    ok(ret_size == lstrlenW(value),
       "should return length without terminating 0 ret_size=%d\n", ret_size);

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

    lstrcpyW(buf, fooW);
    ret_size = GetEnvironmentVariableW(name, buf, lstrlenW(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());
    ok(lstrcmpW(buf, empty_strW) == 0, "should copy an empty string\n");

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

    if (0) /* Both tests crash on Vista */
    {
        ret_size = GetEnvironmentVariableW(NULL, buf, lstrlenW(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());

        ret = SetEnvironmentVariableW(NULL, NULL);
        ok(ret == FALSE && (GetLastError() == ERROR_INVALID_PARAMETER || GetLastError() == ERROR_ENVVAR_NOT_FOUND),
           "should fail with NULL, NULL but ret=%d and GetLastError=%d\n",
           ret, GetLastError());
    }
}
Пример #22
0
char *GetHomeDirFromToken(char *userName, HANDLE token)
{
  UCHAR domain[200];
  wchar_t pw_buf[MAX_PATH] = { L'\0' };
  
  debug("-> GetHomeDirFromToken()...");
  
  PROFILEINFO profileInfo;

  // find the server name of the domain controller which created this token
  GetDomainFromToken ( &token, domain, sizeof(domain));
  //if (MultiByteToWideChar(CP_UTF8, 0, domain, -1, domainW, sizeof(domainW)) == 0)
  //{
    //debug("DomainServerName encoding conversion failure");
    //return NULL;
  //}

  profileInfo.dwFlags = PI_NOUI;
  profileInfo.lpProfilePath = NULL;
  profileInfo.lpUserName = userName;
  profileInfo.lpDefaultPath = NULL;
  profileInfo.lpServerName = domain;
  profileInfo.lpPolicyPath = NULL;
  profileInfo.hProfile = NULL;
  profileInfo.dwSize = sizeof(profileInfo);


  
  if (LoadUserProfile(token, &profileInfo) == FALSE)
  {
    debug("<- GetHomeDirFromToken()...");
    debug("LoadUserProfile failure: %d", GetLastError());
    
    return NULL;
  }

  /*
   * And retrieve homedir from profile.
   */
        
  if (!SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PROFILE, token, 0, pw_homedir)))
  {
    debug("<- GetHomeDirFromToken()...");
    debug("SHGetFolderPath failed");
    
    return NULL;
  }

  // update APPDATA user's env variable
  if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_APPDATA, token, 0, pw_buf)))
  {
	  SetEnvironmentVariableW(L"APPDATA", pw_buf);
  }

  // update LOCALAPPDATA user's env variable
  if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA, token, 0, pw_buf)))
  {
	  SetEnvironmentVariableW(L"LOCALAPPDATA", pw_buf);
  }

  /*
   * Unload user profile.
   */
       
  if (UnloadUserProfile(token, profileInfo.hProfile) == FALSE)
  {
    debug("WARNING. Cannot unload user profile (%u).", GetLastError());
  }
  
  debug("<- GetHomeDirFromToken()...");
  
  return pw_homedir;
}