summaryrefslogtreecommitdiffstats
path: root/base/native_library_mac.mm
blob: 577f5acaef09dff2b921b9010d7466cb9c705587 (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
// Copyright (c) 2009 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>
#import <Carbon/Carbon.h>

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/scoped_cftyperef.h"
#include "base/string_util.h"

namespace base {

// static
NativeLibrary LoadNativeLibrary(const FilePath& library_path) {
  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;
  }
  scoped_cftyperef<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;
  return native_lib;
}

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

// static
void* GetFunctionPointerFromNativeLibrary(NativeLibrary library,
                                          const char* name) {
  if (library->type == BUNDLE)
    return CFBundleGetFunctionPointerForName(library->bundle,
        CFStringCreateWithCString(kCFAllocatorDefault, name,
                                  kCFStringEncodingUTF8));

  return dlsym(library->dylib, name);
}

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

}  // namespace base