blob: 481b1caa15cacb974d30384151521bbadbc7e4ea [file] [log] [blame]
Alex Light185d1342016-08-11 10:48:03 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "plugin.h"
18
19#include <dlfcn.h>
20#include "base/stringprintf.h"
21#include "base/logging.h"
22
23namespace art {
24
25const char* PLUGIN_INITIALIZATION_FUNCTION_NAME = "ArtPlugin_Initialize";
26const char* PLUGIN_DEINITIALIZATION_FUNCTION_NAME = "ArtPlugin_Deinitialize";
27
28Plugin::Plugin(const Plugin& other) : library_(other.library_), dlopen_handle_(nullptr) {
29 if (other.IsLoaded()) {
30 std::string err;
31 Load(&err);
32 }
33}
34
35bool Plugin::Load(/*out*/std::string* error_msg) {
36 DCHECK(!IsLoaded());
37 void* res = dlopen(library_.c_str(), RTLD_LAZY);
38 if (res == nullptr) {
39 *error_msg = StringPrintf("dlopen failed: %s", dlerror());
40 return false;
41 }
42 // Get the initializer function
43 PluginInitializationFunction init = reinterpret_cast<PluginInitializationFunction>(
44 dlsym(res, PLUGIN_INITIALIZATION_FUNCTION_NAME));
45 if (init != nullptr) {
46 if (!init()) {
47 dlclose(res);
48 *error_msg = StringPrintf("Initialization of plugin failed");
49 return false;
50 }
51 } else {
52 LOG(WARNING) << this << " does not include an initialization function";
53 }
54 dlopen_handle_ = res;
55 return true;
56}
57
58bool Plugin::Unload() {
59 DCHECK(IsLoaded());
60 bool ret = true;
61 void* handle = dlopen_handle_;
62 PluginDeinitializationFunction deinit = reinterpret_cast<PluginDeinitializationFunction>(
63 dlsym(handle, PLUGIN_DEINITIALIZATION_FUNCTION_NAME));
64 if (deinit != nullptr) {
65 if (!deinit()) {
66 LOG(WARNING) << this << " failed deinitialization";
67 ret = false;
68 }
69 } else {
70 LOG(WARNING) << this << " does not include a deinitialization function";
71 }
72 dlopen_handle_ = nullptr;
73 if (dlclose(handle) != 0) {
74 LOG(ERROR) << this << " failed to dlclose: " << dlerror();
75 ret = false;
76 }
77 return ret;
78}
79
80std::ostream& operator<<(std::ostream &os, const Plugin* m) {
81 return os << *m;
82}
83
84std::ostream& operator<<(std::ostream &os, Plugin const& m) {
85 return os << "Plugin { library=\"" << m.library_ << "\", handle=" << m.dlopen_handle_ << " }";
86}
87
88} // namespace art