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