native_library_posix.cc 2.3 KB

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