Exemplo n.º 1
0
OffsetBacktrace
backtrace_to_offset_backtrace(const Backtrace & backtrace) {
  HMODULE exe_module;
  auto success = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
                                    (LPCWSTR) &backtrace_to_offset_backtrace,
                                    &exe_module);
  if (!success) abort();

  std::vector<ptrdiff_t> stack_trace;
  for (const auto & addr : backtrace) {
    // find module of function
    HMODULE return_addr_module;
    auto success2 = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
                                       // NB: we subtract one because the return address might be after the
                                       //     last byte in the module (remote chance of this happening for noreturn functions)
                                       (LPCWSTR) ((char *) addr - 1),
                                       &return_addr_module);

    stack_trace.push_back(!success2
                          ? (ptrdiff_t) -1
                          : return_addr_module == exe_module
                          ? pointer_difference_in_bytes(addr, (decltype(addr)) exe_module)
                          : 0);
  }

  return stack_trace;
}
Exemplo n.º 2
0
/*
 * __wt_dlopen --
 *	Open a dynamic library.
 */
int
__wt_dlopen(WT_SESSION_IMPL *session, const char *path, WT_DLH **dlhp)
{
	DWORD windows_error;
	WT_DECL_RET;
	WT_DLH *dlh;

	WT_RET(__wt_calloc_one(session, &dlh));
	WT_ERR(__wt_strdup(session, path, &dlh->name));
	WT_ERR(__wt_strdup(session, path == NULL ? "local" : path, &dlh->name));

	/* NULL means load from the current binary */
	if (path == NULL) {
		if (GetModuleHandleExW(
		    0, NULL, (HMODULE *)&dlh->handle) == FALSE) {
			windows_error = __wt_getlasterror();
			__wt_errx(session,
			    "GetModuleHandleExW: %s: %s",
			    path, __wt_formatmessage(session, windows_error));
			WT_ERR(__wt_map_windows_error(windows_error));
		}
	} else {
		// TODO: load dll here
		DebugBreak();
	}

	*dlhp = dlh;
	if (0) {
err:		__wt_free(session, dlh->name);
		__wt_free(session, dlh);
	}
	return (ret);
}
Exemplo n.º 3
0
static __acrt_thread_parameter* __cdecl create_thread_parameter(
    void* const procedure,
    void* const context
    ) throw()
{
    unique_thread_parameter parameter(_calloc_crt_t(__acrt_thread_parameter, 1).detach());
    if (!parameter)
    {
        return nullptr;
    }

    parameter.get()->_procedure = procedure;
    parameter.get()->_context   = context;

    // Attempt to bump the reference count of the module in which the user's
    // thread procedure is defined, to ensure that the module will stay loaded
    // as long as the thread is executing.  We will release this HMDOULE when
    // the thread procedure returns or _endthreadex is called.
    GetModuleHandleExW(
        GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
        reinterpret_cast<LPCWSTR>(procedure),
        &parameter.get()->_module_handle);

    return parameter.detach();
}
Exemplo n.º 4
0
/***********************************************************************
 *           DllMain (DSOUND.init)
 */
BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
    int i;
    TRACE("(%p %d %p)\n", hInstDLL, fdwReason, lpvReserved);

    switch (fdwReason) {
    case DLL_PROCESS_ATTACH:
        TRACE("DLL_PROCESS_ATTACH\n");
        for (i = 0; i < MAXWAVEDRIVERS; i++) {
            DSOUND_renderer[i] = NULL;
            DSOUND_capture[i] = NULL;
            INIT_GUID(DSOUND_renderer_guids[i], 0xbd6dd71a, 0x3deb, 0x11d1, 0xb1, 0x71, 0x00, 0xc0, 0x4f, 0xc2, 0x00, 0x00 + i);
            INIT_GUID(DSOUND_capture_guids[i],  0xbd6dd71b, 0x3deb, 0x11d1, 0xb1, 0x71, 0x00, 0xc0, 0x4f, 0xc2, 0x00, 0x00 + i);
        }
        instance = hInstDLL;
        DisableThreadLibraryCalls(hInstDLL);
        /* Increase refcount on dsound by 1 */
        GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)hInstDLL, &hInstDLL);
        break;
    case DLL_PROCESS_DETACH:
        TRACE("DLL_PROCESS_DETACH\n");
        break;
    default:
        TRACE("UNKNOWN REASON\n");
        break;
    }
    return TRUE;
}
Exemplo n.º 5
0
void *TclWinGetTclInstance()
{
    void *hInstance = NULL;
    GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
	    (const char *)&winTCharEncoding, &hInstance);
    return hInstance;
}
Exemplo n.º 6
0
/* LoadLib
 *  load a dynamic library
 *
 *  "lib" [ OUT ] - return parameter for loaded library
 *
 *  "path" [ IN ] - NUL terminated string in directory-native
 *  character set denoting target library
 */
