Port PluginObject fix downstream. See http://trac.webkit.org/changeset/61415/ for...
[chromium-blink-merge.git] / base / native_library_mac.mm
blob8aaeeb12ff0dde6fabfce20aca6f32a501d0e1ad
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.
5 #include "base/native_library.h"
7 #include <dlfcn.h>
8 #import <Carbon/Carbon.h>
10 #include "base/file_path.h"
11 #include "base/file_util.h"
12 #include "base/scoped_cftyperef.h"
13 #include "base/string_util.h"
15 namespace base {
17 // static
18 NativeLibrary 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;
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;
47 // static
48 void 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;
59 // static
60 void* 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);
71 // static
72 string16 GetNativeLibraryName(const string16& name) {
73   return name + ASCIIToUTF16(".dylib");
76 }  // namespace base