// qgetenv doesn't handle environment variables containing Unicode // characters very well. Breakpad-for-Windows works exclusively with // Unicode paths anyway, so we use the native API to retrieve %TEMP% // as Unicode. This code based upon qglobal.cpp::qgetenv. static QString q_wgetenv(const wchar_t *varName) { size_t requiredSize; _wgetenv_s(&requiredSize, 0, 0, varName); if (requiredSize == 0 || requiredSize > size_t(INT_MAX / sizeof(wchar_t))) return QString(); // Unfortunately it does not appear to be safe to pass QString::data() // to a Windows API that expects wchar_t*. QChar is too different. // We have to employ a scratch buffer. Limiting the length to // INT_MAX / sizeof(wchar_t), above, ensures that the multiplication // here cannot overflow. wchar_t *buffer = (wchar_t *)malloc(requiredSize * sizeof(wchar_t)); if (!buffer) return QString(); // requiredSize includes the terminating null, which we don't want. // The range-check above also ensures that the conversion to int here // does not overflow. _wgetenv_s(&requiredSize, buffer, requiredSize, varName); Q_ASSERT(buffer[requiredSize-1] == L'\0'); QString ret = QString::fromWCharArray(buffer, int(requiredSize - 1)); free(buffer); return ret; }
void os_init() { __pfnDliNotifyHook2 = delayHook; __cpuid(cpuinfo, 1); #define MMXSSE 0x02800000 if ((cpuinfo[3] & MMXSSE) != MMXSSE) { ::MessageBoxA(NULL, "Mumble requires a SSE capable processor (Pentium 3 / Ahtlon-XP)", "Mumble", MB_OK | MB_ICONERROR); exit(0); } unsigned int currentControl = 0; _controlfp_s(¤tControl, _DN_FLUSH, _MCW_DN); mumble_speex_init(); #ifdef QT_NO_DEBUG #ifdef COMPAT_CLIENT errno_t res = 0; size_t reqSize, bSize; _wgetenv_s(&reqSize, NULL, 0, L"APPDATA"); if (reqSize > 0) { reqSize += strlen("/Mumble/Console11x.txt"); bSize = reqSize; STACKVAR(wchar_t, buff, reqSize+1); _wgetenv_s(&reqSize, buff, bSize, L"APPDATA"); wcscat_s(buff, bSize, L"/Mumble/Console11x.txt"); res = _wfopen_s(&fConsole, buff, L"a+"); }
bool Utils::GetEnvironmentString (/*[in]*/ const char * lpszName, /*[out]*/ char * lpszOut, /*[in]*/ size_t sizeOut) { #if defined(_MSC_VER) && (_MSC_VER >= 1400) size_t bufSize; if (_wgetenv_s(&bufSize, 0, 0, UW_(lpszName)) != 0) { return (false); } if (bufSize == 0) { return (false); } CharBuffer<wchar_t> buf (bufSize); if (_wgetenv_s(&bufSize, buf.GetBuffer(), bufSize, UW_(lpszName)) != 0) { FATAL_CRT_ERROR ("_wgetenv_s", lpszName); } Utils::CopyString (lpszOut, sizeOut, buf.Get()); return (true); #else const char * lpsz = getenv(lpszName); if (lpsz == 0) { return (false); } Utils::CopyString (lpszOut, sizeOut, lpsz); return (true); #endif }
tstring GetAppDataDirectory(const tstring& sDirectory, const tstring& sFile) { size_t iSize; _wgetenv_s(&iSize, NULL, 0, L"APPDATA"); tstring sSuffix; sSuffix.append(sDirectory).append("\\").append(sFile); if (!iSize) return sSuffix; wchar_t* pszVar = (wchar_t*)malloc(iSize * sizeof(wchar_t)); if (!pszVar) return sSuffix; _wgetenv_s(&iSize, pszVar, iSize, L"APPDATA"); tstring sReturn = convert_from_wstring(pszVar); free(pszVar); CreateDirectory(convert_to_wstring(tstring(sReturn).append("\\").append(sDirectory)).c_str(), NULL); sReturn.append("\\").append(sSuffix); return sReturn; }
std::string getenv(const char *var) { size_t bufSize; std::wstring wvar = boost::filesystem::path(var, qi::unicodeFacet()).wstring(qi::unicodeFacet()); #ifdef _MSC_VER wchar_t *envDir = NULL; _wdupenv_s(&envDir, &bufSize, wvar.c_str()); if (envDir == NULL) return ""; boost::filesystem::path dest(envDir, qi::unicodeFacet()); std::string ret(dest.string(qi::unicodeFacet()).c_str()); free(envDir); return ret; #else _wgetenv_s(&bufSize, NULL, 0, wvar.c_str()); wchar_t *envDir = (wchar_t *) malloc(bufSize * sizeof(wchar_t)); _wgetenv_s(&bufSize, envDir, bufSize, wvar.c_str()); if (envDir == NULL) return ""; boost::filesystem::path dest(envDir, qi::unicodeFacet()); std::string ret(dest.string(qi::unicodeFacet()).c_str()); free(envDir); return ret; #endif }
static wstring getenv(const std::wstring& variableName) { wstring value; size_t ret = 0; wchar_t buf[MAX_PATH+1] = {0}; _wgetenv_s(&ret, buf, variableName.c_str()); return buf; }
HostEnvironment(Logger *logger) : m_log(logger), m_CLRRuntimeHost(nullptr) { // Discover the path to this exe's module. All other files are expected to be in the same directory. DWORD thisModuleLength = ::GetModuleFileNameW(::GetModuleHandleW(nullptr), m_hostPath, MAX_PATH); // Search for the last backslash in the host path. int lastBackslashIndex; for (lastBackslashIndex = thisModuleLength-1; lastBackslashIndex >= 0; lastBackslashIndex--) { if (m_hostPath[lastBackslashIndex] == W('\\')) { break; } } // Copy the directory path ::wcsncpy_s(m_hostDirectoryPath, m_hostPath, lastBackslashIndex + 1); // Save the exe name m_hostExeName = m_hostPath + lastBackslashIndex + 1; *m_log << W("Host directory: ") << m_hostDirectoryPath << Logger::endl; // Check for %CORE_ROOT% and try to load CoreCLR.dll from it if it is set wchar_t coreRoot[MAX_PATH]; size_t outSize; m_coreCLRModule = NULL; // Initialize this here since we don't call TryLoadCoreCLR if CORE_ROOT is unset. if (_wgetenv_s(&outSize, coreRoot, MAX_PATH, W("CORE_ROOT")) == 0 && outSize > 0) { wcscat_s(coreRoot, MAX_PATH, W("\\")); m_coreCLRModule = TryLoadCoreCLR(coreRoot); } else { *m_log << W("CORE_ROOT not set; skipping") << Logger::endl; *m_log << W("You can set the environment variable CORE_ROOT to point to the path") << Logger::endl; *m_log << W("where CoreCLR.dll lives to help this executable find it.") << Logger::endl; } // Try to load CoreCLR from the directory that this exexutable is in if (!m_coreCLRModule) { m_coreCLRModule = TryLoadCoreCLR(m_hostDirectoryPath); } if (m_coreCLRModule) { // Save the directory that CoreCLR was found in DWORD modulePathLength = ::GetModuleFileNameW(m_coreCLRModule, m_coreCLRDirectoryPath, MAX_PATH); // Search for the last backslash and terminate it there to keep just the directory path with trailing slash for (lastBackslashIndex = modulePathLength-1; lastBackslashIndex >= 0; lastBackslashIndex--) { if (m_coreCLRDirectoryPath[lastBackslashIndex] == W('\\')) { m_coreCLRDirectoryPath[lastBackslashIndex + 1] = W('\0'); break; } } } else { *m_log << W("Unable to load ") << coreCLRDll << Logger::endl; } }
// Returns the semicolon-separated list of paths to runtime dlls that are considered trusted. // On first call, scans the coreclr directory for dlls and adds them all to the list. const wchar_t * GetTpaList() { if (!m_tpaList.CStr()) { wchar_t *rgTPAExtensions[] = { W("*.ni.dll"), // Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir W("*.dll"), W("*.ni.exe"), W("*.exe"), }; // Add files from %CORE_LIBRARIES% if specified wchar_t coreLibraries[MAX_PATH]; size_t outSize; if (_wgetenv_s(&outSize, coreLibraries, MAX_PATH, W("CORE_LIBRARIES")) == 0 && outSize > 0) { wcscat_s(coreLibraries, MAX_PATH, W("\\")); AddFilesFromDirectoryToTPAList(coreLibraries, rgTPAExtensions, _countof(rgTPAExtensions)); } else { *m_log << W("CORE_LIBRARIES not set; skipping") << Logger::endl; *m_log << W("You can set the environment variable CORE_LIBRARIES to point to a") << Logger::endl; *m_log << W("path containing additional platform assemblies,") << Logger::endl; } AddFilesFromDirectoryToTPAList(m_coreCLRDirectoryPath, rgTPAExtensions, _countof(rgTPAExtensions)); } return m_tpaList.CStr(); }
void MetaParams::read(QString fname) { if (fname.isEmpty()) { QStringList datapaths; #if defined(Q_OS_WIN) datapaths << QDesktopServices::storageLocation(QDesktopServices::DataLocation); size_t reqSize; _wgetenv_s(&reqSize, NULL, 0, L"APPDATA"); if (reqSize > 0) { STACKVAR(wchar_t, buff, reqSize+1); _wgetenv_s(&reqSize, buff, reqSize, L"APPDATA"); QDir appdir = QDir(QDir::fromNativeSeparators(QString::fromWCharArray(buff))); datapaths << appdir.absolutePath() + QLatin1String("/Mumble"); }
std::wstring GetEnvironmentVariableString(_In_z_ PCWSTR const variable) { std::vector<wchar_t> buffer(500); rsize_t sizeRequired = 0; // The _wgetenv_s are supposed to be more secure than the regular versions, // although I really don't see the advantage. They are certainly less convenient // than they could be, which certainly helps to discourage their use. They should // return a std::wstring. errno_t result = _wgetenv_s(&sizeRequired, &buffer[0], buffer.size(), variable); if (result == ERANGE) { buffer.resize(sizeRequired); result = _wgetenv_s(&sizeRequired, &buffer[0], buffer.size(), variable); } if (result == 0) return &buffer[0]; return L""; }
/* this function MUST be called before calling readline() for the first time returns 0 if successful, -1 if not */ int using_history() { wchar_t *string_size; int size = DEFAULT_HISTORY_SIZE; int temp_size; size_t n; /* try to load .editrc; if it does not exist or is malformed, use the default history size */ source_editrc(); _wgetenv_s(&n, NULL, 0, _T("MINGWEDITLINE_HISTORY_SIZE")); if (n) { if ((string_size = malloc((n + 1) * sizeof(wchar_t)))) { _wgetenv_s(&n, string_size, n, _T("MINGWEDITLINE_HISTORY_SIZE")); } else { n = 0; } } if (n) { swscanf_s(string_size, _T("%d"), &temp_size); if (temp_size >= _EL_MIN_HIST_SIZE) { size = temp_size; } } /* initialize history */ memset(&_el_hs, 0, sizeof(HISTORY_STATE)); _el_hs.entries = (HIST_ENTRY **)_el_alloc_array (size + 1, sizeof(HIST_ENTRY)); if (!(_el_hs.entries)) { return -1; } _el_hs.length = 1; _el_hs.size = size; return 0; }
int setenv(const char *name, const char *value, int overwrite) { int errcode = 0; std::wstring wname = cstring_to_wstring(name); std::wstring wvalue = cstring_to_wstring(value); if (!overwrite) { size_t envsize = 0; errcode = _wgetenv_s(&envsize, nullptr, 0, wname.c_str()); if (errcode || envsize) return errcode; } return _wputenv_s(wname.c_str(), wvalue.c_str()); }
/* this function copies the "filename" string to "name" if filename is a NULL pointer, %APPDATA%\.history is copied to "name" */ int _el_find_history_file(const char *filename, wchar_t **name) { wchar_t *appdata = NULL; size_t n; if (!filename) { _wgetenv_s(&n, NULL, 0, _T("APPDATA")); if (n) { if ((appdata = malloc((n + 1) * sizeof(wchar_t)))) { _wgetenv_s(&n, appdata, n, _T("APPDATA")); } else { n = 0; } } if (n) { n = (wcslen(appdata) + _EL_ENV_BUF_LEN); if (!(*name = malloc(n * sizeof(wchar_t)))) { return -1; } swprintf_s(*name, n, _T("%s\\"), appdata); } wcscat_s(*name, n, _T(".history")); } else { if (!_el_mb2w((char *)filename, name)) { return -1; } } if (appdata) { free(appdata); } return 0; }
error_t TP_getenv_s(size_t* pReturnValue, LPWSTR buffer, size_t sizeInWords, LPCWSTR varname) { if (NULL == pReturnValue || NULL == varname) return 1; #ifdef WINDOWS size_t returnValue; WCHAR buf[100]; if( 0 != _wgetenv_s(&returnValue, buf, 100, varname) || returnValue<=0 ) return 2; TP_scpy_s(buffer, sizeInWords, (LPWSTR)buf); #else LPSTR pRet; pRet = getenv( HackyConvertToSTR((LPWSTR)varname) ); if (NULL == pRet) return 2; TP_scpy_s(buffer, sizeInWords, HackyConvertToWSTR(pRet)); #endif return 0; }
STRING Port::GetEnv(const char * var) { STRING env; #ifdef WIN32 size_t tLen = 0; #ifdef UNICODE wchar_t path[80]; wchar_t var2[256] = {0}; int size = strlen(var)+1; mbstowcs_s(&tLen, var2, size, var, size); _wgetenv_s(&tLen, path, 80, var2); #else char path[80]; getenv_s(&tLen, path, 80, var); #endif env = path; #elif defined(UNIX) char * temp = getenv(var); env.assign(temp, temp+strlen(temp)); #endif return env; }
// One large main method to keep this sample streamlined. // // This function demonstrates how to start the .NET Core runtime, // create an AppDomain, and execute managed code. // // It is meant as an educational sample, so not all error paths are checked, // cross-platform functionality is not yet implemented, and some design // decisions have been made to emphasize readability over efficiency. int wmain(int argc, wchar_t* argv[]) { printf("Sample CoreCLR Host\n\n"); // // STEP 1: Get the app to be run from the command line // if (argc < 2) { printf("ERROR - Specify exe to run as the app's first parameter"); return -1; } // <Snippet1> // The managed application to run should be the first command-line parameter. // Subsequent command line parameters will be passed to the managed app later in this host. wchar_t targetApp[MAX_PATH]; GetFullPathNameW(argv[1], MAX_PATH, targetApp, NULL); // </Snippet1> // Also note the directory the target app is in, as it will be referenced later. // The directory is determined by simply truncating the target app's full path // at the last path delimiter (\) wchar_t targetAppPath[MAX_PATH]; wcscpy_s(targetAppPath, targetApp); size_t i = wcslen(targetAppPath - 1); while (i >= 0 && targetAppPath[i] != L'\\') i--; targetAppPath[i] = L'\0'; // // STEP 2: Find and load CoreCLR.dll // HMODULE coreCLRModule; // Look in %CORE_ROOT% wchar_t coreRoot[MAX_PATH]; size_t outSize; _wgetenv_s(&outSize, coreRoot, MAX_PATH, L"CORE_ROOT"); coreCLRModule = LoadCoreCLR(coreRoot); // If CoreCLR.dll wasn't in %CORE_ROOT%, look next to the target app if (!coreCLRModule) { wcscpy_s(coreRoot, MAX_PATH, targetAppPath); coreCLRModule = LoadCoreCLR(coreRoot); } // If CoreCLR.dll wasn't in %CORE_ROOT% or next to the app, // look in the common 1.1.0 install directory if (!coreCLRModule) { ::ExpandEnvironmentStringsW(coreCLRInstallDirectory, coreRoot, MAX_PATH); coreCLRModule = LoadCoreCLR(coreRoot); } if (!coreCLRModule) { printf("ERROR - CoreCLR.dll could not be found"); return -1; } else { wprintf(L"CoreCLR loaded from %s\n", coreRoot); } // // STEP 3: Get ICLRRuntimeHost2 instance // // <Snippet3> ICLRRuntimeHost2* runtimeHost; FnGetCLRRuntimeHost pfnGetCLRRuntimeHost = (FnGetCLRRuntimeHost)::GetProcAddress(coreCLRModule, "GetCLRRuntimeHost"); if (!pfnGetCLRRuntimeHost) { printf("ERROR - GetCLRRuntimeHost not found"); return -1; } // Get the hosting interface HRESULT hr = pfnGetCLRRuntimeHost(IID_ICLRRuntimeHost2, (IUnknown**)&runtimeHost); // </Snippet3> if (FAILED(hr)) { printf("ERROR - Failed to get ICLRRuntimeHost2 instance.\nError code:%x\n", hr); return -1; } // // STEP 4: Set desired startup flags and start the CLR // // <Snippet4> hr = runtimeHost->SetStartupFlags( // These startup flags control runtime-wide behaviors. // A complete list of STARTUP_FLAGS can be found in mscoree.h, // but some of the more common ones are listed below. static_cast<STARTUP_FLAGS>( // STARTUP_FLAGS::STARTUP_SERVER_GC | // Use server GC // STARTUP_FLAGS::STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN | // Maximize domain-neutral loading // STARTUP_FLAGS::STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN_HOST | // Domain-neutral loading for strongly-named assemblies STARTUP_FLAGS::STARTUP_CONCURRENT_GC | // Use concurrent GC STARTUP_FLAGS::STARTUP_SINGLE_APPDOMAIN | // All code executes in the default AppDomain // (required to use the runtimeHost->ExecuteAssembly helper function) STARTUP_FLAGS::STARTUP_LOADER_OPTIMIZATION_SINGLE_DOMAIN // Prevents domain-neutral loading ) ); // </Snippet4> if (FAILED(hr)) { printf("ERROR - Failed to set startup flags.\nError code:%x\n", hr); return -1; } // Starting the runtime will initialize the JIT, GC, loader, etc. hr = runtimeHost->Start(); if (FAILED(hr)) { printf("ERROR - Failed to start the runtime.\nError code:%x\n", hr); return -1; } else { printf("Runtime started\n"); } // // STEP 5: Prepare properties for the AppDomain we will create // // Flags // <Snippet5> int appDomainFlags = // APPDOMAIN_FORCE_TRIVIAL_WAIT_OPERATIONS | // Do not pump messages during wait // APPDOMAIN_SECURITY_SANDBOXED | // Causes assemblies not from the TPA list to be loaded as partially trusted APPDOMAIN_ENABLE_PLATFORM_SPECIFIC_APPS | // Enable platform-specific assemblies to run APPDOMAIN_ENABLE_PINVOKE_AND_CLASSIC_COMINTEROP | // Allow PInvoking from non-TPA assemblies APPDOMAIN_DISABLE_TRANSPARENCY_ENFORCEMENT; // Entirely disables transparency checks // </Snippet5> // <Snippet6> // TRUSTED_PLATFORM_ASSEMBLIES // "Trusted Platform Assemblies" are prioritized by the loader and always loaded with full trust. // A common pattern is to include any assemblies next to CoreCLR.dll as platform assemblies. // More sophisticated hosts may also include their own Framework extensions (such as AppDomain managers) // in this list. int tpaSize = 100 * MAX_PATH; // Starting size for our TPA (Trusted Platform Assemblies) list wchar_t* trustedPlatformAssemblies = new wchar_t[tpaSize]; trustedPlatformAssemblies[0] = L'\0'; // Extensions to probe for when finding TPA list files wchar_t *tpaExtensions[] = { L"*.dll", L"*.exe", L"*.winmd" }; // Probe next to CoreCLR.dll for any files matching the extensions from tpaExtensions and // add them to the TPA list. In a real host, this would likely be extracted into a separate function // and perhaps also run on other directories of interest. for (int i = 0; i < _countof(tpaExtensions); i++) { // Construct the file name search pattern wchar_t searchPath[MAX_PATH]; wcscpy_s(searchPath, MAX_PATH, coreRoot); wcscat_s(searchPath, MAX_PATH, L"\\"); wcscat_s(searchPath, MAX_PATH, tpaExtensions[i]); // Find files matching the search pattern WIN32_FIND_DATAW findData; HANDLE fileHandle = FindFirstFileW(searchPath, &findData); if (fileHandle != INVALID_HANDLE_VALUE) { do { // Construct the full path of the trusted assembly wchar_t pathToAdd[MAX_PATH]; wcscpy_s(pathToAdd, MAX_PATH, coreRoot); wcscat_s(pathToAdd, MAX_PATH, L"\\"); wcscat_s(pathToAdd, MAX_PATH, findData.cFileName); // Check to see if TPA list needs expanded if (wcslen(pathToAdd) + (3) + wcslen(trustedPlatformAssemblies) >= tpaSize) { // Expand, if needed tpaSize *= 2; wchar_t* newTPAList = new wchar_t[tpaSize]; wcscpy_s(newTPAList, tpaSize, trustedPlatformAssemblies); trustedPlatformAssemblies = newTPAList; } // Add the assembly to the list and delimited with a semi-colon wcscat_s(trustedPlatformAssemblies, tpaSize, pathToAdd); wcscat_s(trustedPlatformAssemblies, tpaSize, L";"); // Note that the CLR does not guarantee which assembly will be loaded if an assembly // is in the TPA list multiple times (perhaps from different paths or perhaps with different NI/NI.dll // extensions. Therefore, a real host should probably add items to the list in priority order and only // add a file if it's not already present on the list. // // For this simple sample, though, and because we're only loading TPA assemblies from a single path, // we can ignore that complication. } while (FindNextFileW(fileHandle, &findData)); FindClose(fileHandle); } } // APP_PATHS // App paths are directories to probe in for assemblies which are not one of the well-known Framework assemblies // included in the TPA list. // // For this simple sample, we just include the directory the target application is in. // More complex hosts may want to also check the current working directory or other // locations known to contain application assets. wchar_t appPaths[MAX_PATH * 50]; // Just use the targetApp provided by the user and remove the file name wcscpy_s(appPaths, targetAppPath); // APP_NI_PATHS // App (NI) paths are the paths that will be probed for native images not found on the TPA list. // It will typically be similar to the app paths. // For this sample, we probe next to the app and in a hypothetical directory of the same name with 'NI' suffixed to the end. wchar_t appNiPaths[MAX_PATH * 50]; wcscpy_s(appNiPaths, targetAppPath); wcscat_s(appNiPaths, MAX_PATH * 50, L";"); wcscat_s(appNiPaths, MAX_PATH * 50, targetAppPath); wcscat_s(appNiPaths, MAX_PATH * 50, L"NI"); // NATIVE_DLL_SEARCH_DIRECTORIES // Native dll search directories are paths that the runtime will probe for native DLLs called via PInvoke wchar_t nativeDllSearchDirectories[MAX_PATH * 50]; wcscpy_s(nativeDllSearchDirectories, appPaths); wcscat_s(nativeDllSearchDirectories, MAX_PATH * 50, L";"); wcscat_s(nativeDllSearchDirectories, MAX_PATH * 50, coreRoot); // PLATFORM_RESOURCE_ROOTS // Platform resource roots are paths to probe in for resource assemblies (in culture-specific sub-directories) wchar_t platformResourceRoots[MAX_PATH * 50]; wcscpy_s(platformResourceRoots, appPaths); // AppDomainCompatSwitch // Specifies compatibility behavior for the app domain. This indicates which compatibility // quirks to apply if an assembly doesn't have an explicit Target Framework Moniker. If a TFM is // present on an assembly, the runtime will always attempt to use quirks appropriate to the version // of the TFM. // // Typically the latest behavior is desired, but some hosts may want to default to older Silverlight // or Windows Phone behaviors for compatibility reasons. wchar_t* appDomainCompatSwitch = L"UseLatestBehaviorWhenTFMNotSpecified"; // </Snippet6> // // STEP 6: Create the AppDomain // // <Snippet7> DWORD domainId; // Setup key/value pairs for AppDomain properties const wchar_t* propertyKeys[] = { L"TRUSTED_PLATFORM_ASSEMBLIES", L"APP_PATHS", L"APP_NI_PATHS", L"NATIVE_DLL_SEARCH_DIRECTORIES", L"PLATFORM_RESOURCE_ROOTS", L"AppDomainCompatSwitch" }; // Property values which were constructed in step 5 const wchar_t* propertyValues[] = { trustedPlatformAssemblies, appPaths, appNiPaths, nativeDllSearchDirectories, platformResourceRoots, appDomainCompatSwitch }; // Create the AppDomain hr = runtimeHost->CreateAppDomainWithManager( L"Sample Host AppDomain", // Friendly AD name appDomainFlags, NULL, // Optional AppDomain manager assembly name NULL, // Optional AppDomain manager type (including namespace) sizeof(propertyKeys)/sizeof(wchar_t*), propertyKeys, propertyValues, &domainId); // </Snippet7> if (FAILED(hr)) { printf("ERROR - Failed to create AppDomain.\nError code:%x\n", hr); return -1; } else { printf("AppDomain %d created\n\n", domainId); } // // STEP 7: Run managed code // // ExecuteAssembly will load a managed assembly and execute its entry point. wprintf(L"Executing %s...\n\n", targetApp); // <Snippet8> DWORD exitCode = -1; hr = runtimeHost->ExecuteAssembly(domainId, targetApp, argc - 1, (LPCWSTR*)(argc > 1 ? &argv[1] : NULL), &exitCode); // </Snippet8> if (FAILED(hr)) { wprintf(L"ERROR - Failed to execute %s.\nError code:%x\n", targetApp, hr); return -1; } // Alternatively, to start managed code execution with a method other than an assembly's entrypoint, // runtimeHost->CreateDelegate can be used to create a pointer to an arbitrary static managed method // which can then be executed directly or via runtimeHost->ExecuteInAppDomain. // // void *pfnDelegate = NULL; // hr = runtimeHost->CreateDelegate( // domainId, // L"HW, Version=1.0.0.0, Culture=neutral", // Target managed assembly // L"ConsoleApplication.Program", // Target managed type // L"Main", // Target entry point (static method) // (INT_PTR*)&pfnDelegate); // if (FAILED(hr)) // { // printf("ERROR - Failed to create delegate.\nError code:%x\n", hr); // return -1; // } // ((MainMethodFp*)pfnDelegate)(NULL); // // STEP 8: Clean up // // <Snippet9> runtimeHost->UnloadAppDomain(domainId, true /* Wait until unload complete */); runtimeHost->Stop(); runtimeHost->Release(); // </Snippet9> printf("\nDone\n"); return exitCode; }
extern "C" _declspec(dllexport) int main(int argc, char **argv) { #else int main(int argc, char **argv) { #endif int res = 0; QT_REQUIRE_VERSION(argc, argv, "4.4.0"); #if defined(Q_OS_WIN) SetDllDirectory(L""); #else #ifndef Q_OS_MAC setenv("AVAHI_COMPAT_NOWARN", "1", 1); #endif #endif // Initialize application object. MumbleApplication a(argc, argv); a.setApplicationName(QLatin1String("Mumble")); a.setOrganizationName(QLatin1String("Mumble")); a.setOrganizationDomain(QLatin1String("mumble.sourceforge.net")); a.setQuitOnLastWindowClosed(false); #if QT_VERSION >= 0x050100 a.setAttribute(Qt::AA_UseHighDpiPixmaps); #endif #if QT_VERSION >= 0x050000 && defined(Q_OS_WIN) a.installNativeEventFilter(&a); #endif #ifdef USE_SBCELT { QDir d(a.applicationVersionRootPath()); QString helper = d.absoluteFilePath(QString::fromLatin1("sbcelt-helper")); setenv("SBCELT_HELPER_BINARY", helper.toUtf8().constData(), 1); } #endif Global::g_global_struct = new Global(); qsrand(QDateTime::currentDateTime().toTime_t()); #if defined(Q_OS_WIN) || defined(Q_OS_MAC) os_init(); #endif bool bAllowMultiple = false; bool suppressIdentity = false; bool bRpcMode = false; QString rpcCommand; QUrl url; if (a.arguments().count() > 1) { QStringList args = a.arguments(); for (int i = 1; i < args.count(); ++i) { if (args.at(i) == QLatin1String("-h") || args.at(i) == QLatin1String("--help") #if defined(Q_OS_WIN) || args.at(i) == QLatin1String("/?") #endif ) { QString helpMessage = MainWindow::tr( "Usage: mumble [options] [<url>]\n" "\n" "<url> specifies a URL to connect to after startup instead of showing\n" "the connection window, and has the following form:\n" "mumble://[<username>[:<password>]@]<host>[:<port>][/<channel>[/<subchannel>...]][?version=<x.y.z>]\n" "\n" "The version query parameter has to be set in order to invoke the\n" "correct client version. It currently defaults to 1.2.0.\n" "\n" "Valid options are:\n" " -h, --help Show this help text and exit.\n" " -m, --multiple\n" " Allow multiple instances of the client to be started.\n" " -n, --noidentity\n" " Suppress loading of identity files (i.e., certificates.)\n" "\n" ); QString rpcHelpBanner = MainWindow::tr( "Remote controlling Mumble:\n" "\n" ); QString rpcHelpMessage = MainWindow::tr( "Usage: mumble rpc <action> [options]\n" "\n" "It is possible to remote control a running instance of Mumble by using\n" "the 'mumble rpc' command.\n" "\n" "Valid actions are:\n" " mute\n" " Mute self\n" " unmute\n" " Unmute self\n" " deaf\n" " Deafen self\n" " undeaf\n" " Undeafen self\n" "\n" ); QString helpOutput = helpMessage + rpcHelpBanner + rpcHelpMessage; if (bRpcMode) { helpOutput = rpcHelpMessage; } #if defined(Q_OS_WIN) QMessageBox::information(NULL, MainWindow::tr("Invocation"), helpOutput); #else printf("%s", qPrintable(helpOutput)); #endif return 1; } else if (args.at(i) == QLatin1String("-m") || args.at(i) == QLatin1String("--multiple")) { bAllowMultiple = true; } else if (args.at(i) == QLatin1String("-n") || args.at(i) == QLatin1String("--noidentity")) { suppressIdentity = true; g.s.bSuppressIdentity = true; } else if (args.at(i) == QLatin1String("rpc")) { bRpcMode = true; if (args.count() - 1 > i) { rpcCommand = QString(args.at(i + 1)); } else { QString rpcError = MainWindow::tr("Error: No RPC command specified"); #if defined(Q_OS_WIN) QMessageBox::information(NULL, MainWindow::tr("RPC"), rpcError); #else printf("%s\n", qPrintable(rpcError)); #endif return 1; } } else { if (!bRpcMode) { QUrl u = QUrl::fromEncoded(args.at(i).toUtf8()); if (u.isValid() && (u.scheme() == QLatin1String("mumble"))) { url = u; } else { QFile f(args.at(i)); if (f.exists()) { url = QUrl::fromLocalFile(f.fileName()); } } } } } } #ifdef USE_DBUS #ifdef Q_OS_WIN // By default, windbus expects the path to dbus-daemon to be in PATH, and the path // should contain bin\\, and the path to the config is hardcoded as ..\etc { size_t reqSize; _wgetenv_s(&reqSize, NULL, 0, L"PATH"); if (reqSize > 0) { STACKVAR(wchar_t, buff, reqSize+1); _wgetenv_s(&reqSize, buff, reqSize, L"PATH"); QString path = QString::fromLatin1("%1;%2").arg(QDir::toNativeSeparators(MumbleApplication::instance()->applicationVersionRootPath())).arg(QString::fromWCharArray(buff)); STACKVAR(wchar_t, buffout, path.length() + 1); path.toWCharArray(buffout); _wputenv_s(L"PATH", buffout); } }
extern "C" JNIEXPORT jstring JNICALL Java_java_lang_System_getProperty(JNIEnv* e, jclass, jstring name, jbooleanArray found) { jstring r = 0; const char* chars = e->GetStringUTFChars(name, 0); if (chars) { #ifdef PLATFORM_WINDOWS if (strcmp(chars, "line.separator") == 0) { r = e->NewStringUTF("\r\n"); } else if (strcmp(chars, "file.separator") == 0) { r = e->NewStringUTF("\\"); } else if (strcmp(chars, "os.name") == 0) { r = e->NewStringUTF("Windows"); } else if (strcmp(chars, "os.version") == 0) { unsigned size = 32; RUNTIME_ARRAY(char, buffer, size); OSVERSIONINFO OSversion; OSversion.dwOSVersionInfoSize=sizeof(OSVERSIONINFO); ::GetVersionEx(&OSversion); snprintf(RUNTIME_ARRAY_BODY(buffer), size, "%i.%i", (int)OSversion.dwMajorVersion, (int)OSversion.dwMinorVersion); r = e->NewStringUTF(RUNTIME_ARRAY_BODY(buffer)); } else if (strcmp(chars, "os.arch") == 0) { #ifdef ARCH_x86_32 r = e->NewStringUTF("x86"); #elif defined ARCH_x86_64 r = e->NewStringUTF("x86_64"); #elif defined ARCH_powerpc r = e->NewStringUTF("ppc"); #elif defined ARCH_arm r = e->NewStringUTF("arm"); #endif } else if (strcmp(chars, "java.io.tmpdir") == 0) { TCHAR buffer[MAX_PATH]; GetTempPath(MAX_PATH, buffer); r = e->NewStringUTF(buffer); } else if (strcmp(chars, "user.dir") == 0) { TCHAR buffer[MAX_PATH]; GetCurrentDirectory(MAX_PATH, buffer); r = e->NewStringUTF(buffer); } else if (strcmp(chars, "user.home") == 0) { # ifdef _MSC_VER WCHAR buffer[MAX_PATH]; size_t needed; if (_wgetenv_s(&needed, buffer, MAX_PATH, L"USERPROFILE") == 0) { r = e->NewString(reinterpret_cast<jchar*>(buffer), lstrlenW(buffer)); } else { r = 0; } # else LPWSTR home = _wgetenv(L"USERPROFILE"); r = e->NewString(reinterpret_cast<jchar*>(home), lstrlenW(home)); # endif } #else if (strcmp(chars, "line.separator") == 0) { r = e->NewStringUTF("\n"); } else if (strcmp(chars, "file.separator") == 0) { r = e->NewStringUTF("/"); } else if (strcmp(chars, "os.name") == 0) { #ifdef __APPLE__ r = e->NewStringUTF("Mac OS X"); #elif defined __FreeBSD__ r = e->NewStringUTF("FreeBSD"); #else r = e->NewStringUTF("Linux"); #endif } else if (strcmp(chars, "os.version") == 0) { #if (defined __APPLE__) && (! defined AVIAN_IOS) unsigned size = 32; char buffer[size]; #ifdef ARCH_x86_64 int32_t minorVersion, majorVersion; #else long minorVersion, majorVersion; #endif Gestalt(gestaltSystemVersionMajor, &majorVersion); Gestalt(gestaltSystemVersionMinor, &minorVersion); snprintf(buffer, size, "%d.%d", static_cast<int32_t>(majorVersion), static_cast<int32_t>(minorVersion)); r = e->NewStringUTF(buffer); #else struct utsname system_id; uname(&system_id); r = e->NewStringUTF(system_id.release); #endif } else if (strcmp(chars, "os.arch") == 0) { #ifdef ARCH_x86_32 r = e->NewStringUTF("x86"); #elif defined ARCH_x86_64 r = e->NewStringUTF("x86_64"); #elif defined ARCH_powerpc r = e->NewStringUTF("ppc"); #elif defined ARCH_arm r = e->NewStringUTF("arm"); #endif } else if (strcmp(chars, "java.io.tmpdir") == 0) { r = e->NewStringUTF("/tmp"); } else if (strcmp(chars, "user.dir") == 0) { char buffer[PATH_MAX]; r = e->NewStringUTF(getcwd(buffer, PATH_MAX)); } else if (strcmp(chars, "user.home") == 0) { r = e->NewStringUTF(getenv("HOME")); } #endif else if (strcmp(chars, "user.language") == 0) { Locale locale = getLocale(); if (strlen(locale.getLanguage())) r = e->NewStringUTF(locale.getLanguage()); } else if (strcmp(chars, "user.region") == 0) { Locale locale = getLocale(); if (strlen(locale.getRegion())) r = e->NewStringUTF(locale.getRegion()); } e->ReleaseStringUTFChars(name, chars); } if (r) { jboolean v = true; e->SetBooleanArrayRegion(found, 0, 1, &v); } return r; }
/* 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); }
bool TryRun(const int argc, const wchar_t* argv[], Logger &log, const bool verbose, const bool waitForDebugger, DWORD &exitCode, wchar_t* programPath) { // Assume failure exitCode = -1; HostEnvironment hostEnvironment(&log); wchar_t appPath[MAX_PATH] = W(""); wchar_t appNiPath[MAX_PATH * 2] = W(""); wchar_t managedAssemblyFullName[MAX_PATH] = W(""); wchar_t* filePart = NULL; if (!::GetFullPathName(programPath, MAX_PATH, appPath, &filePart)) { log << W("Failed to get full path: ") << programPath << Logger::endl; log << W("Error code: ") << GetLastError() << Logger::endl; return false; } wcscpy_s(managedAssemblyFullName, appPath); *(filePart) = W('\0'); log << W("Loading: ") << managedAssemblyFullName << Logger::endl; wcscpy_s(appNiPath, appPath); wcscat_s(appNiPath, MAX_PATH * 2, W(";")); wcscat_s(appNiPath, MAX_PATH * 2, appPath); // Construct native search directory paths wchar_t nativeDllSearchDirs[MAX_PATH * 3]; wcscpy_s(nativeDllSearchDirs, appPath); wchar_t coreLibraries[MAX_PATH]; size_t outSize; if (_wgetenv_s(&outSize, coreLibraries, MAX_PATH, W("CORE_LIBRARIES")) == 0 && outSize > 0) { wcscat_s(nativeDllSearchDirs, MAX_PATH * 3, W(";")); wcscat_s(nativeDllSearchDirs, MAX_PATH * 3, coreLibraries); } wcscat_s(nativeDllSearchDirs, MAX_PATH * 3, W(";")); wcscat_s(nativeDllSearchDirs, MAX_PATH * 3, hostEnvironment.m_coreCLRDirectoryPath); // Start the CoreCLR ICLRRuntimeHost2 *host = hostEnvironment.GetCLRRuntimeHost(); if (!host) { return false; } HRESULT hr; log << W("Setting ICLRRuntimeHost2 startup flags") << Logger::endl; // Default startup flags hr = host->SetStartupFlags((STARTUP_FLAGS) (STARTUP_FLAGS::STARTUP_LOADER_OPTIMIZATION_SINGLE_DOMAIN | STARTUP_FLAGS::STARTUP_SINGLE_APPDOMAIN)); if (FAILED(hr)) { log << W("Failed to set startup flags. ERRORCODE: ") << hr << Logger::endl; return false; } log << W("Starting ICLRRuntimeHost2") << Logger::endl; hr = host->Start(); if (FAILED(hr)) { log << W("Failed to start CoreCLR. ERRORCODE: ") << hr << Logger:: endl; return false; } //------------------------------------------------------------- // Create an AppDomain // Allowed property names: // APPBASE // - The base path of the application from which the exe and other assemblies will be loaded // // TRUSTED_PLATFORM_ASSEMBLIES // - The list of complete paths to each of the fully trusted assemblies // // APP_PATHS // - The list of paths which will be probed by the assembly loader // // APP_NI_PATHS // - The list of additional paths that the assembly loader will probe for ngen images // // NATIVE_DLL_SEARCH_DIRECTORIES // - The list of paths that will be probed for native DLLs called by PInvoke // const wchar_t *property_keys[] = { W("TRUSTED_PLATFORM_ASSEMBLIES"), W("APP_PATHS"), W("APP_NI_PATHS"), W("NATIVE_DLL_SEARCH_DIRECTORIES") W("AppDomainCompatSwitch"), }; const wchar_t *property_values[] = { // TRUSTED_PLATFORM_ASSEMBLIES hostEnvironment.GetTpaList(), // APP_PATHS appPath, // APP_NI_PATHS appNiPath, // NATIVE_DLL_SEARCH_DIRECTORIES nativeDllSearchDirs, }; log << W("Creating an AppDomain") << Logger::endl; log << W("TRUSTED_PLATFORM_ASSEMBLIES=") << property_values[0] << Logger::endl; log << W("APP_PATHS=") << property_values[1] << Logger::endl; log << W("APP_NI_PATHS=") << property_values[2] << Logger::endl; log << W("NATIVE_DLL_SEARCH_DIRECTORIES=") << property_values[3] << Logger::endl; DWORD domainId; hr = host->CreateAppDomainWithManager( hostEnvironment.GetHostExeName(), // The friendly name of the AppDomain // Flags: // APPDOMAIN_ENABLE_PLATFORM_SPECIFIC_APPS // - By default CoreCLR only allows platform neutral assembly to be run. To allow // assemblies marked as platform specific, include this flag // // APPDOMAIN_ENABLE_PINVOKE_AND_CLASSIC_COMINTEROP // - Allows sandboxed applications to make P/Invoke calls and use COM interop // // APPDOMAIN_SECURITY_SANDBOXED // - Enables sandboxing. If not set, the app is considered full trust // // APPDOMAIN_IGNORE_UNHANDLED_EXCEPTION // - Prevents the application from being torn down if a managed exception is unhandled // APPDOMAIN_ENABLE_PLATFORM_SPECIFIC_APPS | APPDOMAIN_ENABLE_PINVOKE_AND_CLASSIC_COMINTEROP | APPDOMAIN_DISABLE_TRANSPARENCY_ENFORCEMENT, NULL, // Name of the assembly that contains the AppDomainManager implementation NULL, // The AppDomainManager implementation type name sizeof(property_keys)/sizeof(wchar_t*), // The number of properties property_keys, property_values, &domainId); if (FAILED(hr)) { log << W("Failed call to CreateAppDomainWithManager. ERRORCODE: ") << hr << Logger::endl; return false; } if(waitForDebugger) { if(!IsDebuggerPresent()) { log << W("Waiting for the debugger to attach. Press any key to continue ...") << Logger::endl; getchar(); if (IsDebuggerPresent()) { log << "Debugger is attached." << Logger::endl; } else { log << "Debugger failed to attach." << Logger::endl; } } } hr = host->ExecuteAssembly(domainId, managedAssemblyFullName, argc, (argc)?&(argv[0]):NULL, &exitCode); if (FAILED(hr)) { log << W("Failed call to ExecuteAssembly. ERRORCODE: ") << hr << Logger::endl; return false; } log << W("App exit value = ") << exitCode << Logger::endl; //------------------------------------------------------------- // Unload the AppDomain log << W("Unloading the AppDomain") << Logger::endl; hr = host->UnloadAppDomain( domainId, true); // Wait until done if (FAILED(hr)) { log << W("Failed to unload the AppDomain. ERRORCODE: ") << hr << Logger::endl; return false; } //------------------------------------------------------------- // Stop the host log << W("Stopping the host") << Logger::endl; hr = host->Stop(); if (FAILED(hr)) { log << W("Failed to stop the host. ERRORCODE: ") << hr << Logger::endl; return false; } //------------------------------------------------------------- // Release the reference to the host log << W("Releasing ICLRRuntimeHost2") << Logger::endl; host->Release(); return true; }
int main(int argc, char **argv) { int res = 0; QT_REQUIRE_VERSION(argc, argv, "4.4.0"); #if defined(Q_OS_WIN) SetDllDirectory(L""); #else #ifndef Q_OS_MAC setenv("AVAHI_COMPAT_NOWARN", "1", 1); #endif #endif // Initialize application object. QAppMumble a(argc, argv); a.setApplicationName(QLatin1String("Mumble")); a.setOrganizationName(QLatin1String("Mumble")); a.setOrganizationDomain(QLatin1String("mumble.sourceforge.net")); a.setQuitOnLastWindowClosed(false); Global::g_global_struct = new Global(); qsrand(QDateTime::currentDateTime().toTime_t()); #if defined(Q_OS_WIN) || defined(Q_OS_MAC) os_init(); #endif bool bAllowMultiple = false; QUrl url; if (a.arguments().count() > 1) { QStringList args = a.arguments(); for (int i = 1; i < args.count(); ++i) { if (args.at(i) == QLatin1String("-m")) { bAllowMultiple = true; } else if (args.at(i) == QLatin1String("-n")) { g.s.bSuppressIdentity = true; } else { QUrl u = QUrl::fromEncoded(args.at(i).toUtf8()); if (u.isValid() && (u.scheme() == QLatin1String("mumble"))) { url = u; } else { QFile f(args.at(i)); if (f.exists()) { url = QUrl::fromLocalFile(f.fileName()); } } } } } #ifdef USE_DBUS #ifdef Q_OS_WIN // By default, windbus expects the path to dbus-daemon to be in PATH, and the path // should contain bin\\, and the path to the config is hardcoded as ..\etc { size_t reqSize; _wgetenv_s(&reqSize, NULL, 0, L"PATH"); if (reqSize > 0) { STACKVAR(wchar_t, buff, reqSize+1); _wgetenv_s(&reqSize, buff, reqSize, L"PATH"); QString path = QString::fromLatin1("%1;%2").arg(QDir::toNativeSeparators(a.applicationDirPath())).arg(QString::fromWCharArray(buff)); STACKVAR(wchar_t, buffout, path.length() + 1); path.toWCharArray(buffout); _wputenv_s(L"PATH", buffout); } }