static
rc_t KDyldLoad ( KDyld *self, KDylib *lib, const wchar_t *path )
{
    DWORD err;
#if WE_WERE_BUILDING_FOR_WINDOWS_7_ALONE
    UINT errMode = GetErrorMode();
#endif

	if ( path == NULL )
	{
		if ( GetModuleHandleExW( 0, NULL, &( lib -> handle ) ) )
			return 0;

        return RC ( rcFS, rcDylib, rcLoading, rcNoObj, rcUnknown );
	}

    SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX); /* suppress the message box in case of an error */
    lib -> handle = LoadLibraryW ( path );
#if WE_WERE_BUILDING_FOR_WINDOWS_7_ALONE
    SetErrorMode(errMode);
#endif
    if ( lib -> handle != NULL )
        return KDylibSetLogging ( lib );

    err = GetLastError ();
    switch ( err )
    {
    case ERROR_MOD_NOT_FOUND :
        return RC ( rcFS, rcDylib, rcLoading, rcPath, rcNotFound );
    case ERROR_BAD_EXE_FORMAT :
        return RC ( rcFS, rcDylib, rcLoading, rcFormat, rcInvalid );
    }

    return RC ( rcFS, rcDylib, rcLoading, rcNoObj, rcUnknown );
}
Exemplo n.º 7
0
HMODULE GetCurrentModuleHandle()
{
    HMODULE hMod = NULL;
    GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
          reinterpret_cast<LPCWSTR>(&GetCurrentModuleHandle),
          &hMod);
     return hMod;
}
Exemplo n.º 8
0
void *Tk_GetHINSTANCE()
{
    void *hInstance = NULL;

    GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
	    (const char *) &tkIntStubs, &hInstance);
    return hInstance;
}
	HINSTANCE GetInstance( void* addressOfItemInModule ) {
		HINSTANCE	instance( nullptr );

		if( !addressOfItemInModule ) {
			addressOfItemInModule = reinterpret_cast<void*>( &GetInstance );
		}

		GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, static_cast<LPWSTR>(addressOfItemInModule), &instance );

		return instance;
	}
Exemplo n.º 10
0
/**
 * Loads a string from the EXE/DLL/etc.'s string table. If that fails, copies
 * the default string.
 * @param res The ID of the string resource to read.
 * @param def The default string.
 * @param buf Buffer into which to store the string.
 * @param bufsize Size of buf (in units of wchar_t).
 */
static void xlate(unsigned int res, const wchar_t *def, wchar_t *buf, size_t bufsize)
{
	HMODULE inst;
	GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, NULL, &inst);

	if (LoadStringW(inst, res, buf, bufsize) == 0)
	{
		wcsncpy(buf, def, bufsize);
		buf[bufsize-1] = '\0';
	}
}
Exemplo n.º 11
0
__declspec(dllexport) HMODULE STDMETHODCALLTYPE GetCrazyNateHModule()
{
  HMODULE myHModule = NULL;
  if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
    (LPCWSTR)&GetCrazyNateHModule,
    &myHModule))
  {
    myHModule = NULL;
  }
  return myHModule;
}
Exemplo n.º 12
0
static void real_init(void) {
#ifdef VS_TARGET_OS_WINDOWS
    // portable
    const std::wstring pythonDllName = L"python37.dll";
    HMODULE module;
    GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)&real_init, &module);
    std::vector<wchar_t> pathBuf(65536);
    GetModuleFileNameW(module, pathBuf.data(), (DWORD)pathBuf.size());
    std::wstring dllPath = pathBuf.data();
    dllPath.resize(dllPath.find_last_of('\\') + 1);
    std::wstring portableFilePath = dllPath + L"portable.vs";
    FILE *portableFile = _wfopen(portableFilePath.c_str(), L"rb");
    bool isPortable = !!portableFile;
    if (portableFile)
        fclose(portableFile);

    HMODULE pythonDll = nullptr;

    if (isPortable) {
        std::wstring pyPath = dllPath + L"\\" + pythonDllName;
        pythonDll = LoadLibraryExW(pyPath.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR);
    } else {
        DWORD dwType = REG_SZ;
        HKEY hKey = 0;

        wchar_t value[1024];
        DWORD valueLength = 1000;
        if (RegOpenKeyW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\VapourSynth", &hKey) != ERROR_SUCCESS)
            return;
        LSTATUS status = RegQueryValueExW(hKey, L"PythonPath", nullptr, &dwType, (LPBYTE)&value, &valueLength);
        RegCloseKey(hKey);
        if (status != ERROR_SUCCESS)
            return;

        std::wstring pyPath = value;
        pyPath += L"\\" + pythonDllName;

        pythonDll = LoadLibraryExW(pyPath.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR);
    }
    if (!pythonDll)
        return;
#endif
    int preInitialized = Py_IsInitialized();
    if (!preInitialized)
        Py_InitializeEx(0);
    s = PyGILState_Ensure();
    if (import_vapoursynth())
        return;
    if (vpy_initVSScript())
        return;
    ts = PyEval_SaveThread();
    initialized = true;
}
Exemplo n.º 13
0
Arquivo: hook.c Projeto: AndreRH/wine
/***********************************************************************
 *		get_hook_proc
 *
 * Retrieve the hook procedure real value for a module-relative proc
 */
