blob: 60175106ee73f25917d2739d0820ab7ba37e643f [file] [log] [blame]
Jeff Tinker1de11dc2016-12-19 15:21:26 -08001/**
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 PLUGIN_LOADER_H_
18#define PLUGIN_LOADER_H_
19
20#include "SharedLibrary.h"
21#include <utils/Log.h>
22#include <utils/String8.h>
23#include <utils/Vector.h>
24
25namespace android {
26
27template <class T>
28class PluginLoader {
29
30 public:
31 PluginLoader(const char *dir, const char *entry, const char *type) {
32 /**
33 * scan all plugins in the plugin directory and add them to the
34 * factories list.
35 */
36 String8 pluginDir(dir);
37
38 DIR* pDir = opendir(pluginDir.string());
39 if (pDir == NULL) {
40 ALOGE("Failed to find plugin directory %s", pluginDir.string());
41 } else {
42 struct dirent* pEntry;
43 while ((pEntry = readdir(pDir))) {
44 String8 file(pEntry->d_name);
45 if (file.getPathExtension() == ".so") {
46 String8 path = pluginDir + pEntry->d_name;
47 T *plugin = loadOne(path, entry, type);
48 if (plugin) {
49 factories.push(plugin);
50 }
51 }
52 }
53 closedir(pDir);
54 }
55 }
56
57 ~PluginLoader() {
58 for (size_t i = 0; i < factories.size(); i++) {
59 delete factories[i];
60 }
61 }
62
63 T *getFactory(size_t i) const {return factories[i];}
64 size_t factoryCount() const {return factories.size();}
65
66 private:
67 T* loadOne(const char *path, const char *entry, const char *type) {
68 sp<SharedLibrary> library = new SharedLibrary(String8(path));
69 if (!library.get()) {
70 ALOGE("Failed to open %s plugin library %s: %s", type, path,
71 library->lastError());
72 } else {
73 typedef T *(*CreateFactoryFunc)();
74 CreateFactoryFunc createFactoryFunc =
75 (CreateFactoryFunc)library->lookup(entry);
76 if (createFactoryFunc) {
77 libraries.push(library);
78 return createFactoryFunc();
79 } else {
80 ALOGE("Failed to create %s plugin factory from %s", type, path);
81 }
82 }
83 return NULL;
84 }
85
86 Vector<T *> factories;
87 Vector<sp<SharedLibrary> > libraries;
88
89 PluginLoader(const PluginLoader &) = delete;
90 void operator=(const PluginLoader &) = delete;
91};
92
93} // namespace android
94
95#endif // PLUGIN_LOADER_H_
96