summaryrefslogtreecommitdiffstats
path: root/base/native_library_mac.mm
blob: 9f7a9679dcae220a544ae485e0572c5c2c98901c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/native_library.h"

#include <dlfcn.h>

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/string_util.h"
#include "base/threading/thread_restrictions.h"
#include "base/utf_string_conversions.h"

namespace base {

// static
NativeLibrary LoadNativeLibrary(const FilePath& library_path,
                                std::string* error) {
  // dlopen() etc. open the file off disk.
  if (library_path.Extension() == "dylib" ||
      !file_util::DirectoryExists(library_path)) {
    void* dylib = dlopen(library_path.value().c_str(), RTLD_LAZY);
    if (!dylib)
      return NULL;
    NativeLibrary native_lib = new NativeLibraryStruct();
    native_lib->type = DYNAMIC_LIB;
    native_lib->dylib = dylib;
    return native_lib;
  }
  base::mac::ScopedCFTypeRef<CFURLRef> url(
      CFURLCreateFromFileSystemRepresentation(
          kCFAllocatorDefault,
          (const UInt8*)library_path.value().c_str(),
          library_path.value().length(),
          true));
  if (!url)
    return NULL;
  CFBundleRef bundle = CFBundleCreate(kCFAllocatorDefault, url.get());
  if (!bundle)
    return NULL;

  NativeLibrary native_lib = new NativeLibraryStruct();
  native_lib->type = BUNDLE;
  native_lib->bundle = bundle;
  native_lib->bundle_resource_ref = CFBundleOpenBundleResourceMap(bundle);
  return native_lib;
}

// static
void UnloadNativeLibrary(NativeLibrary library) {
  if (library->type == BUNDLE) {
    CFBundleCloseBundleResourceMap(library->bundle,
                                   library->bundle_resource_ref);
    CFRelease(library->bundle);
  } else {
    dlclose(library->dylib);
  }
  delete library;
}

// static
void* GetFunctionPointerFromNativeLibrary(NativeLibrary library,
                                          const char* name) {
  if (library->type == BUNDLE) {
    base::mac::ScopedCFTypeRef<CFStringRef> symbol_name(
        CFStringCreateWithCString(kCFAllocatorDefault, name,
                                  kCFStringEncodingUTF8));
    return CFBundleGetFunctionPointerForName(library->bundle, symbol_name);
  }
  return dlsym(library->dylib, name);
}

// static
string16 GetNativeLibraryName(const string16& name) {
  return name + ASCIIToUTF16(".dylib");
}

}  // namespace base