void *get_hook_proc( void *proc, const WCHAR *module, HMODULE *free_module )
{
    HMODULE mod;

    GetModuleHandleExW( 0, module, &mod );
    *free_module = mod;
    if (!mod)
    {
        TRACE( "loading %s\n", debugstr_w(module) );
        /* FIXME: the library will never be freed */
        if (!(mod = LoadLibraryExW(module, NULL, LOAD_WITH_ALTERED_SEARCH_PATH))) return NULL;
    }
    return (char *)mod + (ULONG_PTR)proc;
}
Exemplo n.º 14
0
bool PinModule(HMODULE module, dnx::trace_writer& trace_writer)
{
    wchar_t module_path_buffer[MAX_PATH];
    GetModuleFileName(module, module_path_buffer, MAX_PATH);

    HMODULE ignoreModule;
    // Pin the module - CoreCLR.dll does not support being unloaded.
    if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN, module_path_buffer, &ignoreModule))
    {
        trace_writer.write(L"Failed to pin coreclr.dll", false);
        return false;
    }

    return true;
}
Exemplo n.º 15
0
/* Get handle and path of loaded executable (handle for module itself)
 * Returns TRUE if it successes, FALSE if not. */
BOOL GetDllInfo(HMODULE *_out_module, wchar_t *_out_dllpath) {
	if (hModule == NULL) {
		if (!GetModuleHandleExW(
				GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
				GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
				(LPWSTR) &GetDllInfo, &hModule) ||
			GetModuleFileNameW(hModule, dllPath, _countof(dllPath)) == 0) {
			return FALSE;
		}
	}
	if (_out_module != NULL)
		*_out_module = hModule;
	if (_out_dllpath != NULL)
		wcscpy(_out_dllpath, dllPath);
	return TRUE;
}
Exemplo n.º 16
0
/***********************************************************************
 *           DllMain (DSOUND.init)
 */
BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
    TRACE("(%p %d %p)\n", hInstDLL, fdwReason, lpvReserved);

    switch (fdwReason) {
    case DLL_PROCESS_ATTACH:
        instance = hInstDLL;
        DisableThreadLibraryCalls(hInstDLL);
        /* Increase refcount on dsound by 1 */
        GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)hInstDLL, &hInstDLL);
        break;
    case DLL_PROCESS_DETACH:
        if (lpvReserved) break;
        DeleteCriticalSection(&DSOUND_renderers_lock);
        DeleteCriticalSection(&DSOUND_capturers_lock);
        break;
    }
    return TRUE;
}
Exemplo n.º 17
0
JNIEXPORT void JNICALL
Java_java_io_WinNTFileSystem_initIDs(JNIEnv *env, jclass cls)
{
    HMODULE handle;
    jclass fileClass;

    fileClass = (*env)->FindClass(env, "java/io/File");
    CHECK_NULL(fileClass);
    ids.path = (*env)->GetFieldID(env, fileClass, "path", "Ljava/lang/String;");
    CHECK_NULL(ids.path);

    // GetFinalPathNameByHandle requires Windows Vista or newer
    if (GetModuleHandleExW((GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
                            GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT),
                           (LPCWSTR)&CreateFileW, &handle) != 0)
    {
        GetFinalPathNameByHandle_func = (GetFinalPathNameByHandleProc)
            GetProcAddress(handle, "GetFinalPathNameByHandleW");
    }
}
Exemplo n.º 18
0
// static
void
IMEHandler::Initialize()
{
#ifdef NS_ENABLE_TSF
  nsTextStore::Initialize();
  sIsInTSFMode = nsTextStore::IsInTSFMode();
  if (!sIsInTSFMode) {
    // When full nsTextStore is not available, try to use SetInputScopes API
    // to enable at least InputScope. Use GET_MODULE_HANDLE_EX_FLAG_PIN to
    // ensure that msctf.dll will not be unloaded.
    HMODULE module = nullptr;
    if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN, L"msctf.dll",
                           &module)) {
      sSetInputScopes = reinterpret_cast<SetInputScopesFunc>(
        GetProcAddress(module, "SetInputScopes"));
    }
  }
