Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / base / native_library_win.cc
blob1ca3e92f54768b5608faabdb9489631c2cc5cf08
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"
7 #include <windows.h>
9 #include "base/files/file_util.h"
10 #include "base/strings/stringprintf.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "base/threading/thread_restrictions.h"
14 namespace base {
16 typedef HMODULE (WINAPI* LoadLibraryFunction)(const wchar_t* file_name);
18 namespace {
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(&current_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);
47 return module;
50 } // namespace
52 std::string NativeLibraryLoadError::ToString() const {
53 return StringPrintf("%u", code);
56 // static
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);
72 // static
73 void UnloadNativeLibrary(NativeLibrary library) {
74 FreeLibrary(library);
77 // static
78 void* GetFunctionPointerFromNativeLibrary(NativeLibrary library,
79 const char* name) {
80 return GetProcAddress(library, name);
83 // static
84 string16 GetNativeLibraryName(const string16& name) {
85 return name + ASCIIToUTF16(".dll");
88 } // namespace base