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