#endif // #ifdef NS_ENABLE_TSF

  nsIMM32Handler::Initialize();
}
Exemplo n.º 19
0
crts_caller::crts_caller(const char* func_name)
{
  assert(func_name);
  assert(func_name[0]);
  if (func_name == NULL)
    return;

  for (const std::wstring& crtName : s_crtNames)
  {
    HMODULE hCrt = NULL;
    if (!GetModuleHandleExW(0, crtName.c_str(), &hCrt) || hCrt == NULL) // Flag 0 ensures that CRL will not be unloaded while we are using it here
      continue; // Module not loaded

    void* func_ptr = GetProcAddress(hCrt, func_name);
    if (func_ptr != NULL)
    {
      m_crts.push_back(hCrt);
      m_funcPointers.push_back(func_ptr);
    }
    else
      FreeLibrary(hCrt); // this CRT will not be used
  }
}
Exemplo n.º 20
0
BOOL WINAPI is_specialdll(UINT_PTR callerAddress,LPCWSTR dll_file)
{
    BOOL	ret = FALSE;
    HMODULE hCallerModule = NULL;
    if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)callerAddress, &hCallerModule))
    {
        WCHAR szModuleName[VALUE_LEN+1] = {0};
        if ( GetModuleFileNameW(hCallerModule, szModuleName, VALUE_LEN) )
        {
            if ( StrChrW(dll_file,L'*') || StrChrW(dll_file,L'?') )
            {
                if ( PathMatchSpecW(szModuleName, dll_file) )
                {
                    ret = TRUE;
                }
            }
            else if ( stristrW(szModuleName, dll_file) )
            {
                ret = TRUE;
            }
        }
    }
    return ret;
}
Exemplo n.º 21
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;
}
Exemplo n.º 22
0
static uv_lib_t *jl_load_dynamic_library_(const char *modname, unsigned flags, int throw_err)
{
    int error;
    char *ext;
    char path[PATHBUF];
    int i;
    uv_stat_t stbuf;
    uv_lib_t *handle = (uv_lib_t*)malloc(sizeof(uv_lib_t));
    handle->errmsg = NULL;

    /*
        this branch returns handle of libjulia
    */
    if (modname == NULL) {
#ifdef _OS_WINDOWS_
        if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
                                (LPCWSTR)(&jl_load_dynamic_library),
                                &handle->handle)) {
            free(handle);
            jl_error("could not load base module");
        }
#else
        handle->handle = dlopen(NULL,RTLD_NOW);
#endif
        goto done;
    }
    /*
        this branch shortcuts absolute paths
    */
#ifdef _OS_WINDOWS_
    else if (modname[1] == ':') {
#else
    else if (modname[0] == '/') {
#endif
        error = jl_uv_dlopen(modname,handle,flags);
        if (!error)
            goto done;
        // bail out and show the error if file actually exists
        if (jl_stat(modname, (char*)&stbuf) == 0)
            goto notfound;
        if (handle->errmsg)
            uv_dlclose(handle);
    }
    /*
        this branch permutes all base paths in DL_LOAD_PATH with all extensions
        note: skip when !jl_base_module to avoid UndefVarError(:DL_LOAD_PATH)
    */
    else if (jl_base_module != NULL) {
        jl_array_t *DL_LOAD_PATH = (jl_array_t*)jl_get_global(jl_base_module, jl_symbol("DL_LOAD_PATH"));
        if (DL_LOAD_PATH != NULL) {
            size_t j;
            for (j = 0; j < jl_array_len(DL_LOAD_PATH); j++) {
                char *dl_path = jl_string_data(jl_cell_data(DL_LOAD_PATH)[j]);
                size_t len = strlen(dl_path);
                if (len == 0)
                    continue;
                for(i=0; i < N_EXTENSIONS; i++) {
                    ext = extensions[i];
                    path[0] = '\0';
                    handle->handle = NULL;
                    if (dl_path[len-1] == PATHSEPSTRING[0])
                        snprintf(path, PATHBUF, "%s%s%s", dl_path, modname, ext);
                    else
                        snprintf(path, PATHBUF, "%s" PATHSEPSTRING "%s%s", dl_path, modname, ext);
                    // free handle->errmsg, else it will leak on next uv_dlopen
                    if (handle->errmsg)
                        uv_dlclose(handle);
                    error = jl_uv_dlopen(path, handle, flags);
                    if (!error)
                        goto done;
                    // bail out and show the error if file actually exists
                    if (jl_stat(path, (char*)&stbuf) == 0)
                        goto notfound;
                }
            }
        }
    }

    // now fall back and look in default library paths, for all extensions
    for(i=0; i < N_EXTENSIONS; i++) {
        ext = extensions[i];
        path[0] = '\0';
        handle->handle = NULL;
        snprintf(path, PATHBUF, "%s%s", modname, ext);
        if (handle->errmsg)
            uv_dlclose(handle);
        error = jl_uv_dlopen(path, handle, flags);
        if (!error)
            goto done;
    }

#if defined(__linux__) || defined(__FreeBSD__)
// check map of versioned libs from "libX" to full soname "libX.so.ver"
    {
        const char *soname = jl_lookup_soname(modname, strlen(modname));
        error = (soname==NULL) || jl_uv_dlopen(soname, handle, flags);
        if (!error)
            goto done;
    }
#endif

notfound:
    // copy the error message into the path buffer so we can free the lib handle
    path[0] = '\0';
    snprintf(path, PATHBUF, "%s", uv_dlerror(handle));
    uv_dlclose(handle);
    free(handle);
    if (throw_err)
        jl_errorf("could not load library '%s'\n%s", modname, path);
    return NULL;

done:
    return handle;
}

jl_uv_libhandle jl_load_dynamic_library_e(const char *modname, unsigned flags)
{
    return (jl_uv_libhandle) jl_load_dynamic_library_(modname, flags, 0);
}

