• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 // The API layer of the loader defines Vulkan API and manages layers.  The
18 // entrypoints are generated and defined in api_dispatch.cpp.  Most of them
19 // simply find the dispatch table and jump.
20 //
21 // There are a few of them requiring manual code for things such as layer
22 // discovery or chaining.  They call into functions defined in this file.
23 
24 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
25 
26 #include <stdlib.h>
27 #include <string.h>
28 
29 #include <algorithm>
30 #include <mutex>
31 #include <new>
32 #include <string>
33 #include <unordered_set>
34 #include <utility>
35 
36 #include <android-base/strings.h>
37 #include <cutils/properties.h>
38 #include <log/log.h>
39 #include <utils/Trace.h>
40 
41 #include <vulkan/vk_layer_interface.h>
42 #include <graphicsenv/GraphicsEnv.h>
43 #include "api.h"
44 #include "driver.h"
45 #include "layers_extensions.h"
46 
47 
48 namespace vulkan {
49 namespace api {
50 
51 namespace {
52 
53 // Provide overridden layer names when there are implicit layers.  No effect
54 // otherwise.
55 class OverrideLayerNames {
56    public:
OverrideLayerNames(bool is_instance,const VkAllocationCallbacks & allocator)57     OverrideLayerNames(bool is_instance, const VkAllocationCallbacks& allocator)
58         : is_instance_(is_instance),
59           allocator_(allocator),
60           scope_(VK_SYSTEM_ALLOCATION_SCOPE_COMMAND),
61           names_(nullptr),
62           name_count_(0),
63           implicit_layers_() {
64         implicit_layers_.result = VK_SUCCESS;
65     }
66 
~OverrideLayerNames()67     ~OverrideLayerNames() {
68         allocator_.pfnFree(allocator_.pUserData, names_);
69         allocator_.pfnFree(allocator_.pUserData, implicit_layers_.elements);
70         allocator_.pfnFree(allocator_.pUserData, implicit_layers_.name_pool);
71     }
72 
Parse(const char * const * names,uint32_t count)73     VkResult Parse(const char* const* names, uint32_t count) {
74         AddImplicitLayers();
75 
76         const auto& arr = implicit_layers_;
77         if (arr.result != VK_SUCCESS)
78             return arr.result;
79 
80         // no need to override when there is no implicit layer
81         if (!arr.count)
82             return VK_SUCCESS;
83 
84         names_ = AllocateNameArray(arr.count + count);
85         if (!names_)
86             return VK_ERROR_OUT_OF_HOST_MEMORY;
87 
88         // add implicit layer names
89         for (uint32_t i = 0; i < arr.count; i++)
90             names_[i] = GetImplicitLayerName(i);
91 
92         name_count_ = arr.count;
93 
94         // add explicit layer names
95         for (uint32_t i = 0; i < count; i++) {
96             // ignore explicit layers that are also implicit
97             if (IsImplicitLayer(names[i]))
98                 continue;
99 
100             names_[name_count_++] = names[i];
101         }
102 
103         return VK_SUCCESS;
104     }
105 
Names() const106     const char* const* Names() const { return names_; }
107 
Count() const108     uint32_t Count() const { return name_count_; }
109 
110    private:
111     struct ImplicitLayer {
112         int priority;
113         size_t name_offset;
114     };
115 
116     struct ImplicitLayerArray {
117         ImplicitLayer* elements;
118         uint32_t max_count;
119         uint32_t count;
120 
121         char* name_pool;
122         size_t max_pool_size;
123         size_t pool_size;
124 
125         VkResult result;
126     };
127 
AddImplicitLayers()128     void AddImplicitLayers() {
129         if (!is_instance_)
130             return;
131 
132         GetLayersFromSettings();
133 
134         // If no layers specified via Settings, check legacy properties
135         if (implicit_layers_.count <= 0) {
136             ParseDebugVulkanLayers();
137             property_list(ParseDebugVulkanLayer, this);
138 
139             // sort by priorities
140             auto& arr = implicit_layers_;
141             std::sort(arr.elements, arr.elements + arr.count,
142                       [](const ImplicitLayer& a, const ImplicitLayer& b) {
143                           return (a.priority < b.priority);
144                       });
145         }
146     }
147 
GetLayersFromSettings()148     void GetLayersFromSettings() {
149         // These will only be available if conditions are met in GraphicsEnvironment
150         // gpu_debug_layers = layer1:layer2:layerN
151         const std::string layers = android::GraphicsEnv::getInstance().getDebugLayers();
152         if (!layers.empty()) {
153             ALOGV("Debug layer list: %s", layers.c_str());
154             std::vector<std::string> paths = android::base::Split(layers, ":");
155             for (uint32_t i = 0; i < paths.size(); i++) {
156                 AddImplicitLayer(int(i), paths[i].c_str(), paths[i].length());
157             }
158         }
159     }
160 
ParseDebugVulkanLayers()161     void ParseDebugVulkanLayers() {
162         // debug.vulkan.layers specifies colon-separated layer names
163         char prop[PROPERTY_VALUE_MAX];
164         if (!property_get("debug.vulkan.layers", prop, ""))
165             return;
166 
167         // assign negative/high priorities to them
168         int prio = -PROPERTY_VALUE_MAX;
169 
170         const char* p = prop;
171         const char* delim;
172         while ((delim = strchr(p, ':'))) {
173             if (delim > p)
174                 AddImplicitLayer(prio, p, static_cast<size_t>(delim - p));
175 
176             prio++;
177             p = delim + 1;
178         }
179 
180         if (p[0] != '\0')
181             AddImplicitLayer(prio, p, strlen(p));
182     }
183 
ParseDebugVulkanLayer(const char * key,const char * val,void * user_data)184     static void ParseDebugVulkanLayer(const char* key,
185                                       const char* val,
186                                       void* user_data) {
187         static const char prefix[] = "debug.vulkan.layer.";
188         const size_t prefix_len = sizeof(prefix) - 1;
189 
190         if (strncmp(key, prefix, prefix_len) || val[0] == '\0')
191             return;
192         key += prefix_len;
193 
194         // debug.vulkan.layer.<priority>
195         int priority = -1;
196         if (key[0] >= '0' && key[0] <= '9')
197             priority = atoi(key);
198 
199         if (priority < 0) {
200             ALOGW("Ignored implicit layer %s with invalid priority %s", val,
201                   key);
202             return;
203         }
204 
205         OverrideLayerNames& override_layers =
206             *reinterpret_cast<OverrideLayerNames*>(user_data);
207         override_layers.AddImplicitLayer(priority, val, strlen(val));
208     }
209 
AddImplicitLayer(int priority,const char * name,size_t len)210     void AddImplicitLayer(int priority, const char* name, size_t len) {
211         if (!GrowImplicitLayerArray(1, 0))
212             return;
213 
214         auto& arr = implicit_layers_;
215         auto& layer = arr.elements[arr.count++];
216 
217         layer.priority = priority;
218         layer.name_offset = AddImplicitLayerName(name, len);
219 
220         ALOGV("Added implicit layer %s", GetImplicitLayerName(arr.count - 1));
221     }
222 
AddImplicitLayerName(const char * name,size_t len)223     size_t AddImplicitLayerName(const char* name, size_t len) {
224         if (!GrowImplicitLayerArray(0, len + 1))
225             return 0;
226 
227         // add the name to the pool
228         auto& arr = implicit_layers_;
229         size_t offset = arr.pool_size;
230         char* dst = arr.name_pool + offset;
231 
232         std::copy(name, name + len, dst);
233         dst[len] = '\0';
234 
235         arr.pool_size += len + 1;
236 
237         return offset;
238     }
239 
GrowImplicitLayerArray(uint32_t layer_count,size_t name_size)240     bool GrowImplicitLayerArray(uint32_t layer_count, size_t name_size) {
241         const uint32_t initial_max_count = 16;
242         const size_t initial_max_pool_size = 512;
243 
244         auto& arr = implicit_layers_;
245 
246         // grow the element array if needed
247         while (arr.count + layer_count > arr.max_count) {
248             uint32_t new_max_count =
249                 (arr.max_count) ? (arr.max_count << 1) : initial_max_count;
250             void* new_mem = nullptr;
251 
252             if (new_max_count > arr.max_count) {
253                 new_mem = allocator_.pfnReallocation(
254                     allocator_.pUserData, arr.elements,
255                     sizeof(ImplicitLayer) * new_max_count,
256                     alignof(ImplicitLayer), scope_);
257             }
258 
259             if (!new_mem) {
260                 arr.result = VK_ERROR_OUT_OF_HOST_MEMORY;
261                 arr.count = 0;
262                 return false;
263             }
264 
265             arr.elements = reinterpret_cast<ImplicitLayer*>(new_mem);
266             arr.max_count = new_max_count;
267         }
268 
269         // grow the name pool if needed
270         while (arr.pool_size + name_size > arr.max_pool_size) {
271             size_t new_max_pool_size = (arr.max_pool_size)
272                                            ? (arr.max_pool_size << 1)
273                                            : initial_max_pool_size;
274             void* new_mem = nullptr;
275 
276             if (new_max_pool_size > arr.max_pool_size) {
277                 new_mem = allocator_.pfnReallocation(
278                     allocator_.pUserData, arr.name_pool, new_max_pool_size,
279                     alignof(char), scope_);
280             }
281 
282             if (!new_mem) {
283                 arr.result = VK_ERROR_OUT_OF_HOST_MEMORY;
284                 arr.pool_size = 0;
285                 return false;
286             }
287 
288             arr.name_pool = reinterpret_cast<char*>(new_mem);
289             arr.max_pool_size = new_max_pool_size;
290         }
291 
292         return true;
293     }
294 
GetImplicitLayerName(uint32_t index) const295     const char* GetImplicitLayerName(uint32_t index) const {
296         const auto& arr = implicit_layers_;
297 
298         // this may return nullptr when arr.result is not VK_SUCCESS
299         return implicit_layers_.name_pool + arr.elements[index].name_offset;
300     }
301 
IsImplicitLayer(const char * name) const302     bool IsImplicitLayer(const char* name) const {
303         const auto& arr = implicit_layers_;
304 
305         for (uint32_t i = 0; i < arr.count; i++) {
306             if (strcmp(name, GetImplicitLayerName(i)) == 0)
307                 return true;
308         }
309 
310         return false;
311     }
312 
AllocateNameArray(uint32_t count) const313     const char** AllocateNameArray(uint32_t count) const {
314         return reinterpret_cast<const char**>(allocator_.pfnAllocation(
315             allocator_.pUserData, sizeof(const char*) * count,
316             alignof(const char*), scope_));
317     }
318 
319     const bool is_instance_;
320     const VkAllocationCallbacks& allocator_;
321     const VkSystemAllocationScope scope_;
322 
323     const char** names_;
324     uint32_t name_count_;
325 
326     ImplicitLayerArray implicit_layers_;
327 };
328 
329 // Provide overridden extension names when there are implicit extensions.
330 // No effect otherwise.
331 //
332 // This is used only to enable VK_EXT_debug_report.
333 class OverrideExtensionNames {
334    public:
OverrideExtensionNames(bool is_instance,const VkAllocationCallbacks & allocator)335     OverrideExtensionNames(bool is_instance,
336                            const VkAllocationCallbacks& allocator)
337         : is_instance_(is_instance),
338           allocator_(allocator),
339           scope_(VK_SYSTEM_ALLOCATION_SCOPE_COMMAND),
340           names_(nullptr),
341           name_count_(0),
342           install_debug_callback_(false) {}
343 
~OverrideExtensionNames()344     ~OverrideExtensionNames() {
345         allocator_.pfnFree(allocator_.pUserData, names_);
346     }
347 
Parse(const char * const * names,uint32_t count)348     VkResult Parse(const char* const* names, uint32_t count) {
349         // this is only for debug.vulkan.enable_callback
350         if (!EnableDebugCallback())
351             return VK_SUCCESS;
352 
353         names_ = AllocateNameArray(count + 1);
354         if (!names_)
355             return VK_ERROR_OUT_OF_HOST_MEMORY;
356 
357         std::copy(names, names + count, names_);
358 
359         name_count_ = count;
360         names_[name_count_++] = "VK_EXT_debug_report";
361 
362         install_debug_callback_ = true;
363 
364         return VK_SUCCESS;
365     }
366 
Names() const367     const char* const* Names() const { return names_; }
368 
Count() const369     uint32_t Count() const { return name_count_; }
370 
InstallDebugCallback() const371     bool InstallDebugCallback() const { return install_debug_callback_; }
372 
373    private:
EnableDebugCallback() const374     bool EnableDebugCallback() const {
375         return (is_instance_ &&
376                 android::GraphicsEnv::getInstance().isDebuggable() &&
377                 property_get_bool("debug.vulkan.enable_callback", false));
378     }
379 
AllocateNameArray(uint32_t count) const380     const char** AllocateNameArray(uint32_t count) const {
381         return reinterpret_cast<const char**>(allocator_.pfnAllocation(
382             allocator_.pUserData, sizeof(const char*) * count,
383             alignof(const char*), scope_));
384     }
385 
386     const bool is_instance_;
387     const VkAllocationCallbacks& allocator_;
388     const VkSystemAllocationScope scope_;
389 
390     const char** names_;
391     uint32_t name_count_;
392     bool install_debug_callback_;
393 };
394 
395 // vkCreateInstance and vkCreateDevice helpers with support for layer
396 // chaining.
397 class LayerChain {
398    public:
399     struct ActiveLayer {
400         LayerRef ref;
401         union {
402             VkLayerInstanceLink instance_link;
403             VkLayerDeviceLink device_link;
404         };
405     };
406 
407     static VkResult CreateInstance(const VkInstanceCreateInfo* create_info,
408                                    const VkAllocationCallbacks* allocator,
409                                    VkInstance* instance_out);
410 
411     static VkResult CreateDevice(VkPhysicalDevice physical_dev,
412                                  const VkDeviceCreateInfo* create_info,
413                                  const VkAllocationCallbacks* allocator,
414                                  VkDevice* dev_out);
415 
416     static void DestroyInstance(VkInstance instance,
417                                 const VkAllocationCallbacks* allocator);
418 
419     static void DestroyDevice(VkDevice dev,
420                               const VkAllocationCallbacks* allocator);
421 
422     static const ActiveLayer* GetActiveLayers(VkPhysicalDevice physical_dev,
423                                               uint32_t& count);
424 
425    private:
426     LayerChain(bool is_instance,
427                const driver::DebugReportLogger& logger,
428                const VkAllocationCallbacks& allocator);
429     ~LayerChain();
430 
431     VkResult ActivateLayers(const char* const* layer_names,
432                             uint32_t layer_count,
433                             const char* const* extension_names,
434                             uint32_t extension_count);
435     VkResult ActivateLayers(VkPhysicalDevice physical_dev,
436                             const char* const* layer_names,
437                             uint32_t layer_count,
438                             const char* const* extension_names,
439                             uint32_t extension_count);
440     ActiveLayer* AllocateLayerArray(uint32_t count) const;
441     VkResult LoadLayer(ActiveLayer& layer, const char* name);
442     void SetupLayerLinks();
443 
444     bool Empty() const;
445     void ModifyCreateInfo(VkInstanceCreateInfo& info);
446     void ModifyCreateInfo(VkDeviceCreateInfo& info);
447 
448     VkResult Create(const VkInstanceCreateInfo* create_info,
449                     const VkAllocationCallbacks* allocator,
450                     VkInstance* instance_out);
451 
452     VkResult Create(VkPhysicalDevice physical_dev,
453                     const VkDeviceCreateInfo* create_info,
454                     const VkAllocationCallbacks* allocator,
455                     VkDevice* dev_out);
456 
457     VkResult ValidateExtensions(const char* const* extension_names,
458                                 uint32_t extension_count);
459     VkResult ValidateExtensions(VkPhysicalDevice physical_dev,
460                                 const char* const* extension_names,
461                                 uint32_t extension_count);
462     VkExtensionProperties* AllocateDriverExtensionArray(uint32_t count) const;
463     bool IsLayerExtension(const char* name) const;
464     bool IsDriverExtension(const char* name) const;
465 
466     template <typename DataType>
467     void StealLayers(DataType& data);
468 
469     static void DestroyLayers(ActiveLayer* layers,
470                               uint32_t count,
471                               const VkAllocationCallbacks& allocator);
472 
473     static VKAPI_ATTR VkResult SetInstanceLoaderData(VkInstance instance,
474                                                      void* object);
475     static VKAPI_ATTR VkResult SetDeviceLoaderData(VkDevice device,
476                                                    void* object);
477 
478     static VKAPI_ATTR VkBool32
479     DebugReportCallback(VkDebugReportFlagsEXT flags,
480                         VkDebugReportObjectTypeEXT obj_type,
481                         uint64_t obj,
482                         size_t location,
483                         int32_t msg_code,
484                         const char* layer_prefix,
485                         const char* msg,
486                         void* user_data);
487 
488     const bool is_instance_;
489     const driver::DebugReportLogger& logger_;
490     const VkAllocationCallbacks& allocator_;
491 
492     OverrideLayerNames override_layers_;
493     OverrideExtensionNames override_extensions_;
494 
495     ActiveLayer* layers_;
496     uint32_t layer_count_;
497 
498     PFN_vkGetInstanceProcAddr get_instance_proc_addr_;
499     PFN_vkGetDeviceProcAddr get_device_proc_addr_;
500 
501     union {
502         VkLayerInstanceCreateInfo instance_chain_info_[2];
503         VkLayerDeviceCreateInfo device_chain_info_[2];
504     };
505 
506     VkExtensionProperties* driver_extensions_;
507     uint32_t driver_extension_count_;
508     std::bitset<driver::ProcHook::EXTENSION_COUNT> enabled_extensions_;
509 };
510 
LayerChain(bool is_instance,const driver::DebugReportLogger & logger,const VkAllocationCallbacks & allocator)511 LayerChain::LayerChain(bool is_instance,
512                        const driver::DebugReportLogger& logger,
513                        const VkAllocationCallbacks& allocator)
514     : is_instance_(is_instance),
515       logger_(logger),
516       allocator_(allocator),
517       override_layers_(is_instance, allocator),
518       override_extensions_(is_instance, allocator),
519       layers_(nullptr),
520       layer_count_(0),
521       get_instance_proc_addr_(nullptr),
522       get_device_proc_addr_(nullptr),
523       driver_extensions_(nullptr),
524       driver_extension_count_(0) {
525     // advertise the loader supported core Vulkan API version at vulkan::api
526     for (uint32_t i = driver::ProcHook::EXTENSION_CORE_1_0;
527          i != driver::ProcHook::EXTENSION_COUNT; ++i) {
528         enabled_extensions_.set(i);
529     }
530 }
531 
~LayerChain()532 LayerChain::~LayerChain() {
533     allocator_.pfnFree(allocator_.pUserData, driver_extensions_);
534     DestroyLayers(layers_, layer_count_, allocator_);
535 }
536 
ActivateLayers(const char * const * layer_names,uint32_t layer_count,const char * const * extension_names,uint32_t extension_count)537 VkResult LayerChain::ActivateLayers(const char* const* layer_names,
538                                     uint32_t layer_count,
539                                     const char* const* extension_names,
540                                     uint32_t extension_count) {
541     VkResult result = override_layers_.Parse(layer_names, layer_count);
542     if (result != VK_SUCCESS)
543         return result;
544 
545     result = override_extensions_.Parse(extension_names, extension_count);
546     if (result != VK_SUCCESS)
547         return result;
548 
549     if (override_layers_.Count()) {
550         layer_names = override_layers_.Names();
551         layer_count = override_layers_.Count();
552     }
553 
554     if (!layer_count) {
555         // point head of chain to the driver
556         get_instance_proc_addr_ = driver::GetInstanceProcAddr;
557 
558         return VK_SUCCESS;
559     }
560 
561     layers_ = AllocateLayerArray(layer_count);
562     if (!layers_)
563         return VK_ERROR_OUT_OF_HOST_MEMORY;
564 
565     // load layers
566     for (uint32_t i = 0; i < layer_count; i++) {
567         result = LoadLayer(layers_[i], layer_names[i]);
568         if (result != VK_SUCCESS)
569             return result;
570 
571         // count loaded layers for proper destructions on errors
572         layer_count_++;
573     }
574 
575     SetupLayerLinks();
576 
577     return VK_SUCCESS;
578 }
579 
ActivateLayers(VkPhysicalDevice physical_dev,const char * const * layer_names,uint32_t layer_count,const char * const * extension_names,uint32_t extension_count)580 VkResult LayerChain::ActivateLayers(VkPhysicalDevice physical_dev,
581                                     const char* const* layer_names,
582                                     uint32_t layer_count,
583                                     const char* const* extension_names,
584                                     uint32_t extension_count) {
585     uint32_t instance_layer_count;
586     const ActiveLayer* instance_layers =
587         GetActiveLayers(physical_dev, instance_layer_count);
588 
589     // log a message if the application device layer array is not empty nor an
590     // exact match of the instance layer array.
591     if (layer_count) {
592         bool exact_match = (instance_layer_count == layer_count);
593         if (exact_match) {
594             for (uint32_t i = 0; i < instance_layer_count; i++) {
595                 const Layer& l = *instance_layers[i].ref;
596                 if (strcmp(GetLayerProperties(l).layerName, layer_names[i])) {
597                     exact_match = false;
598                     break;
599                 }
600             }
601         }
602 
603         if (!exact_match) {
604             logger_.Warn(physical_dev,
605                          "Device layers disagree with instance layers and are "
606                          "overridden by instance layers");
607         }
608     }
609 
610     VkResult result =
611         override_extensions_.Parse(extension_names, extension_count);
612     if (result != VK_SUCCESS)
613         return result;
614 
615     if (!instance_layer_count) {
616         // point head of chain to the driver
617         get_instance_proc_addr_ = driver::GetInstanceProcAddr;
618         get_device_proc_addr_ = driver::GetDeviceProcAddr;
619 
620         return VK_SUCCESS;
621     }
622 
623     layers_ = AllocateLayerArray(instance_layer_count);
624     if (!layers_)
625         return VK_ERROR_OUT_OF_HOST_MEMORY;
626 
627     for (uint32_t i = 0; i < instance_layer_count; i++) {
628         const Layer& l = *instance_layers[i].ref;
629 
630         // no need to and cannot chain non-global layers
631         if (!IsLayerGlobal(l))
632             continue;
633 
634         // this never fails
635         new (&layers_[layer_count_++]) ActiveLayer{GetLayerRef(l), {}};
636     }
637 
638     // this may happen when all layers are non-global ones
639     if (!layer_count_) {
640         get_instance_proc_addr_ = driver::GetInstanceProcAddr;
641         get_device_proc_addr_ = driver::GetDeviceProcAddr;
642         return VK_SUCCESS;
643     }
644 
645     SetupLayerLinks();
646 
647     return VK_SUCCESS;
648 }
649 
AllocateLayerArray(uint32_t count) const650 LayerChain::ActiveLayer* LayerChain::AllocateLayerArray(uint32_t count) const {
651     VkSystemAllocationScope scope = (is_instance_)
652                                         ? VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE
653                                         : VK_SYSTEM_ALLOCATION_SCOPE_COMMAND;
654 
655     return reinterpret_cast<ActiveLayer*>(allocator_.pfnAllocation(
656         allocator_.pUserData, sizeof(ActiveLayer) * count, alignof(ActiveLayer),
657         scope));
658 }
659 
LoadLayer(ActiveLayer & layer,const char * name)660 VkResult LayerChain::LoadLayer(ActiveLayer& layer, const char* name) {
661     const Layer* l = FindLayer(name);
662     if (!l) {
663         logger_.Err(VK_NULL_HANDLE, "Failed to find layer %s", name);
664         return VK_ERROR_LAYER_NOT_PRESENT;
665     }
666 
667     new (&layer) ActiveLayer{GetLayerRef(*l), {}};
668     if (!layer.ref) {
669         ALOGW("Failed to open layer %s", name);
670         layer.ref.~LayerRef();
671         return VK_ERROR_LAYER_NOT_PRESENT;
672     }
673 
674     if (!layer.ref.GetGetInstanceProcAddr()) {
675         ALOGW("Failed to locate vkGetInstanceProcAddr in layer %s", name);
676         layer.ref.~LayerRef();
677         return VK_ERROR_LAYER_NOT_PRESENT;
678     }
679 
680     ALOGI("Loaded layer %s", name);
681 
682     return VK_SUCCESS;
683 }
684 
SetupLayerLinks()685 void LayerChain::SetupLayerLinks() {
686     if (is_instance_) {
687         for (uint32_t i = 0; i < layer_count_; i++) {
688             ActiveLayer& layer = layers_[i];
689 
690             // point head of chain to the first layer
691             if (i == 0)
692                 get_instance_proc_addr_ = layer.ref.GetGetInstanceProcAddr();
693 
694             // point tail of chain to the driver
695             if (i == layer_count_ - 1) {
696                 layer.instance_link.pNext = nullptr;
697                 layer.instance_link.pfnNextGetInstanceProcAddr =
698                     driver::GetInstanceProcAddr;
699                 break;
700             }
701 
702             const ActiveLayer& next = layers_[i + 1];
703 
704             // const_cast as some naughty layers want to modify our links!
705             layer.instance_link.pNext =
706                 const_cast<VkLayerInstanceLink*>(&next.instance_link);
707             layer.instance_link.pfnNextGetInstanceProcAddr =
708                 next.ref.GetGetInstanceProcAddr();
709         }
710     } else {
711         for (uint32_t i = 0; i < layer_count_; i++) {
712             ActiveLayer& layer = layers_[i];
713 
714             // point head of chain to the first layer
715             if (i == 0) {
716                 get_instance_proc_addr_ = layer.ref.GetGetInstanceProcAddr();
717                 get_device_proc_addr_ = layer.ref.GetGetDeviceProcAddr();
718             }
719 
720             // point tail of chain to the driver
721             if (i == layer_count_ - 1) {
722                 layer.device_link.pNext = nullptr;
723                 layer.device_link.pfnNextGetInstanceProcAddr =
724                     driver::GetInstanceProcAddr;
725                 layer.device_link.pfnNextGetDeviceProcAddr =
726                     driver::GetDeviceProcAddr;
727                 break;
728             }
729 
730             const ActiveLayer& next = layers_[i + 1];
731 
732             // const_cast as some naughty layers want to modify our links!
733             layer.device_link.pNext =
734                 const_cast<VkLayerDeviceLink*>(&next.device_link);
735             layer.device_link.pfnNextGetInstanceProcAddr =
736                 next.ref.GetGetInstanceProcAddr();
737             layer.device_link.pfnNextGetDeviceProcAddr =
738                 next.ref.GetGetDeviceProcAddr();
739         }
740     }
741 }
742 
Empty() const743 bool LayerChain::Empty() const {
744     return (!layer_count_ && !override_layers_.Count() &&
745             !override_extensions_.Count());
746 }
747 
ModifyCreateInfo(VkInstanceCreateInfo & info)748 void LayerChain::ModifyCreateInfo(VkInstanceCreateInfo& info) {
749     if (layer_count_) {
750         auto& link_info = instance_chain_info_[1];
751         link_info.sType = VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO;
752         link_info.pNext = info.pNext;
753         link_info.function = VK_LAYER_FUNCTION_LINK;
754         link_info.u.pLayerInfo = &layers_[0].instance_link;
755 
756         auto& cb_info = instance_chain_info_[0];
757         cb_info.sType = VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO;
758         cb_info.pNext = &link_info;
759         cb_info.function = VK_LAYER_FUNCTION_DATA_CALLBACK;
760         cb_info.u.pfnSetInstanceLoaderData = SetInstanceLoaderData;
761 
762         info.pNext = &cb_info;
763     }
764 
765     if (override_layers_.Count()) {
766         info.enabledLayerCount = override_layers_.Count();
767         info.ppEnabledLayerNames = override_layers_.Names();
768     }
769 
770     if (override_extensions_.Count()) {
771         info.enabledExtensionCount = override_extensions_.Count();
772         info.ppEnabledExtensionNames = override_extensions_.Names();
773     }
774 }
775 
ModifyCreateInfo(VkDeviceCreateInfo & info)776 void LayerChain::ModifyCreateInfo(VkDeviceCreateInfo& info) {
777     if (layer_count_) {
778         auto& link_info = device_chain_info_[1];
779         link_info.sType = VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO;
780         link_info.pNext = info.pNext;
781         link_info.function = VK_LAYER_FUNCTION_LINK;
782         link_info.u.pLayerInfo = &layers_[0].device_link;
783 
784         auto& cb_info = device_chain_info_[0];
785         cb_info.sType = VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO;
786         cb_info.pNext = &link_info;
787         cb_info.function = VK_LAYER_FUNCTION_DATA_CALLBACK;
788         cb_info.u.pfnSetDeviceLoaderData = SetDeviceLoaderData;
789 
790         info.pNext = &cb_info;
791     }
792 
793     if (override_layers_.Count()) {
794         info.enabledLayerCount = override_layers_.Count();
795         info.ppEnabledLayerNames = override_layers_.Names();
796     }
797 
798     if (override_extensions_.Count()) {
799         info.enabledExtensionCount = override_extensions_.Count();
800         info.ppEnabledExtensionNames = override_extensions_.Names();
801     }
802 }
803 
Create(const VkInstanceCreateInfo * create_info,const VkAllocationCallbacks * allocator,VkInstance * instance_out)804 VkResult LayerChain::Create(const VkInstanceCreateInfo* create_info,
805                             const VkAllocationCallbacks* allocator,
806                             VkInstance* instance_out) {
807     VkResult result = ValidateExtensions(create_info->ppEnabledExtensionNames,
808                                          create_info->enabledExtensionCount);
809     if (result != VK_SUCCESS)
810         return result;
811 
812     // call down the chain
813     PFN_vkCreateInstance create_instance =
814         reinterpret_cast<PFN_vkCreateInstance>(
815             get_instance_proc_addr_(VK_NULL_HANDLE, "vkCreateInstance"));
816     VkInstance instance;
817     result = create_instance(create_info, allocator, &instance);
818     if (result != VK_SUCCESS)
819         return result;
820 
821     // initialize InstanceData
822     InstanceData& data = GetData(instance);
823 
824     if (!InitDispatchTable(instance, get_instance_proc_addr_,
825                            enabled_extensions_)) {
826         if (data.dispatch.DestroyInstance)
827             data.dispatch.DestroyInstance(instance, allocator);
828 
829         return VK_ERROR_INITIALIZATION_FAILED;
830     }
831 
832     // install debug report callback
833     if (override_extensions_.InstallDebugCallback()) {
834         PFN_vkCreateDebugReportCallbackEXT create_debug_report_callback =
835             reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>(
836                 get_instance_proc_addr_(instance,
837                                         "vkCreateDebugReportCallbackEXT"));
838         data.destroy_debug_callback =
839             reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>(
840                 get_instance_proc_addr_(instance,
841                                         "vkDestroyDebugReportCallbackEXT"));
842         if (!create_debug_report_callback || !data.destroy_debug_callback) {
843             ALOGE("Broken VK_EXT_debug_report support");
844             data.dispatch.DestroyInstance(instance, allocator);
845             return VK_ERROR_INITIALIZATION_FAILED;
846         }
847 
848         VkDebugReportCallbackCreateInfoEXT debug_callback_info = {};
849         debug_callback_info.sType =
850             VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
851         debug_callback_info.flags =
852             VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
853         debug_callback_info.pfnCallback = DebugReportCallback;
854 
855         VkDebugReportCallbackEXT debug_callback;
856         result = create_debug_report_callback(instance, &debug_callback_info,
857                                               nullptr, &debug_callback);
858         if (result != VK_SUCCESS) {
859             ALOGE("Failed to install debug report callback");
860             data.dispatch.DestroyInstance(instance, allocator);
861             return VK_ERROR_INITIALIZATION_FAILED;
862         }
863 
864         data.debug_callback = debug_callback;
865 
866         ALOGI("Installed debug report callback");
867     }
868 
869     StealLayers(data);
870 
871     *instance_out = instance;
872 
873     return VK_SUCCESS;
874 }
875 
Create(VkPhysicalDevice physical_dev,const VkDeviceCreateInfo * create_info,const VkAllocationCallbacks * allocator,VkDevice * dev_out)876 VkResult LayerChain::Create(VkPhysicalDevice physical_dev,
877                             const VkDeviceCreateInfo* create_info,
878                             const VkAllocationCallbacks* allocator,
879                             VkDevice* dev_out) {
880     VkResult result =
881         ValidateExtensions(physical_dev, create_info->ppEnabledExtensionNames,
882                            create_info->enabledExtensionCount);
883     if (result != VK_SUCCESS)
884         return result;
885 
886     // call down the chain
887     PFN_vkCreateDevice create_device =
888         GetData(physical_dev).dispatch.CreateDevice;
889     VkDevice dev;
890     result = create_device(physical_dev, create_info, allocator, &dev);
891     if (result != VK_SUCCESS)
892         return result;
893 
894     // initialize DeviceData
895     DeviceData& data = GetData(dev);
896 
897     if (!InitDispatchTable(dev, get_device_proc_addr_, enabled_extensions_)) {
898         if (data.dispatch.DestroyDevice)
899             data.dispatch.DestroyDevice(dev, allocator);
900 
901         return VK_ERROR_INITIALIZATION_FAILED;
902     }
903 
904     // no StealLayers so that active layers are destroyed with this
905     // LayerChain
906     *dev_out = dev;
907 
908     return VK_SUCCESS;
909 }
910 
ValidateExtensions(const char * const * extension_names,uint32_t extension_count)911 VkResult LayerChain::ValidateExtensions(const char* const* extension_names,
912                                         uint32_t extension_count) {
913     if (!extension_count)
914         return VK_SUCCESS;
915 
916     // query driver instance extensions
917     uint32_t count;
918     VkResult result =
919         EnumerateInstanceExtensionProperties(nullptr, &count, nullptr);
920     if (result == VK_SUCCESS && count) {
921         driver_extensions_ = AllocateDriverExtensionArray(count);
922         result = (driver_extensions_) ? EnumerateInstanceExtensionProperties(
923                                             nullptr, &count, driver_extensions_)
924                                       : VK_ERROR_OUT_OF_HOST_MEMORY;
925     }
926     if (result != VK_SUCCESS)
927         return result;
928 
929     driver_extension_count_ = count;
930 
931     for (uint32_t i = 0; i < extension_count; i++) {
932         const char* name = extension_names[i];
933         if (!IsLayerExtension(name) && !IsDriverExtension(name)) {
934             logger_.Err(VK_NULL_HANDLE,
935                         "Failed to enable missing instance extension %s", name);
936             return VK_ERROR_EXTENSION_NOT_PRESENT;
937         }
938 
939         auto ext_bit = driver::GetProcHookExtension(name);
940         if (ext_bit != driver::ProcHook::EXTENSION_UNKNOWN)
941             enabled_extensions_.set(ext_bit);
942     }
943 
944     return VK_SUCCESS;
945 }
946 
ValidateExtensions(VkPhysicalDevice physical_dev,const char * const * extension_names,uint32_t extension_count)947 VkResult LayerChain::ValidateExtensions(VkPhysicalDevice physical_dev,
948                                         const char* const* extension_names,
949                                         uint32_t extension_count) {
950     if (!extension_count)
951         return VK_SUCCESS;
952 
953     // query driver device extensions
954     uint32_t count;
955     VkResult result = EnumerateDeviceExtensionProperties(physical_dev, nullptr,
956                                                          &count, nullptr);
957     if (result == VK_SUCCESS && count) {
958         driver_extensions_ = AllocateDriverExtensionArray(count);
959         result = (driver_extensions_)
960                      ? EnumerateDeviceExtensionProperties(
961                            physical_dev, nullptr, &count, driver_extensions_)
962                      : VK_ERROR_OUT_OF_HOST_MEMORY;
963     }
964     if (result != VK_SUCCESS)
965         return result;
966 
967     driver_extension_count_ = count;
968 
969     for (uint32_t i = 0; i < extension_count; i++) {
970         const char* name = extension_names[i];
971         if (!IsLayerExtension(name) && !IsDriverExtension(name)) {
972             logger_.Err(physical_dev,
973                         "Failed to enable missing device extension %s", name);
974             return VK_ERROR_EXTENSION_NOT_PRESENT;
975         }
976 
977         auto ext_bit = driver::GetProcHookExtension(name);
978         if (ext_bit != driver::ProcHook::EXTENSION_UNKNOWN)
979             enabled_extensions_.set(ext_bit);
980     }
981 
982     return VK_SUCCESS;
983 }
984 
AllocateDriverExtensionArray(uint32_t count) const985 VkExtensionProperties* LayerChain::AllocateDriverExtensionArray(
986     uint32_t count) const {
987     return reinterpret_cast<VkExtensionProperties*>(allocator_.pfnAllocation(
988         allocator_.pUserData, sizeof(VkExtensionProperties) * count,
989         alignof(VkExtensionProperties), VK_SYSTEM_ALLOCATION_SCOPE_COMMAND));
990 }
991 
IsLayerExtension(const char * name) const992 bool LayerChain::IsLayerExtension(const char* name) const {
993     if (is_instance_) {
994         for (uint32_t i = 0; i < layer_count_; i++) {
995             const ActiveLayer& layer = layers_[i];
996             if (FindLayerInstanceExtension(*layer.ref, name))
997                 return true;
998         }
999     } else {
1000         for (uint32_t i = 0; i < layer_count_; i++) {
1001             const ActiveLayer& layer = layers_[i];
1002             if (FindLayerDeviceExtension(*layer.ref, name))
1003                 return true;
1004         }
1005     }
1006 
1007     return false;
1008 }
1009 
IsDriverExtension(const char * name) const1010 bool LayerChain::IsDriverExtension(const char* name) const {
1011     for (uint32_t i = 0; i < driver_extension_count_; i++) {
1012         if (strcmp(driver_extensions_[i].extensionName, name) == 0)
1013             return true;
1014     }
1015 
1016     return false;
1017 }
1018 
1019 template <typename DataType>
StealLayers(DataType & data)1020 void LayerChain::StealLayers(DataType& data) {
1021     data.layers = layers_;
1022     data.layer_count = layer_count_;
1023 
1024     layers_ = nullptr;
1025     layer_count_ = 0;
1026 }
1027 
DestroyLayers(ActiveLayer * layers,uint32_t count,const VkAllocationCallbacks & allocator)1028 void LayerChain::DestroyLayers(ActiveLayer* layers,
1029                                uint32_t count,
1030                                const VkAllocationCallbacks& allocator) {
1031     for (uint32_t i = 0; i < count; i++)
1032         layers[i].ref.~LayerRef();
1033 
1034     allocator.pfnFree(allocator.pUserData, layers);
1035 }
1036 
SetInstanceLoaderData(VkInstance instance,void * object)1037 VkResult LayerChain::SetInstanceLoaderData(VkInstance instance, void* object) {
1038     driver::InstanceDispatchable dispatchable =
1039         reinterpret_cast<driver::InstanceDispatchable>(object);
1040 
1041     return (driver::SetDataInternal(dispatchable, &driver::GetData(instance)))
1042                ? VK_SUCCESS
1043                : VK_ERROR_INITIALIZATION_FAILED;
1044 }
1045 
SetDeviceLoaderData(VkDevice device,void * object)1046 VkResult LayerChain::SetDeviceLoaderData(VkDevice device, void* object) {
1047     driver::DeviceDispatchable dispatchable =
1048         reinterpret_cast<driver::DeviceDispatchable>(object);
1049 
1050     return (driver::SetDataInternal(dispatchable, &driver::GetData(device)))
1051                ? VK_SUCCESS
1052                : VK_ERROR_INITIALIZATION_FAILED;
1053 }
1054 
DebugReportCallback(VkDebugReportFlagsEXT flags,VkDebugReportObjectTypeEXT obj_type,uint64_t obj,size_t location,int32_t msg_code,const char * layer_prefix,const char * msg,void * user_data)1055 VkBool32 LayerChain::DebugReportCallback(VkDebugReportFlagsEXT flags,
1056                                          VkDebugReportObjectTypeEXT obj_type,
1057                                          uint64_t obj,
1058                                          size_t location,
1059                                          int32_t msg_code,
1060                                          const char* layer_prefix,
1061                                          const char* msg,
1062                                          void* user_data) {
1063     int prio;
1064 
1065     if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT)
1066         prio = ANDROID_LOG_ERROR;
1067     else if (flags & (VK_DEBUG_REPORT_WARNING_BIT_EXT |
1068                       VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT))
1069         prio = ANDROID_LOG_WARN;
1070     else if (flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT)
1071         prio = ANDROID_LOG_INFO;
1072     else if (flags & VK_DEBUG_REPORT_DEBUG_BIT_EXT)
1073         prio = ANDROID_LOG_DEBUG;
1074     else
1075         prio = ANDROID_LOG_UNKNOWN;
1076 
1077     LOG_PRI(prio, LOG_TAG, "[%s] Code %d : %s", layer_prefix, msg_code, msg);
1078 
1079     (void)obj_type;
1080     (void)obj;
1081     (void)location;
1082     (void)user_data;
1083 
1084     return false;
1085 }
1086 
CreateInstance(const VkInstanceCreateInfo * create_info,const VkAllocationCallbacks * allocator,VkInstance * instance_out)1087 VkResult LayerChain::CreateInstance(const VkInstanceCreateInfo* create_info,
1088                                     const VkAllocationCallbacks* allocator,
1089                                     VkInstance* instance_out) {
1090     const driver::DebugReportLogger logger(*create_info);
1091     LayerChain chain(true, logger,
1092                      (allocator) ? *allocator : driver::GetDefaultAllocator());
1093 
1094     VkResult result = chain.ActivateLayers(create_info->ppEnabledLayerNames,
1095                                            create_info->enabledLayerCount,
1096                                            create_info->ppEnabledExtensionNames,
1097                                            create_info->enabledExtensionCount);
1098     if (result != VK_SUCCESS)
1099         return result;
1100 
1101     // use a local create info when the chain is not empty
1102     VkInstanceCreateInfo local_create_info;
1103     if (!chain.Empty()) {
1104         local_create_info = *create_info;
1105         chain.ModifyCreateInfo(local_create_info);
1106         create_info = &local_create_info;
1107     }
1108 
1109     return chain.Create(create_info, allocator, instance_out);
1110 }
1111 
CreateDevice(VkPhysicalDevice physical_dev,const VkDeviceCreateInfo * create_info,const VkAllocationCallbacks * allocator,VkDevice * dev_out)1112 VkResult LayerChain::CreateDevice(VkPhysicalDevice physical_dev,
1113                                   const VkDeviceCreateInfo* create_info,
1114                                   const VkAllocationCallbacks* allocator,
1115                                   VkDevice* dev_out) {
1116     const driver::DebugReportLogger logger = driver::Logger(physical_dev);
1117     LayerChain chain(
1118         false, logger,
1119         (allocator) ? *allocator : driver::GetData(physical_dev).allocator);
1120 
1121     VkResult result = chain.ActivateLayers(
1122         physical_dev, create_info->ppEnabledLayerNames,
1123         create_info->enabledLayerCount, create_info->ppEnabledExtensionNames,
1124         create_info->enabledExtensionCount);
1125     if (result != VK_SUCCESS)
1126         return result;
1127 
1128     // use a local create info when the chain is not empty
1129     VkDeviceCreateInfo local_create_info;
1130     if (!chain.Empty()) {
1131         local_create_info = *create_info;
1132         chain.ModifyCreateInfo(local_create_info);
1133         create_info = &local_create_info;
1134     }
1135 
1136     return chain.Create(physical_dev, create_info, allocator, dev_out);
1137 }
1138 
DestroyInstance(VkInstance instance,const VkAllocationCallbacks * allocator)1139 void LayerChain::DestroyInstance(VkInstance instance,
1140                                  const VkAllocationCallbacks* allocator) {
1141     InstanceData& data = GetData(instance);
1142 
1143     if (data.debug_callback != VK_NULL_HANDLE)
1144         data.destroy_debug_callback(instance, data.debug_callback, allocator);
1145 
1146     ActiveLayer* layers = reinterpret_cast<ActiveLayer*>(data.layers);
1147     uint32_t layer_count = data.layer_count;
1148 
1149     VkAllocationCallbacks local_allocator;
1150     if (!allocator)
1151         local_allocator = driver::GetData(instance).allocator;
1152 
1153     // this also destroys InstanceData
1154     data.dispatch.DestroyInstance(instance, allocator);
1155 
1156     DestroyLayers(layers, layer_count,
1157                   (allocator) ? *allocator : local_allocator);
1158 }
1159 
DestroyDevice(VkDevice device,const VkAllocationCallbacks * allocator)1160 void LayerChain::DestroyDevice(VkDevice device,
1161                                const VkAllocationCallbacks* allocator) {
1162     DeviceData& data = GetData(device);
1163     // this also destroys DeviceData
1164     data.dispatch.DestroyDevice(device, allocator);
1165 }
1166 
GetActiveLayers(VkPhysicalDevice physical_dev,uint32_t & count)1167 const LayerChain::ActiveLayer* LayerChain::GetActiveLayers(
1168     VkPhysicalDevice physical_dev,
1169     uint32_t& count) {
1170     count = GetData(physical_dev).layer_count;
1171     return reinterpret_cast<const ActiveLayer*>(GetData(physical_dev).layers);
1172 }
1173 
1174 // ----------------------------------------------------------------------------
1175 
EnsureInitialized()1176 bool EnsureInitialized() {
1177     static std::once_flag once_flag;
1178     static bool initialized;
1179 
1180     std::call_once(once_flag, []() {
1181         if (driver::OpenHAL()) {
1182             initialized = true;
1183         }
1184     });
1185 
1186     {
1187         static pid_t pid = getpid() + 1;
1188         static std::mutex layer_lock;
1189         std::lock_guard<std::mutex> lock(layer_lock);
1190         if (pid != getpid()) {
1191             pid = getpid();
1192             DiscoverLayers();
1193         }
1194     }
1195 
1196     return initialized;
1197 }
1198 
1199 template <typename Functor>
ForEachLayerFromSettings(Functor functor)1200 void ForEachLayerFromSettings(Functor functor) {
1201     const std::string layersSetting =
1202         android::GraphicsEnv::getInstance().getDebugLayers();
1203     if (!layersSetting.empty()) {
1204         std::vector<std::string> layers =
1205             android::base::Split(layersSetting, ":");
1206         for (uint32_t i = 0; i < layers.size(); i++) {
1207             const Layer* layer = FindLayer(layers[i].c_str());
1208             if (!layer) {
1209                 continue;
1210             }
1211             functor(layer);
1212         }
1213     }
1214 }
1215 
1216 }  // anonymous namespace
1217 
CreateInstance(const VkInstanceCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkInstance * pInstance)1218 VkResult CreateInstance(const VkInstanceCreateInfo* pCreateInfo,
1219                         const VkAllocationCallbacks* pAllocator,
1220                         VkInstance* pInstance) {
1221     ATRACE_CALL();
1222 
1223     if (!EnsureInitialized())
1224         return VK_ERROR_INITIALIZATION_FAILED;
1225 
1226     return LayerChain::CreateInstance(pCreateInfo, pAllocator, pInstance);
1227 }
1228 
DestroyInstance(VkInstance instance,const VkAllocationCallbacks * pAllocator)1229 void DestroyInstance(VkInstance instance,
1230                      const VkAllocationCallbacks* pAllocator) {
1231     ATRACE_CALL();
1232 
1233     if (instance != VK_NULL_HANDLE)
1234         LayerChain::DestroyInstance(instance, pAllocator);
1235 }
1236 
CreateDevice(VkPhysicalDevice physicalDevice,const VkDeviceCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkDevice * pDevice)1237 VkResult CreateDevice(VkPhysicalDevice physicalDevice,
1238                       const VkDeviceCreateInfo* pCreateInfo,
1239                       const VkAllocationCallbacks* pAllocator,
1240                       VkDevice* pDevice) {
1241     ATRACE_CALL();
1242 
1243     return LayerChain::CreateDevice(physicalDevice, pCreateInfo, pAllocator,
1244                                     pDevice);
1245 }
1246 
DestroyDevice(VkDevice device,const VkAllocationCallbacks * pAllocator)1247 void DestroyDevice(VkDevice device, const VkAllocationCallbacks* pAllocator) {
1248     ATRACE_CALL();
1249 
1250     if (device != VK_NULL_HANDLE)
1251         LayerChain::DestroyDevice(device, pAllocator);
1252 }
1253 
EnumerateInstanceLayerProperties(uint32_t * pPropertyCount,VkLayerProperties * pProperties)1254 VkResult EnumerateInstanceLayerProperties(uint32_t* pPropertyCount,
1255                                           VkLayerProperties* pProperties) {
1256     ATRACE_CALL();
1257 
1258     if (!EnsureInitialized())
1259         return VK_ERROR_INITIALIZATION_FAILED;
1260 
1261     uint32_t count = GetLayerCount();
1262 
1263     if (!pProperties) {
1264         *pPropertyCount = count;
1265         return VK_SUCCESS;
1266     }
1267 
1268     uint32_t copied = std::min(*pPropertyCount, count);
1269     for (uint32_t i = 0; i < copied; i++)
1270         pProperties[i] = GetLayerProperties(GetLayer(i));
1271     *pPropertyCount = copied;
1272 
1273     return (copied == count) ? VK_SUCCESS : VK_INCOMPLETE;
1274 }
1275 
EnumerateInstanceExtensionProperties(const char * pLayerName,uint32_t * pPropertyCount,VkExtensionProperties * pProperties)1276 VkResult EnumerateInstanceExtensionProperties(
1277     const char* pLayerName,
1278     uint32_t* pPropertyCount,
1279     VkExtensionProperties* pProperties) {
1280     ATRACE_CALL();
1281 
1282     if (!EnsureInitialized())
1283         return VK_ERROR_INITIALIZATION_FAILED;
1284 
1285     if (pLayerName) {
1286         const Layer* layer = FindLayer(pLayerName);
1287         if (!layer)
1288             return VK_ERROR_LAYER_NOT_PRESENT;
1289 
1290         uint32_t count;
1291         const VkExtensionProperties* props =
1292             GetLayerInstanceExtensions(*layer, count);
1293 
1294         if (!pProperties || *pPropertyCount > count)
1295             *pPropertyCount = count;
1296         if (pProperties)
1297             std::copy(props, props + *pPropertyCount, pProperties);
1298 
1299         return *pPropertyCount < count ? VK_INCOMPLETE : VK_SUCCESS;
1300     }
1301 
1302     // If the pLayerName is nullptr, we must advertise all instance extensions
1303     // from all implicitly enabled layers and the driver implementation. If
1304     // there are duplicates among layers and the driver implementation, always
1305     // only preserve the top layer closest to the application regardless of the
1306     // spec version.
1307     std::vector<VkExtensionProperties> properties;
1308     std::unordered_set<std::string> extensionNames;
1309 
1310     // Expose extensions from implicitly enabled layers.
1311     ForEachLayerFromSettings([&](const Layer* layer) {
1312         uint32_t count = 0;
1313         const VkExtensionProperties* props =
1314             GetLayerInstanceExtensions(*layer, count);
1315         if (count > 0) {
1316             for (uint32_t i = 0; i < count; ++i) {
1317                 if (extensionNames.emplace(props[i].extensionName).second) {
1318                     properties.push_back(props[i]);
1319                 }
1320             }
1321         }
1322     });
1323 
1324     // TODO(b/143293104): Parse debug.vulkan.layers properties
1325 
1326     // Expose extensions from driver implementation.
1327     {
1328         uint32_t count = 0;
1329         VkResult result = vulkan::driver::EnumerateInstanceExtensionProperties(
1330             nullptr, &count, nullptr);
1331         if (result == VK_SUCCESS && count > 0) {
1332             std::vector<VkExtensionProperties> props(count);
1333             result = vulkan::driver::EnumerateInstanceExtensionProperties(
1334                 nullptr, &count, props.data());
1335             for (auto prop : props) {
1336                 if (extensionNames.emplace(prop.extensionName).second) {
1337                     properties.push_back(prop);
1338                 }
1339             }
1340         }
1341     }
1342 
1343     uint32_t totalCount = properties.size();
1344     if (!pProperties || *pPropertyCount > totalCount) {
1345         *pPropertyCount = totalCount;
1346     }
1347     if (pProperties) {
1348         std::copy(properties.data(), properties.data() + *pPropertyCount,
1349                   pProperties);
1350     }
1351     return *pPropertyCount < totalCount ? VK_INCOMPLETE : VK_SUCCESS;
1352 }
1353 
EnumerateDeviceLayerProperties(VkPhysicalDevice physicalDevice,uint32_t * pPropertyCount,VkLayerProperties * pProperties)1354 VkResult EnumerateDeviceLayerProperties(VkPhysicalDevice physicalDevice,
1355                                         uint32_t* pPropertyCount,
1356                                         VkLayerProperties* pProperties) {
1357     ATRACE_CALL();
1358 
1359     uint32_t count;
1360     const LayerChain::ActiveLayer* layers =
1361         LayerChain::GetActiveLayers(physicalDevice, count);
1362 
1363     if (!pProperties) {
1364         *pPropertyCount = count;
1365         return VK_SUCCESS;
1366     }
1367 
1368     uint32_t copied = std::min(*pPropertyCount, count);
1369     for (uint32_t i = 0; i < copied; i++)
1370         pProperties[i] = GetLayerProperties(*layers[i].ref);
1371     *pPropertyCount = copied;
1372 
1373     return (copied == count) ? VK_SUCCESS : VK_INCOMPLETE;
1374 }
1375 
EnumerateDeviceExtensionProperties(VkPhysicalDevice physicalDevice,const char * pLayerName,uint32_t * pPropertyCount,VkExtensionProperties * pProperties)1376 VkResult EnumerateDeviceExtensionProperties(
1377     VkPhysicalDevice physicalDevice,
1378     const char* pLayerName,
1379     uint32_t* pPropertyCount,
1380     VkExtensionProperties* pProperties) {
1381     ATRACE_CALL();
1382 
1383     if (pLayerName) {
1384         // EnumerateDeviceLayerProperties enumerates active layers for
1385         // backward compatibility.  The extension query here should work for
1386         // all layers.
1387         const Layer* layer = FindLayer(pLayerName);
1388         if (!layer)
1389             return VK_ERROR_LAYER_NOT_PRESENT;
1390 
1391         uint32_t count;
1392         const VkExtensionProperties* props =
1393             GetLayerDeviceExtensions(*layer, count);
1394 
1395         if (!pProperties || *pPropertyCount > count)
1396             *pPropertyCount = count;
1397         if (pProperties)
1398             std::copy(props, props + *pPropertyCount, pProperties);
1399 
1400         return *pPropertyCount < count ? VK_INCOMPLETE : VK_SUCCESS;
1401     }
1402 
1403     // If the pLayerName is nullptr, we must advertise all device extensions
1404     // from all implicitly enabled layers and the driver implementation. If
1405     // there are duplicates among layers and the driver implementation, always
1406     // only preserve the top layer closest to the application regardless of the
1407     // spec version.
1408     std::vector<VkExtensionProperties> properties;
1409     std::unordered_set<std::string> extensionNames;
1410 
1411     // Expose extensions from implicitly enabled layers.
1412     ForEachLayerFromSettings([&](const Layer* layer) {
1413         uint32_t count = 0;
1414         const VkExtensionProperties* props =
1415             GetLayerDeviceExtensions(*layer, count);
1416         if (count > 0) {
1417             for (uint32_t i = 0; i < count; ++i) {
1418                 if (extensionNames.emplace(props[i].extensionName).second) {
1419                     properties.push_back(props[i]);
1420                 }
1421             }
1422         }
1423     });
1424 
1425     // TODO(b/143293104): Parse debug.vulkan.layers properties
1426 
1427     // Expose extensions from driver implementation.
1428     {
1429         const InstanceData& data = GetData(physicalDevice);
1430         uint32_t count = 0;
1431         VkResult result = data.dispatch.EnumerateDeviceExtensionProperties(
1432             physicalDevice, nullptr, &count, nullptr);
1433         if (result == VK_SUCCESS && count > 0) {
1434             std::vector<VkExtensionProperties> props(count);
1435             result = data.dispatch.EnumerateDeviceExtensionProperties(
1436                 physicalDevice, nullptr, &count, props.data());
1437             for (auto prop : props) {
1438                 if (extensionNames.emplace(prop.extensionName).second) {
1439                     properties.push_back(prop);
1440                 }
1441             }
1442         }
1443     }
1444 
1445     uint32_t totalCount = properties.size();
1446     if (!pProperties || *pPropertyCount > totalCount) {
1447         *pPropertyCount = totalCount;
1448     }
1449     if (pProperties) {
1450         std::copy(properties.data(), properties.data() + *pPropertyCount,
1451                   pProperties);
1452     }
1453     return *pPropertyCount < totalCount ? VK_INCOMPLETE : VK_SUCCESS;
1454 }
1455 
EnumerateInstanceVersion(uint32_t * pApiVersion)1456 VkResult EnumerateInstanceVersion(uint32_t* pApiVersion) {
1457     ATRACE_CALL();
1458 
1459     *pApiVersion = VK_API_VERSION_1_1;
1460     return VK_SUCCESS;
1461 }
1462 
1463 }  // namespace api
1464 }  // namespace vulkan
1465