1 /*
2 * Copyright (C) 2017 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 #define LOG_TAG "EffectsFactoryConfigLoader"
18 //#define LOG_NDEBUG 0
19
20 #include <dlfcn.h>
21 #include <set>
22 #include <stdlib.h>
23 #include <string>
24
25 #include <log/log.h>
26
27 #include <media/EffectsConfig.h>
28
29 #include "EffectsConfigLoader.h"
30 #include "EffectsFactoryState.h"
31 #include "EffectsXmlConfigLoader.h"
32
33 namespace android {
34
35 using namespace effectsConfig;
36
37 /////////////////////////////////////////////////
38 // Local functions
39 /////////////////////////////////////////////////
40
41 namespace {
42
43 /** Similarly to dlopen, looks for the provided path in LD_EFFECT_LIBRARY_PATH.
44 * @return true if the library is found and set resolvedPath to its absolute path.
45 * false if not found
46 */
resolveLibrary(const std::string & path,std::string * resolvedPath)47 bool resolveLibrary(const std::string& path, std::string* resolvedPath) {
48 for (auto* libraryDirectory : LD_EFFECT_LIBRARY_PATH) {
49 std::string candidatePath = std::string(libraryDirectory) + '/' + path;
50 if (access(candidatePath.c_str(), R_OK) == 0) {
51 *resolvedPath = std::move(candidatePath);
52 return true;
53 }
54 }
55 return false;
56 }
57
58 /** Loads a library given its relative path and stores the result in libEntry.
59 * @return true on success with libEntry's path, handle and desc filled
60 * false on success with libEntry's path filled with the path of the failed lib
61 * The caller MUST free the resources path (free) and handle (dlclose) if filled.
62 */
loadLibrary(const char * relativePath,lib_entry_t * libEntry)63 bool loadLibrary(const char* relativePath, lib_entry_t* libEntry) noexcept {
64
65 std::string absolutePath;
66 if (!resolveLibrary(relativePath, &absolutePath)) {
67 ALOGE("%s Could not find library in effect directories: %s", __func__, relativePath);
68 libEntry->path = strdup(relativePath);
69 return false;
70 }
71 const char* path = absolutePath.c_str();
72 libEntry->path = strdup(path);
73
74 // Make sure the lib is closed on early return
75 std::unique_ptr<void, decltype(dlclose)*> libHandle(dlopen(path, RTLD_NOW),
76 dlclose);
77 if (libHandle == nullptr) {
78 ALOGE("%s Could not dlopen library %s: %s", __func__, path, dlerror());
79 return false;
80 }
81
82 auto* description = static_cast<audio_effect_library_t*>(
83 dlsym(libHandle.get(), AUDIO_EFFECT_LIBRARY_INFO_SYM_AS_STR));
84 if (description == nullptr) {
85 ALOGE("%s Invalid effect library, failed not find symbol '%s' in %s: %s", __func__,
86 AUDIO_EFFECT_LIBRARY_INFO_SYM_AS_STR, path, dlerror());
87 return false;
88 }
89
90 if (description->tag != AUDIO_EFFECT_LIBRARY_TAG) {
91 ALOGE("%s Bad tag %#08x in description structure, expected %#08x for library %s", __func__,
92 description->tag, AUDIO_EFFECT_LIBRARY_TAG, path);
93 return false;
94 }
95
96 uint32_t majorVersion = EFFECT_API_VERSION_MAJOR(description->version);
97 uint32_t expectedMajorVersion = EFFECT_API_VERSION_MAJOR(EFFECT_LIBRARY_API_VERSION_CURRENT);
98 if (majorVersion != expectedMajorVersion) {
99 ALOGE("%s Unsupported major version %#08x, expected %#08x for library %s",
100 __func__, majorVersion, expectedMajorVersion, path);
101 return false;
102 }
103
104 libEntry->handle = libHandle.release();
105 libEntry->desc = description;
106 return true;
107 }
108
109 /** Because the structures will be destroyed by c code, using new to allocate shared structure
110 * is not possible. Provide a equivalent of unique_ptr for malloc/freed structure to make sure
111 * they are not leaked in the c++ code.
112 @{ */
113 struct FreeDeleter {
operator ()android::__anone7873cb40111::FreeDeleter114 void operator()(void* p) {
115 free(p);
116 }
117 };
118 /** unique_ptr for object created with malloc. */
119 template <class T>
120 using UniqueCPtr = std::unique_ptr<T, FreeDeleter>;
121
122 /** c version of std::make_unique. Uses malloc and free. */
123 template <class T>
makeUniqueC()124 UniqueCPtr<T> makeUniqueC() {
125 T* ptr = new (malloc(sizeof(T))) T{}; // Use placement new to initialize the structure
126 return UniqueCPtr<T>{ptr};
127 }
128
129 /** @} */
130
131 /** Push an not owned element in a list_elem link list with an optional lock. */
132 template <class T, class ListElem>
listPush(T * object,ListElem ** list,pthread_mutex_t * mutex=nullptr)133 void listPush(T* object, ListElem** list, pthread_mutex_t* mutex = nullptr) noexcept {
134 auto listElem = makeUniqueC<ListElem>();
135 listElem->object = object;
136 if (mutex != nullptr) {
137 pthread_mutex_lock(mutex);
138 }
139 listElem->next = *list;
140 *list = listElem.release();
141 if (mutex != nullptr) {
142 pthread_mutex_unlock(mutex);
143 }
144 }
145
146 /** Push an owned element in a list_elem link list with an optional lock. */
147 template <class T, class ListElem>
listPush(UniqueCPtr<T> && object,ListElem ** list,pthread_mutex_t * mutex=nullptr)148 void listPush(UniqueCPtr<T>&& object, ListElem** list, pthread_mutex_t* mutex = nullptr) noexcept {
149 listPush(object.release(), list, mutex);
150 }
151
loadLibraries(const effectsConfig::Libraries & libs,list_elem_t ** libList,pthread_mutex_t * libListLock,list_elem_t ** libFailedList)152 size_t loadLibraries(const effectsConfig::Libraries& libs,
153 list_elem_t** libList, pthread_mutex_t* libListLock,
154 list_elem_t** libFailedList)
155 {
156 size_t nbSkippedElement = 0;
157 for (auto& library : libs) {
158 // Construct a lib entry
159 auto libEntry = makeUniqueC<lib_entry_t>();
160 libEntry->name = strdup(library->name.c_str());
161 libEntry->effects = nullptr;
162 pthread_mutex_init(&libEntry->lock, nullptr);
163
164 if (!loadLibrary(library->path.c_str(), libEntry.get())) {
165 // Register library load failure
166 listPush(std::move(libEntry), libFailedList);
167 ++nbSkippedElement;
168 continue;
169 }
170 listPush(std::move(libEntry), libList, libListLock);
171 }
172 return nbSkippedElement;
173 }
174
175 /** Find a library with the given name in the given list. */
findLibrary(const char * name,list_elem_t * list)176 lib_entry_t* findLibrary(const char* name, list_elem_t* list) {
177
178 while (list != nullptr) {
179 auto* object = static_cast<lib_entry_t*>(list->object);
180 if (strcmp(object->name, name) == 0) {
181 return object;
182 }
183 list = list->next;
184 }
185 return nullptr;
186 }
187
188 struct UuidStr {
189 /** Length of an uuid represented as string. @TODO: use a constant instead of 40. */
190 char buff[40];
191 };
192
193 /** @return a string representing the provided uuid.
194 * By not providing an output buffer, it is implicitly created in the caller context.
195 * In such case the return pointer has the same lifetime as the expression containing uuidToString()
196 */
uuidToString(const effect_uuid_t & uuid,UuidStr && str={})197 char* uuidToString(const effect_uuid_t& uuid, UuidStr&& str = {}) {
198 uuidToString(&uuid, str.buff, sizeof(str.buff));
199 return str.buff;
200 }
201
202 struct LoadEffectResult {
203 /** true if the effect is usable (aka, existing lib, desc, right version, unique uuid) */
204 bool success = false;
205 /** Set if the effect lib was found*/
206 lib_entry_t* lib = nullptr;
207 //* Set if the description was successfuly retrieved from the lib */
208 UniqueCPtr<effect_descriptor_t> effectDesc;
209 };
210
loadEffect(const std::shared_ptr<const EffectImpl> & effect,const std::string & name,list_elem_t * libList)211 LoadEffectResult loadEffect(const std::shared_ptr<const EffectImpl>& effect,
212 const std::string& name, list_elem_t* libList) {
213 LoadEffectResult result;
214
215 // Find the effect library
216 result.lib = findLibrary(effect->library->name.c_str(), libList);
217 if (result.lib == nullptr) {
218 ALOGE("%s Could not find library %s to load effect %s",
219 __func__, effect->library->name.c_str(), name.c_str());
220 return result;
221 }
222
223 result.effectDesc = makeUniqueC<effect_descriptor_t>();
224
225 // Get the effect descriptor
226 if (result.lib->desc->get_descriptor(&effect->uuid, result.effectDesc.get()) != 0) {
227 ALOGE("Error querying effect %s on lib %s",
228 uuidToString(effect->uuid), result.lib->name);
229 result.effectDesc.reset();
230 return result;
231 }
232
233 // Dump effect for debug
234 #if (LOG_NDEBUG==0)
235 char s[512];
236 dumpEffectDescriptor(result.effectDesc.get(), s, sizeof(s), 0 /* indent */);
237 ALOGV("loadEffect() read descriptor %p:%s", result.effectDesc.get(), s);
238 #endif
239
240 // Check effect is supported
241 uint32_t expectedMajorVersion = EFFECT_API_VERSION_MAJOR(EFFECT_CONTROL_API_VERSION);
242 if (EFFECT_API_VERSION_MAJOR(result.effectDesc->apiVersion) != expectedMajorVersion) {
243 ALOGE("%s Bad API version %#08x for effect %s in lib %s, expected major %#08x", __func__,
244 result.effectDesc->apiVersion, name.c_str(), result.lib->name, expectedMajorVersion);
245 return result;
246 }
247
248 lib_entry_t *_;
249 if (findEffect(nullptr, &effect->uuid, &_, nullptr) == 0) {
250 ALOGE("%s Effect %s uuid %s already exist", __func__, uuidToString(effect->uuid),
251 name.c_str());
252 return result;
253 }
254
255 result.success = true;
256 return result;
257 }
258
loadEffects(const Effects & effects,list_elem_t * libList,list_elem_t ** skippedEffects,list_sub_elem_t ** subEffectList)259 size_t loadEffects(const Effects& effects, list_elem_t* libList, list_elem_t** skippedEffects,
260 list_sub_elem_t** subEffectList) {
261 size_t nbSkippedElement = 0;
262
263 for (auto& effect : effects) {
264 if (!effect) {
265 continue;
266 }
267
268 auto effectLoadResult = loadEffect(effect, effect->name, libList);
269 if (!effectLoadResult.success) {
270 if (effectLoadResult.effectDesc != nullptr) {
271 listPush(std::move(effectLoadResult.effectDesc), skippedEffects);
272 }
273 ++nbSkippedElement;
274 continue;
275 }
276
277 if (effect->isProxy) {
278 auto swEffectLoadResult = loadEffect(effect->libSw, effect->name + " libsw", libList);
279 auto hwEffectLoadResult = loadEffect(effect->libHw, effect->name + " libhw", libList);
280 if (!swEffectLoadResult.success || !hwEffectLoadResult.success) {
281 // Push the main effect in the skipped list even if only a subeffect is invalid
282 // as the main effect is not usable without its subeffects.
283 listPush(std::move(effectLoadResult.effectDesc), skippedEffects);
284 ++nbSkippedElement;
285 continue;
286 }
287 listPush(effectLoadResult.effectDesc.get(), subEffectList);
288
289 // Since we return a stub descriptor for the proxy during
290 // get_descriptor call, we replace it with the corresponding
291 // sw effect descriptor, but keep the Proxy UUID
292 *effectLoadResult.effectDesc = *swEffectLoadResult.effectDesc;
293 effectLoadResult.effectDesc->uuid = effect->uuid;
294
295 effectLoadResult.effectDesc->flags |= EFFECT_FLAG_OFFLOAD_SUPPORTED;
296
297 auto registerSubEffect = [subEffectList](auto&& result) {
298 auto entry = makeUniqueC<sub_effect_entry_t>();
299 entry->object = result.effectDesc.release();
300 // lib_entry_t is stored since the sub effects are not linked to the library
301 entry->lib = result.lib;
302 listPush(std::move(entry), &(*subEffectList)->sub_elem);
303 };
304 registerSubEffect(std::move(swEffectLoadResult));
305 registerSubEffect(std::move(hwEffectLoadResult));
306 }
307
308 listPush(std::move(effectLoadResult.effectDesc), &effectLoadResult.lib->effects);
309 }
310 return nbSkippedElement;
311 }
312
313 } // namespace
314
315 /////////////////////////////////////////////////
316 // Interface function
317 /////////////////////////////////////////////////
318
EffectLoadXmlEffectConfig(const char * path)319 extern "C" ssize_t EffectLoadXmlEffectConfig(const char* path)
320 {
321 using effectsConfig::parse;
322 auto result = path ? parse(path) : parse();
323 if (result.parsedConfig == nullptr) {
324 ALOGE("Failed to parse XML configuration file");
325 return -1;
326 }
327 result.nbSkippedElement += loadLibraries(result.parsedConfig->libraries,
328 &gLibraryList, &gLibLock, &gLibraryFailedList) +
329 loadEffects(result.parsedConfig->effects, gLibraryList,
330 &gSkippedEffects, &gSubEffectList);
331
332 ALOGE_IF(result.nbSkippedElement != 0, "%s %zu errors during loading of configuration: %s",
333 __func__, result.nbSkippedElement,
334 result.configPath.empty() ? "No config file found" : result.configPath.c_str());
335
336 return result.nbSkippedElement;
337 }
338
339 } // namespace android
340