jl_uv_libhandle jl_load_dynamic_library(const char *modname, unsigned flags)
{
    return (jl_uv_libhandle) jl_load_dynamic_library_(modname, flags, 1);
}

void *jl_dlsym_e(jl_uv_libhandle handle, const char *symbol)
{
    void *ptr;
    int error = uv_dlsym((uv_lib_t *) handle, symbol, &ptr);
    if (error) ptr=NULL;
    return ptr;
}
Exemplo n.º 23
0
static void *jl_load_dynamic_library_(const char *modname, unsigned flags, int throw_err)
{
    char *ext;
    char path[PATHBUF];
    int i;
    uv_stat_t stbuf;
    void *handle;

/*
    this branch returns handle of libjulia
*/
    if (modname == NULL) {
#ifdef _OS_WINDOWS_
        if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
                                (LPCWSTR)(&jl_load_dynamic_library),
                                (HMODULE*)&handle)) {
            jl_error("could not load base module");
        }
#else
        handle = dlopen(NULL, RTLD_NOW);
#endif
        goto done;
    }
/*
    this branch shortcuts absolute paths
*/
#ifdef _OS_WINDOWS_
    else if (modname[1] == ':') {
#else
    else if (modname[0] == '/') {
#endif
        handle = jl_dlopen(modname, flags);
        if (handle)
            goto done;
        // bail out and show the error if file actually exists
        if (jl_stat(modname, (char*)&stbuf) == 0)
            goto notfound;
    }
/*
    this branch permutes all base paths in DL_LOAD_PATH with all extensions
    note: skip when !jl_base_module to avoid UndefVarError(:DL_LOAD_PATH)
*/
    else if (jl_base_module != NULL) {
        jl_array_t *DL_LOAD_PATH = (jl_array_t*)jl_get_global(jl_base_module, jl_symbol("DL_LOAD_PATH"));
        if (DL_LOAD_PATH != NULL) {
            size_t j;
            for (j = 0; j < jl_array_len(DL_LOAD_PATH); j++) {
                char *dl_path = jl_string_data(jl_cell_data(DL_LOAD_PATH)[j]);
                size_t len = strlen(dl_path);
                if (len == 0)
                    continue;
                for(i=0; i < N_EXTENSIONS; i++) {
                    ext = extensions[i];
                    path[0] = '\0';
                    handle = NULL;
                    if (dl_path[len-1] == PATHSEPSTRING[0])
                        snprintf(path, PATHBUF, "%s%s%s", dl_path, modname, ext);
                    else
                        snprintf(path, PATHBUF, "%s" PATHSEPSTRING "%s%s", dl_path, modname, ext);
                    handle = jl_dlopen(path, flags);
                    if (handle)
                        goto done;
                    // bail out and show the error if file actually exists
                    if (jl_stat(path, (char*)&stbuf) == 0)
                        goto notfound;
                }
            }
        }
    }

    // now fall back and look in default library paths, for all extensions
    for(i=0; i < N_EXTENSIONS; i++) {
        ext = extensions[i];
        path[0] = '\0';
        handle = NULL;
        snprintf(path, PATHBUF, "%s%s", modname, ext);
        handle = jl_dlopen(path, flags);
        if (handle)
            goto done;
    }

#if defined(__linux__) || defined(__FreeBSD__)
// check map of versioned libs from "libX" to full soname "libX.so.ver"
    {
        const char *soname = jl_lookup_soname(modname, strlen(modname));
        if (soname) {
            handle = jl_dlopen(soname, flags);
            if (handle)
                goto done;
        }
    }
#endif

notfound:
    if (throw_err)
        jl_dlerror("could not load library \"%s\"\n%s", modname);
    return NULL;

done:
    return handle;
}

JL_DLLEXPORT void *jl_load_dynamic_library_e(const char *modname, unsigned flags)
{
    return jl_load_dynamic_library_(modname, flags, 0);
}

JL_DLLEXPORT void *jl_load_dynamic_library(const char *modname, unsigned flags)
{
    return jl_load_dynamic_library_(modname, flags, 1);
}

JL_DLLEXPORT void *jl_dlsym_e(void *handle, const char *symbol)
{
#ifdef _OS_WINDOWS_
    void *ptr = GetProcAddress((HMODULE) handle, symbol);
#else
    dlerror(); /* Reset error status. */
    void *ptr = dlsym(handle, symbol);
#endif
    return ptr;
}
Exemplo n.º 24
0
static uv_lib_t *jl_load_dynamic_library_(const char *modname, unsigned flags, int throw_err)
{
    int error;
    char *ext;
    char path[PATHBUF];
    int i;
    uv_lib_t *handle = (uv_lib_t*)malloc(sizeof(uv_lib_t));
    handle->errmsg = NULL;

    if (modname == NULL) {
#ifdef _OS_WINDOWS_
        if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
                                (LPCWSTR)(&jl_load_dynamic_library),
                                &handle->handle))
            jl_errorf("could not load base module", modname);
#else
        handle->handle = dlopen(NULL,RTLD_NOW);
#endif
        goto done;
    }
