native_library_mac.mm revision 3f50c38dc070f4bb515c1b64450dae14f316474e
1// Copyright (c) 2010 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/file_path.h"
10#include "base/file_util.h"
11#include "base/mac/scoped_cftyperef.h"
12#include "base/string_util.h"
13#include "base/threading/thread_restrictions.h"
14#include "base/utf_string_conversions.h"
15
16namespace base {
17
18// static
19NativeLibrary LoadNativeLibrary(const FilePath& library_path) {
20  // dlopen() etc. open the file off disk.
21  if (library_path.Extension() == "dylib" ||
22      !file_util::DirectoryExists(library_path)) {
23    void* dylib = dlopen(library_path.value().c_str(), RTLD_LAZY);
24    if (!dylib)
25      return NULL;
26    NativeLibrary native_lib = new NativeLibraryStruct();
27    native_lib->type = DYNAMIC_LIB;
28    native_lib->dylib = dylib;
29    return native_lib;
30  }
31  base::mac::ScopedCFTypeRef<CFURLRef> url(
32      CFURLCreateFromFileSystemRepresentation(
33          kCFAllocatorDefault,
34          (const UInt8*)library_path.value().c_str(),
35          library_path.value().length(),
36          true));
37  if (!url)
38    return NULL;
39  CFBundleRef bundle = CFBundleCreate(kCFAllocatorDefault, url.get());
40  if (!bundle)
41    return NULL;
42
43  NativeLibrary native_lib = new NativeLibraryStruct();
44  native_lib->type = BUNDLE;
45  native_lib->bundle = bundle;
46  native_lib->bundle_resource_ref = CFBundleOpenBundleResourceMap(bundle);
47  return native_lib;
48}
49
50// static
51void UnloadNativeLibrary(NativeLibrary library) {
52  if (library->type == BUNDLE) {
53    CFBundleCloseBundleResourceMap(library->bundle,
54                                   library->bundle_resource_ref);
55    CFRelease(library->bundle);
56  } else {
57    dlclose(library->dylib);
58  }
59  delete library;
60}
61
62// static
63void* GetFunctionPointerFromNativeLibrary(NativeLibrary library,
64                                          const char* name) {
65  if (library->type == BUNDLE) {
66    base::mac::ScopedCFTypeRef<CFStringRef> symbol_name(
67        CFStringCreateWithCString(kCFAllocatorDefault, name,
68                                  kCFStringEncodingUTF8));
69    return CFBundleGetFunctionPointerForName(library->bundle, symbol_name);
70  }
71  return dlsym(library->dylib, name);
72}
73
74// static
75string16 GetNativeLibraryName(const string16& name) {
76  return name + ASCIIToUTF16(".dylib");
77}
78
79}  // namespace base
80