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