#ifdef _OS_WINDOWS_
    else if (modname[1] == ':') {
#else
    else if (modname[0] == '/') {
#endif
        error = jl_uv_dlopen(modname,handle,flags);
        if (!error) goto done;
    }
    else if (jl_base_module != NULL) {
        jl_array_t *DL_LOAD_PATH = (jl_array_t*)jl_get_global(jl_base_module, jl_symbol("DL_LOAD_PATH"));
        if (DL_LOAD_PATH != NULL) {
            size_t j;
            for (j = 0; j < jl_array_len(DL_LOAD_PATH); j++) {
                char *dl_path = jl_string_data(jl_cell_data(DL_LOAD_PATH)[j]);
                size_t len = strlen(dl_path);
                if (len == 0)
                    continue;
                for(i=0; i < N_EXTENSIONS; i++) {
                    ext = extensions[i];
                    path[0] = '\0';
                    handle->handle = NULL;
                    if (dl_path[len-1] == PATHSEPSTRING[0])
                        snprintf(path, PATHBUF, "%s%s%s", dl_path, modname, ext);
                    else
                        snprintf(path, PATHBUF, "%s" PATHSEPSTRING "%s%s", dl_path, modname, ext);
                    if (handle->errmsg) {
                        uv_dlclose(handle);
                    }
                    error = jl_uv_dlopen(path, handle, flags);
                    if (!error) goto done;
                }
            }
        }
    }
    for(i=0; i < N_EXTENSIONS; i++) {
        ext = extensions[i];
        path[0] = '\0';
        handle->handle = NULL;
        /* try loading from standard library path */
        snprintf(path, PATHBUF, "%s%s", modname, ext);
        if (handle->errmsg) {
            uv_dlclose(handle);
        }
        error = jl_uv_dlopen(path, handle, flags);
        if (!error) goto done;
    }

#if defined(__linux__) || defined(__FreeBSD__)
    {
        const char *soname = jl_lookup_soname(modname, strlen(modname));
        if (handle->errmsg) {
            free(handle->errmsg);
            handle->errmsg = NULL;
        }
        error = (soname==NULL) || jl_uv_dlopen(soname, handle, flags);
        if (!error) goto done;
    }
#endif

    if (throw_err) {
        //jl_printf(JL_STDERR, "could not load module %s (%d): %s\n", modname, error, uv_dlerror(handle));
        jl_errorf("could not load module %s: %s", modname, uv_dlerror(handle));
    }
    uv_dlclose(handle);
    free(handle);
    return NULL;
done:
    return handle;
}

jl_uv_libhandle jl_load_dynamic_library_e(const char *modname, unsigned flags)
{
    return (jl_uv_libhandle) jl_load_dynamic_library_(modname, flags, 0);
}

jl_uv_libhandle jl_load_dynamic_library(const char *modname, unsigned flags)
{
    return (jl_uv_libhandle) jl_load_dynamic_library_(modname, flags, 1);
}

void *jl_dlsym_e(jl_uv_libhandle handle, const char *symbol)
{
    void *ptr;
    int  error=uv_dlsym((uv_lib_t *) handle, symbol, &ptr);
    if (error) ptr=NULL;
    return ptr;
}
Exemplo n.º 25
0
JL_DLLEXPORT void *jl_load_dynamic_library(const char *modname, unsigned flags, int throw_err)
{
    char path[PATHBUF];
    int i;
    uv_stat_t stbuf;
    void *handle;
    int abspath;
    // number of extensions to try — if modname already ends with the
    // standard extension, then we don't try adding additional extensions
    int n_extensions = endswith_extension(modname) ? 1 : N_EXTENSIONS;

    /*
      this branch returns handle of libjulia
    */
    if (modname == NULL) {
#ifdef _OS_WINDOWS_
        if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
                                (LPCWSTR)(uintptr_t)(&jl_load_dynamic_library),
                                (HMODULE*)&handle)) {
            jl_error("could not load base module");
        }
#else
        Dl_info info;
        if (!dladdr((void*)(uintptr_t)&jl_load_dynamic_library, &info) || !info.dli_fname)
            jl_error("could not load base module");
        handle = dlopen(info.dli_fname, RTLD_NOW);
#endif
        goto done;
    }

    abspath = isabspath(modname);

    /*
      this branch permutes all base paths in DL_LOAD_PATH with all extensions
      note: skip when !jl_base_module to avoid UndefVarError(:DL_LOAD_PATH),
            and also skip for absolute paths
    */
    if (!abspath && jl_base_module != NULL) {
        jl_array_t *DL_LOAD_PATH = (jl_array_t*)jl_get_global(jl_base_module, jl_symbol("DL_LOAD_PATH"));
        if (DL_LOAD_PATH != NULL) {
            size_t j;
            for (j = 0; j < jl_array_len(DL_LOAD_PATH); j++) {
                char *dl_path = jl_string_data(jl_array_ptr_data(DL_LOAD_PATH)[j]);
                size_t len = strlen(dl_path);
                if (len == 0)
                    continue;
                for (i=0; i < n_extensions; i++) {
                    const char *ext = extensions[i];
                    path[0] = '\0';
                    if (dl_path[len-1] == PATHSEPSTRING[0])
                        snprintf(path, PATHBUF, "%s%s%s", dl_path, modname, ext);
                    else
                        snprintf(path, PATHBUF, "%s" PATHSEPSTRING "%s%s", dl_path, modname, ext);
                    handle = jl_dlopen(path, flags);
                    if (handle)
                        goto done;
                    // bail out and show the error if file actually exists
                    if (jl_stat(path, (char*)&stbuf) == 0)
                        goto notfound;
                }
            }
        }
    }

    // now fall back and look in default library paths, for all extensions
    for(i=0; i < n_extensions; i++) {
        const char *ext = extensions[i];
        path[0] = '\0';
        snprintf(path, PATHBUF, "%s%s", modname, ext);
        handle = jl_dlopen(path, flags);
        if (handle)
            goto done;
    }

