1 //===- Win32/DynamicLibrary.cpp - Win32 DL Implementation -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Jeff Cohen and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides the Win32 specific implementation of DynamicLibrary.
12 //===----------------------------------------------------------------------===//
17 #pragma comment(lib, "dbghelp.lib")
22 //===----------------------------------------------------------------------===//
23 //=== WARNING: Implementation here must contain only Win32 specific code
24 //=== and must not be UNIX code.
25 //===----------------------------------------------------------------------===//
27 static std::vector<HMODULE> OpenedHandles;
29 BOOL CALLBACK ELM_Callback(PSTR ModuleName,
34 OpenedHandles.push_back((HMODULE)ModuleBase);
38 DynamicLibrary::DynamicLibrary() : handle(0) {
39 handle = GetModuleHandle(NULL);
40 OpenedHandles.push_back((HMODULE)handle);
43 DynamicLibrary::DynamicLibrary(const char*filename) : handle(0) {
44 HMODULE a_handle = LoadLibrary(filename);
47 ThrowError(std::string(filename) + ": Can't open : ");
50 OpenedHandles.push_back(a_handle);
53 DynamicLibrary::~DynamicLibrary() {
57 // GetModuleHandle() does not increment the ref count, so we must not free
58 // the handle to the executable.
59 if (handle != GetModuleHandle(NULL))
60 FreeLibrary((HMODULE)handle);
63 for (std::vector<HMODULE>::iterator I = OpenedHandles.begin(),
64 E = OpenedHandles.end(); I != E; ++I) {
66 // Note: don't use the swap/pop_back trick here. Order is important.
67 OpenedHandles.erase(I);
72 void DynamicLibrary::LoadLibraryPermanently(const char* filename) {
74 HMODULE a_handle = LoadLibrary(filename);
77 ThrowError(std::string(filename) + ": Can't open : ");
79 OpenedHandles.push_back(a_handle);
81 // When no file is specified, enumerate all DLLs and EXEs in the
83 EnumerateLoadedModules(GetCurrentProcess(), ELM_Callback, 0);
86 // Because we don't remember the handles, we will never free them; hence,
87 // it is loaded permanently.
90 void* DynamicLibrary::SearchForAddressOfSymbol(const char* symbolName) {
91 for (std::vector<HMODULE>::iterator I = OpenedHandles.begin(),
92 E = OpenedHandles.end(); I != E; ++I) {
93 FARPROC ptr = GetProcAddress((HMODULE)*I, symbolName);
101 void *DynamicLibrary::GetAddressOfSymbol(const char *symbolName) {
102 assert(handle != 0 && "Invalid DynamicLibrary handle");
103 return GetProcAddress((HMODULE)handle, symbolName);
108 // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab