1 /*
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 #ifndef ART_RUNTIME_PLUGIN_H_
18 #define ART_RUNTIME_PLUGIN_H_
19 
20 #include <string>
21 
22 #include <android-base/logging.h>
23 
24 namespace art {
25 
26 // This function is loaded from the plugin (if present) and called during runtime initialization.
27 // By the time this has been called the runtime has been fully initialized but not other native
28 // libraries have been loaded yet. Failure to initialize is considered a fatal error.
29 // TODO might want to give initialization function some arguments
30 using PluginInitializationFunction = bool (*)();
31 using PluginDeinitializationFunction = bool (*)();
32 
33 // A class encapsulating a plugin. There is no stable plugin ABI or API and likely never will be.
34 // TODO Might want to put some locking in this but ATM we only load these at initialization in a
35 // single-threaded fashion so not much need
36 class Plugin {
37  public:
Create(const std::string & lib)38   static Plugin Create(const std::string& lib) {
39     return Plugin(lib);
40   }
41 
IsLoaded()42   bool IsLoaded() const {
43     return dlopen_handle_ != nullptr;
44   }
45 
GetLibrary()46   const std::string& GetLibrary() const {
47     return library_;
48   }
49 
50   bool Load(/*out*/std::string* error_msg);
51   bool Unload();
52 
53 
~Plugin()54   ~Plugin() {
55     if (IsLoaded() && !Unload()) {
56       LOG(ERROR) << "Error unloading " << this;
57     }
58   }
59 
60   Plugin(const Plugin& other);
61 
62   // Create move constructor for putting this in a list
Plugin(Plugin && other)63   Plugin(Plugin&& other) noexcept
64       : library_(other.library_),
65         dlopen_handle_(other.dlopen_handle_) {
66     other.dlopen_handle_ = nullptr;
67   }
68 
69  private:
Plugin(const std::string & library)70   explicit Plugin(const std::string& library) : library_(library), dlopen_handle_(nullptr) { }
71 
72   std::string library_;
73   void* dlopen_handle_;
74 
75   friend std::ostream& operator<<(std::ostream &os, Plugin const& m);
76 };
77 
78 std::ostream& operator<<(std::ostream &os, Plugin const& m);
79 std::ostream& operator<<(std::ostream &os, const Plugin* m);
80 
81 }  // namespace art
82 
83 #endif  // ART_RUNTIME_PLUGIN_H_
84