1 /*
2  * Copyright 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 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
18 
19 #include "layers_extensions.h"
20 
21 #include <alloca.h>
22 #include <dirent.h>
23 #include <dlfcn.h>
24 #include <string.h>
25 #include <sys/prctl.h>
26 
27 #include <memory>
28 #include <mutex>
29 #include <string>
30 #include <vector>
31 
32 #include <android/dlext.h>
33 #include <android-base/strings.h>
34 #include <cutils/properties.h>
35 #include <graphicsenv/GraphicsEnv.h>
36 #include <log/log.h>
37 #include <nativebridge/native_bridge.h>
38 #include <nativeloader/native_loader.h>
39 #include <utils/Trace.h>
40 #include <ziparchive/zip_archive.h>
41 
42 // TODO(jessehall): The whole way we deal with extensions is pretty hokey, and
43 // not a good long-term solution. Having a hard-coded enum of extensions is
44 // bad, of course. Representing sets of extensions (requested, supported, etc.)
45 // as a bitset isn't necessarily bad, if the mapping from extension to bit were
46 // dynamic. Need to rethink this completely when there's a little more time.
47 
48 // TODO(jessehall): This file currently builds up global data structures as it
49 // loads, and never cleans them up. This means we're doing heap allocations
50 // without going through an app-provided allocator, but worse, we'll leak those
51 // allocations if the loader is unloaded.
52 //
53 // We should allocate "enough" BSS space, and suballocate from there. Will
54 // probably want to intern strings, etc., and will need some custom/manual data
55 // structures.
56 
57 namespace vulkan {
58 namespace api {
59 
60 struct Layer {
61     VkLayerProperties properties;
62     size_t library_idx;
63 
64     // true if the layer intercepts vkCreateDevice and device commands
65     bool is_global;
66 
67     std::vector<VkExtensionProperties> instance_extensions;
68     std::vector<VkExtensionProperties> device_extensions;
69 };
70 
71 namespace {
72 
73 const char kSystemLayerLibraryDir[] = "/data/local/debug/vulkan";
74 
75 class LayerLibrary {
76    public:
LayerLibrary(const std::string & path,const std::string & filename)77     explicit LayerLibrary(const std::string& path,
78                           const std::string& filename)
79         : path_(path),
80           filename_(filename),
81           dlhandle_(nullptr),
82           native_bridge_(false),
83           refcount_(0) {}
84 
LayerLibrary(LayerLibrary && other)85     LayerLibrary(LayerLibrary&& other) noexcept
86         : path_(std::move(other.path_)),
87           filename_(std::move(other.filename_)),
88           dlhandle_(other.dlhandle_),
89           native_bridge_(other.native_bridge_),
90           refcount_(other.refcount_) {
91         other.dlhandle_ = nullptr;
92         other.refcount_ = 0;
93     }
94 
95     LayerLibrary(const LayerLibrary&) = delete;
96     LayerLibrary& operator=(const LayerLibrary&) = delete;
97 
98     // these are thread-safe
99     bool Open();
100     void Close();
101 
102     bool EnumerateLayers(size_t library_idx,
103                          std::vector<Layer>& instance_layers) const;
104 
105     void* GetGPA(const Layer& layer, const std::string_view gpa_name) const;
106 
GetFilename()107     const std::string GetFilename() { return filename_; }
108 
109    private:
110     // TODO(b/79940628): remove that adapter when we could use NativeBridgeGetTrampoline
111     // for native libraries.
112     template<typename Func = void*>
GetTrampoline(const char * name) const113     Func GetTrampoline(const char* name) const {
114         if (native_bridge_) {
115             return reinterpret_cast<Func>(android::NativeBridgeGetTrampoline(
116                 dlhandle_, name, nullptr, 0));
117         }
118         return reinterpret_cast<Func>(dlsym(dlhandle_, name));
119     }
120 
121     const std::string path_;
122 
123     // Track the filename alone so we can detect duplicates
124     const std::string filename_;
125 
126     std::mutex mutex_;
127     void* dlhandle_;
128     bool native_bridge_;
129     size_t refcount_;
130 };
131 
Open()132 bool LayerLibrary::Open() {
133     std::lock_guard<std::mutex> lock(mutex_);
134     if (refcount_++ == 0) {
135         ALOGV("opening layer library '%s'", path_.c_str());
136         // Libraries in the system layer library dir can't be loaded into
137         // the application namespace. That causes compatibility problems, since
138         // any symbol dependencies will be resolved by system libraries. They
139         // can't safely use libc++_shared, for example. Which is one reason
140         // (among several) we only allow them in non-user builds.
141         auto app_namespace = android::GraphicsEnv::getInstance().getAppNamespace();
142         if (app_namespace &&
143             !android::base::StartsWith(path_, kSystemLayerLibraryDir)) {
144             char* error_msg = nullptr;
145             dlhandle_ = OpenNativeLibraryInNamespace(
146                 app_namespace, path_.c_str(), &native_bridge_, &error_msg);
147             if (!dlhandle_) {
148                 ALOGE("failed to load layer library '%s': %s", path_.c_str(), error_msg);
149                 android::NativeLoaderFreeErrorMessage(error_msg);
150                 refcount_ = 0;
151                 return false;
152             }
153         } else {
154           dlhandle_ = dlopen(path_.c_str(), RTLD_NOW | RTLD_LOCAL);
155             if (!dlhandle_) {
156                 ALOGE("failed to load layer library '%s': %s", path_.c_str(),
157                       dlerror());
158                 refcount_ = 0;
159                 return false;
160             }
161         }
162     }
163     return true;
164 }
165 
Close()166 void LayerLibrary::Close() {
167     std::lock_guard<std::mutex> lock(mutex_);
168     if (--refcount_ == 0) {
169         ALOGV("closing layer library '%s'", path_.c_str());
170         char* error_msg = nullptr;
171         if (!android::CloseNativeLibrary(dlhandle_, native_bridge_, &error_msg)) {
172             ALOGE("failed to unload library '%s': %s", path_.c_str(), error_msg);
173             android::NativeLoaderFreeErrorMessage(error_msg);
174             refcount_++;
175         } else {
176            dlhandle_ = nullptr;
177         }
178     }
179 }
180 
EnumerateLayers(size_t library_idx,std::vector<Layer> & instance_layers) const181 bool LayerLibrary::EnumerateLayers(size_t library_idx,
182                                    std::vector<Layer>& instance_layers) const {
183     PFN_vkEnumerateInstanceLayerProperties enumerate_instance_layers =
184         GetTrampoline<PFN_vkEnumerateInstanceLayerProperties>(
185             "vkEnumerateInstanceLayerProperties");
186     PFN_vkEnumerateInstanceExtensionProperties enumerate_instance_extensions =
187         GetTrampoline<PFN_vkEnumerateInstanceExtensionProperties>(
188             "vkEnumerateInstanceExtensionProperties");
189     if (!enumerate_instance_layers || !enumerate_instance_extensions) {
190         ALOGE("layer library '%s' missing some instance enumeration functions",
191               path_.c_str());
192         return false;
193     }
194 
195     // device functions are optional
196     PFN_vkEnumerateDeviceLayerProperties enumerate_device_layers =
197         GetTrampoline<PFN_vkEnumerateDeviceLayerProperties>(
198             "vkEnumerateDeviceLayerProperties");
199     PFN_vkEnumerateDeviceExtensionProperties enumerate_device_extensions =
200         GetTrampoline<PFN_vkEnumerateDeviceExtensionProperties>(
201             "vkEnumerateDeviceExtensionProperties");
202 
203     // get layer counts
204     uint32_t num_instance_layers = 0;
205     uint32_t num_device_layers = 0;
206     VkResult result = enumerate_instance_layers(&num_instance_layers, nullptr);
207     if (result != VK_SUCCESS || !num_instance_layers) {
208         if (result != VK_SUCCESS) {
209             ALOGE(
210                 "vkEnumerateInstanceLayerProperties failed for library '%s': "
211                 "%d",
212                 path_.c_str(), result);
213         }
214         return false;
215     }
216     if (enumerate_device_layers) {
217         result = enumerate_device_layers(VK_NULL_HANDLE, &num_device_layers,
218                                          nullptr);
219         if (result != VK_SUCCESS) {
220             ALOGE(
221                 "vkEnumerateDeviceLayerProperties failed for library '%s': %d",
222                 path_.c_str(), result);
223             return false;
224         }
225     }
226 
227     // get layer properties
228     auto properties = std::make_unique<VkLayerProperties[]>(num_instance_layers + num_device_layers);
229     if (num_device_layers > 0) {
230         result = enumerate_device_layers(VK_NULL_HANDLE, &num_device_layers,
231                                          properties.get() + num_instance_layers);
232         if (result != VK_SUCCESS) {
233             ALOGE(
234                 "vkEnumerateDeviceLayerProperties failed for library '%s': %d",
235                 path_.c_str(), result);
236             return false;
237         }
238     }
239 
240     // append layers to instance_layers
241     size_t prev_num_instance_layers = instance_layers.size();
242     instance_layers.reserve(prev_num_instance_layers + num_instance_layers);
243     for (size_t i = 0; i < num_instance_layers; i++) {
244         const VkLayerProperties& props = properties[i];
245 
246         Layer layer;
247         layer.properties = props;
248         layer.library_idx = library_idx;
249         layer.is_global = false;
250 
251         uint32_t count = 0;
252         result =
253             enumerate_instance_extensions(props.layerName, &count, nullptr);
254         if (result != VK_SUCCESS) {
255             ALOGE(
256                 "vkEnumerateInstanceExtensionProperties(\"%s\") failed for "
257                 "library '%s': %d",
258                 props.layerName, path_.c_str(), result);
259             instance_layers.resize(prev_num_instance_layers);
260             return false;
261         }
262         layer.instance_extensions.resize(count);
263         result = enumerate_instance_extensions(
264             props.layerName, &count, layer.instance_extensions.data());
265         if (result != VK_SUCCESS) {
266             ALOGE(
267                 "vkEnumerateInstanceExtensionProperties(\"%s\") failed for "
268                 "library '%s': %d",
269                 props.layerName, path_.c_str(), result);
270             instance_layers.resize(prev_num_instance_layers);
271             return false;
272         }
273 
274         for (size_t j = 0; j < num_device_layers; j++) {
275             const auto& dev_props = properties[num_instance_layers + j];
276             if (memcmp(&props, &dev_props, sizeof(props)) == 0) {
277                 layer.is_global = true;
278                 break;
279             }
280         }
281 
282         if (layer.is_global && enumerate_device_extensions) {
283             result = enumerate_device_extensions(
284                 VK_NULL_HANDLE, props.layerName, &count, nullptr);
285             if (result != VK_SUCCESS) {
286                 ALOGE(
287                     "vkEnumerateDeviceExtensionProperties(\"%s\") failed for "
288                     "library '%s': %d",
289                     props.layerName, path_.c_str(), result);
290                 instance_layers.resize(prev_num_instance_layers);
291                 return false;
292             }
293             layer.device_extensions.resize(count);
294             result = enumerate_device_extensions(
295                 VK_NULL_HANDLE, props.layerName, &count,
296                 layer.device_extensions.data());
297             if (result != VK_SUCCESS) {
298                 ALOGE(
299                     "vkEnumerateDeviceExtensionProperties(\"%s\") failed for "
300                     "library '%s': %d",
301                     props.layerName, path_.c_str(), result);
302                 instance_layers.resize(prev_num_instance_layers);
303                 return false;
304             }
305         }
306 
307         instance_layers.push_back(layer);
308         ALOGD("added %s layer '%s' from library '%s'",
309               (layer.is_global) ? "global" : "instance", props.layerName,
310               path_.c_str());
311     }
312 
313     return true;
314 }
315 
GetGPA(const Layer & layer,const std::string_view gpa_name) const316 void* LayerLibrary::GetGPA(const Layer& layer, const std::string_view gpa_name) const {
317     std::string layer_name { layer.properties.layerName };
318     if (void* gpa = GetTrampoline((layer_name.append(gpa_name).c_str())))
319         return gpa;
320     return GetTrampoline((std::string {"vk"}.append(gpa_name)).c_str());
321 }
322 
323 // ----------------------------------------------------------------------------
324 
325 std::vector<LayerLibrary> g_layer_libraries;
326 std::vector<Layer> g_instance_layers;
327 
AddLayerLibrary(const std::string & path,const std::string & filename)328 void AddLayerLibrary(const std::string& path, const std::string& filename) {
329     LayerLibrary library(path + "/" + filename, filename);
330     if (!library.Open())
331         return;
332 
333     if (!library.EnumerateLayers(g_layer_libraries.size(), g_instance_layers)) {
334         library.Close();
335         return;
336     }
337 
338     library.Close();
339 
340     g_layer_libraries.emplace_back(std::move(library));
341 }
342 
343 template <typename Functor>
ForEachFileInDir(const std::string & dirname,Functor functor)344 void ForEachFileInDir(const std::string& dirname, Functor functor) {
345     auto dir_deleter = [](DIR* handle) { closedir(handle); };
346     std::unique_ptr<DIR, decltype(dir_deleter)> dir(opendir(dirname.c_str()),
347                                                     dir_deleter);
348     if (!dir) {
349         // It's normal for some search directories to not exist, especially
350         // /data/local/debug/vulkan.
351         int err = errno;
352         ALOGW_IF(err != ENOENT, "failed to open layer directory '%s': %s",
353                  dirname.c_str(), strerror(err));
354         return;
355     }
356     ALOGD("searching for layers in '%s'", dirname.c_str());
357     dirent* entry;
358     while ((entry = readdir(dir.get())) != nullptr)
359         functor(entry->d_name);
360 }
361 
362 template <typename Functor>
ForEachFileInZip(const std::string & zipname,const std::string & dir_in_zip,Functor functor)363 void ForEachFileInZip(const std::string& zipname,
364                       const std::string& dir_in_zip,
365                       Functor functor) {
366     int32_t err;
367     ZipArchiveHandle zip = nullptr;
368     if ((err = OpenArchive(zipname.c_str(), &zip)) != 0) {
369         ALOGE("failed to open apk '%s': %d", zipname.c_str(), err);
370         return;
371     }
372     std::string prefix(dir_in_zip + "/");
373     void* iter_cookie = nullptr;
374     if ((err = StartIteration(zip, &iter_cookie, prefix, "")) != 0) {
375         ALOGE("failed to iterate entries in apk '%s': %d", zipname.c_str(),
376               err);
377         CloseArchive(zip);
378         return;
379     }
380     ALOGD("searching for layers in '%s!/%s'", zipname.c_str(),
381           dir_in_zip.c_str());
382     ZipEntry entry;
383     std::string name;
384     while (Next(iter_cookie, &entry, &name) == 0) {
385         std::string filename(name.substr(prefix.length()));
386         // only enumerate direct entries of the directory, not subdirectories
387         if (filename.find('/') != filename.npos)
388             continue;
389         // Check whether it *may* be possible to load the library directly from
390         // the APK. Loading still may fail for other reasons, but this at least
391         // lets us avoid failed-to-load log messages in the typical case of
392         // compressed and/or unaligned libraries.
393         if (entry.method != kCompressStored || entry.offset % PAGE_SIZE != 0)
394             continue;
395         functor(filename);
396     }
397     EndIteration(iter_cookie);
398     CloseArchive(zip);
399 }
400 
401 template <typename Functor>
ForEachFileInPath(const std::string & path,Functor functor)402 void ForEachFileInPath(const std::string& path, Functor functor) {
403     size_t zip_pos = path.find("!/");
404     if (zip_pos == std::string::npos) {
405         ForEachFileInDir(path, functor);
406     } else {
407         ForEachFileInZip(path.substr(0, zip_pos), path.substr(zip_pos + 2),
408                          functor);
409     }
410 }
411 
DiscoverLayersInPathList(const std::string & pathstr)412 void DiscoverLayersInPathList(const std::string& pathstr) {
413     ATRACE_CALL();
414 
415     std::vector<std::string> paths = android::base::Split(pathstr, ":");
416     for (const auto& path : paths) {
417         ForEachFileInPath(path, [&](const std::string& filename) {
418             if (android::base::StartsWith(filename, "libVkLayer") &&
419                 android::base::EndsWith(filename, ".so")) {
420 
421                 // Check to ensure we haven't seen this layer already
422                 // Let the first instance of the shared object be enumerated
423                 // We're searching for layers in following order:
424                 // 1. system path
425                 // 2. libraryPermittedPath (if enabled)
426                 // 3. libraryPath
427 
428                 bool duplicate = false;
429                 for (auto& layer : g_layer_libraries) {
430                     if (layer.GetFilename() == filename) {
431                         ALOGV("Skipping duplicate layer %s in %s",
432                               filename.c_str(), path.c_str());
433                         duplicate = true;
434                     }
435                 }
436 
437                 if (!duplicate)
438                     AddLayerLibrary(path, filename);
439             }
440         });
441     }
442 }
443 
FindExtension(const std::vector<VkExtensionProperties> & extensions,const char * name)444 const VkExtensionProperties* FindExtension(
445     const std::vector<VkExtensionProperties>& extensions,
446     const char* name) {
447     auto it = std::find_if(extensions.cbegin(), extensions.cend(),
448                            [=](const VkExtensionProperties& ext) {
449                                return (strcmp(ext.extensionName, name) == 0);
450                            });
451     return (it != extensions.cend()) ? &*it : nullptr;
452 }
453 
GetLayerGetProcAddr(const Layer & layer,const std::string_view gpa_name)454 void* GetLayerGetProcAddr(const Layer& layer,
455                           const std::string_view gpa_name) {
456     const LayerLibrary& library = g_layer_libraries[layer.library_idx];
457     return library.GetGPA(layer, gpa_name);
458 }
459 
460 }  // anonymous namespace
461 
DiscoverLayers()462 void DiscoverLayers() {
463     ATRACE_CALL();
464 
465     if (android::GraphicsEnv::getInstance().isDebuggable()) {
466         DiscoverLayersInPathList(kSystemLayerLibraryDir);
467     }
468     if (!android::GraphicsEnv::getInstance().getLayerPaths().empty())
469         DiscoverLayersInPathList(android::GraphicsEnv::getInstance().getLayerPaths());
470 }
471 
GetLayerCount()472 uint32_t GetLayerCount() {
473     return static_cast<uint32_t>(g_instance_layers.size());
474 }
475 
GetLayer(uint32_t index)476 const Layer& GetLayer(uint32_t index) {
477     return g_instance_layers[index];
478 }
479 
FindLayer(const char * name)480 const Layer* FindLayer(const char* name) {
481     auto layer =
482         std::find_if(g_instance_layers.cbegin(), g_instance_layers.cend(),
483                      [=](const Layer& entry) {
484                          return strcmp(entry.properties.layerName, name) == 0;
485                      });
486     return (layer != g_instance_layers.cend()) ? &*layer : nullptr;
487 }
488 
GetLayerProperties(const Layer & layer)489 const VkLayerProperties& GetLayerProperties(const Layer& layer) {
490     return layer.properties;
491 }
492 
IsLayerGlobal(const Layer & layer)493 bool IsLayerGlobal(const Layer& layer) {
494     return layer.is_global;
495 }
496 
GetLayerInstanceExtensions(const Layer & layer,uint32_t & count)497 const VkExtensionProperties* GetLayerInstanceExtensions(const Layer& layer,
498                                                         uint32_t& count) {
499     count = static_cast<uint32_t>(layer.instance_extensions.size());
500     return layer.instance_extensions.data();
501 }
502 
GetLayerDeviceExtensions(const Layer & layer,uint32_t & count)503 const VkExtensionProperties* GetLayerDeviceExtensions(const Layer& layer,
504                                                       uint32_t& count) {
505     count = static_cast<uint32_t>(layer.device_extensions.size());
506     return layer.device_extensions.data();
507 }
508 
FindLayerInstanceExtension(const Layer & layer,const char * name)509 const VkExtensionProperties* FindLayerInstanceExtension(const Layer& layer,
510                                                         const char* name) {
511     return FindExtension(layer.instance_extensions, name);
512 }
513 
FindLayerDeviceExtension(const Layer & layer,const char * name)514 const VkExtensionProperties* FindLayerDeviceExtension(const Layer& layer,
515                                                       const char* name) {
516     return FindExtension(layer.device_extensions, name);
517 }
518 
GetLayerRef(const Layer & layer)519 LayerRef GetLayerRef(const Layer& layer) {
520     LayerLibrary& library = g_layer_libraries[layer.library_idx];
521     return LayerRef((library.Open()) ? &layer : nullptr);
522 }
523 
LayerRef(const Layer * layer)524 LayerRef::LayerRef(const Layer* layer) : layer_(layer) {}
525 
~LayerRef()526 LayerRef::~LayerRef() {
527     if (layer_) {
528         LayerLibrary& library = g_layer_libraries[layer_->library_idx];
529         library.Close();
530     }
531 }
532 
LayerRef(LayerRef && other)533 LayerRef::LayerRef(LayerRef&& other) noexcept : layer_(other.layer_) {
534     other.layer_ = nullptr;
535 }
536 
GetGetInstanceProcAddr() const537 PFN_vkGetInstanceProcAddr LayerRef::GetGetInstanceProcAddr() const {
538     return layer_ ? reinterpret_cast<PFN_vkGetInstanceProcAddr>(
539                         GetLayerGetProcAddr(*layer_, "GetInstanceProcAddr"))
540                   : nullptr;
541 }
542 
GetGetDeviceProcAddr() const543 PFN_vkGetDeviceProcAddr LayerRef::GetGetDeviceProcAddr() const {
544     return layer_ ? reinterpret_cast<PFN_vkGetDeviceProcAddr>(
545                         GetLayerGetProcAddr(*layer_, "GetDeviceProcAddr"))
546                   : nullptr;
547 }
548 
549 }  // namespace api
550 }  // namespace vulkan
551