notfound:
    if (throw_err) {
        const char * reason = jl_dlerror();
        jl_errorf("could not load library \"%s\"\n%s", modname, reason);
    }
    return NULL;

done:
    return handle;
}
Exemplo n.º 26
0
static
DWORD
WINAPI
GPNotificationThreadProc(IN LPVOID lpParameter)
{
    HMODULE hModule;
    DWORD WaitResult, WaitCount;
    HANDLE WaitHandles[3];

    /* reference the library so we don't screw up if the application
       causes the DLL to unload while this thread is still running */
    if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
                           (LPCWSTR)hInstance,
                           &hModule))
    {
        ASSERT(hModule == hInstance);

        EnterCriticalSection(&GPNotifyLock);

        ASSERT(hNotificationThreadEvent != NULL);
        WaitHandles[0] = hNotificationThreadEvent;
        for (;;)
        {
            ASSERT(hMachineGPAppliedEvent != NULL);

            if (NotificationList == NULL)
                break;

            WaitCount = 2;
            WaitHandles[1] = hMachineGPAppliedEvent;

            if (hLocalGPAppliedEvent != NULL)
            {
                WaitHandles[2] = hLocalGPAppliedEvent;
                WaitCount++;
            }

            LeaveCriticalSection(&GPNotifyLock);

            WaitResult = WaitForMultipleObjects(WaitCount,
                                                WaitHandles,
                                                FALSE,
                                                INFINITE);

            EnterCriticalSection(&GPNotifyLock);

            if (WaitResult != WAIT_FAILED)
            {
                if (WaitResult == WAIT_OBJECT_0)
                {
                    ResetEvent(hNotificationThreadEvent);

                    if (GPNotificationAction == gpaTerminate)
                    {
                        /* terminate the thread */
                        break;
                    }
                }
                else if (WaitResult == WAIT_OBJECT_0 + 1 || WaitResult == WAIT_OBJECT_0 + 2)
                {
                    /* group policies have been applied */
                    if (NotificationList != NULL)
                    {
                        NotifyGPEvents((WaitResult == WAIT_OBJECT_0 + 1));
                    }
                }
                else if (WaitResult == WAIT_ABANDONED_0 + 2)
                {
                    /* In case the local group policies event was abandoned, keep watching!
                       But close the handle as it's no longer of any use. */
                    if (hLocalGPAppliedEvent != NULL)
                    {
                        CloseHandle(hLocalGPAppliedEvent);
                        hLocalGPAppliedEvent = NULL;
                    }
                }
                else if (WaitResult == WAIT_ABANDONED_0 || WaitResult == WAIT_ABANDONED_0 + 1)
                {
                    /* terminate the thread if the machine group policies event was abandoned
                       or for some reason the rundown event got abandoned. */
                    break;
                }
                else
                {
                    DPRINT("Unexpected wait result watching the group policy events: 0x%x\n", WaitResult);
                    ASSERT(FALSE);
                    break;
                }

                if (NotificationList == NULL)
                    break;
            }
            else
                break;

        }

        /* cleanup handles no longer used */
        ASSERT(hNotificationThread != NULL);
        ASSERT(hNotificationThreadEvent != NULL);

        CloseHandle(hNotificationThread);
        CloseHandle(hNotificationThreadEvent);
        hNotificationThread = NULL;
        hNotificationThreadEvent = NULL;

        if (hLocalGPAppliedEvent != NULL)
        {
            CloseHandle(hLocalGPAppliedEvent);
            hLocalGPAppliedEvent = NULL;
        }
        if (hMachineGPAppliedEvent != NULL)
        {
            CloseHandle(hMachineGPAppliedEvent);
            hMachineGPAppliedEvent = NULL;
        }

        LeaveCriticalSection(&GPNotifyLock);

        /* dereference the library and exit */
        FreeLibraryAndExitThread(hModule,
                                 0);
    }
    else
    {
        DPRINT1("Referencing the library failed!\n");
    }

    return 1;
}
Exemplo n.º 27
0
FileResolver::FileResolver() {
	/* Try to detect the base path of the Mitsuba installation */
	fs::path basePath;
#if defined(__LINUX__)
	Dl_info info;

	dladdr((const void *) &dummySymbol, &info);
	if (info.dli_fname) {
		/* Try to detect a few default setups */
		if (boost::starts_with(info.dli_fname, "/usr/lib") ||
			boost::starts_with(info.dli_fname, "/lib")) {
			basePath = fs::path("/usr/share/mitsuba");
		} else if (boost::starts_with(info.dli_fname, "/usr/local/lib")) {
			basePath = fs::path("/usr/local/share/mitsuba");
		} else {
			/* This is a locally-compiled repository */
			basePath = fs::path(info.dli_fname).parent_path();
		}
	}
#elif defined(__OSX__)
	MTS_AUTORELEASE_BEGIN()
	uint32_t imageCount = _dyld_image_count();
	for (uint32_t i=0; i<imageCount; ++i) {
		const char *imageName = _dyld_get_image_name(i);
		if (boost::ends_with(imageName, "libmitsuba-core.dylib")) {
			basePath = fs::canonical(imageName).parent_path().parent_path().parent_path();
			break;
		}
	}
	MTS_AUTORELEASE_END()
	if (basePath.empty())
		Log(EError, "Could not detect the executable path!");
#elif defined(__WINDOWS__)
	std::vector<WCHAR> lpFilename(MAX_PATH);

	// Module handle to this DLL. If the function fails it sets handle to NULL.
	// In that case GetModuleFileName will get the name of the executable which
	// is acceptable soft-failure behavior.
	HMODULE handle;
	GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
	                 | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
          reinterpret_cast<LPCWSTR>(&dummySymbol), &handle);

	// Try to get the path with the default MAX_PATH length (260 chars)
	DWORD nSize = GetModuleFileNameW(handle, &lpFilename[0], MAX_PATH);

	// Adjust the buffer size in case if was too short
	while (nSize != 0 && nSize == lpFilename.size()) {
		lpFilename.resize(nSize * 2);
		nSize = GetModuleFileNameW(handle, &lpFilename[0],
			static_cast<DWORD>(lpFilename.size()));
	}

	// There is an error if and only if the function returns 0
	if (nSize != 0)
		basePath = fs::path(lpFilename).parent_path();
	else
		Log(EError, "Could not detect the executable path! (%s)", lastErrorText().c_str());
