• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2011 The Chromium Authors
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 <string_view>
10 
11 #include "base/files/file_path.h"
12 #include "base/logging.h"
13 #include "base/notreached.h"
14 #include "base/strings/strcat.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/threading/scoped_blocking_call.h"
18 #include "build/build_config.h"
19 
20 namespace base {
21 
ToString() const22 std::string NativeLibraryLoadError::ToString() const {
23   return message;
24 }
25 
LoadNativeLibraryWithOptions(const FilePath & library_path,const NativeLibraryOptions & options,NativeLibraryLoadError * error)26 NativeLibrary LoadNativeLibraryWithOptions(const FilePath& library_path,
27                                            const NativeLibraryOptions& options,
28                                            NativeLibraryLoadError* error) {
29   // dlopen() opens the file off disk.
30   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
31 
32   // We deliberately do not use RTLD_DEEPBIND by default.  For the history why,
33   // please refer to the bug tracker.  Some useful bug reports to read include:
34   // http://crbug.com/17943, http://crbug.com/17557, http://crbug.com/36892,
35   // and http://crbug.com/40794.
36   int flags = RTLD_LAZY;
37 #if BUILDFLAG(IS_ANDROID) || !defined(RTLD_DEEPBIND)
38   // Certain platforms don't define RTLD_DEEPBIND. Android dlopen() requires
39   // further investigation, as it might vary across versions. Crash here to
40   // warn developers that they're trying to rely on uncertain behavior.
41   CHECK(!options.prefer_own_symbols);
42 #else
43   if (options.prefer_own_symbols)
44     flags |= RTLD_DEEPBIND;
45 #endif
46   void* dl = dlopen(library_path.value().c_str(), flags);
47   if (!dl && error)
48     error->message = dlerror();
49 
50   return dl;
51 }
52 
UnloadNativeLibrary(NativeLibrary library)53 void UnloadNativeLibrary(NativeLibrary library) {
54   int ret = dlclose(library);
55   if (ret < 0) {
56     DLOG(ERROR) << "dlclose failed: " << dlerror();
57     NOTREACHED();
58   }
59 }
60 
GetFunctionPointerFromNativeLibrary(NativeLibrary library,const char * name)61 void* GetFunctionPointerFromNativeLibrary(NativeLibrary library,
62                                           const char* name) {
63   return dlsym(library, name);
64 }
65 
GetNativeLibraryName(std::string_view name)66 std::string GetNativeLibraryName(std::string_view name) {
67   DCHECK(IsStringASCII(name));
68   return StrCat({"lib", name, ".so"});
69 }
70 
GetLoadableModuleName(std::string_view name)71 std::string GetLoadableModuleName(std::string_view name) {
72   return GetNativeLibraryName(name);
73 }
74 
75 }  // namespace base
76