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