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