#endif
	#if BOOST_VERSION >= 104800
		m_paths.push_back(fs::canonical(basePath));
	#else
		m_paths.push_back(fs::absolute(basePath));
	#endif
	m_paths.push_back(fs::current_path());
}
Exemplo n.º 28
0
void WINAPI do_it(void)
{
	HANDLE		 hc = NULL;
	UINT_PTR	 dwCaller = 0;
#ifdef _LOGDEBUG
	if ( GetEnvironmentVariableA("APPDATA",logfile_buf,MAX_PATH) > 0 )
	{
		strncat(logfile_buf,"\\",1);
		strncat(logfile_buf,LOG_FILE,strlen((LPCSTR)LOG_FILE));
	}
#endif
	if (!dll_module)
	{
	#ifdef __GNUC__
		dwCaller = (UINT_PTR)__builtin_return_address(0);
	#else
		dwCaller = (UINT_PTR)_ReturnAddress();
	#endif
	}
	if (dwCaller)
	{
		GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)dwCaller, &dll_module);
	}
	if ( read_appint(L"General",L"SafeEx") > 0 )
	{
		init_safed(NULL);
	}
	if ( read_appint(L"General", L"Portable") > 0 )
	{
		env_thread = (HANDLE)_beginthreadex(NULL,0,&init_global_env,NULL,0,NULL);
		if (env_thread) 
		{
			SetThreadPriority(env_thread,THREAD_PRIORITY_HIGHEST);
			init_portable(NULL);
		}
	}
	if ( is_browser() || is_thunderbird() )
	{
		if ( read_appint(L"General",L"GdiBatchLimit") > 0 )
		{
			hc = OpenThread(THREAD_ALL_ACCESS, 0, GetCurrentThreadId());
			if (hc)
			{
				CloseHandle((HANDLE)_beginthreadex(NULL,0,&GdiSetLimit_tt,hc,0,NULL));
			}
		}
		if ( read_appint(L"General",L"ProcessAffinityMask") > 0 )
		{
			hc = OpenThread(THREAD_ALL_ACCESS, 0, GetCurrentThreadId());
			if (hc)
			{
				CloseHandle((HANDLE)_beginthreadex(NULL,0,&SetCpuAffinity_tt,hc,0,NULL));
			}
		}
		if ( read_appint(L"General",L"CreateCrashDump") > 0 )
		{
			CloseHandle((HANDLE)_beginthreadex(NULL,0,&init_exeception,NULL,0,NULL));
		}
		if ( read_appint(L"General", L"Bosskey") > 0 )
		{
			CloseHandle((HANDLE)_beginthreadex(NULL,0,&bosskey_thread,&ff_info,0,NULL));
		}
		CloseHandle((HANDLE)_beginthreadex(NULL,0,&SetPluginPath,NULL,0,NULL));
	}
}