• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
LoadNativeLibraryWithOptions(const FilePath & library_path,const NativeLibraryOptions & options,NativeLibraryLoadError * error)21 NativeLibrary LoadNativeLibraryWithOptions(const FilePath& library_path,
22                                            const NativeLibraryOptions& options,
23                                            NativeLibraryLoadError* error) {
24   // dlopen() opens the file off disk.
25   AssertBlockingAllowed();
26 
27   // We deliberately do not use RTLD_DEEPBIND by default.  For the history why,
28   // please 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   int flags = RTLD_LAZY;
32 #if defined(OS_ANDROID) || !defined(RTLD_DEEPBIND)
33   // Certain platforms don't define RTLD_DEEPBIND. Android dlopen() requires
34   // further investigation, as it might vary across versions. Crash here to
35   // warn developers that they're trying to rely on uncertain behavior.
36   CHECK(!options.prefer_own_symbols);
37 #else
38   if (options.prefer_own_symbols)
39     flags |= RTLD_DEEPBIND;
40 #endif
41   void* dl = dlopen(library_path.value().c_str(), flags);
42   if (!dl && error)
43     error->message = dlerror();
44 
45   return dl;
46 }
47 
UnloadNativeLibrary(NativeLibrary library)48 void UnloadNativeLibrary(NativeLibrary library) {
49   int ret = dlclose(library);
50   if (ret < 0) {
51     DLOG(ERROR) << "dlclose failed: " << dlerror();
52     NOTREACHED();
53   }
54 }
55 
GetFunctionPointerFromNativeLibrary(NativeLibrary library,StringPiece name)56 void* GetFunctionPointerFromNativeLibrary(NativeLibrary library,
57                                           StringPiece name) {
58   return dlsym(library, name.data());
59 }
60 
GetNativeLibraryName(StringPiece name)61 std::string GetNativeLibraryName(StringPiece name) {
62   DCHECK(IsStringASCII(name));
63   return "lib" + name.as_string() + ".so";
64 }
65 
GetLoadableModuleName(StringPiece name)66 std::string GetLoadableModuleName(StringPiece name) {
67   return GetNativeLibraryName(name);
68 }
69 
70 }  // namespace base
71