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 <dlfcn.h>
8 
9 #include "base/files/file_path.h"
10 #include "base/logging.h"
11 #include "base/strings/string_util.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "base/threading/thread_restrictions.h"
14 
15 namespace base {
16 
ToString() const17 std::string NativeLibraryLoadError::ToString() const {
18   return message;
19 }
20 
21 // static
LoadNativeLibrary(const FilePath & library_path,NativeLibraryLoadError * error)22 NativeLibrary LoadNativeLibrary(const FilePath& library_path,
23                                 NativeLibraryLoadError* error) {
24   // dlopen() opens the file off disk.
25   ThreadRestrictions::AssertIOAllowed();
26 
27   // We deliberately do not use RTLD_DEEPBIND.  For the history why, please
28   // refer to the bug tracker.  Some useful bug reports to read include:
29   // http://crbug.com/17943, http://crbug.com/17557, http://crbug.com/36892,
30   // and http://crbug.com/40794.
31   void* dl = dlopen(library_path.value().c_str(), RTLD_LAZY);
32   if (!dl && error)
33     error->message = dlerror();
34 
35   return dl;
36 }
37 
38 // static
UnloadNativeLibrary(NativeLibrary library)39 void UnloadNativeLibrary(NativeLibrary library) {
40   int ret = dlclose(library);
41   if (ret < 0) {
42     DLOG(ERROR) << "dlclose failed: " << dlerror();
43     NOTREACHED();
44   }
45 }
46 
47 // static
GetFunctionPointerFromNativeLibrary(NativeLibrary library,StringPiece name)48 void* GetFunctionPointerFromNativeLibrary(NativeLibrary library,
49                                           StringPiece name) {
50   return dlsym(library, name.data());
51 }
52 
53 // static
GetNativeLibraryName(StringPiece name)54 std::string GetNativeLibraryName(StringPiece name) {
55   DCHECK(IsStringASCII(name));
56   return "lib" + name.as_string() + ".so";
57 }
58 
59 }  // namespace base
60