1//===- Win32/DynamicLibrary.cpp - Win32 DL Implementation -------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides the Win32 specific implementation of DynamicLibrary.
11//
12// FIXME: This file leaks OpenedHandles!
13//
14//===----------------------------------------------------------------------===//
15
16#include "WindowsSupport.h"
17
18#ifdef __MINGW32__
19 #include <imagehlp.h>
20#else
21 #include <dbghelp.h>
22#endif
23
24#ifdef _MSC_VER
25 #include <ntverp.h>
26#endif
27
28namespace llvm {
29using namespace sys;
30
31//===----------------------------------------------------------------------===//
32//=== WARNING: Implementation here must contain only Win32 specific code
33//===          and must not be UNIX code.
34//===----------------------------------------------------------------------===//
35
36typedef BOOL (WINAPI *fpEnumerateLoadedModules)(HANDLE,PENUMLOADED_MODULES_CALLBACK64,PVOID);
37static fpEnumerateLoadedModules fEnumerateLoadedModules;
38static DenseSet<HMODULE> *OpenedHandles;
39
40static bool loadDebugHelp(void) {
41  HMODULE hLib = ::LoadLibraryW(L"Dbghelp.dll");
42  if (hLib) {
43    fEnumerateLoadedModules = (fpEnumerateLoadedModules)
44      ::GetProcAddress(hLib, "EnumerateLoadedModules64");
45  }
46  return fEnumerateLoadedModules != 0;
47}
48
49static BOOL CALLBACK
50ELM_Callback(PCSTR ModuleName, DWORD64 ModuleBase,
51             ULONG ModuleSize, PVOID UserContext) {
52  OpenedHandles->insert((HMODULE)ModuleBase);
53  return TRUE;
54}
55
56DynamicLibrary DynamicLibrary::getPermanentLibrary(const char *filename,
57                                                   std::string *errMsg) {
58  SmartScopedLock<true> lock(*SymbolsMutex);
59
60  if (!filename) {
61    // When no file is specified, enumerate all DLLs and EXEs in the process.
62    if (OpenedHandles == 0)
63      OpenedHandles = new DenseSet<HMODULE>();
64
65    if (!fEnumerateLoadedModules) {
66      if (!loadDebugHelp()) {
67        assert(false && "These APIs should always be available");
68        return DynamicLibrary();
69      }
70    }
71
72    fEnumerateLoadedModules(GetCurrentProcess(), ELM_Callback, 0);
73    // Dummy library that represents "search all handles".
74    // This is mostly to ensure that the return value still shows up as "valid".
75    return DynamicLibrary(&OpenedHandles);
76  }
77
78  SmallVector<wchar_t, MAX_PATH> filenameUnicode;
79  if (std::error_code ec = windows::UTF8ToUTF16(filename, filenameUnicode)) {
80    SetLastError(ec.value());
81    MakeErrMsg(errMsg, std::string(filename) + ": Can't convert to UTF-16");
82    return DynamicLibrary();
83  }
84
85  HMODULE a_handle = LoadLibraryW(filenameUnicode.data());
86
87  if (a_handle == 0) {
88    MakeErrMsg(errMsg, std::string(filename) + ": Can't open");
89    return DynamicLibrary();
90  }
91
92  if (OpenedHandles == 0)
93    OpenedHandles = new DenseSet<HMODULE>();
94
95  // If we've already loaded this library, FreeLibrary() the handle in order to
96  // keep the internal refcount at +1.
97  if (!OpenedHandles->insert(a_handle).second)
98    FreeLibrary(a_handle);
99
100  return DynamicLibrary(a_handle);
101}
102
103// Stack probing routines are in the support library (e.g. libgcc), but we don't
104// have dynamic linking on windows. Provide a hook.
105#define EXPLICIT_SYMBOL(SYM)                    \
106  extern "C" { extern void *SYM; }
107#define EXPLICIT_SYMBOL2(SYMFROM, SYMTO) EXPLICIT_SYMBOL(SYMTO)
108
109#ifdef _M_IX86
110// Win32 on x86 implements certain single-precision math functions as macros.
111// These functions are not exported by the DLL, but will still be needed
112// for symbol-resolution by the JIT loader. Therefore, this Support libray
113// provides helper functions with the same implementation.
114
115#define INLINE_DEF_SYMBOL1(TYP, SYM)                                           \
116  extern "C" TYP inline_##SYM(TYP _X) { return SYM(_X); }
117#define INLINE_DEF_SYMBOL2(TYP, SYM)                                           \
118  extern "C" TYP inline_##SYM(TYP _X, TYP _Y) { return SYM(_X, _Y); }
119#endif
120
121#include "explicit_symbols.inc"
122
123#undef EXPLICIT_SYMBOL
124#undef EXPLICIT_SYMBOL2
125#undef INLINE_DEF_SYMBOL1
126#undef INLINE_DEF_SYMBOL2
127
128void* DynamicLibrary::SearchForAddressOfSymbol(const char* symbolName) {
129  SmartScopedLock<true> Lock(*SymbolsMutex);
130
131  // First check symbols added via AddSymbol().
132  if (ExplicitSymbols.isConstructed()) {
133    StringMap<void *>::iterator i = ExplicitSymbols->find(symbolName);
134
135    if (i != ExplicitSymbols->end())
136      return i->second;
137  }
138
139  // Now search the libraries.
140  if (OpenedHandles) {
141    for (DenseSet<HMODULE>::iterator I = OpenedHandles->begin(),
142         E = OpenedHandles->end(); I != E; ++I) {
143      FARPROC ptr = GetProcAddress((HMODULE)*I, symbolName);
144      if (ptr) {
145        return (void *)(intptr_t)ptr;
146      }
147    }
148  }
149
150#define EXPLICIT_SYMBOL(SYM)                                                   \
151  if (!strcmp(symbolName, #SYM))                                               \
152    return (void *)&SYM;
153#define EXPLICIT_SYMBOL2(SYMFROM, SYMTO)                                       \
154  if (!strcmp(symbolName, #SYMFROM))                                           \
155    return (void *)&SYMTO;
156
157#ifdef _M_IX86
158#define INLINE_DEF_SYMBOL1(TYP, SYM)                                           \
159  if (!strcmp(symbolName, #SYM))                                               \
160    return (void *)&inline_##SYM;
161#define INLINE_DEF_SYMBOL2(TYP, SYM) INLINE_DEF_SYMBOL1(TYP, SYM)
162#endif
163
164  {
165#include "explicit_symbols.inc"
166  }
167
168#undef EXPLICIT_SYMBOL
169#undef EXPLICIT_SYMBOL2
170#undef INLINE_DEF_SYMBOL1
171#undef INLINE_DEF_SYMBOL2
172
173  return 0;
174}
175
176void *DynamicLibrary::getAddressOfSymbol(const char *symbolName) {
177  if (!isValid())
178    return NULL;
179  if (Data == &OpenedHandles)
180    return SearchForAddressOfSymbol(symbolName);
181  return (void *)(intptr_t)GetProcAddress((HMODULE)Data, symbolName);
182}
183
184}
185