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