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.
5 #include "base/native_library.h"
9 #include "base/file_util.h"
10 #include "base/strings/stringprintf.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "base/threading/thread_restrictions.h"
16 typedef HMODULE (WINAPI
* LoadLibraryFunction
)(const wchar_t* file_name
);
20 NativeLibrary
LoadNativeLibraryHelper(const FilePath
& library_path
,
21 LoadLibraryFunction load_library_api
,
22 NativeLibraryLoadError
* error
) {
23 // LoadLibrary() opens the file off disk.
24 ThreadRestrictions::AssertIOAllowed();
26 // Switch the current directory to the library directory as the library
27 // may have dependencies on DLLs in this directory.
28 bool restore_directory
= false;
29 FilePath current_directory
;
30 if (GetCurrentDirectory(¤t_directory
)) {
31 FilePath plugin_path
= library_path
.DirName();
32 if (!plugin_path
.empty()) {
33 SetCurrentDirectory(plugin_path
);
34 restore_directory
= true;
38 HMODULE module
= (*load_library_api
)(library_path
.value().c_str());
39 if (!module
&& error
) {
40 // GetLastError() needs to be called immediately after |load_library_api|.
41 error
->code
= GetLastError();
44 if (restore_directory
)
45 SetCurrentDirectory(current_directory
);
52 std::string
NativeLibraryLoadError::ToString() const {
53 return StringPrintf("%u", code
);
57 NativeLibrary
LoadNativeLibrary(const FilePath
& library_path
,
58 NativeLibraryLoadError
* error
) {
59 return LoadNativeLibraryHelper(library_path
, LoadLibraryW
, error
);
62 NativeLibrary
LoadNativeLibraryDynamically(const FilePath
& library_path
) {
63 typedef HMODULE (WINAPI
* LoadLibraryFunction
)(const wchar_t* file_name
);
65 LoadLibraryFunction load_library
;
66 load_library
= reinterpret_cast<LoadLibraryFunction
>(
67 GetProcAddress(GetModuleHandle(L
"kernel32.dll"), "LoadLibraryW"));
69 return LoadNativeLibraryHelper(library_path
, load_library
, NULL
);
73 void UnloadNativeLibrary(NativeLibrary library
) {
78 void* GetFunctionPointerFromNativeLibrary(NativeLibrary library
,
80 return GetProcAddress(library
, name
);
84 string16
GetNativeLibraryName(const string16
& name
) {
85 return name
+ ASCIIToUTF16(".dll");