1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/native_library.h"
6 
7 #include <windows.h>
8 
9 #include "base/files/file_util.h"
10 #include "base/metrics/histogram_macros.h"
11 #include "base/path_service.h"
12 #include "base/scoped_native_library.h"
13 #include "base/strings/string_util.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/threading/scoped_blocking_call.h"
17 
18 namespace base {
19 
20 namespace {
21 
22 // forward declare
23 HMODULE AddDllDirectory(PCWSTR new_directory);
24 
25 // This enum is used to back an UMA histogram, and should therefore be treated
26 // as append-only.
27 enum LoadLibraryResult {
28   // LoadLibraryExW API/flags are available and the call succeeds.
29   SUCCEED = 0,
30   // LoadLibraryExW API/flags are availabe to use but the call fails, then
31   // LoadLibraryW is used and succeeds.
32   FAIL_AND_SUCCEED,
33   // LoadLibraryExW API/flags are availabe to use but the call fails, then
34   // LoadLibraryW is used but fails as well.
35   FAIL_AND_FAIL,
36   // LoadLibraryExW API/flags are unavailabe to use, then LoadLibraryW is used
37   // and succeeds.
38   UNAVAILABLE_AND_SUCCEED,
39   // LoadLibraryExW API/flags are unavailabe to use, then LoadLibraryW is used
40   // but fails.
41   UNAVAILABLE_AND_FAIL,
42   // Add new items before this one, always keep this one at the end.
43   END
44 };
45 
46 // A helper method to log library loading result to UMA.
LogLibrarayLoadResultToUMA(LoadLibraryResult result)47 void LogLibrarayLoadResultToUMA(LoadLibraryResult result) {
48   UMA_HISTOGRAM_ENUMERATION("LibraryLoader.LoadNativeLibraryWindows", result,
49                             LoadLibraryResult::END);
50 }
51 
52 // A helper method to check if AddDllDirectory method is available, thus
53 // LOAD_LIBRARY_SEARCH_* flags are available on systems.
AreSearchFlagsAvailable()54 bool AreSearchFlagsAvailable() {
55   // The LOAD_LIBRARY_SEARCH_* flags are available on systems that have
56   // KB2533623 installed. To determine whether the flags are available, use
57   // GetProcAddress to get the address of the AddDllDirectory,
58   // RemoveDllDirectory, or SetDefaultDllDirectories function. If GetProcAddress
59   // succeeds, the LOAD_LIBRARY_SEARCH_* flags can be used with LoadLibraryEx.
60   // https://msdn.microsoft.com/en-us/library/windows/desktop/ms684179(v=vs.85).aspx
61   // The LOAD_LIBRARY_SEARCH_* flags are used in the LoadNativeLibraryHelper
62   // method.
63   static const auto add_dll_dir_func =
64       reinterpret_cast<decltype(AddDllDirectory)*>(
65           GetProcAddress(GetModuleHandle(L"kernel32.dll"), "AddDllDirectory"));
66   return !!add_dll_dir_func;
67 }
68 
69 // A helper method to encode the library loading result to enum
70 // LoadLibraryResult.
GetLoadLibraryResult(bool are_search_flags_available,bool has_load_library_succeeded)71 LoadLibraryResult GetLoadLibraryResult(bool are_search_flags_available,
72                                        bool has_load_library_succeeded) {
73   LoadLibraryResult result;
74   if (are_search_flags_available) {
75     if (has_load_library_succeeded)
76       result = LoadLibraryResult::FAIL_AND_SUCCEED;
77     else
78       result = LoadLibraryResult::FAIL_AND_FAIL;
79   } else if (has_load_library_succeeded) {
80     result = LoadLibraryResult::UNAVAILABLE_AND_SUCCEED;
81   } else {
82     result = LoadLibraryResult::UNAVAILABLE_AND_FAIL;
83   }
84   return result;
85 }
86 
LoadNativeLibraryHelper(const FilePath & library_path,NativeLibraryLoadError * error)87 NativeLibrary LoadNativeLibraryHelper(const FilePath& library_path,
88                                       NativeLibraryLoadError* error) {
89   // LoadLibrary() opens the file off disk and acquires the LoaderLock, hence
90   // must not be called from DllMain.
91   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
92 
93   HMODULE module = nullptr;
94 
95   // This variable records the library loading result.
96   LoadLibraryResult load_library_result = LoadLibraryResult::SUCCEED;
97 
98   bool are_search_flags_available = AreSearchFlagsAvailable();
99   if (are_search_flags_available) {
100     // LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR flag is needed to search the library
101     // directory as the library may have dependencies on DLLs in this
102     // directory.
103     module = ::LoadLibraryExW(
104         library_path.value().c_str(), nullptr,
105         LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
106     // If LoadLibraryExW succeeds, log this metric and return.
107     if (module) {
108       LogLibrarayLoadResultToUMA(load_library_result);
109       return module;
110     }
111     // GetLastError() needs to be called immediately after
112     // LoadLibraryExW call.
113     if (error)
114       error->code = ::GetLastError();
115   }
116 
117   // If LoadLibraryExW API/flags are unavailable or API call fails, try
118   // LoadLibraryW API. From UMA, this fallback is necessary for many users.
119 
120   // Switch the current directory to the library directory as the library
121   // may have dependencies on DLLs in this directory.
122   bool restore_directory = false;
123   FilePath current_directory;
124   if (GetCurrentDirectory(&current_directory)) {
125     FilePath plugin_path = library_path.DirName();
126     if (!plugin_path.empty()) {
127       SetCurrentDirectory(plugin_path);
128       restore_directory = true;
129     }
130   }
131   module = ::LoadLibraryW(library_path.value().c_str());
132 
133   // GetLastError() needs to be called immediately after LoadLibraryW call.
134   if (!module && error)
135     error->code = ::GetLastError();
136 
137   if (restore_directory)
138     SetCurrentDirectory(current_directory);
139 
140   // Get the library loading result and log it to UMA.
141   LogLibrarayLoadResultToUMA(
142       GetLoadLibraryResult(are_search_flags_available, !!module));
143 
144   return module;
145 }
146 
LoadSystemLibraryHelper(const FilePath & library_path,NativeLibraryLoadError * error)147 NativeLibrary LoadSystemLibraryHelper(const FilePath& library_path,
148                                       NativeLibraryLoadError* error) {
149   // GetModuleHandleEx and subsequently LoadLibraryEx acquire the LoaderLock,
150   // hence must not be called from Dllmain.
151   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
152   NativeLibrary module;
153   BOOL module_found =
154       ::GetModuleHandleExW(0, library_path.value().c_str(), &module);
155   if (!module_found) {
156     bool are_search_flags_available = AreSearchFlagsAvailable();
157     // Prefer LOAD_LIBRARY_SEARCH_SYSTEM32 to avoid DLL preloading attacks.
158     DWORD flags = are_search_flags_available ? LOAD_LIBRARY_SEARCH_SYSTEM32
159                                              : LOAD_WITH_ALTERED_SEARCH_PATH;
160     module = ::LoadLibraryExW(library_path.value().c_str(), nullptr, flags);
161 
162     if (!module && error)
163       error->code = ::GetLastError();
164 
165     LogLibrarayLoadResultToUMA(
166         GetLoadLibraryResult(are_search_flags_available, !!module));
167   }
168 
169   return module;
170 }
171 
GetSystemLibraryName(FilePath::StringPieceType name)172 FilePath GetSystemLibraryName(FilePath::StringPieceType name) {
173   FilePath library_path;
174   // Use an absolute path to load the DLL to avoid DLL preloading attacks.
175   if (PathService::Get(DIR_SYSTEM, &library_path))
176     library_path = library_path.Append(name);
177   return library_path;
178 }
179 
180 }  // namespace
181 
ToString() const182 std::string NativeLibraryLoadError::ToString() const {
183   return StringPrintf("%lu", code);
184 }
185 
LoadNativeLibraryWithOptions(const FilePath & library_path,const NativeLibraryOptions & options,NativeLibraryLoadError * error)186 NativeLibrary LoadNativeLibraryWithOptions(const FilePath& library_path,
187                                            const NativeLibraryOptions& options,
188                                            NativeLibraryLoadError* error) {
189   return LoadNativeLibraryHelper(library_path, error);
190 }
191 
UnloadNativeLibrary(NativeLibrary library)192 void UnloadNativeLibrary(NativeLibrary library) {
193   FreeLibrary(library);
194 }
195 
GetFunctionPointerFromNativeLibrary(NativeLibrary library,StringPiece name)196 void* GetFunctionPointerFromNativeLibrary(NativeLibrary library,
197                                           StringPiece name) {
198   return reinterpret_cast<void*>(GetProcAddress(library, name.data()));
199 }
200 
GetNativeLibraryName(StringPiece name)201 std::string GetNativeLibraryName(StringPiece name) {
202   DCHECK(IsStringASCII(name));
203   return name.as_string() + ".dll";
204 }
205 
GetLoadableModuleName(StringPiece name)206 std::string GetLoadableModuleName(StringPiece name) {
207   return GetNativeLibraryName(name);
208 }
209 
LoadSystemLibrary(FilePath::StringPieceType name,NativeLibraryLoadError * error)210 NativeLibrary LoadSystemLibrary(FilePath::StringPieceType name,
211                                 NativeLibraryLoadError* error) {
212   FilePath library_path = GetSystemLibraryName(name);
213   if (library_path.empty()) {
214     if (error)
215       error->code = ERROR_NOT_FOUND;
216     return nullptr;
217   }
218   return LoadSystemLibraryHelper(library_path, error);
219 }
220 
PinSystemLibrary(FilePath::StringPieceType name,NativeLibraryLoadError * error)221 NativeLibrary PinSystemLibrary(FilePath::StringPieceType name,
222                                NativeLibraryLoadError* error) {
223   FilePath library_path = GetSystemLibraryName(name);
224   if (library_path.empty()) {
225     if (error)
226       error->code = ERROR_NOT_FOUND;
227     return nullptr;
228   }
229 
230   // GetModuleHandleEx acquires the LoaderLock, hence must not be called from
231   // Dllmain.
232   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
233   ScopedNativeLibrary module;
234   if (::GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN,
235                            library_path.value().c_str(),
236                            ScopedNativeLibrary::Receiver(module).get())) {
237     return module.release();
238   }
239 
240   // Load and pin the library since it wasn't already loaded.
241   module = ScopedNativeLibrary(LoadSystemLibraryHelper(library_path, error));
242   if (!module.is_valid())
243     return nullptr;
244 
245   ScopedNativeLibrary temp;
246   if (::GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN,
247                            library_path.value().c_str(),
248                            ScopedNativeLibrary::Receiver(temp).get())) {
249     return module.release();
250   }
251 
252   if (error)
253     error->code = ::GetLastError();
254   // Return nullptr since we failed to pin the module.
255   return nullptr;
256 }
257 
258 }  // namespace base
259