core_validation.cpp revision dcf917f7e9b04916caf3f7bb067f7f760d0daa99
1/* Copyright (c) 2015-2016 The Khronos Group Inc.
2 * Copyright (c) 2015-2016 Valve Corporation
3 * Copyright (c) 2015-2016 LunarG, Inc.
4 * Copyright (C) 2015-2016 Google Inc.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and/or associated documentation files (the "Materials"), to
8 * deal in the Materials without restriction, including without limitation the
9 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 * sell copies of the Materials, and to permit persons to whom the Materials
11 * are furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice(s) and this permission notice shall be included
14 * in all copies or substantial portions of the Materials.
15 *
16 * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19 *
20 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
21 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
22 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE
23 * USE OR OTHER DEALINGS IN THE MATERIALS
24 *
25 * Author: Cody Northrop <cnorthrop@google.com>
26 * Author: Michael Lentine <mlentine@google.com>
27 * Author: Tobin Ehlis <tobine@google.com>
28 * Author: Chia-I Wu <olv@google.com>
29 * Author: Chris Forbes <chrisf@ijw.co.nz>
30 * Author: Mark Lobodzinski <mark@lunarg.com>
31 * Author: Ian Elliott <ianelliott@google.com>
32 */
33
34// Allow use of STL min and max functions in Windows
35#define NOMINMAX
36
37// Turn on mem_tracker merged code
38#define MTMERGESOURCE 1
39
40#include <SPIRV/spirv.hpp>
41#include <algorithm>
42#include <assert.h>
43#include <iostream>
44#include <list>
45#include <map>
46#include <set>
47#include <stdio.h>
48#include <stdlib.h>
49#include <string.h>
50#include <string>
51#include <unordered_map>
52#include <unordered_set>
53
54#include "vk_loader_platform.h"
55#include "vk_dispatch_table_helper.h"
56#include "vk_struct_string_helper_cpp.h"
57#if defined(__GNUC__)
58#pragma GCC diagnostic ignored "-Wwrite-strings"
59#endif
60#if defined(__GNUC__)
61#pragma GCC diagnostic warning "-Wwrite-strings"
62#endif
63#include "vk_struct_size_helper.h"
64#include "core_validation.h"
65#include "vk_layer_config.h"
66#include "vk_layer_table.h"
67#include "vk_layer_data.h"
68#include "vk_layer_logging.h"
69#include "vk_layer_extension_utils.h"
70#include "vk_layer_utils.h"
71
72#if defined __ANDROID__
73#include <android/log.h>
74#define LOGCONSOLE(...) ((void)__android_log_print(ANDROID_LOG_INFO, "DS", __VA_ARGS__))
75#else
76#define LOGCONSOLE(...) printf(__VA_ARGS__)
77#endif
78
79using std::unordered_map;
80using std::unordered_set;
81
82// WSI Image Objects bypass usual Image Object creation methods.  A special Memory
83// Object value will be used to identify them internally.
84static const VkDeviceMemory MEMTRACKER_SWAP_CHAIN_IMAGE_KEY = (VkDeviceMemory)(-1);
85
86// Track command pools and their command buffers
87struct CMD_POOL_INFO {
88    VkCommandPoolCreateFlags createFlags;
89    uint32_t queueFamilyIndex;
90    list<VkCommandBuffer> commandBuffers; // list container of cmd buffers allocated from this pool
91};
92
93struct devExts {
94    bool wsi_enabled;
95    unordered_map<VkSwapchainKHR, SWAPCHAIN_NODE *> swapchainMap;
96    unordered_map<VkImage, VkSwapchainKHR> imageToSwapchainMap;
97};
98
99// fwd decls
100struct shader_module;
101
102// TODO : Split this into separate structs for instance and device level data?
103struct layer_data {
104    debug_report_data *report_data;
105    std::vector<VkDebugReportCallbackEXT> logging_callback;
106    VkLayerDispatchTable *device_dispatch_table;
107    VkLayerInstanceDispatchTable *instance_dispatch_table;
108
109    devExts device_extensions;
110    uint64_t currentFenceId;
111    unordered_set<VkQueue> queues;  // all queues under given device
112    // Global set of all cmdBuffers that are inFlight on this device
113    unordered_set<VkCommandBuffer> globalInFlightCmdBuffers;
114    // Layer specific data
115    unordered_map<VkSampler, unique_ptr<SAMPLER_NODE>> sampleMap;
116    unordered_map<VkImageView, VkImageViewCreateInfo> imageViewMap;
117    unordered_map<VkImage, IMAGE_NODE> imageMap;
118    unordered_map<VkBufferView, VkBufferViewCreateInfo> bufferViewMap;
119    unordered_map<VkBuffer, BUFFER_NODE> bufferMap;
120    unordered_map<VkPipeline, PIPELINE_NODE *> pipelineMap;
121    unordered_map<VkCommandPool, CMD_POOL_INFO> commandPoolMap;
122    unordered_map<VkDescriptorPool, DESCRIPTOR_POOL_NODE *> descriptorPoolMap;
123    unordered_map<VkDescriptorSet, SET_NODE *> setMap;
124    unordered_map<VkDescriptorSetLayout, LAYOUT_NODE *> descriptorSetLayoutMap;
125    unordered_map<VkPipelineLayout, PIPELINE_LAYOUT_NODE> pipelineLayoutMap;
126    unordered_map<VkDeviceMemory, DEVICE_MEM_INFO> memObjMap;
127    unordered_map<VkFence, FENCE_NODE> fenceMap;
128    unordered_map<VkQueue, QUEUE_NODE> queueMap;
129    unordered_map<VkEvent, EVENT_NODE> eventMap;
130    unordered_map<QueryObject, bool> queryToStateMap;
131    unordered_map<VkQueryPool, QUERY_POOL_NODE> queryPoolMap;
132    unordered_map<VkSemaphore, SEMAPHORE_NODE> semaphoreMap;
133    unordered_map<VkCommandBuffer, GLOBAL_CB_NODE *> commandBufferMap;
134    unordered_map<VkFramebuffer, FRAMEBUFFER_NODE> frameBufferMap;
135    unordered_map<VkImage, vector<ImageSubresourcePair>> imageSubresourceMap;
136    unordered_map<ImageSubresourcePair, IMAGE_LAYOUT_NODE> imageLayoutMap;
137    unordered_map<VkRenderPass, RENDER_PASS_NODE *> renderPassMap;
138    unordered_map<VkShaderModule, unique_ptr<shader_module>> shaderModuleMap;
139    VkDevice device;
140
141    // Device specific data
142    PHYS_DEV_PROPERTIES_NODE phys_dev_properties;
143    VkPhysicalDeviceMemoryProperties phys_dev_mem_props;
144
145    layer_data()
146        : report_data(nullptr), device_dispatch_table(nullptr), instance_dispatch_table(nullptr), device_extensions(),
147          currentFenceId(1), device(VK_NULL_HANDLE), phys_dev_properties{},
148          phys_dev_mem_props{} {};
149};
150
151// TODO : Do we need to guard access to layer_data_map w/ lock?
152static unordered_map<void *, layer_data *> layer_data_map;
153
154static const VkLayerProperties cv_global_layers[] = {{
155    "VK_LAYER_LUNARG_core_validation", VK_LAYER_API_VERSION, 1, "LunarG Validation Layer",
156}};
157
158template <class TCreateInfo> void ValidateLayerOrdering(const TCreateInfo &createInfo) {
159    bool foundLayer = false;
160    for (uint32_t i = 0; i < createInfo.enabledLayerCount; ++i) {
161        if (!strcmp(createInfo.ppEnabledLayerNames[i], cv_global_layers[0].layerName)) {
162            foundLayer = true;
163        }
164        // This has to be logged to console as we don't have a callback at this point.
165        if (!foundLayer && !strcmp(createInfo.ppEnabledLayerNames[0], "VK_LAYER_GOOGLE_unique_objects")) {
166            LOGCONSOLE("Cannot activate layer VK_LAYER_GOOGLE_unique_objects prior to activating %s.",
167                       cv_global_layers[0].layerName);
168        }
169    }
170}
171
172// Code imported from shader_checker
173static void build_def_index(shader_module *);
174
175// A forward iterator over spirv instructions. Provides easy access to len, opcode, and content words
176// without the caller needing to care too much about the physical SPIRV module layout.
177struct spirv_inst_iter {
178    std::vector<uint32_t>::const_iterator zero;
179    std::vector<uint32_t>::const_iterator it;
180
181    uint32_t len() { return *it >> 16; }
182    uint32_t opcode() { return *it & 0x0ffffu; }
183    uint32_t const &word(unsigned n) { return it[n]; }
184    uint32_t offset() { return (uint32_t)(it - zero); }
185
186    spirv_inst_iter() {}
187
188    spirv_inst_iter(std::vector<uint32_t>::const_iterator zero, std::vector<uint32_t>::const_iterator it) : zero(zero), it(it) {}
189
190    bool operator==(spirv_inst_iter const &other) { return it == other.it; }
191
192    bool operator!=(spirv_inst_iter const &other) { return it != other.it; }
193
194    spirv_inst_iter operator++(int) { /* x++ */
195        spirv_inst_iter ii = *this;
196        it += len();
197        return ii;
198    }
199
200    spirv_inst_iter operator++() { /* ++x; */
201        it += len();
202        return *this;
203    }
204
205    /* The iterator and the value are the same thing. */
206    spirv_inst_iter &operator*() { return *this; }
207    spirv_inst_iter const &operator*() const { return *this; }
208};
209
210struct shader_module {
211    /* the spirv image itself */
212    vector<uint32_t> words;
213    /* a mapping of <id> to the first word of its def. this is useful because walking type
214     * trees, constant expressions, etc requires jumping all over the instruction stream.
215     */
216    unordered_map<unsigned, unsigned> def_index;
217
218    shader_module(VkShaderModuleCreateInfo const *pCreateInfo)
219        : words((uint32_t *)pCreateInfo->pCode, (uint32_t *)pCreateInfo->pCode + pCreateInfo->codeSize / sizeof(uint32_t)),
220          def_index() {
221
222        build_def_index(this);
223    }
224
225    /* expose begin() / end() to enable range-based for */
226    spirv_inst_iter begin() const { return spirv_inst_iter(words.begin(), words.begin() + 5); } /* first insn */
227    spirv_inst_iter end() const { return spirv_inst_iter(words.begin(), words.end()); }         /* just past last insn */
228    /* given an offset into the module, produce an iterator there. */
229    spirv_inst_iter at(unsigned offset) const { return spirv_inst_iter(words.begin(), words.begin() + offset); }
230
231    /* gets an iterator to the definition of an id */
232    spirv_inst_iter get_def(unsigned id) const {
233        auto it = def_index.find(id);
234        if (it == def_index.end()) {
235            return end();
236        }
237        return at(it->second);
238    }
239};
240
241// TODO : This can be much smarter, using separate locks for separate global data
242static int globalLockInitialized = 0;
243static loader_platform_thread_mutex globalLock;
244#if MTMERGESOURCE
245// MTMERGESOURCE - start of direct pull
246static VkDeviceMemory *get_object_mem_binding(layer_data *my_data, uint64_t handle, VkDebugReportObjectTypeEXT type) {
247    switch (type) {
248    case VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT: {
249        auto it = my_data->imageMap.find(VkImage(handle));
250        if (it != my_data->imageMap.end())
251            return &(*it).second.mem;
252        break;
253    }
254    case VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT: {
255        auto it = my_data->bufferMap.find(VkBuffer(handle));
256        if (it != my_data->bufferMap.end())
257            return &(*it).second.mem;
258        break;
259    }
260    default:
261        break;
262    }
263    return nullptr;
264}
265// MTMERGESOURCE - end section
266#endif
267template layer_data *get_my_data_ptr<layer_data>(void *data_key, std::unordered_map<void *, layer_data *> &data_map);
268
269// prototype
270static GLOBAL_CB_NODE *getCBNode(layer_data *, const VkCommandBuffer);
271
272#if MTMERGESOURCE
273// Add a fence, creating one if necessary to our list of fences/fenceIds
274static bool add_fence_info(layer_data *my_data, VkFence fence, VkQueue queue, uint64_t *fenceId) {
275    bool skipCall = false;
276    *fenceId = my_data->currentFenceId++;
277
278    // If no fence, create an internal fence to track the submissions
279    if (fence != VK_NULL_HANDLE) {
280        my_data->fenceMap[fence].fenceId = *fenceId;
281        my_data->fenceMap[fence].queue = queue;
282        // Validate that fence is in UNSIGNALED state
283        VkFenceCreateInfo *pFenceCI = &(my_data->fenceMap[fence].createInfo);
284        if (pFenceCI->flags & VK_FENCE_CREATE_SIGNALED_BIT) {
285            skipCall = log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT,
286                               (uint64_t)fence, __LINE__, MEMTRACK_INVALID_FENCE_STATE, "MEM",
287                               "Fence %#" PRIxLEAST64 " submitted in SIGNALED state.  Fences must be reset before being submitted",
288                               (uint64_t)fence);
289        }
290    } else {
291        // TODO : Do we need to create an internal fence here for tracking purposes?
292    }
293    // Update most recently submitted fence and fenceId for Queue
294    my_data->queueMap[queue].lastSubmittedId = *fenceId;
295    return skipCall;
296}
297
298// Record information when a fence is known to be signalled
299static void update_fence_tracking(layer_data *my_data, VkFence fence) {
300    auto fence_item = my_data->fenceMap.find(fence);
301    if (fence_item != my_data->fenceMap.end()) {
302        FENCE_NODE *pCurFenceInfo = &(*fence_item).second;
303        VkQueue queue = pCurFenceInfo->queue;
304        auto queue_item = my_data->queueMap.find(queue);
305        if (queue_item != my_data->queueMap.end()) {
306            QUEUE_NODE *pQueueInfo = &(*queue_item).second;
307            if (pQueueInfo->lastRetiredId < pCurFenceInfo->fenceId) {
308                pQueueInfo->lastRetiredId = pCurFenceInfo->fenceId;
309            }
310        }
311    }
312
313    // Update fence state in fenceCreateInfo structure
314    auto pFCI = &(my_data->fenceMap[fence].createInfo);
315    pFCI->flags = static_cast<VkFenceCreateFlags>(pFCI->flags | VK_FENCE_CREATE_SIGNALED_BIT);
316}
317
318// Helper routine that updates the fence list for a specific queue to all-retired
319static void retire_queue_fences(layer_data *my_data, VkQueue queue) {
320    QUEUE_NODE *pQueueInfo = &my_data->queueMap[queue];
321    // Set queue's lastRetired to lastSubmitted indicating all fences completed
322    pQueueInfo->lastRetiredId = pQueueInfo->lastSubmittedId;
323}
324
325// Helper routine that updates all queues to all-retired
326static void retire_device_fences(layer_data *my_data, VkDevice device) {
327    // Process each queue for device
328    // TODO: Add multiple device support
329    for (auto ii = my_data->queueMap.begin(); ii != my_data->queueMap.end(); ++ii) {
330        // Set queue's lastRetired to lastSubmitted indicating all fences completed
331        QUEUE_NODE *pQueueInfo = &(*ii).second;
332        pQueueInfo->lastRetiredId = pQueueInfo->lastSubmittedId;
333    }
334}
335
336// Helper function to validate correct usage bits set for buffers or images
337//  Verify that (actual & desired) flags != 0 or,
338//   if strict is true, verify that (actual & desired) flags == desired
339//  In case of error, report it via dbg callbacks
340static bool validate_usage_flags(layer_data *my_data, VkFlags actual, VkFlags desired, VkBool32 strict,
341                                     uint64_t obj_handle, VkDebugReportObjectTypeEXT obj_type, char const *ty_str,
342                                     char const *func_name, char const *usage_str) {
343    bool correct_usage = false;
344    bool skipCall = false;
345    if (strict)
346        correct_usage = ((actual & desired) == desired);
347    else
348        correct_usage = ((actual & desired) != 0);
349    if (!correct_usage) {
350        skipCall = log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, obj_type, obj_handle, __LINE__,
351                           MEMTRACK_INVALID_USAGE_FLAG, "MEM", "Invalid usage flag for %s %#" PRIxLEAST64
352                                                               " used by %s. In this case, %s should have %s set during creation.",
353                           ty_str, obj_handle, func_name, ty_str, usage_str);
354    }
355    return skipCall;
356}
357
358// Helper function to validate usage flags for images
359// Pulls image info and then sends actual vs. desired usage off to helper above where
360//  an error will be flagged if usage is not correct
361static bool validate_image_usage_flags(layer_data *dev_data, VkImage image, VkFlags desired, VkBool32 strict,
362                                           char const *func_name, char const *usage_string) {
363    bool skipCall = false;
364    auto const image_node = dev_data->imageMap.find(image);
365    if (image_node != dev_data->imageMap.end()) {
366        skipCall = validate_usage_flags(dev_data, image_node->second.createInfo.usage, desired, strict, (uint64_t)image,
367                                        VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, "image", func_name, usage_string);
368    }
369    return skipCall;
370}
371
372// Helper function to validate usage flags for buffers
373// Pulls buffer info and then sends actual vs. desired usage off to helper above where
374//  an error will be flagged if usage is not correct
375static bool validate_buffer_usage_flags(layer_data *dev_data, VkBuffer buffer, VkFlags desired, VkBool32 strict,
376                                            char const *func_name, char const *usage_string) {
377    bool skipCall = false;
378    auto const buffer_node = dev_data->bufferMap.find(buffer);
379    if (buffer_node != dev_data->bufferMap.end()) {
380        skipCall = validate_usage_flags(dev_data, buffer_node->second.createInfo.usage, desired, strict, (uint64_t)buffer,
381                                        VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, "buffer", func_name, usage_string);
382    }
383    return skipCall;
384}
385
386// Return ptr to info in map container containing mem, or NULL if not found
387//  Calls to this function should be wrapped in mutex
388static DEVICE_MEM_INFO *get_mem_obj_info(layer_data *dev_data, const VkDeviceMemory mem) {
389    auto item = dev_data->memObjMap.find(mem);
390    if (item != dev_data->memObjMap.end()) {
391        return &(*item).second;
392    } else {
393        return NULL;
394    }
395}
396
397static void add_mem_obj_info(layer_data *my_data, void *object, const VkDeviceMemory mem,
398                             const VkMemoryAllocateInfo *pAllocateInfo) {
399    assert(object != NULL);
400
401    memcpy(&my_data->memObjMap[mem].allocInfo, pAllocateInfo, sizeof(VkMemoryAllocateInfo));
402    // TODO:  Update for real hardware, actually process allocation info structures
403    my_data->memObjMap[mem].allocInfo.pNext = NULL;
404    my_data->memObjMap[mem].object = object;
405    my_data->memObjMap[mem].mem = mem;
406    my_data->memObjMap[mem].image = VK_NULL_HANDLE;
407    my_data->memObjMap[mem].memRange.offset = 0;
408    my_data->memObjMap[mem].memRange.size = 0;
409    my_data->memObjMap[mem].pData = 0;
410    my_data->memObjMap[mem].pDriverData = 0;
411    my_data->memObjMap[mem].valid = false;
412}
413
414static bool validate_memory_is_valid(layer_data *dev_data, VkDeviceMemory mem, const char *functionName,
415                                     VkImage image = VK_NULL_HANDLE) {
416    if (mem == MEMTRACKER_SWAP_CHAIN_IMAGE_KEY) {
417        auto const image_node = dev_data->imageMap.find(image);
418        if (image_node != dev_data->imageMap.end() && !image_node->second.valid) {
419            return log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
420                           (uint64_t)(mem), __LINE__, MEMTRACK_INVALID_USAGE_FLAG, "MEM",
421                           "%s: Cannot read invalid swapchain image %" PRIx64 ", please fill the memory before using.",
422                           functionName, (uint64_t)(image));
423        }
424    } else {
425        DEVICE_MEM_INFO *pMemObj = get_mem_obj_info(dev_data, mem);
426        if (pMemObj && !pMemObj->valid) {
427            return log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
428                           (uint64_t)(mem), __LINE__, MEMTRACK_INVALID_USAGE_FLAG, "MEM",
429                           "%s: Cannot read invalid memory %" PRIx64 ", please fill the memory before using.", functionName,
430                           (uint64_t)(mem));
431        }
432    }
433    return false;
434}
435
436static void set_memory_valid(layer_data *dev_data, VkDeviceMemory mem, bool valid, VkImage image = VK_NULL_HANDLE) {
437    if (mem == MEMTRACKER_SWAP_CHAIN_IMAGE_KEY) {
438        auto image_node = dev_data->imageMap.find(image);
439        if (image_node != dev_data->imageMap.end()) {
440            image_node->second.valid = valid;
441        }
442    } else {
443        DEVICE_MEM_INFO *pMemObj = get_mem_obj_info(dev_data, mem);
444        if (pMemObj) {
445            pMemObj->valid = valid;
446        }
447    }
448}
449
450// Find CB Info and add mem reference to list container
451// Find Mem Obj Info and add CB reference to list container
452static bool update_cmd_buf_and_mem_references(layer_data *dev_data, const VkCommandBuffer cb, const VkDeviceMemory mem,
453                                              const char *apiName) {
454    bool skipCall = false;
455
456    // Skip validation if this image was created through WSI
457    if (mem != MEMTRACKER_SWAP_CHAIN_IMAGE_KEY) {
458
459        // First update CB binding in MemObj mini CB list
460        DEVICE_MEM_INFO *pMemInfo = get_mem_obj_info(dev_data, mem);
461        if (pMemInfo) {
462            pMemInfo->commandBufferBindings.insert(cb);
463            // Now update CBInfo's Mem reference list
464            GLOBAL_CB_NODE *pCBNode = getCBNode(dev_data, cb);
465            // TODO: keep track of all destroyed CBs so we know if this is a stale or simply invalid object
466            if (pCBNode) {
467                pCBNode->memObjs.insert(mem);
468            }
469        }
470    }
471    return skipCall;
472}
473// For every mem obj bound to particular CB, free bindings related to that CB
474static void clear_cmd_buf_and_mem_references(layer_data *dev_data, GLOBAL_CB_NODE *pCBNode) {
475    if (pCBNode) {
476        if (pCBNode->memObjs.size() > 0) {
477            for (auto mem : pCBNode->memObjs) {
478                DEVICE_MEM_INFO *pInfo = get_mem_obj_info(dev_data, mem);
479                if (pInfo) {
480                    pInfo->commandBufferBindings.erase(pCBNode->commandBuffer);
481                }
482            }
483            pCBNode->memObjs.clear();
484        }
485        pCBNode->validate_functions.clear();
486    }
487}
488// Overloaded call to above function when GLOBAL_CB_NODE has not already been looked-up
489static void clear_cmd_buf_and_mem_references(layer_data *dev_data, const VkCommandBuffer cb) {
490    clear_cmd_buf_and_mem_references(dev_data, getCBNode(dev_data, cb));
491}
492
493// For given MemObjInfo, report Obj & CB bindings
494static bool reportMemReferencesAndCleanUp(layer_data *dev_data, DEVICE_MEM_INFO *pMemObjInfo) {
495    bool skipCall = false;
496    size_t cmdBufRefCount = pMemObjInfo->commandBufferBindings.size();
497    size_t objRefCount = pMemObjInfo->objBindings.size();
498
499    if ((pMemObjInfo->commandBufferBindings.size()) != 0) {
500        skipCall = log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
501                           (uint64_t)pMemObjInfo->mem, __LINE__, MEMTRACK_FREED_MEM_REF, "MEM",
502                           "Attempting to free memory object %#" PRIxLEAST64 " which still contains " PRINTF_SIZE_T_SPECIFIER
503                           " references",
504                           (uint64_t)pMemObjInfo->mem, (cmdBufRefCount + objRefCount));
505    }
506
507    if (cmdBufRefCount > 0 && pMemObjInfo->commandBufferBindings.size() > 0) {
508        for (auto cb : pMemObjInfo->commandBufferBindings) {
509            log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
510                    (uint64_t)cb, __LINE__, MEMTRACK_FREED_MEM_REF, "MEM",
511                    "Command Buffer %p still has a reference to mem obj %#" PRIxLEAST64, cb, (uint64_t)pMemObjInfo->mem);
512        }
513        // Clear the list of hanging references
514        pMemObjInfo->commandBufferBindings.clear();
515    }
516
517    if (objRefCount > 0 && pMemObjInfo->objBindings.size() > 0) {
518        for (auto obj : pMemObjInfo->objBindings) {
519            log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, obj.type, obj.handle, __LINE__,
520                    MEMTRACK_FREED_MEM_REF, "MEM", "VK Object %#" PRIxLEAST64 " still has a reference to mem obj %#" PRIxLEAST64,
521                    obj.handle, (uint64_t)pMemObjInfo->mem);
522        }
523        // Clear the list of hanging references
524        pMemObjInfo->objBindings.clear();
525    }
526    return skipCall;
527}
528
529static bool deleteMemObjInfo(layer_data *my_data, void *object, VkDeviceMemory mem) {
530    bool skipCall = false;
531    auto item = my_data->memObjMap.find(mem);
532    if (item != my_data->memObjMap.end()) {
533        my_data->memObjMap.erase(item);
534    } else {
535        skipCall = log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
536                           (uint64_t)mem, __LINE__, MEMTRACK_INVALID_MEM_OBJ, "MEM",
537                           "Request to delete memory object %#" PRIxLEAST64 " not present in memory Object Map", (uint64_t)mem);
538    }
539    return skipCall;
540}
541
542// Check if fence for given CB is completed
543static bool checkCBCompleted(layer_data *my_data, const VkCommandBuffer cb, bool *complete) {
544    GLOBAL_CB_NODE *pCBNode = getCBNode(my_data, cb);
545    bool skipCall = false;
546    *complete = true;
547
548    if (pCBNode) {
549        if (pCBNode->lastSubmittedQueue != NULL) {
550            VkQueue queue = pCBNode->lastSubmittedQueue;
551            QUEUE_NODE *pQueueInfo = &my_data->queueMap[queue];
552            if (pCBNode->fenceId > pQueueInfo->lastRetiredId) {
553                skipCall = log_msg(my_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT,
554                                   VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, (uint64_t)cb, __LINE__, MEMTRACK_NONE, "MEM",
555                                   "fence %#" PRIxLEAST64 " for CB %p has not been checked for completion",
556                                   (uint64_t)pCBNode->lastSubmittedFence, cb);
557                *complete = false;
558            }
559        }
560    }
561    return skipCall;
562}
563
564static bool freeMemObjInfo(layer_data *dev_data, void *object, VkDeviceMemory mem, bool internal) {
565    bool skipCall = false;
566    // Parse global list to find info w/ mem
567    DEVICE_MEM_INFO *pInfo = get_mem_obj_info(dev_data, mem);
568    if (pInfo) {
569        if (pInfo->allocInfo.allocationSize == 0 && !internal) {
570            // TODO: Verify against Valid Use section
571            skipCall = log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
572                               (uint64_t)mem, __LINE__, MEMTRACK_INVALID_MEM_OBJ, "MEM",
573                               "Attempting to free memory associated with a Persistent Image, %#" PRIxLEAST64 ", "
574                               "this should not be explicitly freed\n",
575                               (uint64_t)mem);
576        } else {
577            // Clear any CB bindings for completed CBs
578            //   TODO : Is there a better place to do this?
579
580            assert(pInfo->object != VK_NULL_HANDLE);
581            // clear_cmd_buf_and_mem_references removes elements from
582            // pInfo->commandBufferBindings -- this copy not needed in c++14,
583            // and probably not needed in practice in c++11
584            auto bindings = pInfo->commandBufferBindings;
585            for (auto cb : bindings) {
586                bool commandBufferComplete = false;
587                skipCall |= checkCBCompleted(dev_data, cb, &commandBufferComplete);
588                if (commandBufferComplete) {
589                    clear_cmd_buf_and_mem_references(dev_data, cb);
590                }
591            }
592
593            // Now verify that no references to this mem obj remain and remove bindings
594            if (pInfo->commandBufferBindings.size() || pInfo->objBindings.size()) {
595                skipCall |= reportMemReferencesAndCleanUp(dev_data, pInfo);
596            }
597            // Delete mem obj info
598            skipCall |= deleteMemObjInfo(dev_data, object, mem);
599        }
600    }
601    return skipCall;
602}
603
604static const char *object_type_to_string(VkDebugReportObjectTypeEXT type) {
605    switch (type) {
606    case VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT:
607        return "image";
608    case VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT:
609        return "buffer";
610    case VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT:
611        return "swapchain";
612    default:
613        return "unknown";
614    }
615}
616
617// Remove object binding performs 3 tasks:
618// 1. Remove ObjectInfo from MemObjInfo list container of obj bindings & free it
619// 2. Clear mem binding for image/buffer by setting its handle to 0
620// TODO : This only applied to Buffer, Image, and Swapchain objects now, how should it be updated/customized?
621static bool clear_object_binding(layer_data *dev_data, uint64_t handle, VkDebugReportObjectTypeEXT type) {
622    // TODO : Need to customize images/buffers/swapchains to track mem binding and clear it here appropriately
623    bool skipCall = false;
624    VkDeviceMemory *pMemBinding = get_object_mem_binding(dev_data, handle, type);
625    if (pMemBinding) {
626        DEVICE_MEM_INFO *pMemObjInfo = get_mem_obj_info(dev_data, *pMemBinding);
627        // TODO : Make sure this is a reasonable way to reset mem binding
628        *pMemBinding = VK_NULL_HANDLE;
629        if (pMemObjInfo) {
630            // This obj is bound to a memory object. Remove the reference to this object in that memory object's list,
631            // and set the objects memory binding pointer to NULL.
632            if (!pMemObjInfo->objBindings.erase({handle, type})) {
633                skipCall |=
634                    log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, type, handle, __LINE__, MEMTRACK_INVALID_OBJECT,
635                            "MEM", "While trying to clear mem binding for %s obj %#" PRIxLEAST64
636                                   ", unable to find that object referenced by mem obj %#" PRIxLEAST64,
637                            object_type_to_string(type), handle, (uint64_t)pMemObjInfo->mem);
638            }
639        }
640    }
641    return skipCall;
642}
643
644// For NULL mem case, output warning
645// Make sure given object is in global object map
646//  IF a previous binding existed, output validation error
647//  Otherwise, add reference from objectInfo to memoryInfo
648//  Add reference off of objInfo
649static bool set_mem_binding(layer_data *dev_data, VkDeviceMemory mem, uint64_t handle,
650                                VkDebugReportObjectTypeEXT type, const char *apiName) {
651    bool skipCall = false;
652    // Handle NULL case separately, just clear previous binding & decrement reference
653    if (mem == VK_NULL_HANDLE) {
654        // TODO: Verify against Valid Use section of spec.
655        skipCall = log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, type, handle, __LINE__, MEMTRACK_INVALID_MEM_OBJ,
656                           "MEM", "In %s, attempting to Bind Obj(%#" PRIxLEAST64 ") to NULL", apiName, handle);
657    } else {
658        VkDeviceMemory *pMemBinding = get_object_mem_binding(dev_data, handle, type);
659        if (!pMemBinding) {
660            skipCall |=
661                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, type, handle, __LINE__, MEMTRACK_MISSING_MEM_BINDINGS,
662                        "MEM", "In %s, attempting to update Binding of %s Obj(%#" PRIxLEAST64 ") that's not in global list",
663                        object_type_to_string(type), apiName, handle);
664        } else {
665            // non-null case so should have real mem obj
666            DEVICE_MEM_INFO *pMemInfo = get_mem_obj_info(dev_data, mem);
667            if (pMemInfo) {
668                DEVICE_MEM_INFO *pPrevBinding = get_mem_obj_info(dev_data, *pMemBinding);
669                if (pPrevBinding != NULL) {
670                    skipCall |=
671                        log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
672                                (uint64_t)mem, __LINE__, MEMTRACK_REBIND_OBJECT, "MEM",
673                                "In %s, attempting to bind memory (%#" PRIxLEAST64 ") to object (%#" PRIxLEAST64
674                                ") which has already been bound to mem object %#" PRIxLEAST64,
675                                apiName, (uint64_t)mem, handle, (uint64_t)pPrevBinding->mem);
676                } else {
677                    pMemInfo->objBindings.insert({handle, type});
678                    // For image objects, make sure default memory state is correctly set
679                    // TODO : What's the best/correct way to handle this?
680                    if (VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT == type) {
681                        auto const image_node = dev_data->imageMap.find(VkImage(handle));
682                        if (image_node != dev_data->imageMap.end()) {
683                            VkImageCreateInfo ici = image_node->second.createInfo;
684                            if (ici.usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
685                                // TODO::  More memory state transition stuff.
686                            }
687                        }
688                    }
689                    *pMemBinding = mem;
690                }
691            }
692        }
693    }
694    return skipCall;
695}
696
697// For NULL mem case, clear any previous binding Else...
698// Make sure given object is in its object map
699//  IF a previous binding existed, update binding
700//  Add reference from objectInfo to memoryInfo
701//  Add reference off of object's binding info
702// Return VK_TRUE if addition is successful, VK_FALSE otherwise
703static bool set_sparse_mem_binding(layer_data *dev_data, VkDeviceMemory mem, uint64_t handle,
704                                       VkDebugReportObjectTypeEXT type, const char *apiName) {
705    bool skipCall = VK_FALSE;
706    // Handle NULL case separately, just clear previous binding & decrement reference
707    if (mem == VK_NULL_HANDLE) {
708        skipCall = clear_object_binding(dev_data, handle, type);
709    } else {
710        VkDeviceMemory *pMemBinding = get_object_mem_binding(dev_data, handle, type);
711        if (!pMemBinding) {
712            skipCall |= log_msg(
713                dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, type, handle, __LINE__, MEMTRACK_MISSING_MEM_BINDINGS, "MEM",
714                "In %s, attempting to update Binding of Obj(%#" PRIxLEAST64 ") that's not in global list()", apiName, handle);
715        } else {
716            // non-null case so should have real mem obj
717            DEVICE_MEM_INFO *pInfo = get_mem_obj_info(dev_data, mem);
718            if (pInfo) {
719                pInfo->objBindings.insert({handle, type});
720                // Need to set mem binding for this object
721                *pMemBinding = mem;
722            }
723        }
724    }
725    return skipCall;
726}
727
728// For given Object, get 'mem' obj that it's bound to or NULL if no binding
729static bool get_mem_binding_from_object(layer_data *dev_data, const uint64_t handle,
730                                            const VkDebugReportObjectTypeEXT type, VkDeviceMemory *mem) {
731    bool skipCall = false;
732    *mem = VK_NULL_HANDLE;
733    VkDeviceMemory *pMemBinding = get_object_mem_binding(dev_data, handle, type);
734    if (pMemBinding) {
735        *mem = *pMemBinding;
736    } else {
737        skipCall = log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, type, handle, __LINE__, MEMTRACK_INVALID_OBJECT,
738                           "MEM", "Trying to get mem binding for object %#" PRIxLEAST64 " but no such object in %s list", handle,
739                           object_type_to_string(type));
740    }
741    return skipCall;
742}
743
744// Print details of MemObjInfo list
745static void print_mem_list(layer_data *dev_data) {
746    DEVICE_MEM_INFO *pInfo = NULL;
747
748    // Early out if info is not requested
749    if (!(dev_data->report_data->active_flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT)) {
750        return;
751    }
752
753    // Just printing each msg individually for now, may want to package these into single large print
754    log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, 0, __LINE__,
755            MEMTRACK_NONE, "MEM", "Details of Memory Object list (of size " PRINTF_SIZE_T_SPECIFIER " elements)",
756            dev_data->memObjMap.size());
757    log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, 0, __LINE__,
758            MEMTRACK_NONE, "MEM", "=============================");
759
760    if (dev_data->memObjMap.size() <= 0)
761        return;
762
763    for (auto ii = dev_data->memObjMap.begin(); ii != dev_data->memObjMap.end(); ++ii) {
764        pInfo = &(*ii).second;
765
766        log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, 0,
767                __LINE__, MEMTRACK_NONE, "MEM", "    ===MemObjInfo at %p===", (void *)pInfo);
768        log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, 0,
769                __LINE__, MEMTRACK_NONE, "MEM", "    Mem object: %#" PRIxLEAST64, (uint64_t)(pInfo->mem));
770        log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, 0,
771                __LINE__, MEMTRACK_NONE, "MEM", "    Ref Count: " PRINTF_SIZE_T_SPECIFIER,
772                pInfo->commandBufferBindings.size() + pInfo->objBindings.size());
773        if (0 != pInfo->allocInfo.allocationSize) {
774            string pAllocInfoMsg = vk_print_vkmemoryallocateinfo(&pInfo->allocInfo, "MEM(INFO):         ");
775            log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, 0,
776                    __LINE__, MEMTRACK_NONE, "MEM", "    Mem Alloc info:\n%s", pAllocInfoMsg.c_str());
777        } else {
778            log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, 0,
779                    __LINE__, MEMTRACK_NONE, "MEM", "    Mem Alloc info is NULL (alloc done by vkCreateSwapchainKHR())");
780        }
781
782        log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, 0,
783                __LINE__, MEMTRACK_NONE, "MEM", "    VK OBJECT Binding list of size " PRINTF_SIZE_T_SPECIFIER " elements:",
784                pInfo->objBindings.size());
785        if (pInfo->objBindings.size() > 0) {
786            for (auto obj : pInfo->objBindings) {
787                log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
788                        0, __LINE__, MEMTRACK_NONE, "MEM", "       VK OBJECT %" PRIu64, obj.handle);
789            }
790        }
791
792        log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, 0,
793                __LINE__, MEMTRACK_NONE, "MEM",
794                "    VK Command Buffer (CB) binding list of size " PRINTF_SIZE_T_SPECIFIER " elements",
795                pInfo->commandBufferBindings.size());
796        if (pInfo->commandBufferBindings.size() > 0) {
797            for (auto cb : pInfo->commandBufferBindings) {
798                log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
799                        0, __LINE__, MEMTRACK_NONE, "MEM", "      VK CB %p", cb);
800            }
801        }
802    }
803}
804
805static void printCBList(layer_data *my_data) {
806    GLOBAL_CB_NODE *pCBInfo = NULL;
807
808    // Early out if info is not requested
809    if (!(my_data->report_data->active_flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT)) {
810        return;
811    }
812
813    log_msg(my_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, 0, __LINE__,
814            MEMTRACK_NONE, "MEM", "Details of CB list (of size " PRINTF_SIZE_T_SPECIFIER " elements)",
815            my_data->commandBufferMap.size());
816    log_msg(my_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, 0, __LINE__,
817            MEMTRACK_NONE, "MEM", "==================");
818
819    if (my_data->commandBufferMap.size() <= 0)
820        return;
821
822    for (auto &cb_node : my_data->commandBufferMap) {
823        pCBInfo = cb_node.second;
824
825        log_msg(my_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, 0,
826                __LINE__, MEMTRACK_NONE, "MEM", "    CB Info (%p) has CB %p, fenceId %" PRIx64 ", and fence %#" PRIxLEAST64,
827                (void *)pCBInfo, (void *)pCBInfo->commandBuffer, pCBInfo->fenceId, (uint64_t)pCBInfo->lastSubmittedFence);
828
829        if (pCBInfo->memObjs.size() <= 0)
830            continue;
831        for (auto obj : pCBInfo->memObjs) {
832            log_msg(my_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, 0,
833                    __LINE__, MEMTRACK_NONE, "MEM", "      Mem obj %" PRIu64, (uint64_t)obj);
834        }
835    }
836}
837
838#endif
839
840// Return a string representation of CMD_TYPE enum
841static string cmdTypeToString(CMD_TYPE cmd) {
842    switch (cmd) {
843    case CMD_BINDPIPELINE:
844        return "CMD_BINDPIPELINE";
845    case CMD_BINDPIPELINEDELTA:
846        return "CMD_BINDPIPELINEDELTA";
847    case CMD_SETVIEWPORTSTATE:
848        return "CMD_SETVIEWPORTSTATE";
849    case CMD_SETLINEWIDTHSTATE:
850        return "CMD_SETLINEWIDTHSTATE";
851    case CMD_SETDEPTHBIASSTATE:
852        return "CMD_SETDEPTHBIASSTATE";
853    case CMD_SETBLENDSTATE:
854        return "CMD_SETBLENDSTATE";
855    case CMD_SETDEPTHBOUNDSSTATE:
856        return "CMD_SETDEPTHBOUNDSSTATE";
857    case CMD_SETSTENCILREADMASKSTATE:
858        return "CMD_SETSTENCILREADMASKSTATE";
859    case CMD_SETSTENCILWRITEMASKSTATE:
860        return "CMD_SETSTENCILWRITEMASKSTATE";
861    case CMD_SETSTENCILREFERENCESTATE:
862        return "CMD_SETSTENCILREFERENCESTATE";
863    case CMD_BINDDESCRIPTORSETS:
864        return "CMD_BINDDESCRIPTORSETS";
865    case CMD_BINDINDEXBUFFER:
866        return "CMD_BINDINDEXBUFFER";
867    case CMD_BINDVERTEXBUFFER:
868        return "CMD_BINDVERTEXBUFFER";
869    case CMD_DRAW:
870        return "CMD_DRAW";
871    case CMD_DRAWINDEXED:
872        return "CMD_DRAWINDEXED";
873    case CMD_DRAWINDIRECT:
874        return "CMD_DRAWINDIRECT";
875    case CMD_DRAWINDEXEDINDIRECT:
876        return "CMD_DRAWINDEXEDINDIRECT";
877    case CMD_DISPATCH:
878        return "CMD_DISPATCH";
879    case CMD_DISPATCHINDIRECT:
880        return "CMD_DISPATCHINDIRECT";
881    case CMD_COPYBUFFER:
882        return "CMD_COPYBUFFER";
883    case CMD_COPYIMAGE:
884        return "CMD_COPYIMAGE";
885    case CMD_BLITIMAGE:
886        return "CMD_BLITIMAGE";
887    case CMD_COPYBUFFERTOIMAGE:
888        return "CMD_COPYBUFFERTOIMAGE";
889    case CMD_COPYIMAGETOBUFFER:
890        return "CMD_COPYIMAGETOBUFFER";
891    case CMD_CLONEIMAGEDATA:
892        return "CMD_CLONEIMAGEDATA";
893    case CMD_UPDATEBUFFER:
894        return "CMD_UPDATEBUFFER";
895    case CMD_FILLBUFFER:
896        return "CMD_FILLBUFFER";
897    case CMD_CLEARCOLORIMAGE:
898        return "CMD_CLEARCOLORIMAGE";
899    case CMD_CLEARATTACHMENTS:
900        return "CMD_CLEARCOLORATTACHMENT";
901    case CMD_CLEARDEPTHSTENCILIMAGE:
902        return "CMD_CLEARDEPTHSTENCILIMAGE";
903    case CMD_RESOLVEIMAGE:
904        return "CMD_RESOLVEIMAGE";
905    case CMD_SETEVENT:
906        return "CMD_SETEVENT";
907    case CMD_RESETEVENT:
908        return "CMD_RESETEVENT";
909    case CMD_WAITEVENTS:
910        return "CMD_WAITEVENTS";
911    case CMD_PIPELINEBARRIER:
912        return "CMD_PIPELINEBARRIER";
913    case CMD_BEGINQUERY:
914        return "CMD_BEGINQUERY";
915    case CMD_ENDQUERY:
916        return "CMD_ENDQUERY";
917    case CMD_RESETQUERYPOOL:
918        return "CMD_RESETQUERYPOOL";
919    case CMD_COPYQUERYPOOLRESULTS:
920        return "CMD_COPYQUERYPOOLRESULTS";
921    case CMD_WRITETIMESTAMP:
922        return "CMD_WRITETIMESTAMP";
923    case CMD_INITATOMICCOUNTERS:
924        return "CMD_INITATOMICCOUNTERS";
925    case CMD_LOADATOMICCOUNTERS:
926        return "CMD_LOADATOMICCOUNTERS";
927    case CMD_SAVEATOMICCOUNTERS:
928        return "CMD_SAVEATOMICCOUNTERS";
929    case CMD_BEGINRENDERPASS:
930        return "CMD_BEGINRENDERPASS";
931    case CMD_ENDRENDERPASS:
932        return "CMD_ENDRENDERPASS";
933    default:
934        return "UNKNOWN";
935    }
936}
937
938// SPIRV utility functions
939static void build_def_index(shader_module *module) {
940    for (auto insn : *module) {
941        switch (insn.opcode()) {
942        /* Types */
943        case spv::OpTypeVoid:
944        case spv::OpTypeBool:
945        case spv::OpTypeInt:
946        case spv::OpTypeFloat:
947        case spv::OpTypeVector:
948        case spv::OpTypeMatrix:
949        case spv::OpTypeImage:
950        case spv::OpTypeSampler:
951        case spv::OpTypeSampledImage:
952        case spv::OpTypeArray:
953        case spv::OpTypeRuntimeArray:
954        case spv::OpTypeStruct:
955        case spv::OpTypeOpaque:
956        case spv::OpTypePointer:
957        case spv::OpTypeFunction:
958        case spv::OpTypeEvent:
959        case spv::OpTypeDeviceEvent:
960        case spv::OpTypeReserveId:
961        case spv::OpTypeQueue:
962        case spv::OpTypePipe:
963            module->def_index[insn.word(1)] = insn.offset();
964            break;
965
966        /* Fixed constants */
967        case spv::OpConstantTrue:
968        case spv::OpConstantFalse:
969        case spv::OpConstant:
970        case spv::OpConstantComposite:
971        case spv::OpConstantSampler:
972        case spv::OpConstantNull:
973            module->def_index[insn.word(2)] = insn.offset();
974            break;
975
976        /* Specialization constants */
977        case spv::OpSpecConstantTrue:
978        case spv::OpSpecConstantFalse:
979        case spv::OpSpecConstant:
980        case spv::OpSpecConstantComposite:
981        case spv::OpSpecConstantOp:
982            module->def_index[insn.word(2)] = insn.offset();
983            break;
984
985        /* Variables */
986        case spv::OpVariable:
987            module->def_index[insn.word(2)] = insn.offset();
988            break;
989
990        /* Functions */
991        case spv::OpFunction:
992            module->def_index[insn.word(2)] = insn.offset();
993            break;
994
995        default:
996            /* We don't care about any other defs for now. */
997            break;
998        }
999    }
1000}
1001
1002static spirv_inst_iter find_entrypoint(shader_module *src, char const *name, VkShaderStageFlagBits stageBits) {
1003    for (auto insn : *src) {
1004        if (insn.opcode() == spv::OpEntryPoint) {
1005            auto entrypointName = (char const *)&insn.word(3);
1006            auto entrypointStageBits = 1u << insn.word(1);
1007
1008            if (!strcmp(entrypointName, name) && (entrypointStageBits & stageBits)) {
1009                return insn;
1010            }
1011        }
1012    }
1013
1014    return src->end();
1015}
1016
1017bool shader_is_spirv(VkShaderModuleCreateInfo const *pCreateInfo) {
1018    uint32_t *words = (uint32_t *)pCreateInfo->pCode;
1019    size_t sizeInWords = pCreateInfo->codeSize / sizeof(uint32_t);
1020
1021    /* Just validate that the header makes sense. */
1022    return sizeInWords >= 5 && words[0] == spv::MagicNumber && words[1] == spv::Version;
1023}
1024
1025static char const *storage_class_name(unsigned sc) {
1026    switch (sc) {
1027    case spv::StorageClassInput:
1028        return "input";
1029    case spv::StorageClassOutput:
1030        return "output";
1031    case spv::StorageClassUniformConstant:
1032        return "const uniform";
1033    case spv::StorageClassUniform:
1034        return "uniform";
1035    case spv::StorageClassWorkgroup:
1036        return "workgroup local";
1037    case spv::StorageClassCrossWorkgroup:
1038        return "workgroup global";
1039    case spv::StorageClassPrivate:
1040        return "private global";
1041    case spv::StorageClassFunction:
1042        return "function";
1043    case spv::StorageClassGeneric:
1044        return "generic";
1045    case spv::StorageClassAtomicCounter:
1046        return "atomic counter";
1047    case spv::StorageClassImage:
1048        return "image";
1049    case spv::StorageClassPushConstant:
1050        return "push constant";
1051    default:
1052        return "unknown";
1053    }
1054}
1055
1056/* get the value of an integral constant */
1057unsigned get_constant_value(shader_module const *src, unsigned id) {
1058    auto value = src->get_def(id);
1059    assert(value != src->end());
1060
1061    if (value.opcode() != spv::OpConstant) {
1062        /* TODO: Either ensure that the specialization transform is already performed on a module we're
1063            considering here, OR -- specialize on the fly now.
1064            */
1065        return 1;
1066    }
1067
1068    return value.word(3);
1069}
1070
1071
1072static void describe_type_inner(std::ostringstream &ss, shader_module const *src, unsigned type) {
1073    auto insn = src->get_def(type);
1074    assert(insn != src->end());
1075
1076    switch (insn.opcode()) {
1077    case spv::OpTypeBool:
1078        ss << "bool";
1079        break;
1080    case spv::OpTypeInt:
1081        ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
1082        break;
1083    case spv::OpTypeFloat:
1084        ss << "float" << insn.word(2);
1085        break;
1086    case spv::OpTypeVector:
1087        ss << "vec" << insn.word(3) << " of ";
1088        describe_type_inner(ss, src, insn.word(2));
1089        break;
1090    case spv::OpTypeMatrix:
1091        ss << "mat" << insn.word(3) << " of ";
1092        describe_type_inner(ss, src, insn.word(2));
1093        break;
1094    case spv::OpTypeArray:
1095        ss << "arr[" << get_constant_value(src, insn.word(3)) << "] of ";
1096        describe_type_inner(ss, src, insn.word(2));
1097        break;
1098    case spv::OpTypePointer:
1099        ss << "ptr to " << storage_class_name(insn.word(2)) << " ";
1100        describe_type_inner(ss, src, insn.word(3));
1101        break;
1102    case spv::OpTypeStruct: {
1103        ss << "struct of (";
1104        for (unsigned i = 2; i < insn.len(); i++) {
1105            describe_type_inner(ss, src, insn.word(i));
1106            if (i == insn.len() - 1) {
1107                ss << ")";
1108            } else {
1109                ss << ", ";
1110            }
1111        }
1112        break;
1113    }
1114    case spv::OpTypeSampler:
1115        ss << "sampler";
1116        break;
1117    case spv::OpTypeSampledImage:
1118        ss << "sampler+";
1119        describe_type_inner(ss, src, insn.word(2));
1120        break;
1121    case spv::OpTypeImage:
1122        ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
1123        break;
1124    default:
1125        ss << "oddtype";
1126        break;
1127    }
1128}
1129
1130
1131static std::string describe_type(shader_module const *src, unsigned type) {
1132    std::ostringstream ss;
1133    describe_type_inner(ss, src, type);
1134    return ss.str();
1135}
1136
1137
1138static bool is_narrow_numeric_type(spirv_inst_iter type)
1139{
1140    if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat)
1141        return false;
1142    return type.word(2) < 64;
1143}
1144
1145
1146static bool types_match(shader_module const *a, shader_module const *b, unsigned a_type, unsigned b_type, bool a_arrayed, bool b_arrayed, bool relaxed) {
1147    /* walk two type trees together, and complain about differences */
1148    auto a_insn = a->get_def(a_type);
1149    auto b_insn = b->get_def(b_type);
1150    assert(a_insn != a->end());
1151    assert(b_insn != b->end());
1152
1153    if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
1154        return types_match(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
1155    }
1156
1157    if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
1158        /* we probably just found the extra level of arrayness in b_type: compare the type inside it to a_type */
1159        return types_match(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
1160    }
1161
1162    if (a_insn.opcode() == spv::OpTypeVector && relaxed && is_narrow_numeric_type(b_insn)) {
1163        return types_match(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
1164    }
1165
1166    if (a_insn.opcode() != b_insn.opcode()) {
1167        return false;
1168    }
1169
1170    if (a_insn.opcode() == spv::OpTypePointer) {
1171        /* match on pointee type. storage class is expected to differ */
1172        return types_match(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
1173    }
1174
1175    if (a_arrayed || b_arrayed) {
1176        /* if we havent resolved array-of-verts by here, we're not going to. */
1177        return false;
1178    }
1179
1180    switch (a_insn.opcode()) {
1181    case spv::OpTypeBool:
1182        return true;
1183    case spv::OpTypeInt:
1184        /* match on width, signedness */
1185        return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
1186    case spv::OpTypeFloat:
1187        /* match on width */
1188        return a_insn.word(2) == b_insn.word(2);
1189    case spv::OpTypeVector:
1190        /* match on element type, count. */
1191        if (!types_match(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false))
1192            return false;
1193        if (relaxed && is_narrow_numeric_type(a->get_def(a_insn.word(2)))) {
1194            return a_insn.word(3) >= b_insn.word(3);
1195        }
1196        else {
1197            return a_insn.word(3) == b_insn.word(3);
1198        }
1199    case spv::OpTypeMatrix:
1200        /* match on element type, count. */
1201        return types_match(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) && a_insn.word(3) == b_insn.word(3);
1202    case spv::OpTypeArray:
1203        /* match on element type, count. these all have the same layout. we don't get here if
1204         * b_arrayed. This differs from vector & matrix types in that the array size is the id of a constant instruction,
1205         * not a literal within OpTypeArray */
1206        return types_match(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
1207               get_constant_value(a, a_insn.word(3)) == get_constant_value(b, b_insn.word(3));
1208    case spv::OpTypeStruct:
1209        /* match on all element types */
1210        {
1211            if (a_insn.len() != b_insn.len()) {
1212                return false; /* structs cannot match if member counts differ */
1213            }
1214
1215            for (unsigned i = 2; i < a_insn.len(); i++) {
1216                if (!types_match(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
1217                    return false;
1218                }
1219            }
1220
1221            return true;
1222        }
1223    default:
1224        /* remaining types are CLisms, or may not appear in the interfaces we
1225         * are interested in. Just claim no match.
1226         */
1227        return false;
1228    }
1229}
1230
1231static int value_or_default(std::unordered_map<unsigned, unsigned> const &map, unsigned id, int def) {
1232    auto it = map.find(id);
1233    if (it == map.end())
1234        return def;
1235    else
1236        return it->second;
1237}
1238
1239static unsigned get_locations_consumed_by_type(shader_module const *src, unsigned type, bool strip_array_level) {
1240    auto insn = src->get_def(type);
1241    assert(insn != src->end());
1242
1243    switch (insn.opcode()) {
1244    case spv::OpTypePointer:
1245        /* see through the ptr -- this is only ever at the toplevel for graphics shaders;
1246         * we're never actually passing pointers around. */
1247        return get_locations_consumed_by_type(src, insn.word(3), strip_array_level);
1248    case spv::OpTypeArray:
1249        if (strip_array_level) {
1250            return get_locations_consumed_by_type(src, insn.word(2), false);
1251        } else {
1252            return get_constant_value(src, insn.word(3)) * get_locations_consumed_by_type(src, insn.word(2), false);
1253        }
1254    case spv::OpTypeMatrix:
1255        /* num locations is the dimension * element size */
1256        return insn.word(3) * get_locations_consumed_by_type(src, insn.word(2), false);
1257    default:
1258        /* everything else is just 1. */
1259        return 1;
1260
1261        /* TODO: extend to handle 64bit scalar types, whose vectors may need
1262         * multiple locations. */
1263    }
1264}
1265
1266typedef std::pair<unsigned, unsigned> location_t;
1267typedef std::pair<unsigned, unsigned> descriptor_slot_t;
1268
1269struct interface_var {
1270    uint32_t id;
1271    uint32_t type_id;
1272    uint32_t offset;
1273    bool is_patch;
1274    /* TODO: collect the name, too? Isn't required to be present. */
1275};
1276
1277struct shader_stage_attributes {
1278    char const *const name;
1279    bool arrayed_input;
1280    bool arrayed_output;
1281};
1282
1283static shader_stage_attributes shader_stage_attribs[] = {
1284    {"vertex shader", false, false},
1285    {"tessellation control shader", true, true},
1286    {"tessellation evaluation shader", true, false},
1287    {"geometry shader", true, false},
1288    {"fragment shader", false, false},
1289};
1290
1291static spirv_inst_iter get_struct_type(shader_module const *src, spirv_inst_iter def, bool is_array_of_verts) {
1292    while (true) {
1293
1294        if (def.opcode() == spv::OpTypePointer) {
1295            def = src->get_def(def.word(3));
1296        } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
1297            def = src->get_def(def.word(2));
1298            is_array_of_verts = false;
1299        } else if (def.opcode() == spv::OpTypeStruct) {
1300            return def;
1301        } else {
1302            return src->end();
1303        }
1304    }
1305}
1306
1307static void collect_interface_block_members(layer_data *my_data, shader_module const *src,
1308                                            std::map<location_t, interface_var> &out,
1309                                            std::unordered_map<unsigned, unsigned> const &blocks, bool is_array_of_verts,
1310                                            uint32_t id, uint32_t type_id, bool is_patch) {
1311    /* Walk down the type_id presented, trying to determine whether it's actually an interface block. */
1312    auto type = get_struct_type(src, src->get_def(type_id), is_array_of_verts && !is_patch);
1313    if (type == src->end() || blocks.find(type.word(1)) == blocks.end()) {
1314        /* this isn't an interface block. */
1315        return;
1316    }
1317
1318    std::unordered_map<unsigned, unsigned> member_components;
1319
1320    /* Walk all the OpMemberDecorate for type's result id -- first pass, collect components. */
1321    for (auto insn : *src) {
1322        if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
1323            unsigned member_index = insn.word(2);
1324
1325            if (insn.word(3) == spv::DecorationComponent) {
1326                unsigned component = insn.word(4);
1327                member_components[member_index] = component;
1328            }
1329        }
1330    }
1331
1332    /* Second pass -- produce the output, from Location decorations */
1333    for (auto insn : *src) {
1334        if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
1335            unsigned member_index = insn.word(2);
1336            unsigned member_type_id = type.word(2 + member_index);
1337
1338            if (insn.word(3) == spv::DecorationLocation) {
1339                unsigned location = insn.word(4);
1340                unsigned num_locations = get_locations_consumed_by_type(src, member_type_id, false);
1341                auto component_it = member_components.find(member_index);
1342                unsigned component = component_it == member_components.end() ? 0 : component_it->second;
1343
1344                for (unsigned int offset = 0; offset < num_locations; offset++) {
1345                    interface_var v;
1346                    v.id = id;
1347                    /* TODO: member index in interface_var too? */
1348                    v.type_id = member_type_id;
1349                    v.offset = offset;
1350                    v.is_patch = is_patch;
1351                    out[std::make_pair(location + offset, component)] = v;
1352                }
1353            }
1354        }
1355    }
1356}
1357
1358static void collect_interface_by_location(layer_data *my_data, shader_module const *src, spirv_inst_iter entrypoint,
1359                                          spv::StorageClass sinterface, std::map<location_t, interface_var> &out,
1360                                          bool is_array_of_verts) {
1361    std::unordered_map<unsigned, unsigned> var_locations;
1362    std::unordered_map<unsigned, unsigned> var_builtins;
1363    std::unordered_map<unsigned, unsigned> var_components;
1364    std::unordered_map<unsigned, unsigned> blocks;
1365    std::unordered_map<unsigned, unsigned> var_patch;
1366
1367    for (auto insn : *src) {
1368
1369        /* We consider two interface models: SSO rendezvous-by-location, and
1370         * builtins. Complain about anything that fits neither model.
1371         */
1372        if (insn.opcode() == spv::OpDecorate) {
1373            if (insn.word(2) == spv::DecorationLocation) {
1374                var_locations[insn.word(1)] = insn.word(3);
1375            }
1376
1377            if (insn.word(2) == spv::DecorationBuiltIn) {
1378                var_builtins[insn.word(1)] = insn.word(3);
1379            }
1380
1381            if (insn.word(2) == spv::DecorationComponent) {
1382                var_components[insn.word(1)] = insn.word(3);
1383            }
1384
1385            if (insn.word(2) == spv::DecorationBlock) {
1386                blocks[insn.word(1)] = 1;
1387            }
1388
1389            if (insn.word(2) == spv::DecorationPatch) {
1390                var_patch[insn.word(1)] = 1;
1391            }
1392        }
1393    }
1394
1395    /* TODO: handle grouped decorations */
1396    /* TODO: handle index=1 dual source outputs from FS -- two vars will
1397     * have the same location, and we DON'T want to clobber. */
1398
1399    /* find the end of the entrypoint's name string. additional zero bytes follow the actual null
1400       terminator, to fill out the rest of the word - so we only need to look at the last byte in
1401       the word to determine which word contains the terminator. */
1402    uint32_t word = 3;
1403    while (entrypoint.word(word) & 0xff000000u) {
1404        ++word;
1405    }
1406    ++word;
1407
1408    for (; word < entrypoint.len(); word++) {
1409        auto insn = src->get_def(entrypoint.word(word));
1410        assert(insn != src->end());
1411        assert(insn.opcode() == spv::OpVariable);
1412
1413        if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
1414            unsigned id = insn.word(2);
1415            unsigned type = insn.word(1);
1416
1417            int location = value_or_default(var_locations, id, -1);
1418            int builtin = value_or_default(var_builtins, id, -1);
1419            unsigned component = value_or_default(var_components, id, 0); /* unspecified is OK, is 0 */
1420            bool is_patch = var_patch.find(id) != var_patch.end();
1421
1422            /* All variables and interface block members in the Input or Output storage classes
1423             * must be decorated with either a builtin or an explicit location.
1424             *
1425             * TODO: integrate the interface block support here. For now, don't complain --
1426             * a valid SPIRV module will only hit this path for the interface block case, as the
1427             * individual members of the type are decorated, rather than variable declarations.
1428             */
1429
1430            if (location != -1) {
1431                /* A user-defined interface variable, with a location. Where a variable
1432                 * occupied multiple locations, emit one result for each. */
1433                unsigned num_locations = get_locations_consumed_by_type(src, type, is_array_of_verts && !is_patch);
1434                for (unsigned int offset = 0; offset < num_locations; offset++) {
1435                    interface_var v;
1436                    v.id = id;
1437                    v.type_id = type;
1438                    v.offset = offset;
1439                    v.is_patch = is_patch;
1440                    out[std::make_pair(location + offset, component)] = v;
1441                }
1442            } else if (builtin == -1) {
1443                /* An interface block instance */
1444                collect_interface_block_members(my_data, src, out, blocks, is_array_of_verts, id, type, is_patch);
1445            }
1446        }
1447    }
1448}
1449
1450static void collect_interface_by_descriptor_slot(layer_data *my_data, shader_module const *src,
1451                                                 std::unordered_set<uint32_t> const &accessible_ids,
1452                                                 std::map<descriptor_slot_t, interface_var> &out) {
1453
1454    std::unordered_map<unsigned, unsigned> var_sets;
1455    std::unordered_map<unsigned, unsigned> var_bindings;
1456
1457    for (auto insn : *src) {
1458        /* All variables in the Uniform or UniformConstant storage classes are required to be decorated with both
1459         * DecorationDescriptorSet and DecorationBinding.
1460         */
1461        if (insn.opcode() == spv::OpDecorate) {
1462            if (insn.word(2) == spv::DecorationDescriptorSet) {
1463                var_sets[insn.word(1)] = insn.word(3);
1464            }
1465
1466            if (insn.word(2) == spv::DecorationBinding) {
1467                var_bindings[insn.word(1)] = insn.word(3);
1468            }
1469        }
1470    }
1471
1472    for (auto id : accessible_ids) {
1473        auto insn = src->get_def(id);
1474        assert(insn != src->end());
1475
1476        if (insn.opcode() == spv::OpVariable &&
1477            (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant)) {
1478            unsigned set = value_or_default(var_sets, insn.word(2), 0);
1479            unsigned binding = value_or_default(var_bindings, insn.word(2), 0);
1480
1481            auto existing_it = out.find(std::make_pair(set, binding));
1482            if (existing_it != out.end()) {
1483                /* conflict within spv image */
1484                log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VkDebugReportObjectTypeEXT(0), 0,
1485                        __LINE__, SHADER_CHECKER_INCONSISTENT_SPIRV, "SC",
1486                        "var %d (type %d) in %s interface in descriptor slot (%u,%u) conflicts with existing definition",
1487                        insn.word(2), insn.word(1), storage_class_name(insn.word(3)), existing_it->first.first,
1488                        existing_it->first.second);
1489            }
1490
1491            interface_var v;
1492            v.id = insn.word(2);
1493            v.type_id = insn.word(1);
1494            v.offset = 0;
1495            v.is_patch = false;
1496            out[std::make_pair(set, binding)] = v;
1497        }
1498    }
1499}
1500
1501static bool validate_interface_between_stages(layer_data *my_data, shader_module const *producer,
1502                                              spirv_inst_iter producer_entrypoint, shader_stage_attributes const *producer_stage,
1503                                              shader_module const *consumer, spirv_inst_iter consumer_entrypoint,
1504                                              shader_stage_attributes const *consumer_stage) {
1505    std::map<location_t, interface_var> outputs;
1506    std::map<location_t, interface_var> inputs;
1507
1508    bool pass = true;
1509
1510    collect_interface_by_location(my_data, producer, producer_entrypoint, spv::StorageClassOutput, outputs, producer_stage->arrayed_output);
1511    collect_interface_by_location(my_data, consumer, consumer_entrypoint, spv::StorageClassInput, inputs, consumer_stage->arrayed_input);
1512
1513    auto a_it = outputs.begin();
1514    auto b_it = inputs.begin();
1515
1516    /* maps sorted by key (location); walk them together to find mismatches */
1517    while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
1518        bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
1519        bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
1520        auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
1521        auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
1522
1523        if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
1524            if (log_msg(my_data->report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VkDebugReportObjectTypeEXT(0), 0,
1525                        __LINE__, SHADER_CHECKER_OUTPUT_NOT_CONSUMED, "SC",
1526                        "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name, a_first.first,
1527                        a_first.second, consumer_stage->name)) {
1528                pass = false;
1529            }
1530            a_it++;
1531        } else if (a_at_end || a_first > b_first) {
1532            if (log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VkDebugReportObjectTypeEXT(0), 0,
1533                        __LINE__, SHADER_CHECKER_INPUT_NOT_PRODUCED, "SC",
1534                        "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first, b_first.second,
1535                        producer_stage->name)) {
1536                pass = false;
1537            }
1538            b_it++;
1539        } else {
1540            if (!types_match(producer, consumer, a_it->second.type_id, b_it->second.type_id,
1541                             producer_stage->arrayed_output && !a_it->second.is_patch,
1542                             consumer_stage->arrayed_input && !b_it->second.is_patch,
1543                             true)) {
1544                if (log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VkDebugReportObjectTypeEXT(0), 0,
1545                            __LINE__, SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC", "Type mismatch on location %u.%u: '%s' vs '%s'",
1546                            a_first.first, a_first.second,
1547                            describe_type(producer, a_it->second.type_id).c_str(),
1548                            describe_type(consumer, b_it->second.type_id).c_str())) {
1549                    pass = false;
1550                }
1551            }
1552            if (a_it->second.is_patch != b_it->second.is_patch) {
1553                if (log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, /*dev*/ 0,
1554                            __LINE__, SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC",
1555                            "Decoration mismatch on location %u.%u: is per-%s in %s stage but "
1556                            "per-%s in %s stage", a_first.first, a_first.second,
1557                            a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
1558                            b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name)) {
1559                    pass = false;
1560                }
1561            }
1562            a_it++;
1563            b_it++;
1564        }
1565    }
1566
1567    return pass;
1568}
1569
1570enum FORMAT_TYPE {
1571    FORMAT_TYPE_UNDEFINED,
1572    FORMAT_TYPE_FLOAT, /* UNORM, SNORM, FLOAT, USCALED, SSCALED, SRGB -- anything we consider float in the shader */
1573    FORMAT_TYPE_SINT,
1574    FORMAT_TYPE_UINT,
1575};
1576
1577static unsigned get_format_type(VkFormat fmt) {
1578    switch (fmt) {
1579    case VK_FORMAT_UNDEFINED:
1580        return FORMAT_TYPE_UNDEFINED;
1581    case VK_FORMAT_R8_SINT:
1582    case VK_FORMAT_R8G8_SINT:
1583    case VK_FORMAT_R8G8B8_SINT:
1584    case VK_FORMAT_R8G8B8A8_SINT:
1585    case VK_FORMAT_R16_SINT:
1586    case VK_FORMAT_R16G16_SINT:
1587    case VK_FORMAT_R16G16B16_SINT:
1588    case VK_FORMAT_R16G16B16A16_SINT:
1589    case VK_FORMAT_R32_SINT:
1590    case VK_FORMAT_R32G32_SINT:
1591    case VK_FORMAT_R32G32B32_SINT:
1592    case VK_FORMAT_R32G32B32A32_SINT:
1593    case VK_FORMAT_B8G8R8_SINT:
1594    case VK_FORMAT_B8G8R8A8_SINT:
1595    case VK_FORMAT_A2B10G10R10_SINT_PACK32:
1596    case VK_FORMAT_A2R10G10B10_SINT_PACK32:
1597        return FORMAT_TYPE_SINT;
1598    case VK_FORMAT_R8_UINT:
1599    case VK_FORMAT_R8G8_UINT:
1600    case VK_FORMAT_R8G8B8_UINT:
1601    case VK_FORMAT_R8G8B8A8_UINT:
1602    case VK_FORMAT_R16_UINT:
1603    case VK_FORMAT_R16G16_UINT:
1604    case VK_FORMAT_R16G16B16_UINT:
1605    case VK_FORMAT_R16G16B16A16_UINT:
1606    case VK_FORMAT_R32_UINT:
1607    case VK_FORMAT_R32G32_UINT:
1608    case VK_FORMAT_R32G32B32_UINT:
1609    case VK_FORMAT_R32G32B32A32_UINT:
1610    case VK_FORMAT_B8G8R8_UINT:
1611    case VK_FORMAT_B8G8R8A8_UINT:
1612    case VK_FORMAT_A2B10G10R10_UINT_PACK32:
1613    case VK_FORMAT_A2R10G10B10_UINT_PACK32:
1614        return FORMAT_TYPE_UINT;
1615    default:
1616        return FORMAT_TYPE_FLOAT;
1617    }
1618}
1619
1620/* characterizes a SPIR-V type appearing in an interface to a FF stage,
1621 * for comparison to a VkFormat's characterization above. */
1622static unsigned get_fundamental_type(shader_module const *src, unsigned type) {
1623    auto insn = src->get_def(type);
1624    assert(insn != src->end());
1625
1626    switch (insn.opcode()) {
1627    case spv::OpTypeInt:
1628        return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
1629    case spv::OpTypeFloat:
1630        return FORMAT_TYPE_FLOAT;
1631    case spv::OpTypeVector:
1632        return get_fundamental_type(src, insn.word(2));
1633    case spv::OpTypeMatrix:
1634        return get_fundamental_type(src, insn.word(2));
1635    case spv::OpTypeArray:
1636        return get_fundamental_type(src, insn.word(2));
1637    case spv::OpTypePointer:
1638        return get_fundamental_type(src, insn.word(3));
1639    default:
1640        return FORMAT_TYPE_UNDEFINED;
1641    }
1642}
1643
1644static uint32_t get_shader_stage_id(VkShaderStageFlagBits stage) {
1645    uint32_t bit_pos = u_ffs(stage);
1646    return bit_pos - 1;
1647}
1648
1649static bool validate_vi_consistency(layer_data *my_data, VkPipelineVertexInputStateCreateInfo const *vi) {
1650    /* walk the binding descriptions, which describe the step rate and stride of each vertex buffer.
1651     * each binding should be specified only once.
1652     */
1653    std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
1654    bool pass = true;
1655
1656    for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
1657        auto desc = &vi->pVertexBindingDescriptions[i];
1658        auto &binding = bindings[desc->binding];
1659        if (binding) {
1660            if (log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VkDebugReportObjectTypeEXT(0), 0,
1661                        __LINE__, SHADER_CHECKER_INCONSISTENT_VI, "SC",
1662                        "Duplicate vertex input binding descriptions for binding %d", desc->binding)) {
1663                pass = false;
1664            }
1665        } else {
1666            binding = desc;
1667        }
1668    }
1669
1670    return pass;
1671}
1672
1673static bool validate_vi_against_vs_inputs(layer_data *my_data, VkPipelineVertexInputStateCreateInfo const *vi,
1674                                          shader_module const *vs, spirv_inst_iter entrypoint) {
1675    std::map<location_t, interface_var> inputs;
1676    bool pass = true;
1677
1678    collect_interface_by_location(my_data, vs, entrypoint, spv::StorageClassInput, inputs, false);
1679
1680    /* Build index by location */
1681    std::map<uint32_t, VkVertexInputAttributeDescription const *> attribs;
1682    if (vi) {
1683        for (unsigned i = 0; i < vi->vertexAttributeDescriptionCount; i++)
1684            attribs[vi->pVertexAttributeDescriptions[i].location] = &vi->pVertexAttributeDescriptions[i];
1685    }
1686
1687    auto it_a = attribs.begin();
1688    auto it_b = inputs.begin();
1689
1690    while ((attribs.size() > 0 && it_a != attribs.end()) || (inputs.size() > 0 && it_b != inputs.end())) {
1691        bool a_at_end = attribs.size() == 0 || it_a == attribs.end();
1692        bool b_at_end = inputs.size() == 0 || it_b == inputs.end();
1693        auto a_first = a_at_end ? 0 : it_a->first;
1694        auto b_first = b_at_end ? 0 : it_b->first.first;
1695        if (!a_at_end && (b_at_end || a_first < b_first)) {
1696            if (log_msg(my_data->report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VkDebugReportObjectTypeEXT(0), 0,
1697                        __LINE__, SHADER_CHECKER_OUTPUT_NOT_CONSUMED, "SC",
1698                        "Vertex attribute at location %d not consumed by VS", a_first)) {
1699                pass = false;
1700            }
1701            it_a++;
1702        } else if (!b_at_end && (a_at_end || b_first < a_first)) {
1703            if (log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, /*dev*/ 0,
1704                        __LINE__, SHADER_CHECKER_INPUT_NOT_PRODUCED, "SC", "VS consumes input at location %d but not provided",
1705                        b_first)) {
1706                pass = false;
1707            }
1708            it_b++;
1709        } else {
1710            unsigned attrib_type = get_format_type(it_a->second->format);
1711            unsigned input_type = get_fundamental_type(vs, it_b->second.type_id);
1712
1713            /* type checking */
1714            if (attrib_type != FORMAT_TYPE_UNDEFINED && input_type != FORMAT_TYPE_UNDEFINED && attrib_type != input_type) {
1715                if (log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VkDebugReportObjectTypeEXT(0), 0,
1716                            __LINE__, SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC",
1717                            "Attribute type of `%s` at location %d does not match VS input type of `%s`",
1718                            string_VkFormat(it_a->second->format), a_first,
1719                            describe_type(vs, it_b->second.type_id).c_str())) {
1720                    pass = false;
1721                }
1722            }
1723
1724            /* OK! */
1725            it_a++;
1726            it_b++;
1727        }
1728    }
1729
1730    return pass;
1731}
1732
1733static bool validate_fs_outputs_against_render_pass(layer_data *my_data, shader_module const *fs,
1734                                                    spirv_inst_iter entrypoint, RENDER_PASS_NODE const *rp, uint32_t subpass) {
1735    const std::vector<VkFormat> &color_formats = rp->subpassColorFormats[subpass];
1736    std::map<location_t, interface_var> outputs;
1737    bool pass = true;
1738
1739    /* TODO: dual source blend index (spv::DecIndex, zero if not provided) */
1740
1741    collect_interface_by_location(my_data, fs, entrypoint, spv::StorageClassOutput, outputs, false);
1742
1743    auto it = outputs.begin();
1744    uint32_t attachment = 0;
1745
1746    /* Walk attachment list and outputs together -- this is a little overpowered since attachments
1747     * are currently dense, but the parallel with matching between shader stages is nice.
1748     */
1749
1750    while ((outputs.size() > 0 && it != outputs.end()) || attachment < color_formats.size()) {
1751        if (attachment == color_formats.size() || (it != outputs.end() && it->first.first < attachment)) {
1752            if (log_msg(my_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VkDebugReportObjectTypeEXT(0), 0,
1753                        __LINE__, SHADER_CHECKER_OUTPUT_NOT_CONSUMED, "SC",
1754                        "FS writes to output location %d with no matching attachment", it->first.first)) {
1755                pass = false;
1756            }
1757            it++;
1758        } else if (it == outputs.end() || it->first.first > attachment) {
1759            if (log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VkDebugReportObjectTypeEXT(0), 0,
1760                        __LINE__, SHADER_CHECKER_INPUT_NOT_PRODUCED, "SC", "Attachment %d not written by FS", attachment)) {
1761                pass = false;
1762            }
1763            attachment++;
1764        } else {
1765            unsigned output_type = get_fundamental_type(fs, it->second.type_id);
1766            unsigned att_type = get_format_type(color_formats[attachment]);
1767
1768            /* type checking */
1769            if (att_type != FORMAT_TYPE_UNDEFINED && output_type != FORMAT_TYPE_UNDEFINED && att_type != output_type) {
1770                if (log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VkDebugReportObjectTypeEXT(0), 0,
1771                            __LINE__, SHADER_CHECKER_INTERFACE_TYPE_MISMATCH, "SC",
1772                            "Attachment %d of type `%s` does not match FS output type of `%s`", attachment,
1773                            string_VkFormat(color_formats[attachment]),
1774                            describe_type(fs, it->second.type_id).c_str())) {
1775                    pass = false;
1776                }
1777            }
1778
1779            /* OK! */
1780            it++;
1781            attachment++;
1782        }
1783    }
1784
1785    return pass;
1786}
1787
1788/* For some analyses, we need to know about all ids referenced by the static call tree of a particular
1789 * entrypoint. This is important for identifying the set of shader resources actually used by an entrypoint,
1790 * for example.
1791 * Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1792 *  - NOT the shader input/output interfaces.
1793 *
1794 * TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1795 * converting parts of this to be generated from the machine-readable spec instead.
1796 */
1797static void mark_accessible_ids(shader_module const *src, spirv_inst_iter entrypoint, std::unordered_set<uint32_t> &ids) {
1798    std::unordered_set<uint32_t> worklist;
1799    worklist.insert(entrypoint.word(2));
1800
1801    while (!worklist.empty()) {
1802        auto id_iter = worklist.begin();
1803        auto id = *id_iter;
1804        worklist.erase(id_iter);
1805
1806        auto insn = src->get_def(id);
1807        if (insn == src->end()) {
1808            /* id is something we didn't collect in build_def_index. that's OK -- we'll stumble
1809             * across all kinds of things here that we may not care about. */
1810            continue;
1811        }
1812
1813        /* try to add to the output set */
1814        if (!ids.insert(id).second) {
1815            continue; /* if we already saw this id, we don't want to walk it again. */
1816        }
1817
1818        switch (insn.opcode()) {
1819        case spv::OpFunction:
1820            /* scan whole body of the function, enlisting anything interesting */
1821            while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1822                switch (insn.opcode()) {
1823                case spv::OpLoad:
1824                case spv::OpAtomicLoad:
1825                case spv::OpAtomicExchange:
1826                case spv::OpAtomicCompareExchange:
1827                case spv::OpAtomicCompareExchangeWeak:
1828                case spv::OpAtomicIIncrement:
1829                case spv::OpAtomicIDecrement:
1830                case spv::OpAtomicIAdd:
1831                case spv::OpAtomicISub:
1832                case spv::OpAtomicSMin:
1833                case spv::OpAtomicUMin:
1834                case spv::OpAtomicSMax:
1835                case spv::OpAtomicUMax:
1836                case spv::OpAtomicAnd:
1837                case spv::OpAtomicOr:
1838                case spv::OpAtomicXor:
1839                    worklist.insert(insn.word(3)); /* ptr */
1840                    break;
1841                case spv::OpStore:
1842                case spv::OpAtomicStore:
1843                    worklist.insert(insn.word(1)); /* ptr */
1844                    break;
1845                case spv::OpAccessChain:
1846                case spv::OpInBoundsAccessChain:
1847                    worklist.insert(insn.word(3)); /* base ptr */
1848                    break;
1849                case spv::OpSampledImage:
1850                case spv::OpImageSampleImplicitLod:
1851                case spv::OpImageSampleExplicitLod:
1852                case spv::OpImageSampleDrefImplicitLod:
1853                case spv::OpImageSampleDrefExplicitLod:
1854                case spv::OpImageSampleProjImplicitLod:
1855                case spv::OpImageSampleProjExplicitLod:
1856                case spv::OpImageSampleProjDrefImplicitLod:
1857                case spv::OpImageSampleProjDrefExplicitLod:
1858                case spv::OpImageFetch:
1859                case spv::OpImageGather:
1860                case spv::OpImageDrefGather:
1861                case spv::OpImageRead:
1862                case spv::OpImage:
1863                case spv::OpImageQueryFormat:
1864                case spv::OpImageQueryOrder:
1865                case spv::OpImageQuerySizeLod:
1866                case spv::OpImageQuerySize:
1867                case spv::OpImageQueryLod:
1868                case spv::OpImageQueryLevels:
1869                case spv::OpImageQuerySamples:
1870                case spv::OpImageSparseSampleImplicitLod:
1871                case spv::OpImageSparseSampleExplicitLod:
1872                case spv::OpImageSparseSampleDrefImplicitLod:
1873                case spv::OpImageSparseSampleDrefExplicitLod:
1874                case spv::OpImageSparseSampleProjImplicitLod:
1875                case spv::OpImageSparseSampleProjExplicitLod:
1876                case spv::OpImageSparseSampleProjDrefImplicitLod:
1877                case spv::OpImageSparseSampleProjDrefExplicitLod:
1878                case spv::OpImageSparseFetch:
1879                case spv::OpImageSparseGather:
1880                case spv::OpImageSparseDrefGather:
1881                case spv::OpImageTexelPointer:
1882                    worklist.insert(insn.word(3)); /* image or sampled image */
1883                    break;
1884                case spv::OpImageWrite:
1885                    worklist.insert(insn.word(1)); /* image -- different operand order to above */
1886                    break;
1887                case spv::OpFunctionCall:
1888                    for (uint32_t i = 3; i < insn.len(); i++) {
1889                        worklist.insert(insn.word(i)); /* fn itself, and all args */
1890                    }
1891                    break;
1892
1893                case spv::OpExtInst:
1894                    for (uint32_t i = 5; i < insn.len(); i++) {
1895                        worklist.insert(insn.word(i)); /* operands to ext inst */
1896                    }
1897                    break;
1898                }
1899            }
1900            break;
1901        }
1902    }
1903}
1904
1905static bool validate_push_constant_block_against_pipeline(layer_data *my_data,
1906                                                          std::vector<VkPushConstantRange> const *pushConstantRanges,
1907                                                          shader_module const *src, spirv_inst_iter type,
1908                                                          VkShaderStageFlagBits stage) {
1909    bool pass = true;
1910
1911    /* strip off ptrs etc */
1912    type = get_struct_type(src, type, false);
1913    assert(type != src->end());
1914
1915    /* validate directly off the offsets. this isn't quite correct for arrays
1916     * and matrices, but is a good first step. TODO: arrays, matrices, weird
1917     * sizes */
1918    for (auto insn : *src) {
1919        if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
1920
1921            if (insn.word(3) == spv::DecorationOffset) {
1922                unsigned offset = insn.word(4);
1923                auto size = 4; /* bytes; TODO: calculate this based on the type */
1924
1925                bool found_range = false;
1926                for (auto const &range : *pushConstantRanges) {
1927                    if (range.offset <= offset && range.offset + range.size >= offset + size) {
1928                        found_range = true;
1929
1930                        if ((range.stageFlags & stage) == 0) {
1931                            if (log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VkDebugReportObjectTypeEXT(0), 0,
1932                                        __LINE__, SHADER_CHECKER_PUSH_CONSTANT_NOT_ACCESSIBLE_FROM_STAGE, "SC",
1933                                        "Push constant range covering variable starting at "
1934                                        "offset %u not accessible from stage %s",
1935                                        offset, string_VkShaderStageFlagBits(stage))) {
1936                                pass = false;
1937                            }
1938                        }
1939
1940                        break;
1941                    }
1942                }
1943
1944                if (!found_range) {
1945                    if (log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VkDebugReportObjectTypeEXT(0), 0,
1946                                __LINE__, SHADER_CHECKER_PUSH_CONSTANT_OUT_OF_RANGE, "SC",
1947                                "Push constant range covering variable starting at "
1948                                "offset %u not declared in layout",
1949                                offset)) {
1950                        pass = false;
1951                    }
1952                }
1953            }
1954        }
1955    }
1956
1957    return pass;
1958}
1959
1960static bool validate_push_constant_usage(layer_data *my_data,
1961                                         std::vector<VkPushConstantRange> const *pushConstantRanges, shader_module const *src,
1962                                         std::unordered_set<uint32_t> accessible_ids, VkShaderStageFlagBits stage) {
1963    bool pass = true;
1964
1965    for (auto id : accessible_ids) {
1966        auto def_insn = src->get_def(id);
1967        if (def_insn.opcode() == spv::OpVariable && def_insn.word(3) == spv::StorageClassPushConstant) {
1968            pass &= validate_push_constant_block_against_pipeline(my_data, pushConstantRanges, src,
1969                                                                 src->get_def(def_insn.word(1)), stage);
1970        }
1971    }
1972
1973    return pass;
1974}
1975
1976// For given pipelineLayout verify that the setLayout at slot.first
1977//  has the requested binding at slot.second
1978static VkDescriptorSetLayoutBinding const * get_descriptor_binding(layer_data *my_data, PIPELINE_LAYOUT_NODE *pipelineLayout, descriptor_slot_t slot) {
1979
1980    if (!pipelineLayout)
1981        return nullptr;
1982
1983    if (slot.first >= pipelineLayout->descriptorSetLayouts.size())
1984        return nullptr;
1985
1986    auto const layout_node = my_data->descriptorSetLayoutMap[pipelineLayout->descriptorSetLayouts[slot.first]];
1987
1988    auto bindingIt = layout_node->bindingToIndexMap.find(slot.second);
1989    if ((bindingIt == layout_node->bindingToIndexMap.end()) || (layout_node->createInfo.pBindings == NULL))
1990        return nullptr;
1991
1992    assert(bindingIt->second < layout_node->createInfo.bindingCount);
1993    return &layout_node->createInfo.pBindings[bindingIt->second];
1994}
1995
1996// Block of code at start here for managing/tracking Pipeline state that this layer cares about
1997
1998static uint64_t g_drawCount[NUM_DRAW_TYPES] = {0, 0, 0, 0};
1999
2000// TODO : Should be tracking lastBound per commandBuffer and when draws occur, report based on that cmd buffer lastBound
2001//   Then need to synchronize the accesses based on cmd buffer so that if I'm reading state on one cmd buffer, updates
2002//   to that same cmd buffer by separate thread are not changing state from underneath us
2003// Track the last cmd buffer touched by this thread
2004
2005static bool hasDrawCmd(GLOBAL_CB_NODE *pCB) {
2006    for (uint32_t i = 0; i < NUM_DRAW_TYPES; i++) {
2007        if (pCB->drawCount[i])
2008            return true;
2009    }
2010    return false;
2011}
2012
2013// Check object status for selected flag state
2014static bool validate_status(layer_data *my_data, GLOBAL_CB_NODE *pNode, CBStatusFlags status_mask, VkFlags msg_flags,
2015                            DRAW_STATE_ERROR error_code, const char *fail_msg) {
2016    if (!(pNode->status & status_mask)) {
2017        return log_msg(my_data->report_data, msg_flags, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2018                       reinterpret_cast<const uint64_t &>(pNode->commandBuffer), __LINE__, error_code, "DS",
2019                       "CB object %#" PRIxLEAST64 ": %s", reinterpret_cast<const uint64_t &>(pNode->commandBuffer), fail_msg);
2020    }
2021    return false;
2022}
2023
2024// Retrieve pipeline node ptr for given pipeline object
2025static PIPELINE_NODE *getPipeline(layer_data *my_data, const VkPipeline pipeline) {
2026    if (my_data->pipelineMap.find(pipeline) == my_data->pipelineMap.end()) {
2027        return NULL;
2028    }
2029    return my_data->pipelineMap[pipeline];
2030}
2031
2032// Return true if for a given PSO, the given state enum is dynamic, else return false
2033static bool isDynamic(const PIPELINE_NODE *pPipeline, const VkDynamicState state) {
2034    if (pPipeline && pPipeline->graphicsPipelineCI.pDynamicState) {
2035        for (uint32_t i = 0; i < pPipeline->graphicsPipelineCI.pDynamicState->dynamicStateCount; i++) {
2036            if (state == pPipeline->graphicsPipelineCI.pDynamicState->pDynamicStates[i])
2037                return true;
2038        }
2039    }
2040    return false;
2041}
2042
2043// Validate state stored as flags at time of draw call
2044static bool validate_draw_state_flags(layer_data *dev_data, GLOBAL_CB_NODE *pCB, const PIPELINE_NODE *pPipe, bool indexedDraw) {
2045    bool result;
2046    result = validate_status(dev_data, pCB, CBSTATUS_VIEWPORT_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT, DRAWSTATE_VIEWPORT_NOT_BOUND,
2047                             "Dynamic viewport state not set for this command buffer");
2048    result |= validate_status(dev_data, pCB, CBSTATUS_SCISSOR_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT, DRAWSTATE_SCISSOR_NOT_BOUND,
2049                              "Dynamic scissor state not set for this command buffer");
2050    if (pPipe->graphicsPipelineCI.pInputAssemblyState &&
2051        ((pPipe->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST) ||
2052         (pPipe->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP))) {
2053        result |= validate_status(dev_data, pCB, CBSTATUS_LINE_WIDTH_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT,
2054                                  DRAWSTATE_LINE_WIDTH_NOT_BOUND, "Dynamic line width state not set for this command buffer");
2055    }
2056    if (pPipe->graphicsPipelineCI.pRasterizationState &&
2057        (pPipe->graphicsPipelineCI.pRasterizationState->depthBiasEnable == VK_TRUE)) {
2058        result |= validate_status(dev_data, pCB, CBSTATUS_DEPTH_BIAS_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT,
2059                                  DRAWSTATE_DEPTH_BIAS_NOT_BOUND, "Dynamic depth bias state not set for this command buffer");
2060    }
2061    if (pPipe->blendConstantsEnabled) {
2062        result |= validate_status(dev_data, pCB, CBSTATUS_BLEND_CONSTANTS_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT,
2063                                  DRAWSTATE_BLEND_NOT_BOUND, "Dynamic blend constants state not set for this command buffer");
2064    }
2065    if (pPipe->graphicsPipelineCI.pDepthStencilState &&
2066        (pPipe->graphicsPipelineCI.pDepthStencilState->depthBoundsTestEnable == VK_TRUE)) {
2067        result |= validate_status(dev_data, pCB, CBSTATUS_DEPTH_BOUNDS_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT,
2068                                  DRAWSTATE_DEPTH_BOUNDS_NOT_BOUND, "Dynamic depth bounds state not set for this command buffer");
2069    }
2070    if (pPipe->graphicsPipelineCI.pDepthStencilState &&
2071        (pPipe->graphicsPipelineCI.pDepthStencilState->stencilTestEnable == VK_TRUE)) {
2072        result |= validate_status(dev_data, pCB, CBSTATUS_STENCIL_READ_MASK_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT,
2073                                  DRAWSTATE_STENCIL_NOT_BOUND, "Dynamic stencil read mask state not set for this command buffer");
2074        result |= validate_status(dev_data, pCB, CBSTATUS_STENCIL_WRITE_MASK_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT,
2075                                  DRAWSTATE_STENCIL_NOT_BOUND, "Dynamic stencil write mask state not set for this command buffer");
2076        result |= validate_status(dev_data, pCB, CBSTATUS_STENCIL_REFERENCE_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT,
2077                                  DRAWSTATE_STENCIL_NOT_BOUND, "Dynamic stencil reference state not set for this command buffer");
2078    }
2079    if (indexedDraw) {
2080        result |= validate_status(dev_data, pCB, CBSTATUS_INDEX_BUFFER_BOUND, VK_DEBUG_REPORT_ERROR_BIT_EXT,
2081                                  DRAWSTATE_INDEX_BUFFER_NOT_BOUND,
2082                                  "Index buffer object not bound to this command buffer when Indexed Draw attempted");
2083    }
2084    return result;
2085}
2086
2087// Verify attachment reference compatibility according to spec
2088//  If one array is larger, treat missing elements of shorter array as VK_ATTACHMENT_UNUSED & other array much match this
2089//  If both AttachmentReference arrays have requested index, check their corresponding AttachementDescriptions
2090//   to make sure that format and samples counts match.
2091//  If not, they are not compatible.
2092static bool attachment_references_compatible(const uint32_t index, const VkAttachmentReference *pPrimary,
2093                                             const uint32_t primaryCount, const VkAttachmentDescription *pPrimaryAttachments,
2094                                             const VkAttachmentReference *pSecondary, const uint32_t secondaryCount,
2095                                             const VkAttachmentDescription *pSecondaryAttachments) {
2096    if (index >= primaryCount) { // Check secondary as if primary is VK_ATTACHMENT_UNUSED
2097        if (VK_ATTACHMENT_UNUSED == pSecondary[index].attachment)
2098            return true;
2099    } else if (index >= secondaryCount) { // Check primary as if secondary is VK_ATTACHMENT_UNUSED
2100        if (VK_ATTACHMENT_UNUSED == pPrimary[index].attachment)
2101            return true;
2102    } else { // format and sample count must match
2103        if ((pPrimaryAttachments[pPrimary[index].attachment].format ==
2104             pSecondaryAttachments[pSecondary[index].attachment].format) &&
2105            (pPrimaryAttachments[pPrimary[index].attachment].samples ==
2106             pSecondaryAttachments[pSecondary[index].attachment].samples))
2107            return true;
2108    }
2109    // Format and sample counts didn't match
2110    return false;
2111}
2112
2113// For give primary and secondary RenderPass objects, verify that they're compatible
2114static bool verify_renderpass_compatibility(layer_data *my_data, const VkRenderPass primaryRP, const VkRenderPass secondaryRP,
2115                                            string &errorMsg) {
2116    stringstream errorStr;
2117    if (my_data->renderPassMap.find(primaryRP) == my_data->renderPassMap.end()) {
2118        errorStr << "invalid VkRenderPass (" << primaryRP << ")";
2119        errorMsg = errorStr.str();
2120        return false;
2121    } else if (my_data->renderPassMap.find(secondaryRP) == my_data->renderPassMap.end()) {
2122        errorStr << "invalid VkRenderPass (" << secondaryRP << ")";
2123        errorMsg = errorStr.str();
2124        return false;
2125    }
2126    // Trivial pass case is exact same RP
2127    if (primaryRP == secondaryRP) {
2128        return true;
2129    }
2130    const VkRenderPassCreateInfo *primaryRPCI = my_data->renderPassMap[primaryRP]->pCreateInfo;
2131    const VkRenderPassCreateInfo *secondaryRPCI = my_data->renderPassMap[secondaryRP]->pCreateInfo;
2132    if (primaryRPCI->subpassCount != secondaryRPCI->subpassCount) {
2133        errorStr << "RenderPass for primary cmdBuffer has " << primaryRPCI->subpassCount
2134                 << " subpasses but renderPass for secondary cmdBuffer has " << secondaryRPCI->subpassCount << " subpasses.";
2135        errorMsg = errorStr.str();
2136        return false;
2137    }
2138    uint32_t spIndex = 0;
2139    for (spIndex = 0; spIndex < primaryRPCI->subpassCount; ++spIndex) {
2140        // For each subpass, verify that corresponding color, input, resolve & depth/stencil attachment references are compatible
2141        uint32_t primaryColorCount = primaryRPCI->pSubpasses[spIndex].colorAttachmentCount;
2142        uint32_t secondaryColorCount = secondaryRPCI->pSubpasses[spIndex].colorAttachmentCount;
2143        uint32_t colorMax = std::max(primaryColorCount, secondaryColorCount);
2144        for (uint32_t cIdx = 0; cIdx < colorMax; ++cIdx) {
2145            if (!attachment_references_compatible(cIdx, primaryRPCI->pSubpasses[spIndex].pColorAttachments, primaryColorCount,
2146                                                  primaryRPCI->pAttachments, secondaryRPCI->pSubpasses[spIndex].pColorAttachments,
2147                                                  secondaryColorCount, secondaryRPCI->pAttachments)) {
2148                errorStr << "color attachments at index " << cIdx << " of subpass index " << spIndex << " are not compatible.";
2149                errorMsg = errorStr.str();
2150                return false;
2151            } else if (!attachment_references_compatible(cIdx, primaryRPCI->pSubpasses[spIndex].pResolveAttachments,
2152                                                         primaryColorCount, primaryRPCI->pAttachments,
2153                                                         secondaryRPCI->pSubpasses[spIndex].pResolveAttachments,
2154                                                         secondaryColorCount, secondaryRPCI->pAttachments)) {
2155                errorStr << "resolve attachments at index " << cIdx << " of subpass index " << spIndex << " are not compatible.";
2156                errorMsg = errorStr.str();
2157                return false;
2158            }
2159        }
2160
2161        if (!attachment_references_compatible(0, primaryRPCI->pSubpasses[spIndex].pDepthStencilAttachment,
2162                                              1, primaryRPCI->pAttachments,
2163                                              secondaryRPCI->pSubpasses[spIndex].pDepthStencilAttachment,
2164                                              1, secondaryRPCI->pAttachments)) {
2165            errorStr << "depth/stencil attachments of subpass index " << spIndex << " are not compatible.";
2166            errorMsg = errorStr.str();
2167            return false;
2168        }
2169
2170        uint32_t primaryInputCount = primaryRPCI->pSubpasses[spIndex].inputAttachmentCount;
2171        uint32_t secondaryInputCount = secondaryRPCI->pSubpasses[spIndex].inputAttachmentCount;
2172        uint32_t inputMax = std::max(primaryInputCount, secondaryInputCount);
2173        for (uint32_t i = 0; i < inputMax; ++i) {
2174            if (!attachment_references_compatible(i, primaryRPCI->pSubpasses[spIndex].pInputAttachments, primaryColorCount,
2175                                                  primaryRPCI->pAttachments, secondaryRPCI->pSubpasses[spIndex].pInputAttachments,
2176                                                  secondaryColorCount, secondaryRPCI->pAttachments)) {
2177                errorStr << "input attachments at index " << i << " of subpass index " << spIndex << " are not compatible.";
2178                errorMsg = errorStr.str();
2179                return false;
2180            }
2181        }
2182    }
2183    return true;
2184}
2185
2186// For give SET_NODE, verify that its Set is compatible w/ the setLayout corresponding to pipelineLayout[layoutIndex]
2187static bool verify_set_layout_compatibility(layer_data *my_data, const SET_NODE *pSet, const VkPipelineLayout layout,
2188                                            const uint32_t layoutIndex, string &errorMsg) {
2189    stringstream errorStr;
2190    auto pipeline_layout_it = my_data->pipelineLayoutMap.find(layout);
2191    if (pipeline_layout_it == my_data->pipelineLayoutMap.end()) {
2192        errorStr << "invalid VkPipelineLayout (" << layout << ")";
2193        errorMsg = errorStr.str();
2194        return false;
2195    }
2196    if (layoutIndex >= pipeline_layout_it->second.descriptorSetLayouts.size()) {
2197        errorStr << "VkPipelineLayout (" << layout << ") only contains " << pipeline_layout_it->second.descriptorSetLayouts.size()
2198                 << " setLayouts corresponding to sets 0-" << pipeline_layout_it->second.descriptorSetLayouts.size() - 1
2199                 << ", but you're attempting to bind set to index " << layoutIndex;
2200        errorMsg = errorStr.str();
2201        return false;
2202    }
2203    // Get the specific setLayout from PipelineLayout that overlaps this set
2204    LAYOUT_NODE *pLayoutNode = my_data->descriptorSetLayoutMap[pipeline_layout_it->second.descriptorSetLayouts[layoutIndex]];
2205    if (pLayoutNode->layout == pSet->pLayout->layout) { // trivial pass case
2206        return true;
2207    }
2208    size_t descriptorCount = pLayoutNode->descriptorTypes.size();
2209    if (descriptorCount != pSet->pLayout->descriptorTypes.size()) {
2210        errorStr << "setLayout " << layoutIndex << " from pipelineLayout " << layout << " has " << descriptorCount
2211                 << " descriptors, but corresponding set being bound has " << pSet->pLayout->descriptorTypes.size()
2212                 << " descriptors.";
2213        errorMsg = errorStr.str();
2214        return false; // trivial fail case
2215    }
2216    // Now need to check set against corresponding pipelineLayout to verify compatibility
2217    for (size_t i = 0; i < descriptorCount; ++i) {
2218        // Need to verify that layouts are identically defined
2219        //  TODO : Is below sufficient? Making sure that types & stageFlags match per descriptor
2220        //    do we also need to check immutable samplers?
2221        if (pLayoutNode->descriptorTypes[i] != pSet->pLayout->descriptorTypes[i]) {
2222            errorStr << "descriptor " << i << " for descriptorSet being bound is type '"
2223                     << string_VkDescriptorType(pSet->pLayout->descriptorTypes[i])
2224                     << "' but corresponding descriptor from pipelineLayout is type '"
2225                     << string_VkDescriptorType(pLayoutNode->descriptorTypes[i]) << "'";
2226            errorMsg = errorStr.str();
2227            return false;
2228        }
2229        if (pLayoutNode->stageFlags[i] != pSet->pLayout->stageFlags[i]) {
2230            errorStr << "stageFlags " << i << " for descriptorSet being bound is " << pSet->pLayout->stageFlags[i]
2231                     << "' but corresponding descriptor from pipelineLayout has stageFlags " << pLayoutNode->stageFlags[i];
2232            errorMsg = errorStr.str();
2233            return false;
2234        }
2235    }
2236    return true;
2237}
2238
2239// Validate that data for each specialization entry is fully contained within the buffer.
2240static bool validate_specialization_offsets(layer_data *my_data, VkPipelineShaderStageCreateInfo const *info) {
2241    bool pass = true;
2242
2243    VkSpecializationInfo const *spec = info->pSpecializationInfo;
2244
2245    if (spec) {
2246        for (auto i = 0u; i < spec->mapEntryCount; i++) {
2247            if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
2248                if (log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
2249                            /*dev*/ 0, __LINE__, SHADER_CHECKER_BAD_SPECIALIZATION, "SC",
2250                            "Specialization entry %u (for constant id %u) references memory outside provided "
2251                            "specialization data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER
2252                            " bytes provided)",
2253                            i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
2254                            spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize)) {
2255
2256                    pass = false;
2257                }
2258            }
2259        }
2260    }
2261
2262    return pass;
2263}
2264
2265static bool descriptor_type_match(layer_data *my_data, shader_module const *module, uint32_t type_id,
2266                                  VkDescriptorType descriptor_type, unsigned &descriptor_count) {
2267    auto type = module->get_def(type_id);
2268
2269    descriptor_count = 1;
2270
2271    /* Strip off any array or ptrs. Where we remove array levels, adjust the
2272     * descriptor count for each dimension. */
2273    while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer) {
2274        if (type.opcode() == spv::OpTypeArray) {
2275            descriptor_count *= get_constant_value(module, type.word(3));
2276            type = module->get_def(type.word(2));
2277        }
2278        else {
2279            type = module->get_def(type.word(3));
2280        }
2281    }
2282
2283    switch (type.opcode()) {
2284    case spv::OpTypeStruct: {
2285        for (auto insn : *module) {
2286            if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
2287                if (insn.word(2) == spv::DecorationBlock) {
2288                    return descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER ||
2289                           descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
2290                } else if (insn.word(2) == spv::DecorationBufferBlock) {
2291                    return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER ||
2292                           descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC;
2293                }
2294            }
2295        }
2296
2297        /* Invalid */
2298        return false;
2299    }
2300
2301    case spv::OpTypeSampler:
2302        return descriptor_type == VK_DESCRIPTOR_TYPE_SAMPLER;
2303
2304    case spv::OpTypeSampledImage:
2305        if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER) {
2306            /* Slight relaxation for some GLSL historical madness: samplerBuffer
2307             * doesn't really have a sampler, and a texel buffer descriptor
2308             * doesn't really provide one. Allow this slight mismatch.
2309             */
2310            auto image_type = module->get_def(type.word(2));
2311            auto dim = image_type.word(3);
2312            auto sampled = image_type.word(7);
2313            return dim == spv::DimBuffer && sampled == 1;
2314        }
2315        return descriptor_type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
2316
2317    case spv::OpTypeImage: {
2318        /* Many descriptor types backing image types-- depends on dimension
2319         * and whether the image will be used with a sampler. SPIRV for
2320         * Vulkan requires that sampled be 1 or 2 -- leaving the decision to
2321         * runtime is unacceptable.
2322         */
2323        auto dim = type.word(3);
2324        auto sampled = type.word(7);
2325
2326        if (dim == spv::DimSubpassData) {
2327            return descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
2328        } else if (dim == spv::DimBuffer) {
2329            if (sampled == 1) {
2330                return descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
2331            } else {
2332                return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
2333            }
2334        } else if (sampled == 1) {
2335            return descriptor_type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
2336        } else {
2337            return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
2338        }
2339    }
2340
2341    /* We shouldn't really see any other junk types -- but if we do, they're
2342     * a mismatch.
2343     */
2344    default:
2345        return false; /* Mismatch */
2346    }
2347}
2348
2349static bool require_feature(layer_data *my_data, VkBool32 feature, char const *feature_name) {
2350    if (!feature) {
2351        if (log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VkDebugReportObjectTypeEXT(0), 0,
2352                    __LINE__, SHADER_CHECKER_FEATURE_NOT_ENABLED, "SC",
2353                    "Shader requires VkPhysicalDeviceFeatures::%s but is not "
2354                    "enabled on the device",
2355                    feature_name)) {
2356            return false;
2357        }
2358    }
2359
2360    return true;
2361}
2362
2363static bool validate_shader_capabilities(layer_data *my_data, shader_module const *src) {
2364    bool pass = true;
2365
2366    auto enabledFeatures = &my_data->phys_dev_properties.features;
2367
2368    for (auto insn : *src) {
2369        if (insn.opcode() == spv::OpCapability) {
2370            switch (insn.word(1)) {
2371            case spv::CapabilityMatrix:
2372            case spv::CapabilityShader:
2373            case spv::CapabilityInputAttachment:
2374            case spv::CapabilitySampled1D:
2375            case spv::CapabilityImage1D:
2376            case spv::CapabilitySampledBuffer:
2377            case spv::CapabilityImageBuffer:
2378            case spv::CapabilityImageQuery:
2379            case spv::CapabilityDerivativeControl:
2380                // Always supported by a Vulkan 1.0 implementation -- no feature bits.
2381                break;
2382
2383            case spv::CapabilityGeometry:
2384                pass &= require_feature(my_data, enabledFeatures->geometryShader, "geometryShader");
2385                break;
2386
2387            case spv::CapabilityTessellation:
2388                pass &= require_feature(my_data, enabledFeatures->tessellationShader, "tessellationShader");
2389                break;
2390
2391            case spv::CapabilityFloat64:
2392                pass &= require_feature(my_data, enabledFeatures->shaderFloat64, "shaderFloat64");
2393                break;
2394
2395            case spv::CapabilityInt64:
2396                pass &= require_feature(my_data, enabledFeatures->shaderInt64, "shaderInt64");
2397                break;
2398
2399            case spv::CapabilityTessellationPointSize:
2400            case spv::CapabilityGeometryPointSize:
2401                pass &= require_feature(my_data, enabledFeatures->shaderTessellationAndGeometryPointSize,
2402                                        "shaderTessellationAndGeometryPointSize");
2403                break;
2404
2405            case spv::CapabilityImageGatherExtended:
2406                pass &= require_feature(my_data, enabledFeatures->shaderImageGatherExtended, "shaderImageGatherExtended");
2407                break;
2408
2409            case spv::CapabilityStorageImageMultisample:
2410                pass &= require_feature(my_data, enabledFeatures->shaderStorageImageMultisample, "shaderStorageImageMultisample");
2411                break;
2412
2413            case spv::CapabilityUniformBufferArrayDynamicIndexing:
2414                pass &= require_feature(my_data, enabledFeatures->shaderUniformBufferArrayDynamicIndexing,
2415                                        "shaderUniformBufferArrayDynamicIndexing");
2416                break;
2417
2418            case spv::CapabilitySampledImageArrayDynamicIndexing:
2419                pass &= require_feature(my_data, enabledFeatures->shaderSampledImageArrayDynamicIndexing,
2420                                        "shaderSampledImageArrayDynamicIndexing");
2421                break;
2422
2423            case spv::CapabilityStorageBufferArrayDynamicIndexing:
2424                pass &= require_feature(my_data, enabledFeatures->shaderStorageBufferArrayDynamicIndexing,
2425                                        "shaderStorageBufferArrayDynamicIndexing");
2426                break;
2427
2428            case spv::CapabilityStorageImageArrayDynamicIndexing:
2429                pass &= require_feature(my_data, enabledFeatures->shaderStorageImageArrayDynamicIndexing,
2430                                        "shaderStorageImageArrayDynamicIndexing");
2431                break;
2432
2433            case spv::CapabilityClipDistance:
2434                pass &= require_feature(my_data, enabledFeatures->shaderClipDistance, "shaderClipDistance");
2435                break;
2436
2437            case spv::CapabilityCullDistance:
2438                pass &= require_feature(my_data, enabledFeatures->shaderCullDistance, "shaderCullDistance");
2439                break;
2440
2441            case spv::CapabilityImageCubeArray:
2442                pass &= require_feature(my_data, enabledFeatures->imageCubeArray, "imageCubeArray");
2443                break;
2444
2445            case spv::CapabilitySampleRateShading:
2446                pass &= require_feature(my_data, enabledFeatures->sampleRateShading, "sampleRateShading");
2447                break;
2448
2449            case spv::CapabilitySparseResidency:
2450                pass &= require_feature(my_data, enabledFeatures->shaderResourceResidency, "shaderResourceResidency");
2451                break;
2452
2453            case spv::CapabilityMinLod:
2454                pass &= require_feature(my_data, enabledFeatures->shaderResourceMinLod, "shaderResourceMinLod");
2455                break;
2456
2457            case spv::CapabilitySampledCubeArray:
2458                pass &= require_feature(my_data, enabledFeatures->imageCubeArray, "imageCubeArray");
2459                break;
2460
2461            case spv::CapabilityImageMSArray:
2462                pass &= require_feature(my_data, enabledFeatures->shaderStorageImageMultisample, "shaderStorageImageMultisample");
2463                break;
2464
2465            case spv::CapabilityStorageImageExtendedFormats:
2466                pass &= require_feature(my_data, enabledFeatures->shaderStorageImageExtendedFormats,
2467                                        "shaderStorageImageExtendedFormats");
2468                break;
2469
2470            case spv::CapabilityInterpolationFunction:
2471                pass &= require_feature(my_data, enabledFeatures->sampleRateShading, "sampleRateShading");
2472                break;
2473
2474            case spv::CapabilityStorageImageReadWithoutFormat:
2475                pass &= require_feature(my_data, enabledFeatures->shaderStorageImageReadWithoutFormat,
2476                                        "shaderStorageImageReadWithoutFormat");
2477                break;
2478
2479            case spv::CapabilityStorageImageWriteWithoutFormat:
2480                pass &= require_feature(my_data, enabledFeatures->shaderStorageImageWriteWithoutFormat,
2481                                        "shaderStorageImageWriteWithoutFormat");
2482                break;
2483
2484            case spv::CapabilityMultiViewport:
2485                pass &= require_feature(my_data, enabledFeatures->multiViewport, "multiViewport");
2486                break;
2487
2488            default:
2489                if (log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VkDebugReportObjectTypeEXT(0), 0,
2490                            __LINE__, SHADER_CHECKER_BAD_CAPABILITY, "SC",
2491                            "Shader declares capability %u, not supported in Vulkan.",
2492                            insn.word(1)))
2493                    pass = false;
2494                break;
2495            }
2496        }
2497    }
2498
2499    return pass;
2500}
2501
2502static bool validate_pipeline_shader_stage(layer_data *dev_data, VkPipelineShaderStageCreateInfo const *pStage,
2503                                           PIPELINE_NODE *pipeline, PIPELINE_LAYOUT_NODE *pipelineLayout,
2504                                           shader_module **out_module, spirv_inst_iter *out_entrypoint) {
2505    bool pass = true;
2506    auto module = *out_module = dev_data->shaderModuleMap[pStage->module].get();
2507    pass &= validate_specialization_offsets(dev_data, pStage);
2508
2509    /* find the entrypoint */
2510    auto entrypoint = *out_entrypoint = find_entrypoint(module, pStage->pName, pStage->stage);
2511    if (entrypoint == module->end()) {
2512        if (log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VkDebugReportObjectTypeEXT(0), 0,
2513                    __LINE__, SHADER_CHECKER_MISSING_ENTRYPOINT, "SC",
2514                    "No entrypoint found named `%s` for stage %s", pStage->pName,
2515                    string_VkShaderStageFlagBits(pStage->stage))) {
2516            pass = false;
2517        }
2518    }
2519
2520    /* validate shader capabilities against enabled device features */
2521    pass &= validate_shader_capabilities(dev_data, module);
2522
2523    /* mark accessible ids */
2524    std::unordered_set<uint32_t> accessible_ids;
2525    mark_accessible_ids(module, entrypoint, accessible_ids);
2526
2527    /* validate descriptor set layout against what the entrypoint actually uses */
2528    std::map<descriptor_slot_t, interface_var> descriptor_uses;
2529    collect_interface_by_descriptor_slot(dev_data, module, accessible_ids, descriptor_uses);
2530
2531    /* validate push constant usage */
2532    pass &= validate_push_constant_usage(dev_data, &pipelineLayout->pushConstantRanges,
2533                                        module, accessible_ids, pStage->stage);
2534
2535    /* validate descriptor use */
2536    for (auto use : descriptor_uses) {
2537        // While validating shaders capture which slots are used by the pipeline
2538        pipeline->active_slots[use.first.first].insert(use.first.second);
2539
2540        /* find the matching binding */
2541        auto binding = get_descriptor_binding(dev_data, pipelineLayout, use.first);
2542        unsigned required_descriptor_count;
2543
2544        if (!binding) {
2545            if (log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VkDebugReportObjectTypeEXT(0), 0,
2546                        __LINE__, SHADER_CHECKER_MISSING_DESCRIPTOR, "SC",
2547                        "Shader uses descriptor slot %u.%u (used as type `%s`) but not declared in pipeline layout",
2548                        use.first.first, use.first.second, describe_type(module, use.second.type_id).c_str())) {
2549                pass = false;
2550            }
2551        } else if (~binding->stageFlags & pStage->stage) {
2552            if (log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
2553                        /*dev*/ 0, __LINE__, SHADER_CHECKER_DESCRIPTOR_NOT_ACCESSIBLE_FROM_STAGE, "SC",
2554                        "Shader uses descriptor slot %u.%u (used "
2555                        "as type `%s`) but descriptor not "
2556                        "accessible from stage %s",
2557                        use.first.first, use.first.second,
2558                        describe_type(module, use.second.type_id).c_str(),
2559                        string_VkShaderStageFlagBits(pStage->stage))) {
2560                pass = false;
2561            }
2562        } else if (!descriptor_type_match(dev_data, module, use.second.type_id, binding->descriptorType, /*out*/ required_descriptor_count)) {
2563            if (log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VkDebugReportObjectTypeEXT(0), 0,
2564                        __LINE__, SHADER_CHECKER_DESCRIPTOR_TYPE_MISMATCH, "SC",
2565                        "Type mismatch on descriptor slot "
2566                        "%u.%u (used as type `%s`) but "
2567                        "descriptor of type %s",
2568                        use.first.first, use.first.second,
2569                        describe_type(module, use.second.type_id).c_str(),
2570                        string_VkDescriptorType(binding->descriptorType))) {
2571                pass = false;
2572            }
2573        } else if (binding->descriptorCount < required_descriptor_count) {
2574            if (log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VkDebugReportObjectTypeEXT(0), 0,
2575                        __LINE__, SHADER_CHECKER_DESCRIPTOR_TYPE_MISMATCH, "SC",
2576                        "Shader expects at least %u descriptors for binding %u.%u (used as type `%s`) but only %u provided",
2577                        required_descriptor_count, use.first.first, use.first.second,
2578                        describe_type(module, use.second.type_id).c_str(),
2579                        binding->descriptorCount)) {
2580                pass = false;
2581            }
2582        }
2583    }
2584
2585    return pass;
2586}
2587
2588
2589// Validate that the shaders used by the given pipeline and store the active_slots
2590//  that are actually used by the pipeline into pPipeline->active_slots
2591static bool validate_and_capture_pipeline_shader_state(layer_data *my_data, PIPELINE_NODE *pPipeline) {
2592    auto pCreateInfo = reinterpret_cast<VkGraphicsPipelineCreateInfo const *>(&pPipeline->graphicsPipelineCI);
2593    int vertex_stage = get_shader_stage_id(VK_SHADER_STAGE_VERTEX_BIT);
2594    int fragment_stage = get_shader_stage_id(VK_SHADER_STAGE_FRAGMENT_BIT);
2595
2596    shader_module *shaders[5];
2597    memset(shaders, 0, sizeof(shaders));
2598    spirv_inst_iter entrypoints[5];
2599    memset(entrypoints, 0, sizeof(entrypoints));
2600    VkPipelineVertexInputStateCreateInfo const *vi = 0;
2601    bool pass = true;
2602
2603    auto pipelineLayout = pCreateInfo->layout != VK_NULL_HANDLE ? &my_data->pipelineLayoutMap[pCreateInfo->layout] : nullptr;
2604
2605    for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
2606        VkPipelineShaderStageCreateInfo const *pStage =
2607            reinterpret_cast<VkPipelineShaderStageCreateInfo const *>(&pCreateInfo->pStages[i]);
2608        auto stage_id = get_shader_stage_id(pStage->stage);
2609        pass &= validate_pipeline_shader_stage(my_data, pStage, pPipeline, pipelineLayout,
2610                                               &shaders[stage_id], &entrypoints[stage_id]);
2611    }
2612
2613    vi = pCreateInfo->pVertexInputState;
2614
2615    if (vi) {
2616        pass &= validate_vi_consistency(my_data, vi);
2617    }
2618
2619    if (shaders[vertex_stage]) {
2620        pass &= validate_vi_against_vs_inputs(my_data, vi, shaders[vertex_stage], entrypoints[vertex_stage]);
2621    }
2622
2623    int producer = get_shader_stage_id(VK_SHADER_STAGE_VERTEX_BIT);
2624    int consumer = get_shader_stage_id(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
2625
2626    while (!shaders[producer] && producer != fragment_stage) {
2627        producer++;
2628        consumer++;
2629    }
2630
2631    for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
2632        assert(shaders[producer]);
2633        if (shaders[consumer]) {
2634            pass &= validate_interface_between_stages(my_data,
2635                                                      shaders[producer], entrypoints[producer], &shader_stage_attribs[producer],
2636                                                      shaders[consumer], entrypoints[consumer], &shader_stage_attribs[consumer]);
2637
2638            producer = consumer;
2639        }
2640    }
2641
2642    auto rp = pCreateInfo->renderPass != VK_NULL_HANDLE ? my_data->renderPassMap[pCreateInfo->renderPass] : nullptr;
2643
2644    if (shaders[fragment_stage] && rp) {
2645        pass &= validate_fs_outputs_against_render_pass(my_data, shaders[fragment_stage], entrypoints[fragment_stage], rp,
2646                                                       pCreateInfo->subpass);
2647    }
2648
2649    return pass;
2650}
2651
2652static bool validate_compute_pipeline(layer_data *my_data, PIPELINE_NODE *pPipeline) {
2653    auto pCreateInfo = reinterpret_cast<VkComputePipelineCreateInfo const *>(&pPipeline->computePipelineCI);
2654
2655    auto pipelineLayout = pCreateInfo->layout != VK_NULL_HANDLE ? &my_data->pipelineLayoutMap[pCreateInfo->layout] : nullptr;
2656
2657    shader_module *module;
2658    spirv_inst_iter entrypoint;
2659
2660    return validate_pipeline_shader_stage(my_data, &pCreateInfo->stage, pPipeline, pipelineLayout,
2661                                          &module, &entrypoint);
2662}
2663
2664// Return Set node ptr for specified set or else NULL
2665static SET_NODE *getSetNode(layer_data *my_data, const VkDescriptorSet set) {
2666    if (my_data->setMap.find(set) == my_data->setMap.end()) {
2667        return NULL;
2668    }
2669    return my_data->setMap[set];
2670}
2671
2672// For given Layout Node and binding, return index where that binding begins
2673static uint32_t getBindingStartIndex(const LAYOUT_NODE *pLayout, const uint32_t binding) {
2674    uint32_t offsetIndex = 0;
2675    for (uint32_t i = 0; i < pLayout->createInfo.bindingCount; i++) {
2676        if (pLayout->createInfo.pBindings[i].binding == binding)
2677            break;
2678        offsetIndex += pLayout->createInfo.pBindings[i].descriptorCount;
2679    }
2680    return offsetIndex;
2681}
2682
2683// For given layout node and binding, return last index that is updated
2684static uint32_t getBindingEndIndex(const LAYOUT_NODE *pLayout, const uint32_t binding) {
2685    uint32_t offsetIndex = 0;
2686    for (uint32_t i = 0; i < pLayout->createInfo.bindingCount; i++) {
2687        offsetIndex += pLayout->createInfo.pBindings[i].descriptorCount;
2688        if (pLayout->createInfo.pBindings[i].binding == binding)
2689            break;
2690    }
2691    return offsetIndex - 1;
2692}
2693
2694// For the given command buffer, verify and update the state for activeSetBindingsPairs
2695//  This includes:
2696//  1. Verifying that any dynamic descriptor in that set has a valid dynamic offset bound.
2697//     To be valid, the dynamic offset combined with the offset and range from its
2698//     descriptor update must not overflow the size of its buffer being updated
2699//  2. Grow updateImages for given pCB to include any bound STORAGE_IMAGE descriptor images
2700//  3. Grow updateBuffers for pCB to include buffers from STORAGE*_BUFFER descriptor buffers
2701static bool validate_and_update_drawtime_descriptor_state(
2702    layer_data *dev_data, GLOBAL_CB_NODE *pCB,
2703    const vector<std::pair<SET_NODE *, unordered_set<uint32_t>>> &activeSetBindingsPairs) {
2704    bool result = false;
2705
2706    VkWriteDescriptorSet *pWDS = NULL;
2707    uint32_t dynOffsetIndex = 0;
2708    VkDeviceSize bufferSize = 0;
2709    for (auto set_bindings_pair : activeSetBindingsPairs) {
2710        SET_NODE *set_node = set_bindings_pair.first;
2711        LAYOUT_NODE *layout_node = set_node->pLayout;
2712        for (auto binding : set_bindings_pair.second) {
2713            uint32_t startIdx = getBindingStartIndex(layout_node, binding);
2714            uint32_t endIdx = getBindingEndIndex(layout_node, binding);
2715            for (uint32_t i = startIdx; i <= endIdx; ++i) {
2716                // We did check earlier to verify that set was updated, but now make sure given slot was updated
2717                // TODO : Would be better to store set# that set is bound to so we can report set.binding[index] not updated
2718                if (!set_node->pDescriptorUpdates[i]) {
2719                    result |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
2720                                        VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, reinterpret_cast<const uint64_t &>(set_node->set), __LINE__,
2721                                        DRAWSTATE_DESCRIPTOR_SET_NOT_UPDATED, "DS",
2722                                        "DS %#" PRIxLEAST64 " bound and active but it never had binding %u updated. It is now being used to draw so "
2723                                                            "this will result in undefined behavior.",
2724                                        reinterpret_cast<const uint64_t &>(set_node->set), binding);
2725                } else {
2726                    switch (set_node->pDescriptorUpdates[i]->sType) {
2727                    case VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET:
2728                        pWDS = (VkWriteDescriptorSet *)set_node->pDescriptorUpdates[i];
2729                        if ((pWDS->descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) ||
2730                            (pWDS->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC)) {
2731                            for (uint32_t j = 0; j < pWDS->descriptorCount; ++j) {
2732                                bufferSize = dev_data->bufferMap[pWDS->pBufferInfo[j].buffer].createInfo.size;
2733                                uint32_t dynOffset = pCB->lastBound[VK_PIPELINE_BIND_POINT_GRAPHICS].dynamicOffsets[dynOffsetIndex];
2734                                if (pWDS->pBufferInfo[j].range == VK_WHOLE_SIZE) {
2735                                    if ((dynOffset + pWDS->pBufferInfo[j].offset) > bufferSize) {
2736                                        result |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
2737                                                          VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
2738                                                          reinterpret_cast<const uint64_t &>(set_node->set), __LINE__,
2739                                                          DRAWSTATE_DYNAMIC_OFFSET_OVERFLOW, "DS",
2740                                                          "VkDescriptorSet (%#" PRIxLEAST64 ") bound as set #%u has range of "
2741                                                          "VK_WHOLE_SIZE but dynamic offset %#" PRIxLEAST32 ". "
2742                                                          "combined with offset %#" PRIxLEAST64 " oversteps its buffer (%#" PRIxLEAST64
2743                                                          ") which has a size of %#" PRIxLEAST64 ".",
2744                                                          reinterpret_cast<const uint64_t &>(set_node->set), i, dynOffset,
2745                                                          pWDS->pBufferInfo[j].offset,
2746                                                          reinterpret_cast<const uint64_t &>(pWDS->pBufferInfo[j].buffer), bufferSize);
2747                                    }
2748                                } else if ((dynOffset + pWDS->pBufferInfo[j].offset + pWDS->pBufferInfo[j].range) > bufferSize) {
2749                                    result |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
2750                                                      VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
2751                                                      reinterpret_cast<const uint64_t &>(set_node->set), __LINE__,
2752                                                      DRAWSTATE_DYNAMIC_OFFSET_OVERFLOW, "DS",
2753                                                      "VkDescriptorSet (%#" PRIxLEAST64
2754                                                      ") bound as set #%u has dynamic offset %#" PRIxLEAST32 ". "
2755                                                      "Combined with offset %#" PRIxLEAST64 " and range %#" PRIxLEAST64
2756                                                      " from its update, this oversteps its buffer "
2757                                                      "(%#" PRIxLEAST64 ") which has a size of %#" PRIxLEAST64 ".",
2758                                                      reinterpret_cast<const uint64_t &>(set_node->set), i, dynOffset,
2759                                                      pWDS->pBufferInfo[j].offset, pWDS->pBufferInfo[j].range,
2760                                                      reinterpret_cast<const uint64_t &>(pWDS->pBufferInfo[j].buffer), bufferSize);
2761                                }
2762                                dynOffsetIndex++;
2763                            }
2764                        } else if (pWDS->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) {
2765                            for (uint32_t j = 0; j < pWDS->descriptorCount; ++j) {
2766                                pCB->updateImages.insert(pWDS->pImageInfo[j].imageView);
2767                            }
2768                        } else if (pWDS->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER) {
2769                            for (uint32_t j = 0; j < pWDS->descriptorCount; ++j) {
2770                                assert(dev_data->bufferViewMap.find(pWDS->pTexelBufferView[j]) != dev_data->bufferViewMap.end());
2771                                pCB->updateBuffers.insert(dev_data->bufferViewMap[pWDS->pTexelBufferView[j]].buffer);
2772                            }
2773                        } else if (pWDS->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER ||
2774                                   pWDS->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC) {
2775                            for (uint32_t j = 0; j < pWDS->descriptorCount; ++j) {
2776                                pCB->updateBuffers.insert(pWDS->pBufferInfo[j].buffer);
2777                            }
2778                        }
2779                        i += pWDS->descriptorCount; // Advance i to end of this set of descriptors (++i at end of for loop will move 1
2780                                                    // index past last of these descriptors)
2781                        break;
2782                    default: // Currently only shadowing Write update nodes so shouldn't get here
2783                        assert(0);
2784                        continue;
2785                    }
2786                }
2787            }
2788        }
2789    }
2790    return result;
2791}
2792// TODO : This is a temp function that naively updates bound storage images and buffers based on which descriptor sets are bound.
2793//   When validate_and_update_draw_state() handles computer shaders so that active_slots is correct for compute pipelines, this
2794//   function can be killed and validate_and_update_draw_state() used instead
2795static void update_shader_storage_images_and_buffers(layer_data *dev_data, GLOBAL_CB_NODE *pCB) {
2796    VkWriteDescriptorSet *pWDS = nullptr;
2797    SET_NODE *pSet = nullptr;
2798    // For the bound descriptor sets, pull off any storage images and buffers
2799    //  This may be more than are actually updated depending on which are active, but for now this is a stop-gap for compute
2800    //  pipelines
2801    for (auto set : pCB->lastBound[VK_PIPELINE_BIND_POINT_COMPUTE].uniqueBoundSets) {
2802        // Get the set node
2803        pSet = getSetNode(dev_data, set);
2804        // For each update in the set
2805        for (auto pUpdate : pSet->pDescriptorUpdates) {
2806            // If it's a write update to STORAGE type capture image/buffer being updated
2807            if (pUpdate && (pUpdate->sType == VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET)) {
2808                pWDS = reinterpret_cast<VkWriteDescriptorSet *>(pUpdate);
2809                if (pWDS->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) {
2810                    for (uint32_t j = 0; j < pWDS->descriptorCount; ++j) {
2811                        pCB->updateImages.insert(pWDS->pImageInfo[j].imageView);
2812                    }
2813                } else if (pWDS->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER) {
2814                    for (uint32_t j = 0; j < pWDS->descriptorCount; ++j) {
2815                        pCB->updateBuffers.insert(dev_data->bufferViewMap[pWDS->pTexelBufferView[j]].buffer);
2816                    }
2817                } else if (pWDS->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER ||
2818                           pWDS->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC) {
2819                    for (uint32_t j = 0; j < pWDS->descriptorCount; ++j) {
2820                        pCB->updateBuffers.insert(pWDS->pBufferInfo[j].buffer);
2821                    }
2822                }
2823            }
2824        }
2825    }
2826}
2827
2828// Validate overall state at the time of a draw call
2829static bool validate_and_update_draw_state(layer_data *my_data, GLOBAL_CB_NODE *pCB, const bool indexedDraw,
2830                                           const VkPipelineBindPoint bindPoint) {
2831    bool result = false;
2832    auto const &state = pCB->lastBound[bindPoint];
2833    PIPELINE_NODE *pPipe = getPipeline(my_data, state.pipeline);
2834    // First check flag states
2835    if (VK_PIPELINE_BIND_POINT_GRAPHICS == bindPoint)
2836        result = validate_draw_state_flags(my_data, pCB, pPipe, indexedDraw);
2837
2838    // Now complete other state checks
2839    // TODO : Currently only performing next check if *something* was bound (non-zero last bound)
2840    //  There is probably a better way to gate when this check happens, and to know if something *should* have been bound
2841    //  We should have that check separately and then gate this check based on that check
2842    if (pPipe) {
2843        if (state.pipelineLayout) {
2844            string errorString;
2845            // Need a vector (vs. std::set) of active Sets for dynamicOffset validation in case same set bound w/ different offsets
2846            vector<std::pair<SET_NODE *, unordered_set<uint32_t>>> activeSetBindingsPairs;
2847            for (auto setBindingPair : pPipe->active_slots) {
2848                uint32_t setIndex = setBindingPair.first;
2849                // If valid set is not bound throw an error
2850                if ((state.boundDescriptorSets.size() <= setIndex) || (!state.boundDescriptorSets[setIndex])) {
2851                    result |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
2852                                      __LINE__, DRAWSTATE_DESCRIPTOR_SET_NOT_BOUND, "DS",
2853                                      "VkPipeline %#" PRIxLEAST64 " uses set #%u but that set is not bound.",
2854                                      (uint64_t)pPipe->pipeline, setIndex);
2855                } else if (!verify_set_layout_compatibility(my_data, my_data->setMap[state.boundDescriptorSets[setIndex]],
2856                                                            pPipe->graphicsPipelineCI.layout, setIndex, errorString)) {
2857                    // Set is bound but not compatible w/ overlapping pipelineLayout from PSO
2858                    VkDescriptorSet setHandle = my_data->setMap[state.boundDescriptorSets[setIndex]]->set;
2859                    result |= log_msg(
2860                        my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
2861                        (uint64_t)setHandle, __LINE__, DRAWSTATE_PIPELINE_LAYOUTS_INCOMPATIBLE, "DS",
2862                        "VkDescriptorSet (%#" PRIxLEAST64
2863                        ") bound as set #%u is not compatible with overlapping VkPipelineLayout %#" PRIxLEAST64 " due to: %s",
2864                        (uint64_t)setHandle, setIndex, (uint64_t)pPipe->graphicsPipelineCI.layout, errorString.c_str());
2865                } else { // Valid set is bound and layout compatible, validate that it's updated
2866                    // Pull the set node
2867                    SET_NODE *pSet = my_data->setMap[state.boundDescriptorSets[setIndex]];
2868                    // Save vector of all active sets to verify dynamicOffsets below
2869                    // activeSetNodes.push_back(pSet);
2870                    activeSetBindingsPairs.push_back(std::make_pair(pSet, setBindingPair.second));
2871                    // Make sure set has been updated
2872                    if (!pSet->pUpdateStructs) {
2873                        result |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
2874                                          VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, (uint64_t)pSet->set, __LINE__,
2875                                          DRAWSTATE_DESCRIPTOR_SET_NOT_UPDATED, "DS",
2876                                          "DS %#" PRIxLEAST64 " bound but it was never updated. It is now being used to draw so "
2877                                                              "this will result in undefined behavior.",
2878                                          (uint64_t)pSet->set);
2879                    }
2880                }
2881            }
2882            // For given active slots, verify any dynamic descriptors and record updated images & buffers
2883            result |= validate_and_update_drawtime_descriptor_state(my_data, pCB, activeSetBindingsPairs);
2884        }
2885        if (VK_PIPELINE_BIND_POINT_GRAPHICS == bindPoint) {
2886            // Verify Vtx binding
2887            if (pPipe->vertexBindingDescriptions.size() > 0) {
2888                for (size_t i = 0; i < pPipe->vertexBindingDescriptions.size(); i++) {
2889                    if ((pCB->currentDrawData.buffers.size() < (i + 1)) || (pCB->currentDrawData.buffers[i] == VK_NULL_HANDLE)) {
2890                        result |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
2891                                          __LINE__, DRAWSTATE_VTX_INDEX_OUT_OF_BOUNDS, "DS",
2892                                          "The Pipeline State Object (%#" PRIxLEAST64
2893                                          ") expects that this Command Buffer's vertex binding Index " PRINTF_SIZE_T_SPECIFIER
2894                                          " should be set via vkCmdBindVertexBuffers.",
2895                                          (uint64_t)state.pipeline, i);
2896                    }
2897                }
2898            } else {
2899                if (!pCB->currentDrawData.buffers.empty()) {
2900                    result |= log_msg(my_data->report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
2901                                      (VkDebugReportObjectTypeEXT)0, 0, __LINE__, DRAWSTATE_VTX_INDEX_OUT_OF_BOUNDS, "DS",
2902                                      "Vertex buffers are bound to command buffer (%#" PRIxLEAST64
2903                                      ") but no vertex buffers are attached to this Pipeline State Object (%#" PRIxLEAST64 ").",
2904                                      (uint64_t)pCB->commandBuffer, (uint64_t)state.pipeline);
2905                }
2906            }
2907            // If Viewport or scissors are dynamic, verify that dynamic count matches PSO count.
2908            // Skip check if rasterization is disabled or there is no viewport.
2909            if ((!pPipe->graphicsPipelineCI.pRasterizationState ||
2910                 (pPipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable == VK_FALSE)) &&
2911                pPipe->graphicsPipelineCI.pViewportState) {
2912                bool dynViewport = isDynamic(pPipe, VK_DYNAMIC_STATE_VIEWPORT);
2913                bool dynScissor = isDynamic(pPipe, VK_DYNAMIC_STATE_SCISSOR);
2914                if (dynViewport) {
2915                    if (pCB->viewports.size() != pPipe->graphicsPipelineCI.pViewportState->viewportCount) {
2916                        result |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
2917                                          __LINE__, DRAWSTATE_VIEWPORT_SCISSOR_MISMATCH, "DS",
2918                                          "Dynamic viewportCount from vkCmdSetViewport() is " PRINTF_SIZE_T_SPECIFIER
2919                                          ", but PSO viewportCount is %u. These counts must match.",
2920                                          pCB->viewports.size(), pPipe->graphicsPipelineCI.pViewportState->viewportCount);
2921                    }
2922                }
2923                if (dynScissor) {
2924                    if (pCB->scissors.size() != pPipe->graphicsPipelineCI.pViewportState->scissorCount) {
2925                        result |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
2926                                          __LINE__, DRAWSTATE_VIEWPORT_SCISSOR_MISMATCH, "DS",
2927                                          "Dynamic scissorCount from vkCmdSetScissor() is " PRINTF_SIZE_T_SPECIFIER
2928                                          ", but PSO scissorCount is %u. These counts must match.",
2929                                          pCB->scissors.size(), pPipe->graphicsPipelineCI.pViewportState->scissorCount);
2930                    }
2931                }
2932            }
2933        }
2934    }
2935    return result;
2936}
2937
2938// Verify that create state for a pipeline is valid
2939static bool verifyPipelineCreateState(layer_data *my_data, const VkDevice device, std::vector<PIPELINE_NODE *> pPipelines,
2940                                      int pipelineIndex) {
2941    bool skipCall = false;
2942
2943    PIPELINE_NODE *pPipeline = pPipelines[pipelineIndex];
2944
2945    // If create derivative bit is set, check that we've specified a base
2946    // pipeline correctly, and that the base pipeline was created to allow
2947    // derivatives.
2948    if (pPipeline->graphicsPipelineCI.flags & VK_PIPELINE_CREATE_DERIVATIVE_BIT) {
2949        PIPELINE_NODE *pBasePipeline = nullptr;
2950        if (!((pPipeline->graphicsPipelineCI.basePipelineHandle != VK_NULL_HANDLE) ^
2951              (pPipeline->graphicsPipelineCI.basePipelineIndex != -1))) {
2952            skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
2953                                DRAWSTATE_INVALID_PIPELINE_CREATE_STATE, "DS",
2954                                "Invalid Pipeline CreateInfo: exactly one of base pipeline index and handle must be specified");
2955        } else if (pPipeline->graphicsPipelineCI.basePipelineIndex != -1) {
2956            if (pPipeline->graphicsPipelineCI.basePipelineIndex >= pipelineIndex) {
2957                skipCall |=
2958                    log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
2959                            DRAWSTATE_INVALID_PIPELINE_CREATE_STATE, "DS",
2960                            "Invalid Pipeline CreateInfo: base pipeline must occur earlier in array than derivative pipeline.");
2961            } else {
2962                pBasePipeline = pPipelines[pPipeline->graphicsPipelineCI.basePipelineIndex];
2963            }
2964        } else if (pPipeline->graphicsPipelineCI.basePipelineHandle != VK_NULL_HANDLE) {
2965            pBasePipeline = getPipeline(my_data, pPipeline->graphicsPipelineCI.basePipelineHandle);
2966        }
2967
2968        if (pBasePipeline && !(pBasePipeline->graphicsPipelineCI.flags & VK_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT)) {
2969            skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
2970                                DRAWSTATE_INVALID_PIPELINE_CREATE_STATE, "DS",
2971                                "Invalid Pipeline CreateInfo: base pipeline does not allow derivatives.");
2972        }
2973    }
2974
2975    if (pPipeline->graphicsPipelineCI.pColorBlendState != NULL) {
2976        if (!my_data->phys_dev_properties.features.independentBlend) {
2977            if (pPipeline->attachments.size() > 1) {
2978                VkPipelineColorBlendAttachmentState *pAttachments = &pPipeline->attachments[0];
2979                for (size_t i = 1; i < pPipeline->attachments.size(); i++) {
2980                    if ((pAttachments[0].blendEnable != pAttachments[i].blendEnable) ||
2981                        (pAttachments[0].srcColorBlendFactor != pAttachments[i].srcColorBlendFactor) ||
2982                        (pAttachments[0].dstColorBlendFactor != pAttachments[i].dstColorBlendFactor) ||
2983                        (pAttachments[0].colorBlendOp != pAttachments[i].colorBlendOp) ||
2984                        (pAttachments[0].srcAlphaBlendFactor != pAttachments[i].srcAlphaBlendFactor) ||
2985                        (pAttachments[0].dstAlphaBlendFactor != pAttachments[i].dstAlphaBlendFactor) ||
2986                        (pAttachments[0].alphaBlendOp != pAttachments[i].alphaBlendOp) ||
2987                        (pAttachments[0].colorWriteMask != pAttachments[i].colorWriteMask)) {
2988                        skipCall |=
2989                            log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
2990                            DRAWSTATE_INDEPENDENT_BLEND, "DS", "Invalid Pipeline CreateInfo: If independent blend feature not "
2991                            "enabled, all elements of pAttachments must be identical");
2992                    }
2993                }
2994            }
2995        }
2996        if (!my_data->phys_dev_properties.features.logicOp &&
2997            (pPipeline->graphicsPipelineCI.pColorBlendState->logicOpEnable != VK_FALSE)) {
2998            skipCall |=
2999                log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
3000                        DRAWSTATE_DISABLED_LOGIC_OP, "DS",
3001                        "Invalid Pipeline CreateInfo: If logic operations feature not enabled, logicOpEnable must be VK_FALSE");
3002        }
3003        if ((pPipeline->graphicsPipelineCI.pColorBlendState->logicOpEnable == VK_TRUE) &&
3004            ((pPipeline->graphicsPipelineCI.pColorBlendState->logicOp < VK_LOGIC_OP_CLEAR) ||
3005             (pPipeline->graphicsPipelineCI.pColorBlendState->logicOp > VK_LOGIC_OP_SET))) {
3006            skipCall |=
3007                log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
3008                        DRAWSTATE_INVALID_LOGIC_OP, "DS",
3009                        "Invalid Pipeline CreateInfo: If logicOpEnable is VK_TRUE, logicOp must be a valid VkLogicOp value");
3010        }
3011    }
3012
3013    // Ensure the subpass index is valid. If not, then validate_and_capture_pipeline_shader_state
3014    // produces nonsense errors that confuse users. Other layers should already
3015    // emit errors for renderpass being invalid.
3016    auto rp_data = my_data->renderPassMap.find(pPipeline->graphicsPipelineCI.renderPass);
3017    if (rp_data != my_data->renderPassMap.end() &&
3018        pPipeline->graphicsPipelineCI.subpass >= rp_data->second->pCreateInfo->subpassCount) {
3019        skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
3020                            DRAWSTATE_INVALID_PIPELINE_CREATE_STATE, "DS", "Invalid Pipeline CreateInfo State: Subpass index %u "
3021                                                                           "is out of range for this renderpass (0..%u)",
3022                            pPipeline->graphicsPipelineCI.subpass, rp_data->second->pCreateInfo->subpassCount - 1);
3023    }
3024
3025    if (!validate_and_capture_pipeline_shader_state(my_data, pPipeline)) {
3026        skipCall = true;
3027    }
3028    // Each shader's stage must be unique
3029    if (pPipeline->duplicate_shaders) {
3030        for (uint32_t stage = VK_SHADER_STAGE_VERTEX_BIT; stage & VK_SHADER_STAGE_ALL_GRAPHICS; stage <<= 1) {
3031            if (pPipeline->duplicate_shaders & stage) {
3032                skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VkDebugReportObjectTypeEXT(0), 0,
3033                                    __LINE__, DRAWSTATE_INVALID_PIPELINE_CREATE_STATE, "DS",
3034                                    "Invalid Pipeline CreateInfo State: Multiple shaders provided for stage %s",
3035                                    string_VkShaderStageFlagBits(VkShaderStageFlagBits(stage)));
3036            }
3037        }
3038    }
3039    // VS is required
3040    if (!(pPipeline->active_shaders & VK_SHADER_STAGE_VERTEX_BIT)) {
3041        skipCall |=
3042            log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
3043                    DRAWSTATE_INVALID_PIPELINE_CREATE_STATE, "DS", "Invalid Pipeline CreateInfo State: Vtx Shader required");
3044    }
3045    // Either both or neither TC/TE shaders should be defined
3046    if (((pPipeline->active_shaders & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT) == 0) !=
3047        ((pPipeline->active_shaders & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) == 0)) {
3048        skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
3049                            DRAWSTATE_INVALID_PIPELINE_CREATE_STATE, "DS",
3050                            "Invalid Pipeline CreateInfo State: TE and TC shaders must be included or excluded as a pair");
3051    }
3052    // Compute shaders should be specified independent of Gfx shaders
3053    if ((pPipeline->active_shaders & VK_SHADER_STAGE_COMPUTE_BIT) &&
3054        (pPipeline->active_shaders &
3055         (VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT |
3056          VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT))) {
3057        skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
3058                            DRAWSTATE_INVALID_PIPELINE_CREATE_STATE, "DS",
3059                            "Invalid Pipeline CreateInfo State: Do not specify Compute Shader for Gfx Pipeline");
3060    }
3061    // VK_PRIMITIVE_TOPOLOGY_PATCH_LIST primitive topology is only valid for tessellation pipelines.
3062    // Mismatching primitive topology and tessellation fails graphics pipeline creation.
3063    if (pPipeline->active_shaders & (VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) &&
3064        (!pPipeline->graphicsPipelineCI.pInputAssemblyState ||
3065         pPipeline->graphicsPipelineCI.pInputAssemblyState->topology != VK_PRIMITIVE_TOPOLOGY_PATCH_LIST)) {
3066        skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
3067                            DRAWSTATE_INVALID_PIPELINE_CREATE_STATE, "DS", "Invalid Pipeline CreateInfo State: "
3068                                                                           "VK_PRIMITIVE_TOPOLOGY_PATCH_LIST must be set as IA "
3069                                                                           "topology for tessellation pipelines");
3070    }
3071    if (pPipeline->graphicsPipelineCI.pInputAssemblyState &&
3072        pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_PATCH_LIST) {
3073        if (~pPipeline->active_shaders & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT) {
3074            skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
3075                                DRAWSTATE_INVALID_PIPELINE_CREATE_STATE, "DS", "Invalid Pipeline CreateInfo State: "
3076                                                                               "VK_PRIMITIVE_TOPOLOGY_PATCH_LIST primitive "
3077                                                                               "topology is only valid for tessellation pipelines");
3078        }
3079        if (!pPipeline->graphicsPipelineCI.pTessellationState) {
3080            skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
3081                                DRAWSTATE_INVALID_PIPELINE_CREATE_STATE, "DS",
3082                                "Invalid Pipeline CreateInfo State: "
3083                                "pTessellationState is NULL when VK_PRIMITIVE_TOPOLOGY_PATCH_LIST primitive "
3084                                "topology used. pTessellationState must not be NULL in this case.");
3085        } else if (!pPipeline->graphicsPipelineCI.pTessellationState->patchControlPoints ||
3086                   (pPipeline->graphicsPipelineCI.pTessellationState->patchControlPoints > 32)) {
3087            skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
3088                                DRAWSTATE_INVALID_PIPELINE_CREATE_STATE, "DS", "Invalid Pipeline CreateInfo State: "
3089                                                                               "VK_PRIMITIVE_TOPOLOGY_PATCH_LIST primitive "
3090                                                                               "topology used with patchControlPoints value %u."
3091                                                                               " patchControlPoints should be >0 and <=32.",
3092                                pPipeline->graphicsPipelineCI.pTessellationState->patchControlPoints);
3093        }
3094    }
3095    // Viewport state must be included if rasterization is enabled.
3096    // If the viewport state is included, the viewport and scissor counts should always match.
3097    // NOTE : Even if these are flagged as dynamic, counts need to be set correctly for shader compiler
3098    if (!pPipeline->graphicsPipelineCI.pRasterizationState ||
3099        (pPipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable == VK_FALSE)) {
3100        if (!pPipeline->graphicsPipelineCI.pViewportState) {
3101            skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
3102                                DRAWSTATE_VIEWPORT_SCISSOR_MISMATCH, "DS", "Gfx Pipeline pViewportState is null. Even if viewport "
3103                                                                           "and scissors are dynamic PSO must include "
3104                                                                           "viewportCount and scissorCount in pViewportState.");
3105        } else if (pPipeline->graphicsPipelineCI.pViewportState->scissorCount !=
3106                   pPipeline->graphicsPipelineCI.pViewportState->viewportCount) {
3107            skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
3108                                DRAWSTATE_VIEWPORT_SCISSOR_MISMATCH, "DS",
3109                                "Gfx Pipeline viewport count (%u) must match scissor count (%u).",
3110                                pPipeline->graphicsPipelineCI.pViewportState->viewportCount,
3111                                pPipeline->graphicsPipelineCI.pViewportState->scissorCount);
3112        } else {
3113            // If viewport or scissor are not dynamic, then verify that data is appropriate for count
3114            bool dynViewport = isDynamic(pPipeline, VK_DYNAMIC_STATE_VIEWPORT);
3115            bool dynScissor = isDynamic(pPipeline, VK_DYNAMIC_STATE_SCISSOR);
3116            if (!dynViewport) {
3117                if (pPipeline->graphicsPipelineCI.pViewportState->viewportCount &&
3118                    !pPipeline->graphicsPipelineCI.pViewportState->pViewports) {
3119                    skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
3120                                        __LINE__, DRAWSTATE_VIEWPORT_SCISSOR_MISMATCH, "DS",
3121                                        "Gfx Pipeline viewportCount is %u, but pViewports is NULL. For non-zero viewportCount, you "
3122                                        "must either include pViewports data, or include viewport in pDynamicState and set it with "
3123                                        "vkCmdSetViewport().",
3124                                        pPipeline->graphicsPipelineCI.pViewportState->viewportCount);
3125                }
3126            }
3127            if (!dynScissor) {
3128                if (pPipeline->graphicsPipelineCI.pViewportState->scissorCount &&
3129                    !pPipeline->graphicsPipelineCI.pViewportState->pScissors) {
3130                    skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
3131                                        __LINE__, DRAWSTATE_VIEWPORT_SCISSOR_MISMATCH, "DS",
3132                                        "Gfx Pipeline scissorCount is %u, but pScissors is NULL. For non-zero scissorCount, you "
3133                                        "must either include pScissors data, or include scissor in pDynamicState and set it with "
3134                                        "vkCmdSetScissor().",
3135                                        pPipeline->graphicsPipelineCI.pViewportState->scissorCount);
3136                }
3137            }
3138        }
3139    }
3140    return skipCall;
3141}
3142
3143// Free the Pipeline nodes
3144static void deletePipelines(layer_data *my_data) {
3145    if (my_data->pipelineMap.size() <= 0)
3146        return;
3147    for (auto &pipe_map_pair : my_data->pipelineMap) {
3148        delete pipe_map_pair.second;
3149    }
3150    my_data->pipelineMap.clear();
3151}
3152
3153// For given pipeline, return number of MSAA samples, or one if MSAA disabled
3154static VkSampleCountFlagBits getNumSamples(layer_data *my_data, const VkPipeline pipeline) {
3155    PIPELINE_NODE *pPipe = my_data->pipelineMap[pipeline];
3156    if (pPipe->graphicsPipelineCI.pMultisampleState &&
3157        (VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO == pPipe->graphicsPipelineCI.pMultisampleState->sType)) {
3158        return pPipe->graphicsPipelineCI.pMultisampleState->rasterizationSamples;
3159    }
3160    return VK_SAMPLE_COUNT_1_BIT;
3161}
3162
3163// Validate state related to the PSO
3164static bool validatePipelineState(layer_data *my_data, const GLOBAL_CB_NODE *pCB, const VkPipelineBindPoint pipelineBindPoint,
3165                                  const VkPipeline pipeline) {
3166    bool skipCall = false;
3167    if (VK_PIPELINE_BIND_POINT_GRAPHICS == pipelineBindPoint) {
3168        // Verify that any MSAA request in PSO matches sample# in bound FB
3169        // Skip the check if rasterization is disabled.
3170        PIPELINE_NODE *pPipeline = my_data->pipelineMap[pipeline];
3171        if (!pPipeline->graphicsPipelineCI.pRasterizationState ||
3172            (pPipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable == VK_FALSE)) {
3173            VkSampleCountFlagBits psoNumSamples = getNumSamples(my_data, pipeline);
3174            if (pCB->activeRenderPass) {
3175                const VkRenderPassCreateInfo *pRPCI = my_data->renderPassMap[pCB->activeRenderPass]->pCreateInfo;
3176                const VkSubpassDescription *pSD = &pRPCI->pSubpasses[pCB->activeSubpass];
3177                VkSampleCountFlagBits subpassNumSamples = (VkSampleCountFlagBits)0;
3178                uint32_t i;
3179
3180                for (i = 0; i < pSD->colorAttachmentCount; i++) {
3181                    VkSampleCountFlagBits samples;
3182
3183                    if (pSD->pColorAttachments[i].attachment == VK_ATTACHMENT_UNUSED)
3184                        continue;
3185
3186                    samples = pRPCI->pAttachments[pSD->pColorAttachments[i].attachment].samples;
3187                    if (subpassNumSamples == (VkSampleCountFlagBits)0) {
3188                        subpassNumSamples = samples;
3189                    } else if (subpassNumSamples != samples) {
3190                        subpassNumSamples = (VkSampleCountFlagBits)-1;
3191                        break;
3192                    }
3193                }
3194                if (pSD->pDepthStencilAttachment && pSD->pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
3195                    const VkSampleCountFlagBits samples = pRPCI->pAttachments[pSD->pDepthStencilAttachment->attachment].samples;
3196                    if (subpassNumSamples == (VkSampleCountFlagBits)0)
3197                        subpassNumSamples = samples;
3198                    else if (subpassNumSamples != samples)
3199                        subpassNumSamples = (VkSampleCountFlagBits)-1;
3200                }
3201
3202                if ((pSD->colorAttachmentCount > 0 || pSD->pDepthStencilAttachment) &&
3203                    psoNumSamples != subpassNumSamples) {
3204                    skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
3205                                        (uint64_t)pipeline, __LINE__, DRAWSTATE_NUM_SAMPLES_MISMATCH, "DS",
3206                                        "Num samples mismatch! Binding PSO (%#" PRIxLEAST64
3207                                        ") with %u samples while current RenderPass (%#" PRIxLEAST64 ") w/ %u samples!",
3208                                        (uint64_t)pipeline, psoNumSamples, (uint64_t)pCB->activeRenderPass, subpassNumSamples);
3209                }
3210            } else {
3211                // TODO : I believe it's an error if we reach this point and don't have an activeRenderPass
3212                //   Verify and flag error as appropriate
3213            }
3214        }
3215        // TODO : Add more checks here
3216    } else {
3217        // TODO : Validate non-gfx pipeline updates
3218    }
3219    return skipCall;
3220}
3221
3222// Block of code at start here specifically for managing/tracking DSs
3223
3224// Return Pool node ptr for specified pool or else NULL
3225static DESCRIPTOR_POOL_NODE *getPoolNode(layer_data *my_data, const VkDescriptorPool pool) {
3226    if (my_data->descriptorPoolMap.find(pool) == my_data->descriptorPoolMap.end()) {
3227        return NULL;
3228    }
3229    return my_data->descriptorPoolMap[pool];
3230}
3231
3232static LAYOUT_NODE *getLayoutNode(layer_data *my_data, const VkDescriptorSetLayout layout) {
3233    if (my_data->descriptorSetLayoutMap.find(layout) == my_data->descriptorSetLayoutMap.end()) {
3234        return NULL;
3235    }
3236    return my_data->descriptorSetLayoutMap[layout];
3237}
3238
3239// Return false if update struct is of valid type, otherwise flag error and return code from callback
3240static bool validUpdateStruct(layer_data *my_data, const VkDevice device, const GENERIC_HEADER *pUpdateStruct) {
3241    switch (pUpdateStruct->sType) {
3242    case VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET:
3243    case VK_STRUCTURE_TYPE_COPY_DESCRIPTOR_SET:
3244        return false;
3245    default:
3246        return log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
3247                       DRAWSTATE_INVALID_UPDATE_STRUCT, "DS",
3248                       "Unexpected UPDATE struct of type %s (value %u) in vkUpdateDescriptors() struct tree",
3249                       string_VkStructureType(pUpdateStruct->sType), pUpdateStruct->sType);
3250    }
3251}
3252
3253// Set count for given update struct in the last parameter
3254static uint32_t getUpdateCount(layer_data *my_data, const VkDevice device, const GENERIC_HEADER *pUpdateStruct) {
3255    switch (pUpdateStruct->sType) {
3256    case VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET:
3257        return ((VkWriteDescriptorSet *)pUpdateStruct)->descriptorCount;
3258    case VK_STRUCTURE_TYPE_COPY_DESCRIPTOR_SET:
3259        // TODO : Need to understand this case better and make sure code is correct
3260        return ((VkCopyDescriptorSet *)pUpdateStruct)->descriptorCount;
3261    default:
3262        return 0;
3263    }
3264}
3265
3266// For given layout and update, return the first overall index of the layout that is updated
3267static uint32_t getUpdateStartIndex(layer_data *my_data, const VkDevice device, const LAYOUT_NODE *pLayout, const uint32_t binding,
3268                                    const uint32_t arrayIndex, const GENERIC_HEADER *pUpdateStruct) {
3269    return getBindingStartIndex(pLayout, binding) + arrayIndex;
3270}
3271
3272// For given layout and update, return the last overall index of the layout that is updated
3273static uint32_t getUpdateEndIndex(layer_data *my_data, const VkDevice device, const LAYOUT_NODE *pLayout, const uint32_t binding,
3274                                  const uint32_t arrayIndex, const GENERIC_HEADER *pUpdateStruct) {
3275    uint32_t count = getUpdateCount(my_data, device, pUpdateStruct);
3276    return getBindingStartIndex(pLayout, binding) + arrayIndex + count - 1;
3277}
3278
3279// Verify that the descriptor type in the update struct matches what's expected by the layout
3280static bool validateUpdateConsistency(layer_data *my_data, const VkDevice device, const LAYOUT_NODE *pLayout,
3281                                      const GENERIC_HEADER *pUpdateStruct, uint32_t startIndex, uint32_t endIndex) {
3282    // First get actual type of update
3283    bool skipCall = false;
3284    VkDescriptorType actualType = VK_DESCRIPTOR_TYPE_MAX_ENUM;
3285    uint32_t i = 0;
3286    switch (pUpdateStruct->sType) {
3287    case VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET:
3288        actualType = ((VkWriteDescriptorSet *)pUpdateStruct)->descriptorType;
3289        break;
3290    case VK_STRUCTURE_TYPE_COPY_DESCRIPTOR_SET:
3291        /* no need to validate */
3292        return false;
3293        break;
3294    default:
3295        skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
3296                            DRAWSTATE_INVALID_UPDATE_STRUCT, "DS",
3297                            "Unexpected UPDATE struct of type %s (value %u) in vkUpdateDescriptors() struct tree",
3298                            string_VkStructureType(pUpdateStruct->sType), pUpdateStruct->sType);
3299    }
3300    if (!skipCall) {
3301        // Set first stageFlags as reference and verify that all other updates match it
3302        VkShaderStageFlags refStageFlags = pLayout->stageFlags[startIndex];
3303        for (i = startIndex; i <= endIndex; i++) {
3304            if (pLayout->descriptorTypes[i] != actualType) {
3305                skipCall |= log_msg(
3306                    my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
3307                    DRAWSTATE_DESCRIPTOR_TYPE_MISMATCH, "DS",
3308                    "Write descriptor update has descriptor type %s that does not match overlapping binding descriptor type of %s!",
3309                    string_VkDescriptorType(actualType), string_VkDescriptorType(pLayout->descriptorTypes[i]));
3310            }
3311            if (pLayout->stageFlags[i] != refStageFlags) {
3312                skipCall |= log_msg(
3313                    my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
3314                    DRAWSTATE_DESCRIPTOR_STAGEFLAGS_MISMATCH, "DS",
3315                    "Write descriptor update has stageFlags %x that do not match overlapping binding descriptor stageFlags of %x!",
3316                    refStageFlags, pLayout->stageFlags[i]);
3317            }
3318        }
3319    }
3320    return skipCall;
3321}
3322
3323// Determine the update type, allocate a new struct of that type, shadow the given pUpdate
3324//   struct into the pNewNode param. Return true if error condition encountered and callback signals early exit.
3325// NOTE : Calls to this function should be wrapped in mutex
3326static bool shadowUpdateNode(layer_data *my_data, const VkDevice device, GENERIC_HEADER *pUpdate, GENERIC_HEADER **pNewNode) {
3327    bool skipCall = false;
3328    VkWriteDescriptorSet *pWDS = NULL;
3329    VkCopyDescriptorSet *pCDS = NULL;
3330    switch (pUpdate->sType) {
3331    case VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET:
3332        pWDS = new VkWriteDescriptorSet;
3333        *pNewNode = (GENERIC_HEADER *)pWDS;
3334        memcpy(pWDS, pUpdate, sizeof(VkWriteDescriptorSet));
3335
3336        switch (pWDS->descriptorType) {
3337        case VK_DESCRIPTOR_TYPE_SAMPLER:
3338        case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
3339        case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
3340        case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: {
3341            VkDescriptorImageInfo *info = new VkDescriptorImageInfo[pWDS->descriptorCount];
3342            memcpy(info, pWDS->pImageInfo, pWDS->descriptorCount * sizeof(VkDescriptorImageInfo));
3343            pWDS->pImageInfo = info;
3344        } break;
3345        case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
3346        case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: {
3347            VkBufferView *info = new VkBufferView[pWDS->descriptorCount];
3348            memcpy(info, pWDS->pTexelBufferView, pWDS->descriptorCount * sizeof(VkBufferView));
3349            pWDS->pTexelBufferView = info;
3350        } break;
3351        case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
3352        case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
3353        case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
3354        case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: {
3355            VkDescriptorBufferInfo *info = new VkDescriptorBufferInfo[pWDS->descriptorCount];
3356            memcpy(info, pWDS->pBufferInfo, pWDS->descriptorCount * sizeof(VkDescriptorBufferInfo));
3357            pWDS->pBufferInfo = info;
3358        } break;
3359        default:
3360            return true;
3361            break;
3362        }
3363        break;
3364    case VK_STRUCTURE_TYPE_COPY_DESCRIPTOR_SET:
3365        pCDS = new VkCopyDescriptorSet;
3366        *pNewNode = (GENERIC_HEADER *)pCDS;
3367        memcpy(pCDS, pUpdate, sizeof(VkCopyDescriptorSet));
3368        break;
3369    default:
3370        if (log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
3371                    DRAWSTATE_INVALID_UPDATE_STRUCT, "DS",
3372                    "Unexpected UPDATE struct of type %s (value %u) in vkUpdateDescriptors() struct tree",
3373                    string_VkStructureType(pUpdate->sType), pUpdate->sType))
3374            return true;
3375    }
3376    // Make sure that pNext for the end of shadow copy is NULL
3377    (*pNewNode)->pNext = NULL;
3378    return skipCall;
3379}
3380
3381// Verify that given sampler is valid
3382static bool validateSampler(const layer_data *my_data, const VkSampler *pSampler, const bool immutable) {
3383    bool skipCall = false;
3384    auto sampIt = my_data->sampleMap.find(*pSampler);
3385    if (sampIt == my_data->sampleMap.end()) {
3386        if (!immutable) {
3387            skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT,
3388                                (uint64_t)*pSampler, __LINE__, DRAWSTATE_SAMPLER_DESCRIPTOR_ERROR, "DS",
3389                                "vkUpdateDescriptorSets: Attempt to update descriptor with invalid sampler %#" PRIxLEAST64,
3390                                (uint64_t)*pSampler);
3391        } else { // immutable
3392            skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT,
3393                                (uint64_t)*pSampler, __LINE__, DRAWSTATE_SAMPLER_DESCRIPTOR_ERROR, "DS",
3394                                "vkUpdateDescriptorSets: Attempt to update descriptor whose binding has an invalid immutable "
3395                                "sampler %#" PRIxLEAST64,
3396                                (uint64_t)*pSampler);
3397        }
3398    } else {
3399        // TODO : Any further checks we want to do on the sampler?
3400    }
3401    return skipCall;
3402}
3403
3404//TODO: Consolidate functions
3405bool FindLayout(const GLOBAL_CB_NODE *pCB, ImageSubresourcePair imgpair, IMAGE_CMD_BUF_LAYOUT_NODE &node, const VkImageAspectFlags aspectMask) {
3406    layer_data *my_data = get_my_data_ptr(get_dispatch_key(pCB->commandBuffer), layer_data_map);
3407    if (!(imgpair.subresource.aspectMask & aspectMask)) {
3408        return false;
3409    }
3410    VkImageAspectFlags oldAspectMask = imgpair.subresource.aspectMask;
3411    imgpair.subresource.aspectMask = aspectMask;
3412    auto imgsubIt = pCB->imageLayoutMap.find(imgpair);
3413    if (imgsubIt == pCB->imageLayoutMap.end()) {
3414        return false;
3415    }
3416    if (node.layout != VK_IMAGE_LAYOUT_MAX_ENUM && node.layout != imgsubIt->second.layout) {
3417        log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
3418                reinterpret_cast<uint64_t&>(imgpair.image), __LINE__, DRAWSTATE_INVALID_LAYOUT, "DS",
3419                "Cannot query for VkImage 0x%" PRIx64 " layout when combined aspect mask %d has multiple layout types: %s and %s",
3420                reinterpret_cast<uint64_t&>(imgpair.image), oldAspectMask, string_VkImageLayout(node.layout), string_VkImageLayout(imgsubIt->second.layout));
3421    }
3422    if (node.initialLayout != VK_IMAGE_LAYOUT_MAX_ENUM && node.initialLayout != imgsubIt->second.initialLayout) {
3423        log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
3424                reinterpret_cast<uint64_t&>(imgpair.image), __LINE__, DRAWSTATE_INVALID_LAYOUT, "DS",
3425                "Cannot query for VkImage 0x%" PRIx64 " layout when combined aspect mask %d has multiple initial layout types: %s and %s",
3426                reinterpret_cast<uint64_t&>(imgpair.image), oldAspectMask, string_VkImageLayout(node.initialLayout), string_VkImageLayout(imgsubIt->second.initialLayout));
3427    }
3428    node = imgsubIt->second;
3429    return true;
3430}
3431
3432bool FindLayout(const layer_data *my_data, ImageSubresourcePair imgpair, VkImageLayout &layout, const VkImageAspectFlags aspectMask) {
3433    if (!(imgpair.subresource.aspectMask & aspectMask)) {
3434        return false;
3435    }
3436    VkImageAspectFlags oldAspectMask = imgpair.subresource.aspectMask;
3437    imgpair.subresource.aspectMask = aspectMask;
3438    auto imgsubIt = my_data->imageLayoutMap.find(imgpair);
3439    if (imgsubIt == my_data->imageLayoutMap.end()) {
3440        return false;
3441    }
3442    if (layout != VK_IMAGE_LAYOUT_MAX_ENUM && layout != imgsubIt->second.layout) {
3443        log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
3444                reinterpret_cast<uint64_t&>(imgpair.image), __LINE__, DRAWSTATE_INVALID_LAYOUT, "DS",
3445                "Cannot query for VkImage 0x%" PRIx64 " layout when combined aspect mask %d has multiple layout types: %s and %s",
3446                reinterpret_cast<uint64_t&>(imgpair.image), oldAspectMask, string_VkImageLayout(layout), string_VkImageLayout(imgsubIt->second.layout));
3447    }
3448    layout = imgsubIt->second.layout;
3449    return true;
3450}
3451
3452// find layout(s) on the cmd buf level
3453bool FindLayout(const GLOBAL_CB_NODE *pCB, VkImage image, VkImageSubresource range, IMAGE_CMD_BUF_LAYOUT_NODE &node) {
3454    ImageSubresourcePair imgpair = {image, true, range};
3455    node = IMAGE_CMD_BUF_LAYOUT_NODE(VK_IMAGE_LAYOUT_MAX_ENUM, VK_IMAGE_LAYOUT_MAX_ENUM);
3456    FindLayout(pCB, imgpair, node, VK_IMAGE_ASPECT_COLOR_BIT);
3457    FindLayout(pCB, imgpair, node, VK_IMAGE_ASPECT_DEPTH_BIT);
3458    FindLayout(pCB, imgpair, node, VK_IMAGE_ASPECT_STENCIL_BIT);
3459    FindLayout(pCB, imgpair, node, VK_IMAGE_ASPECT_METADATA_BIT);
3460    if (node.layout == VK_IMAGE_LAYOUT_MAX_ENUM) {
3461        imgpair = {image, false, VkImageSubresource()};
3462        auto imgsubIt = pCB->imageLayoutMap.find(imgpair);
3463        if (imgsubIt == pCB->imageLayoutMap.end())
3464            return false;
3465        node = imgsubIt->second;
3466    }
3467    return true;
3468}
3469
3470// find layout(s) on the global level
3471bool FindLayout(const layer_data *my_data, ImageSubresourcePair imgpair, VkImageLayout &layout) {
3472    layout = VK_IMAGE_LAYOUT_MAX_ENUM;
3473    FindLayout(my_data, imgpair, layout, VK_IMAGE_ASPECT_COLOR_BIT);
3474    FindLayout(my_data, imgpair, layout, VK_IMAGE_ASPECT_DEPTH_BIT);
3475    FindLayout(my_data, imgpair, layout, VK_IMAGE_ASPECT_STENCIL_BIT);
3476    FindLayout(my_data, imgpair, layout, VK_IMAGE_ASPECT_METADATA_BIT);
3477    if (layout == VK_IMAGE_LAYOUT_MAX_ENUM) {
3478        imgpair = {imgpair.image, false, VkImageSubresource()};
3479        auto imgsubIt = my_data->imageLayoutMap.find(imgpair);
3480        if (imgsubIt == my_data->imageLayoutMap.end())
3481            return false;
3482        layout = imgsubIt->second.layout;
3483    }
3484    return true;
3485}
3486
3487bool FindLayout(const layer_data *my_data, VkImage image, VkImageSubresource range, VkImageLayout &layout) {
3488    ImageSubresourcePair imgpair = {image, true, range};
3489    return FindLayout(my_data, imgpair, layout);
3490}
3491
3492bool FindLayouts(const layer_data *my_data, VkImage image, std::vector<VkImageLayout> &layouts) {
3493    auto sub_data = my_data->imageSubresourceMap.find(image);
3494    if (sub_data == my_data->imageSubresourceMap.end())
3495        return false;
3496    auto imgIt = my_data->imageMap.find(image);
3497    if (imgIt == my_data->imageMap.end())
3498        return false;
3499    bool ignoreGlobal = false;
3500    // TODO: Make this robust for >1 aspect mask. Now it will just say ignore
3501    // potential errors in this case.
3502    if (sub_data->second.size() >= (imgIt->second.createInfo.arrayLayers * imgIt->second.createInfo.mipLevels + 1)) {
3503        ignoreGlobal = true;
3504    }
3505    for (auto imgsubpair : sub_data->second) {
3506        if (ignoreGlobal && !imgsubpair.hasSubresource)
3507            continue;
3508        auto img_data = my_data->imageLayoutMap.find(imgsubpair);
3509        if (img_data != my_data->imageLayoutMap.end()) {
3510            layouts.push_back(img_data->second.layout);
3511        }
3512    }
3513    return true;
3514}
3515
3516// Set the layout on the global level
3517void SetLayout(layer_data *my_data, ImageSubresourcePair imgpair, const VkImageLayout &layout) {
3518    VkImage &image = imgpair.image;
3519    // TODO (mlentine): Maybe set format if new? Not used atm.
3520    my_data->imageLayoutMap[imgpair].layout = layout;
3521    // TODO (mlentine): Maybe make vector a set?
3522    auto subresource = std::find(my_data->imageSubresourceMap[image].begin(), my_data->imageSubresourceMap[image].end(), imgpair);
3523    if (subresource == my_data->imageSubresourceMap[image].end()) {
3524        my_data->imageSubresourceMap[image].push_back(imgpair);
3525    }
3526}
3527
3528// Set the layout on the cmdbuf level
3529void SetLayout(GLOBAL_CB_NODE *pCB, ImageSubresourcePair imgpair, const IMAGE_CMD_BUF_LAYOUT_NODE &node) {
3530    pCB->imageLayoutMap[imgpair] = node;
3531    // TODO (mlentine): Maybe make vector a set?
3532    auto subresource =
3533        std::find(pCB->imageSubresourceMap[imgpair.image].begin(), pCB->imageSubresourceMap[imgpair.image].end(), imgpair);
3534    if (subresource == pCB->imageSubresourceMap[imgpair.image].end()) {
3535        pCB->imageSubresourceMap[imgpair.image].push_back(imgpair);
3536    }
3537}
3538
3539void SetLayout(GLOBAL_CB_NODE *pCB, ImageSubresourcePair imgpair, const VkImageLayout &layout) {
3540    // TODO (mlentine): Maybe make vector a set?
3541    if (std::find(pCB->imageSubresourceMap[imgpair.image].begin(), pCB->imageSubresourceMap[imgpair.image].end(), imgpair) !=
3542        pCB->imageSubresourceMap[imgpair.image].end()) {
3543        pCB->imageLayoutMap[imgpair].layout = layout;
3544    } else {
3545        // TODO (mlentine): Could be expensive and might need to be removed.
3546        assert(imgpair.hasSubresource);
3547        IMAGE_CMD_BUF_LAYOUT_NODE node;
3548        if (!FindLayout(pCB, imgpair.image, imgpair.subresource, node)) {
3549            node.initialLayout = layout;
3550        }
3551        SetLayout(pCB, imgpair, {node.initialLayout, layout});
3552    }
3553}
3554
3555template <class OBJECT, class LAYOUT>
3556void SetLayout(OBJECT *pObject, ImageSubresourcePair imgpair, const LAYOUT &layout, VkImageAspectFlags aspectMask) {
3557    if (imgpair.subresource.aspectMask & aspectMask) {
3558        imgpair.subresource.aspectMask = aspectMask;
3559        SetLayout(pObject, imgpair, layout);
3560    }
3561}
3562
3563template <class OBJECT, class LAYOUT>
3564void SetLayout(OBJECT *pObject, VkImage image, VkImageSubresource range, const LAYOUT &layout) {
3565    ImageSubresourcePair imgpair = {image, true, range};
3566    SetLayout(pObject, imgpair, layout, VK_IMAGE_ASPECT_COLOR_BIT);
3567    SetLayout(pObject, imgpair, layout, VK_IMAGE_ASPECT_DEPTH_BIT);
3568    SetLayout(pObject, imgpair, layout, VK_IMAGE_ASPECT_STENCIL_BIT);
3569    SetLayout(pObject, imgpair, layout, VK_IMAGE_ASPECT_METADATA_BIT);
3570}
3571
3572template <class OBJECT, class LAYOUT> void SetLayout(OBJECT *pObject, VkImage image, const LAYOUT &layout) {
3573    ImageSubresourcePair imgpair = {image, false, VkImageSubresource()};
3574    SetLayout(pObject, image, imgpair, layout);
3575}
3576
3577void SetLayout(const layer_data *dev_data, GLOBAL_CB_NODE *pCB, VkImageView imageView, const VkImageLayout &layout) {
3578    auto image_view_data = dev_data->imageViewMap.find(imageView);
3579    assert(image_view_data != dev_data->imageViewMap.end());
3580    const VkImage &image = image_view_data->second.image;
3581    const VkImageSubresourceRange &subRange = image_view_data->second.subresourceRange;
3582    // TODO: Do not iterate over every possibility - consolidate where possible
3583    for (uint32_t j = 0; j < subRange.levelCount; j++) {
3584        uint32_t level = subRange.baseMipLevel + j;
3585        for (uint32_t k = 0; k < subRange.layerCount; k++) {
3586            uint32_t layer = subRange.baseArrayLayer + k;
3587            VkImageSubresource sub = {subRange.aspectMask, level, layer};
3588            SetLayout(pCB, image, sub, layout);
3589        }
3590    }
3591}
3592
3593// Verify that given imageView is valid
3594static bool validateImageView(const layer_data *my_data, const VkImageView *pImageView, const VkImageLayout imageLayout) {
3595    bool skipCall = false;
3596    auto ivIt = my_data->imageViewMap.find(*pImageView);
3597    if (ivIt == my_data->imageViewMap.end()) {
3598        skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT,
3599                            (uint64_t)*pImageView, __LINE__, DRAWSTATE_IMAGEVIEW_DESCRIPTOR_ERROR, "DS",
3600                            "vkUpdateDescriptorSets: Attempt to update descriptor with invalid imageView %#" PRIxLEAST64,
3601                            (uint64_t)*pImageView);
3602    } else {
3603        // Validate that imageLayout is compatible with aspectMask and image format
3604        VkImageAspectFlags aspectMask = ivIt->second.subresourceRange.aspectMask;
3605        VkImage image = ivIt->second.image;
3606        // TODO : Check here in case we have a bad image
3607        VkFormat format = VK_FORMAT_MAX_ENUM;
3608        auto imgIt = my_data->imageMap.find(image);
3609        if (imgIt != my_data->imageMap.end()) {
3610            format = (*imgIt).second.createInfo.format;
3611        } else {
3612            // Also need to check the swapchains.
3613            auto swapchainIt = my_data->device_extensions.imageToSwapchainMap.find(image);
3614            if (swapchainIt != my_data->device_extensions.imageToSwapchainMap.end()) {
3615                VkSwapchainKHR swapchain = swapchainIt->second;
3616                auto swapchain_nodeIt = my_data->device_extensions.swapchainMap.find(swapchain);
3617                if (swapchain_nodeIt != my_data->device_extensions.swapchainMap.end()) {
3618                    SWAPCHAIN_NODE *pswapchain_node = swapchain_nodeIt->second;
3619                    format = pswapchain_node->createInfo.imageFormat;
3620                }
3621            }
3622        }
3623        if (format == VK_FORMAT_MAX_ENUM) {
3624            skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
3625                                (uint64_t)image, __LINE__, DRAWSTATE_IMAGEVIEW_DESCRIPTOR_ERROR, "DS",
3626                                "vkUpdateDescriptorSets: Attempt to update descriptor with invalid image %#" PRIxLEAST64
3627                                " in imageView %#" PRIxLEAST64,
3628                                (uint64_t)image, (uint64_t)*pImageView);
3629        } else {
3630            bool ds = vk_format_is_depth_or_stencil(format);
3631            switch (imageLayout) {
3632            case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
3633                // Only Color bit must be set
3634                if ((aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) != VK_IMAGE_ASPECT_COLOR_BIT) {
3635                    skipCall |=
3636                        log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT,
3637                                (uint64_t)*pImageView, __LINE__, DRAWSTATE_INVALID_IMAGE_ASPECT, "DS",
3638                                "vkUpdateDescriptorSets: Updating descriptor with layout VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL "
3639                                "and imageView %#" PRIxLEAST64 ""
3640                                " that does not have VK_IMAGE_ASPECT_COLOR_BIT set.",
3641                                (uint64_t)*pImageView);
3642                }
3643                // format must NOT be DS
3644                if (ds) {
3645                    skipCall |=
3646                        log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT,
3647                                (uint64_t)*pImageView, __LINE__, DRAWSTATE_IMAGEVIEW_DESCRIPTOR_ERROR, "DS",
3648                                "vkUpdateDescriptorSets: Updating descriptor with layout VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL "
3649                                "and imageView %#" PRIxLEAST64 ""
3650                                " but the image format is %s which is not a color format.",
3651                                (uint64_t)*pImageView, string_VkFormat(format));
3652                }
3653                break;
3654            case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
3655            case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL:
3656                // Depth or stencil bit must be set, but both must NOT be set
3657                if (aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
3658                    if (aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
3659                        // both  must NOT be set
3660                        skipCall |=
3661                            log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT,
3662                                    (uint64_t)*pImageView, __LINE__, DRAWSTATE_INVALID_IMAGE_ASPECT, "DS",
3663                                    "vkUpdateDescriptorSets: Updating descriptor with imageView %#" PRIxLEAST64 ""
3664                                    " that has both STENCIL and DEPTH aspects set",
3665                                    (uint64_t)*pImageView);
3666                    }
3667                } else if (!(aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT)) {
3668                    // Neither were set
3669                    skipCall |=
3670                        log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT,
3671                                (uint64_t)*pImageView, __LINE__, DRAWSTATE_INVALID_IMAGE_ASPECT, "DS",
3672                                "vkUpdateDescriptorSets: Updating descriptor with layout %s and imageView %#" PRIxLEAST64 ""
3673                                " that does not have STENCIL or DEPTH aspect set.",
3674                                string_VkImageLayout(imageLayout), (uint64_t)*pImageView);
3675                }
3676                // format must be DS
3677                if (!ds) {
3678                    skipCall |=
3679                        log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT,
3680                                (uint64_t)*pImageView, __LINE__, DRAWSTATE_IMAGEVIEW_DESCRIPTOR_ERROR, "DS",
3681                                "vkUpdateDescriptorSets: Updating descriptor with layout %s and imageView %#" PRIxLEAST64 ""
3682                                " but the image format is %s which is not a depth/stencil format.",
3683                                string_VkImageLayout(imageLayout), (uint64_t)*pImageView, string_VkFormat(format));
3684                }
3685                break;
3686            default:
3687                // anything to check for other layouts?
3688                break;
3689            }
3690        }
3691    }
3692    return skipCall;
3693}
3694
3695// Verify that given bufferView is valid
3696static bool validateBufferView(const layer_data *my_data, const VkBufferView *pBufferView) {
3697    bool skipCall = false;
3698    auto sampIt = my_data->bufferViewMap.find(*pBufferView);
3699    if (sampIt == my_data->bufferViewMap.end()) {
3700        skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_VIEW_EXT,
3701                            (uint64_t)*pBufferView, __LINE__, DRAWSTATE_BUFFERVIEW_DESCRIPTOR_ERROR, "DS",
3702                            "vkUpdateDescriptorSets: Attempt to update descriptor with invalid bufferView %#" PRIxLEAST64,
3703                            (uint64_t)*pBufferView);
3704    } else {
3705        // TODO : Any further checks we want to do on the bufferView?
3706    }
3707    return skipCall;
3708}
3709
3710// Verify that given bufferInfo is valid
3711static bool validateBufferInfo(const layer_data *my_data, const VkDescriptorBufferInfo *pBufferInfo) {
3712    bool skipCall = false;
3713    auto sampIt = my_data->bufferMap.find(pBufferInfo->buffer);
3714    if (sampIt == my_data->bufferMap.end()) {
3715        skipCall |=
3716            log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
3717                    (uint64_t)pBufferInfo->buffer, __LINE__, DRAWSTATE_BUFFERINFO_DESCRIPTOR_ERROR, "DS",
3718                    "vkUpdateDescriptorSets: Attempt to update descriptor where bufferInfo has invalid buffer %#" PRIxLEAST64,
3719                    (uint64_t)pBufferInfo->buffer);
3720    } else {
3721        // TODO : Any further checks we want to do on the bufferView?
3722    }
3723    return skipCall;
3724}
3725
3726static bool validateUpdateContents(const layer_data *my_data, const VkWriteDescriptorSet *pWDS,
3727                                   const VkDescriptorSetLayoutBinding *pLayoutBinding) {
3728    bool skipCall = false;
3729    // First verify that for the given Descriptor type, the correct DescriptorInfo data is supplied
3730    const VkSampler *pSampler = NULL;
3731    bool immutable = false;
3732    uint32_t i = 0;
3733    // For given update type, verify that update contents are correct
3734    switch (pWDS->descriptorType) {
3735    case VK_DESCRIPTOR_TYPE_SAMPLER:
3736        for (i = 0; i < pWDS->descriptorCount; ++i) {
3737            skipCall |= validateSampler(my_data, &(pWDS->pImageInfo[i].sampler), immutable);
3738        }
3739        break;
3740    case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
3741        for (i = 0; i < pWDS->descriptorCount; ++i) {
3742            if (NULL == pLayoutBinding->pImmutableSamplers) {
3743                pSampler = &(pWDS->pImageInfo[i].sampler);
3744                if (immutable) {
3745                    skipCall |= log_msg(
3746                        my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT,
3747                        (uint64_t)*pSampler, __LINE__, DRAWSTATE_INCONSISTENT_IMMUTABLE_SAMPLER_UPDATE, "DS",
3748                        "vkUpdateDescriptorSets: Update #%u is not an immutable sampler %#" PRIxLEAST64
3749                        ", but previous update(s) from this "
3750                        "VkWriteDescriptorSet struct used an immutable sampler. All updates from a single struct must either "
3751                        "use immutable or non-immutable samplers.",
3752                        i, (uint64_t)*pSampler);
3753                }
3754            } else {
3755                if (i > 0 && !immutable) {
3756                    skipCall |= log_msg(
3757                        my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT,
3758                        (uint64_t)*pSampler, __LINE__, DRAWSTATE_INCONSISTENT_IMMUTABLE_SAMPLER_UPDATE, "DS",
3759                        "vkUpdateDescriptorSets: Update #%u is an immutable sampler, but previous update(s) from this "
3760                        "VkWriteDescriptorSet struct used a non-immutable sampler. All updates from a single struct must either "
3761                        "use immutable or non-immutable samplers.",
3762                        i);
3763                }
3764                immutable = true;
3765                pSampler = &(pLayoutBinding->pImmutableSamplers[i]);
3766            }
3767            skipCall |= validateSampler(my_data, pSampler, immutable);
3768        }
3769    // Intentionally fall through here to also validate image stuff
3770    case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
3771    case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
3772    case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
3773        for (i = 0; i < pWDS->descriptorCount; ++i) {
3774            skipCall |= validateImageView(my_data, &(pWDS->pImageInfo[i].imageView), pWDS->pImageInfo[i].imageLayout);
3775        }
3776        break;
3777    case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
3778    case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
3779        for (i = 0; i < pWDS->descriptorCount; ++i) {
3780            skipCall |= validateBufferView(my_data, &(pWDS->pTexelBufferView[i]));
3781        }
3782        break;
3783    case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
3784    case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
3785    case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
3786    case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
3787        for (i = 0; i < pWDS->descriptorCount; ++i) {
3788            skipCall |= validateBufferInfo(my_data, &(pWDS->pBufferInfo[i]));
3789        }
3790        break;
3791    default:
3792        break;
3793    }
3794    return skipCall;
3795}
3796// Validate that given set is valid and that it's not being used by an in-flight CmdBuffer
3797// func_str is the name of the calling function
3798// Return false if no errors occur
3799// Return true if validation error occurs and callback returns true (to skip upcoming API call down the chain)
3800static bool validateIdleDescriptorSet(const layer_data *my_data, VkDescriptorSet set, std::string func_str) {
3801    bool skip_call = false;
3802    auto set_node = my_data->setMap.find(set);
3803    if (set_node == my_data->setMap.end()) {
3804        skip_call |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
3805                             (uint64_t)(set), __LINE__, DRAWSTATE_DOUBLE_DESTROY, "DS",
3806                             "Cannot call %s() on descriptor set %" PRIxLEAST64 " that has not been allocated.", func_str.c_str(),
3807                             (uint64_t)(set));
3808    } else {
3809        if (set_node->second->in_use.load()) {
3810            skip_call |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
3811                                 VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, (uint64_t)(set), __LINE__, DRAWSTATE_OBJECT_INUSE,
3812                                 "DS", "Cannot call %s() on descriptor set %" PRIxLEAST64 " that is in use by a command buffer.",
3813                                 func_str.c_str(), (uint64_t)(set));
3814        }
3815    }
3816    return skip_call;
3817}
3818static void invalidateBoundCmdBuffers(layer_data *dev_data, const SET_NODE *pSet) {
3819    // Flag any CBs this set is bound to as INVALID
3820    for (auto cb : pSet->boundCmdBuffers) {
3821        auto cb_node = dev_data->commandBufferMap.find(cb);
3822        if (cb_node != dev_data->commandBufferMap.end()) {
3823            cb_node->second->state = CB_INVALID;
3824        }
3825    }
3826}
3827// update DS mappings based on write and copy update arrays
3828static bool dsUpdate(layer_data *my_data, VkDevice device, uint32_t descriptorWriteCount, const VkWriteDescriptorSet *pWDS,
3829                     uint32_t descriptorCopyCount, const VkCopyDescriptorSet *pCDS) {
3830    bool skipCall = false;
3831
3832    LAYOUT_NODE *pLayout = NULL;
3833    VkDescriptorSetLayoutCreateInfo *pLayoutCI = NULL;
3834    // Validate Write updates
3835    uint32_t i = 0;
3836    for (i = 0; i < descriptorWriteCount; i++) {
3837        VkDescriptorSet ds = pWDS[i].dstSet;
3838        SET_NODE *pSet = my_data->setMap[ds];
3839        // Set being updated cannot be in-flight
3840        if ((skipCall = validateIdleDescriptorSet(my_data, ds, "VkUpdateDescriptorSets")) == true)
3841            return skipCall;
3842        // If set is bound to any cmdBuffers, mark them invalid
3843        invalidateBoundCmdBuffers(my_data, pSet);
3844        GENERIC_HEADER *pUpdate = (GENERIC_HEADER *)&pWDS[i];
3845        pLayout = pSet->pLayout;
3846        // First verify valid update struct
3847        if ((skipCall = validUpdateStruct(my_data, device, pUpdate)) == true) {
3848            break;
3849        }
3850        uint32_t binding = 0, endIndex = 0;
3851        binding = pWDS[i].dstBinding;
3852        auto bindingToIndex = pLayout->bindingToIndexMap.find(binding);
3853        // Make sure that layout being updated has the binding being updated
3854        if (bindingToIndex == pLayout->bindingToIndexMap.end()) {
3855            skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
3856                                (uint64_t)(ds), __LINE__, DRAWSTATE_INVALID_UPDATE_INDEX, "DS",
3857                                "Descriptor Set %" PRIu64 " does not have binding to match "
3858                                "update binding %u for update type "
3859                                "%s!",
3860                                (uint64_t)(ds), binding, string_VkStructureType(pUpdate->sType));
3861        } else {
3862            // Next verify that update falls within size of given binding
3863            endIndex = getUpdateEndIndex(my_data, device, pLayout, binding, pWDS[i].dstArrayElement, pUpdate);
3864            if (getBindingEndIndex(pLayout, binding) < endIndex) {
3865                pLayoutCI = &pLayout->createInfo;
3866                string DSstr = vk_print_vkdescriptorsetlayoutcreateinfo(pLayoutCI, "{DS}    ");
3867                skipCall |=
3868                    log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
3869                            (uint64_t)(ds), __LINE__, DRAWSTATE_DESCRIPTOR_UPDATE_OUT_OF_BOUNDS, "DS",
3870                            "Descriptor update type of %s is out of bounds for matching binding %u in Layout w/ CI:\n%s!",
3871                            string_VkStructureType(pUpdate->sType), binding, DSstr.c_str());
3872            } else { // TODO : should we skip update on a type mismatch or force it?
3873                uint32_t startIndex;
3874                startIndex = getUpdateStartIndex(my_data, device, pLayout, binding, pWDS[i].dstArrayElement, pUpdate);
3875                // Layout bindings match w/ update, now verify that update type
3876                // & stageFlags are the same for entire update
3877                if ((skipCall = validateUpdateConsistency(my_data, device, pLayout, pUpdate, startIndex, endIndex)) == false) {
3878                    // The update is within bounds and consistent, but need to
3879                    // make sure contents make sense as well
3880                    if ((skipCall = validateUpdateContents(my_data, &pWDS[i],
3881                                                           &pLayout->createInfo.pBindings[bindingToIndex->second])) == false) {
3882                        // Update is good. Save the update info
3883                        // Create new update struct for this set's shadow copy
3884                        GENERIC_HEADER *pNewNode = NULL;
3885                        skipCall |= shadowUpdateNode(my_data, device, pUpdate, &pNewNode);
3886                        if (NULL == pNewNode) {
3887                            skipCall |= log_msg(
3888                                my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
3889                                (uint64_t)(ds), __LINE__, DRAWSTATE_OUT_OF_MEMORY, "DS",
3890                                "Out of memory while attempting to allocate UPDATE struct in vkUpdateDescriptors()");
3891                        } else {
3892                            // Insert shadow node into LL of updates for this set
3893                            pNewNode->pNext = pSet->pUpdateStructs;
3894                            pSet->pUpdateStructs = pNewNode;
3895                            // Now update appropriate descriptor(s) to point to new Update node
3896                            for (uint32_t j = startIndex; j <= endIndex; j++) {
3897                                assert(j < pSet->descriptorCount);
3898                                pSet->pDescriptorUpdates[j] = pNewNode;
3899                            }
3900                        }
3901                    }
3902                }
3903            }
3904        }
3905    }
3906    // Now validate copy updates
3907    for (i = 0; i < descriptorCopyCount; ++i) {
3908        SET_NODE *pSrcSet = NULL, *pDstSet = NULL;
3909        LAYOUT_NODE *pSrcLayout = NULL, *pDstLayout = NULL;
3910        uint32_t srcStartIndex = 0, srcEndIndex = 0, dstStartIndex = 0, dstEndIndex = 0;
3911        // For each copy make sure that update falls within given layout and that types match
3912        pSrcSet = my_data->setMap[pCDS[i].srcSet];
3913        pDstSet = my_data->setMap[pCDS[i].dstSet];
3914        // Set being updated cannot be in-flight
3915        if ((skipCall = validateIdleDescriptorSet(my_data, pDstSet->set, "VkUpdateDescriptorSets")) == true)
3916            return skipCall;
3917        invalidateBoundCmdBuffers(my_data, pDstSet);
3918        pSrcLayout = pSrcSet->pLayout;
3919        pDstLayout = pDstSet->pLayout;
3920        // Validate that src binding is valid for src set layout
3921        if (pSrcLayout->bindingToIndexMap.find(pCDS[i].srcBinding) == pSrcLayout->bindingToIndexMap.end()) {
3922            skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
3923                                (uint64_t)pSrcSet->set, __LINE__, DRAWSTATE_INVALID_UPDATE_INDEX, "DS",
3924                                "Copy descriptor update %u has srcBinding %u "
3925                                "which is out of bounds for underlying SetLayout "
3926                                "%#" PRIxLEAST64 " which only has bindings 0-%u.",
3927                                i, pCDS[i].srcBinding, (uint64_t)pSrcLayout->layout, pSrcLayout->createInfo.bindingCount - 1);
3928        } else if (pDstLayout->bindingToIndexMap.find(pCDS[i].dstBinding) == pDstLayout->bindingToIndexMap.end()) {
3929            skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
3930                                (uint64_t)pDstSet->set, __LINE__, DRAWSTATE_INVALID_UPDATE_INDEX, "DS",
3931                                "Copy descriptor update %u has dstBinding %u "
3932                                "which is out of bounds for underlying SetLayout "
3933                                "%#" PRIxLEAST64 " which only has bindings 0-%u.",
3934                                i, pCDS[i].dstBinding, (uint64_t)pDstLayout->layout, pDstLayout->createInfo.bindingCount - 1);
3935        } else {
3936            // Proceed with validation. Bindings are ok, but make sure update is within bounds of given layout
3937            srcEndIndex = getUpdateEndIndex(my_data, device, pSrcLayout, pCDS[i].srcBinding, pCDS[i].srcArrayElement,
3938                                            (const GENERIC_HEADER *)&(pCDS[i]));
3939            dstEndIndex = getUpdateEndIndex(my_data, device, pDstLayout, pCDS[i].dstBinding, pCDS[i].dstArrayElement,
3940                                            (const GENERIC_HEADER *)&(pCDS[i]));
3941            if (getBindingEndIndex(pSrcLayout, pCDS[i].srcBinding) < srcEndIndex) {
3942                pLayoutCI = &pSrcLayout->createInfo;
3943                string DSstr = vk_print_vkdescriptorsetlayoutcreateinfo(pLayoutCI, "{DS}    ");
3944                skipCall |=
3945                    log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
3946                            (uint64_t)pSrcSet->set, __LINE__, DRAWSTATE_DESCRIPTOR_UPDATE_OUT_OF_BOUNDS, "DS",
3947                            "Copy descriptor src update is out of bounds for matching binding %u in Layout w/ CI:\n%s!",
3948                            pCDS[i].srcBinding, DSstr.c_str());
3949            } else if (getBindingEndIndex(pDstLayout, pCDS[i].dstBinding) < dstEndIndex) {
3950                pLayoutCI = &pDstLayout->createInfo;
3951                string DSstr = vk_print_vkdescriptorsetlayoutcreateinfo(pLayoutCI, "{DS}    ");
3952                skipCall |=
3953                    log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
3954                            (uint64_t)pDstSet->set, __LINE__, DRAWSTATE_DESCRIPTOR_UPDATE_OUT_OF_BOUNDS, "DS",
3955                            "Copy descriptor dest update is out of bounds for matching binding %u in Layout w/ CI:\n%s!",
3956                            pCDS[i].dstBinding, DSstr.c_str());
3957            } else {
3958                srcStartIndex = getUpdateStartIndex(my_data, device, pSrcLayout, pCDS[i].srcBinding, pCDS[i].srcArrayElement,
3959                                                    (const GENERIC_HEADER *)&(pCDS[i]));
3960                dstStartIndex = getUpdateStartIndex(my_data, device, pDstLayout, pCDS[i].dstBinding, pCDS[i].dstArrayElement,
3961                                                    (const GENERIC_HEADER *)&(pCDS[i]));
3962                for (uint32_t j = 0; j < pCDS[i].descriptorCount; ++j) {
3963                    // For copy just make sure that the types match and then perform the update
3964                    if (pSrcLayout->descriptorTypes[srcStartIndex + j] != pDstLayout->descriptorTypes[dstStartIndex + j]) {
3965                        skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
3966                                            __LINE__, DRAWSTATE_DESCRIPTOR_TYPE_MISMATCH, "DS",
3967                                            "Copy descriptor update index %u, update count #%u, has src update descriptor type %s "
3968                                            "that does not match overlapping dest descriptor type of %s!",
3969                                            i, j + 1, string_VkDescriptorType(pSrcLayout->descriptorTypes[srcStartIndex + j]),
3970                                            string_VkDescriptorType(pDstLayout->descriptorTypes[dstStartIndex + j]));
3971                    } else {
3972                        // point dst descriptor at corresponding src descriptor
3973                        // TODO : This may be a hole. I believe copy should be its own copy,
3974                        //  otherwise a subsequent write update to src will incorrectly affect the copy
3975                        pDstSet->pDescriptorUpdates[j + dstStartIndex] = pSrcSet->pDescriptorUpdates[j + srcStartIndex];
3976                        pDstSet->pUpdateStructs = pSrcSet->pUpdateStructs;
3977                    }
3978                }
3979            }
3980        }
3981    }
3982    return skipCall;
3983}
3984
3985// Verify that given pool has descriptors that are being requested for allocation.
3986// NOTE : Calls to this function should be wrapped in mutex
3987static bool validate_descriptor_availability_in_pool(layer_data *dev_data, DESCRIPTOR_POOL_NODE *pPoolNode, uint32_t count,
3988                                                     const VkDescriptorSetLayout *pSetLayouts) {
3989    bool skipCall = false;
3990    uint32_t i = 0;
3991    uint32_t j = 0;
3992
3993    // Track number of descriptorSets allowable in this pool
3994    if (pPoolNode->availableSets < count) {
3995        skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT,
3996                            reinterpret_cast<uint64_t &>(pPoolNode->pool), __LINE__, DRAWSTATE_DESCRIPTOR_POOL_EMPTY, "DS",
3997                            "Unable to allocate %u descriptorSets from pool %#" PRIxLEAST64
3998                            ". This pool only has %d descriptorSets remaining.",
3999                            count, reinterpret_cast<uint64_t &>(pPoolNode->pool), pPoolNode->availableSets);
4000    } else {
4001        pPoolNode->availableSets -= count;
4002    }
4003
4004    for (i = 0; i < count; ++i) {
4005        LAYOUT_NODE *pLayout = getLayoutNode(dev_data, pSetLayouts[i]);
4006        if (NULL == pLayout) {
4007            skipCall |=
4008                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT,
4009                        (uint64_t)pSetLayouts[i], __LINE__, DRAWSTATE_INVALID_LAYOUT, "DS",
4010                        "Unable to find set layout node for layout %#" PRIxLEAST64 " specified in vkAllocateDescriptorSets() call",
4011                        (uint64_t)pSetLayouts[i]);
4012        } else {
4013            uint32_t typeIndex = 0, poolSizeCount = 0;
4014            for (j = 0; j < pLayout->createInfo.bindingCount; ++j) {
4015                typeIndex = static_cast<uint32_t>(pLayout->createInfo.pBindings[j].descriptorType);
4016                poolSizeCount = pLayout->createInfo.pBindings[j].descriptorCount;
4017                if (poolSizeCount > pPoolNode->availableDescriptorTypeCount[typeIndex]) {
4018                    skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
4019                                        VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT, (uint64_t)pLayout->layout, __LINE__,
4020                                        DRAWSTATE_DESCRIPTOR_POOL_EMPTY, "DS",
4021                                        "Unable to allocate %u descriptors of type %s from pool %#" PRIxLEAST64
4022                                        ". This pool only has %d descriptors of this type remaining.",
4023                                        poolSizeCount, string_VkDescriptorType(pLayout->createInfo.pBindings[j].descriptorType),
4024                                        (uint64_t)pPoolNode->pool, pPoolNode->availableDescriptorTypeCount[typeIndex]);
4025                } else { // Decrement available descriptors of this type
4026                    pPoolNode->availableDescriptorTypeCount[typeIndex] -= poolSizeCount;
4027                }
4028            }
4029        }
4030    }
4031    return skipCall;
4032}
4033
4034// Free the shadowed update node for this Set
4035// NOTE : Calls to this function should be wrapped in mutex
4036static void freeShadowUpdateTree(SET_NODE *pSet) {
4037    GENERIC_HEADER *pShadowUpdate = pSet->pUpdateStructs;
4038    pSet->pUpdateStructs = NULL;
4039    GENERIC_HEADER *pFreeUpdate = pShadowUpdate;
4040    // Clear the descriptor mappings as they will now be invalid
4041    pSet->pDescriptorUpdates.clear();
4042    while (pShadowUpdate) {
4043        pFreeUpdate = pShadowUpdate;
4044        pShadowUpdate = (GENERIC_HEADER *)pShadowUpdate->pNext;
4045        VkWriteDescriptorSet *pWDS = NULL;
4046        switch (pFreeUpdate->sType) {
4047        case VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET:
4048            pWDS = (VkWriteDescriptorSet *)pFreeUpdate;
4049            switch (pWDS->descriptorType) {
4050            case VK_DESCRIPTOR_TYPE_SAMPLER:
4051            case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
4052            case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
4053            case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: {
4054                delete[] pWDS->pImageInfo;
4055            } break;
4056            case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
4057            case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: {
4058                delete[] pWDS->pTexelBufferView;
4059            } break;
4060            case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
4061            case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
4062            case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
4063            case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: {
4064                delete[] pWDS->pBufferInfo;
4065            } break;
4066            default:
4067                break;
4068            }
4069            break;
4070        case VK_STRUCTURE_TYPE_COPY_DESCRIPTOR_SET:
4071            break;
4072        default:
4073            assert(0);
4074            break;
4075        }
4076        delete pFreeUpdate;
4077    }
4078}
4079
4080// Free all DS Pools including their Sets & related sub-structs
4081// NOTE : Calls to this function should be wrapped in mutex
4082static void deletePools(layer_data *my_data) {
4083    if (my_data->descriptorPoolMap.size() <= 0)
4084        return;
4085    for (auto ii = my_data->descriptorPoolMap.begin(); ii != my_data->descriptorPoolMap.end(); ++ii) {
4086        SET_NODE *pSet = (*ii).second->pSets;
4087        SET_NODE *pFreeSet = pSet;
4088        while (pSet) {
4089            pFreeSet = pSet;
4090            pSet = pSet->pNext;
4091            // Freeing layouts handled in deleteLayouts() function
4092            // Free Update shadow struct tree
4093            freeShadowUpdateTree(pFreeSet);
4094            delete pFreeSet;
4095        }
4096        delete (*ii).second;
4097    }
4098    my_data->descriptorPoolMap.clear();
4099}
4100
4101// WARN : Once deleteLayouts() called, any layout ptrs in Pool/Set data structure will be invalid
4102// NOTE : Calls to this function should be wrapped in mutex
4103static void deleteLayouts(layer_data *my_data) {
4104    if (my_data->descriptorSetLayoutMap.size() <= 0)
4105        return;
4106    for (auto ii = my_data->descriptorSetLayoutMap.begin(); ii != my_data->descriptorSetLayoutMap.end(); ++ii) {
4107        LAYOUT_NODE *pLayout = (*ii).second;
4108        if (pLayout->createInfo.pBindings) {
4109            for (uint32_t i = 0; i < pLayout->createInfo.bindingCount; i++) {
4110                delete[] pLayout->createInfo.pBindings[i].pImmutableSamplers;
4111            }
4112            delete[] pLayout->createInfo.pBindings;
4113        }
4114        delete pLayout;
4115    }
4116    my_data->descriptorSetLayoutMap.clear();
4117}
4118
4119// Currently clearing a set is removing all previous updates to that set
4120//  TODO : Validate if this is correct clearing behavior
4121static void clearDescriptorSet(layer_data *my_data, VkDescriptorSet set) {
4122    SET_NODE *pSet = getSetNode(my_data, set);
4123    if (!pSet) {
4124        // TODO : Return error
4125    } else {
4126        freeShadowUpdateTree(pSet);
4127    }
4128}
4129
4130static void clearDescriptorPool(layer_data *my_data, const VkDevice device, const VkDescriptorPool pool,
4131                                VkDescriptorPoolResetFlags flags) {
4132    DESCRIPTOR_POOL_NODE *pPool = getPoolNode(my_data, pool);
4133    if (!pPool) {
4134        log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT,
4135                (uint64_t)pool, __LINE__, DRAWSTATE_INVALID_POOL, "DS",
4136                "Unable to find pool node for pool %#" PRIxLEAST64 " specified in vkResetDescriptorPool() call", (uint64_t)pool);
4137    } else {
4138        // TODO: validate flags
4139        // For every set off of this pool, clear it
4140        SET_NODE *pSet = pPool->pSets;
4141        while (pSet) {
4142            clearDescriptorSet(my_data, pSet->set);
4143            pSet = pSet->pNext;
4144        }
4145        // Reset available count for each type and available sets for this pool
4146        for (uint32_t i = 0; i < pPool->availableDescriptorTypeCount.size(); ++i) {
4147            pPool->availableDescriptorTypeCount[i] = pPool->maxDescriptorTypeCount[i];
4148        }
4149        pPool->availableSets = pPool->maxSets;
4150    }
4151}
4152
4153// For given CB object, fetch associated CB Node from map
4154static GLOBAL_CB_NODE *getCBNode(layer_data *my_data, const VkCommandBuffer cb) {
4155    if (my_data->commandBufferMap.count(cb) == 0) {
4156        log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
4157                reinterpret_cast<const uint64_t &>(cb), __LINE__, DRAWSTATE_INVALID_COMMAND_BUFFER, "DS",
4158                "Attempt to use CommandBuffer %#" PRIxLEAST64 " that doesn't exist!", (uint64_t)(cb));
4159        return NULL;
4160    }
4161    return my_data->commandBufferMap[cb];
4162}
4163
4164// Free all CB Nodes
4165// NOTE : Calls to this function should be wrapped in mutex
4166static void deleteCommandBuffers(layer_data *my_data) {
4167    if (my_data->commandBufferMap.empty()) {
4168        return;
4169    }
4170    for (auto ii = my_data->commandBufferMap.begin(); ii != my_data->commandBufferMap.end(); ++ii) {
4171        delete (*ii).second;
4172    }
4173    my_data->commandBufferMap.clear();
4174}
4175
4176static bool report_error_no_cb_begin(const layer_data *dev_data, const VkCommandBuffer cb, const char *caller_name) {
4177    return log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
4178                   (uint64_t)cb, __LINE__, DRAWSTATE_NO_BEGIN_COMMAND_BUFFER, "DS",
4179                   "You must call vkBeginCommandBuffer() before this call to %s", caller_name);
4180}
4181
4182bool validateCmdsInCmdBuffer(const layer_data *dev_data, const GLOBAL_CB_NODE *pCB, const CMD_TYPE cmd_type) {
4183    if (!pCB->activeRenderPass)
4184        return false;
4185    bool skip_call = false;
4186    if (pCB->activeSubpassContents == VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS && cmd_type != CMD_EXECUTECOMMANDS) {
4187        skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
4188                             DRAWSTATE_INVALID_COMMAND_BUFFER, "DS",
4189                             "Commands cannot be called in a subpass using secondary command buffers.");
4190    } else if (pCB->activeSubpassContents == VK_SUBPASS_CONTENTS_INLINE && cmd_type == CMD_EXECUTECOMMANDS) {
4191        skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
4192                             DRAWSTATE_INVALID_COMMAND_BUFFER, "DS",
4193                             "vkCmdExecuteCommands() cannot be called in a subpass using inline commands.");
4194    }
4195    return skip_call;
4196}
4197
4198static bool checkGraphicsBit(const layer_data *my_data, VkQueueFlags flags, const char *name) {
4199    if (!(flags & VK_QUEUE_GRAPHICS_BIT))
4200        return log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
4201                       DRAWSTATE_INVALID_COMMAND_BUFFER, "DS",
4202                       "Cannot call %s on a command buffer allocated from a pool without graphics capabilities.", name);
4203    return false;
4204}
4205
4206static bool checkComputeBit(const layer_data *my_data, VkQueueFlags flags, const char *name) {
4207    if (!(flags & VK_QUEUE_COMPUTE_BIT))
4208        return log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
4209                       DRAWSTATE_INVALID_COMMAND_BUFFER, "DS",
4210                       "Cannot call %s on a command buffer allocated from a pool without compute capabilities.", name);
4211    return false;
4212}
4213
4214static bool checkGraphicsOrComputeBit(const layer_data *my_data, VkQueueFlags flags, const char *name) {
4215    if (!((flags & VK_QUEUE_GRAPHICS_BIT) || (flags & VK_QUEUE_COMPUTE_BIT)))
4216        return log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
4217                       DRAWSTATE_INVALID_COMMAND_BUFFER, "DS",
4218                       "Cannot call %s on a command buffer allocated from a pool without graphics capabilities.", name);
4219    return false;
4220}
4221
4222// Add specified CMD to the CmdBuffer in given pCB, flagging errors if CB is not
4223//  in the recording state or if there's an issue with the Cmd ordering
4224static bool addCmd(const layer_data *my_data, GLOBAL_CB_NODE *pCB, const CMD_TYPE cmd, const char *caller_name) {
4225    bool skipCall = false;
4226    auto pool_data = my_data->commandPoolMap.find(pCB->createInfo.commandPool);
4227    if (pool_data != my_data->commandPoolMap.end()) {
4228        VkQueueFlags flags = my_data->phys_dev_properties.queue_family_properties[pool_data->second.queueFamilyIndex].queueFlags;
4229        switch (cmd) {
4230        case CMD_BINDPIPELINE:
4231        case CMD_BINDPIPELINEDELTA:
4232        case CMD_BINDDESCRIPTORSETS:
4233        case CMD_FILLBUFFER:
4234        case CMD_CLEARCOLORIMAGE:
4235        case CMD_SETEVENT:
4236        case CMD_RESETEVENT:
4237        case CMD_WAITEVENTS:
4238        case CMD_BEGINQUERY:
4239        case CMD_ENDQUERY:
4240        case CMD_RESETQUERYPOOL:
4241        case CMD_COPYQUERYPOOLRESULTS:
4242        case CMD_WRITETIMESTAMP:
4243            skipCall |= checkGraphicsOrComputeBit(my_data, flags, cmdTypeToString(cmd).c_str());
4244            break;
4245        case CMD_SETVIEWPORTSTATE:
4246        case CMD_SETSCISSORSTATE:
4247        case CMD_SETLINEWIDTHSTATE:
4248        case CMD_SETDEPTHBIASSTATE:
4249        case CMD_SETBLENDSTATE:
4250        case CMD_SETDEPTHBOUNDSSTATE:
4251        case CMD_SETSTENCILREADMASKSTATE:
4252        case CMD_SETSTENCILWRITEMASKSTATE:
4253        case CMD_SETSTENCILREFERENCESTATE:
4254        case CMD_BINDINDEXBUFFER:
4255        case CMD_BINDVERTEXBUFFER:
4256        case CMD_DRAW:
4257        case CMD_DRAWINDEXED:
4258        case CMD_DRAWINDIRECT:
4259        case CMD_DRAWINDEXEDINDIRECT:
4260        case CMD_BLITIMAGE:
4261        case CMD_CLEARATTACHMENTS:
4262        case CMD_CLEARDEPTHSTENCILIMAGE:
4263        case CMD_RESOLVEIMAGE:
4264        case CMD_BEGINRENDERPASS:
4265        case CMD_NEXTSUBPASS:
4266        case CMD_ENDRENDERPASS:
4267            skipCall |= checkGraphicsBit(my_data, flags, cmdTypeToString(cmd).c_str());
4268            break;
4269        case CMD_DISPATCH:
4270        case CMD_DISPATCHINDIRECT:
4271            skipCall |= checkComputeBit(my_data, flags, cmdTypeToString(cmd).c_str());
4272            break;
4273        case CMD_COPYBUFFER:
4274        case CMD_COPYIMAGE:
4275        case CMD_COPYBUFFERTOIMAGE:
4276        case CMD_COPYIMAGETOBUFFER:
4277        case CMD_CLONEIMAGEDATA:
4278        case CMD_UPDATEBUFFER:
4279        case CMD_PIPELINEBARRIER:
4280        case CMD_EXECUTECOMMANDS:
4281            break;
4282        default:
4283            break;
4284        }
4285    }
4286    if (pCB->state != CB_RECORDING) {
4287        skipCall |= report_error_no_cb_begin(my_data, pCB->commandBuffer, caller_name);
4288        skipCall |= validateCmdsInCmdBuffer(my_data, pCB, cmd);
4289        CMD_NODE cmdNode = {};
4290        // init cmd node and append to end of cmd LL
4291        cmdNode.cmdNumber = ++pCB->numCmds;
4292        cmdNode.type = cmd;
4293        pCB->cmds.push_back(cmdNode);
4294    }
4295    return skipCall;
4296}
4297// Reset the command buffer state
4298//  Maintain the createInfo and set state to CB_NEW, but clear all other state
4299static void resetCB(layer_data *dev_data, const VkCommandBuffer cb) {
4300    GLOBAL_CB_NODE *pCB = dev_data->commandBufferMap[cb];
4301    if (pCB) {
4302        pCB->cmds.clear();
4303        // Reset CB state (note that createInfo is not cleared)
4304        pCB->commandBuffer = cb;
4305        memset(&pCB->beginInfo, 0, sizeof(VkCommandBufferBeginInfo));
4306        memset(&pCB->inheritanceInfo, 0, sizeof(VkCommandBufferInheritanceInfo));
4307        pCB->numCmds = 0;
4308        memset(pCB->drawCount, 0, NUM_DRAW_TYPES * sizeof(uint64_t));
4309        pCB->state = CB_NEW;
4310        pCB->submitCount = 0;
4311        pCB->status = 0;
4312        pCB->viewports.clear();
4313        pCB->scissors.clear();
4314        for (uint32_t i = 0; i < VK_PIPELINE_BIND_POINT_RANGE_SIZE; ++i) {
4315            // Before clearing lastBoundState, remove any CB bindings from all uniqueBoundSets
4316            for (auto set : pCB->lastBound[i].uniqueBoundSets) {
4317                auto set_node = dev_data->setMap.find(set);
4318                if (set_node != dev_data->setMap.end()) {
4319                    set_node->second->boundCmdBuffers.erase(pCB->commandBuffer);
4320                }
4321            }
4322            pCB->lastBound[i].reset();
4323        }
4324        memset(&pCB->activeRenderPassBeginInfo, 0, sizeof(pCB->activeRenderPassBeginInfo));
4325        pCB->activeRenderPass = 0;
4326        pCB->activeSubpassContents = VK_SUBPASS_CONTENTS_INLINE;
4327        pCB->activeSubpass = 0;
4328        pCB->framebuffer = 0;
4329        pCB->fenceId = 0;
4330        pCB->lastSubmittedFence = VK_NULL_HANDLE;
4331        pCB->lastSubmittedQueue = VK_NULL_HANDLE;
4332        pCB->destroyedSets.clear();
4333        pCB->updatedSets.clear();
4334        pCB->destroyedFramebuffers.clear();
4335        pCB->waitedEvents.clear();
4336        pCB->semaphores.clear();
4337        pCB->events.clear();
4338        pCB->waitedEventsBeforeQueryReset.clear();
4339        pCB->queryToStateMap.clear();
4340        pCB->activeQueries.clear();
4341        pCB->startedQueries.clear();
4342        pCB->imageLayoutMap.clear();
4343        pCB->eventToStageMap.clear();
4344        pCB->drawData.clear();
4345        pCB->currentDrawData.buffers.clear();
4346        pCB->primaryCommandBuffer = VK_NULL_HANDLE;
4347        pCB->secondaryCommandBuffers.clear();
4348        pCB->updateImages.clear();
4349        pCB->updateBuffers.clear();
4350        clear_cmd_buf_and_mem_references(dev_data, pCB);
4351        pCB->eventUpdates.clear();
4352    }
4353}
4354
4355// Set PSO-related status bits for CB, including dynamic state set via PSO
4356static void set_cb_pso_status(GLOBAL_CB_NODE *pCB, const PIPELINE_NODE *pPipe) {
4357    // Account for any dynamic state not set via this PSO
4358    if (!pPipe->graphicsPipelineCI.pDynamicState ||
4359        !pPipe->graphicsPipelineCI.pDynamicState->dynamicStateCount) { // All state is static
4360        pCB->status = CBSTATUS_ALL;
4361    } else {
4362        // First consider all state on
4363        // Then unset any state that's noted as dynamic in PSO
4364        // Finally OR that into CB statemask
4365        CBStatusFlags psoDynStateMask = CBSTATUS_ALL;
4366        for (uint32_t i = 0; i < pPipe->graphicsPipelineCI.pDynamicState->dynamicStateCount; i++) {
4367            switch (pPipe->graphicsPipelineCI.pDynamicState->pDynamicStates[i]) {
4368            case VK_DYNAMIC_STATE_VIEWPORT:
4369                psoDynStateMask &= ~CBSTATUS_VIEWPORT_SET;
4370                break;
4371            case VK_DYNAMIC_STATE_SCISSOR:
4372                psoDynStateMask &= ~CBSTATUS_SCISSOR_SET;
4373                break;
4374            case VK_DYNAMIC_STATE_LINE_WIDTH:
4375                psoDynStateMask &= ~CBSTATUS_LINE_WIDTH_SET;
4376                break;
4377            case VK_DYNAMIC_STATE_DEPTH_BIAS:
4378                psoDynStateMask &= ~CBSTATUS_DEPTH_BIAS_SET;
4379                break;
4380            case VK_DYNAMIC_STATE_BLEND_CONSTANTS:
4381                psoDynStateMask &= ~CBSTATUS_BLEND_CONSTANTS_SET;
4382                break;
4383            case VK_DYNAMIC_STATE_DEPTH_BOUNDS:
4384                psoDynStateMask &= ~CBSTATUS_DEPTH_BOUNDS_SET;
4385                break;
4386            case VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK:
4387                psoDynStateMask &= ~CBSTATUS_STENCIL_READ_MASK_SET;
4388                break;
4389            case VK_DYNAMIC_STATE_STENCIL_WRITE_MASK:
4390                psoDynStateMask &= ~CBSTATUS_STENCIL_WRITE_MASK_SET;
4391                break;
4392            case VK_DYNAMIC_STATE_STENCIL_REFERENCE:
4393                psoDynStateMask &= ~CBSTATUS_STENCIL_REFERENCE_SET;
4394                break;
4395            default:
4396                // TODO : Flag error here
4397                break;
4398            }
4399        }
4400        pCB->status |= psoDynStateMask;
4401    }
4402}
4403
4404// Print the last bound Gfx Pipeline
4405static bool printPipeline(layer_data *my_data, const VkCommandBuffer cb) {
4406    bool skipCall = false;
4407    GLOBAL_CB_NODE *pCB = getCBNode(my_data, cb);
4408    if (pCB) {
4409        PIPELINE_NODE *pPipeTrav = getPipeline(my_data, pCB->lastBound[VK_PIPELINE_BIND_POINT_GRAPHICS].pipeline);
4410        if (!pPipeTrav) {
4411            // nothing to print
4412        } else {
4413            skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
4414                                __LINE__, DRAWSTATE_NONE, "DS", "%s",
4415                                vk_print_vkgraphicspipelinecreateinfo(
4416                                    reinterpret_cast<const VkGraphicsPipelineCreateInfo *>(&pPipeTrav->graphicsPipelineCI), "{DS}")
4417                                    .c_str());
4418        }
4419    }
4420    return skipCall;
4421}
4422
4423static void printCB(layer_data *my_data, const VkCommandBuffer cb) {
4424    GLOBAL_CB_NODE *pCB = getCBNode(my_data, cb);
4425    if (pCB && pCB->cmds.size() > 0) {
4426        log_msg(my_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
4427                DRAWSTATE_NONE, "DS", "Cmds in CB %p", (void *)cb);
4428        vector<CMD_NODE> cmds = pCB->cmds;
4429        for (auto ii = cmds.begin(); ii != cmds.end(); ++ii) {
4430            // TODO : Need to pass cb as srcObj here
4431            log_msg(my_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0,
4432                    __LINE__, DRAWSTATE_NONE, "DS", "  CMD#%" PRIu64 ": %s", (*ii).cmdNumber, cmdTypeToString((*ii).type).c_str());
4433        }
4434    } else {
4435        // Nothing to print
4436    }
4437}
4438
4439static bool synchAndPrintDSConfig(layer_data *my_data, const VkCommandBuffer cb) {
4440    bool skipCall = false;
4441    if (!(my_data->report_data->active_flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT)) {
4442        return skipCall;
4443    }
4444    skipCall |= printPipeline(my_data, cb);
4445    return skipCall;
4446}
4447
4448// Flags validation error if the associated call is made inside a render pass. The apiName
4449// routine should ONLY be called outside a render pass.
4450static bool insideRenderPass(const layer_data *my_data, GLOBAL_CB_NODE *pCB, const char *apiName) {
4451    bool inside = false;
4452    if (pCB->activeRenderPass) {
4453        inside = log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
4454                         (uint64_t)pCB->commandBuffer, __LINE__, DRAWSTATE_INVALID_RENDERPASS_CMD, "DS",
4455                         "%s: It is invalid to issue this call inside an active render pass (%#" PRIxLEAST64 ")", apiName,
4456                         (uint64_t)pCB->activeRenderPass);
4457    }
4458    return inside;
4459}
4460
4461// Flags validation error if the associated call is made outside a render pass. The apiName
4462// routine should ONLY be called inside a render pass.
4463static bool outsideRenderPass(const layer_data *my_data, GLOBAL_CB_NODE *pCB, const char *apiName) {
4464    bool outside = false;
4465    if (((pCB->createInfo.level == VK_COMMAND_BUFFER_LEVEL_PRIMARY) && (!pCB->activeRenderPass)) ||
4466        ((pCB->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) && (!pCB->activeRenderPass) &&
4467         !(pCB->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT))) {
4468        outside = log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
4469                          (uint64_t)pCB->commandBuffer, __LINE__, DRAWSTATE_NO_ACTIVE_RENDERPASS, "DS",
4470                          "%s: This call must be issued inside an active render pass.", apiName);
4471    }
4472    return outside;
4473}
4474
4475static void init_core_validation(layer_data *instance_data, const VkAllocationCallbacks *pAllocator) {
4476
4477    layer_debug_actions(instance_data->report_data, instance_data->logging_callback, pAllocator, "lunarg_core_validation");
4478
4479    if (!globalLockInitialized) {
4480        loader_platform_thread_create_mutex(&globalLock);
4481        globalLockInitialized = 1;
4482    }
4483}
4484
4485VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
4486vkCreateInstance(const VkInstanceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkInstance *pInstance) {
4487    VkLayerInstanceCreateInfo *chain_info = get_chain_info(pCreateInfo, VK_LAYER_LINK_INFO);
4488
4489    assert(chain_info->u.pLayerInfo);
4490    PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr = chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr;
4491    PFN_vkCreateInstance fpCreateInstance = (PFN_vkCreateInstance)fpGetInstanceProcAddr(NULL, "vkCreateInstance");
4492    if (fpCreateInstance == NULL)
4493        return VK_ERROR_INITIALIZATION_FAILED;
4494
4495    // Advance the link info for the next element on the chain
4496    chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext;
4497
4498    VkResult result = fpCreateInstance(pCreateInfo, pAllocator, pInstance);
4499    if (result != VK_SUCCESS)
4500        return result;
4501
4502    layer_data *instance_data = get_my_data_ptr(get_dispatch_key(*pInstance), layer_data_map);
4503    instance_data->instance_dispatch_table = new VkLayerInstanceDispatchTable;
4504    layer_init_instance_dispatch_table(*pInstance, instance_data->instance_dispatch_table, fpGetInstanceProcAddr);
4505
4506    instance_data->report_data =
4507        debug_report_create_instance(instance_data->instance_dispatch_table, *pInstance, pCreateInfo->enabledExtensionCount,
4508                                     pCreateInfo->ppEnabledExtensionNames);
4509
4510    init_core_validation(instance_data, pAllocator);
4511
4512    ValidateLayerOrdering(*pCreateInfo);
4513
4514    return result;
4515}
4516
4517/* hook DestroyInstance to remove tableInstanceMap entry */
4518VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkDestroyInstance(VkInstance instance, const VkAllocationCallbacks *pAllocator) {
4519    // TODOSC : Shouldn't need any customization here
4520    dispatch_key key = get_dispatch_key(instance);
4521    // TBD: Need any locking this early, in case this function is called at the
4522    // same time by more than one thread?
4523    layer_data *my_data = get_my_data_ptr(key, layer_data_map);
4524    VkLayerInstanceDispatchTable *pTable = my_data->instance_dispatch_table;
4525    pTable->DestroyInstance(instance, pAllocator);
4526
4527    loader_platform_thread_lock_mutex(&globalLock);
4528    // Clean up logging callback, if any
4529    while (my_data->logging_callback.size() > 0) {
4530        VkDebugReportCallbackEXT callback = my_data->logging_callback.back();
4531        layer_destroy_msg_callback(my_data->report_data, callback, pAllocator);
4532        my_data->logging_callback.pop_back();
4533    }
4534
4535    layer_debug_report_destroy_instance(my_data->report_data);
4536    delete my_data->instance_dispatch_table;
4537    layer_data_map.erase(key);
4538    loader_platform_thread_unlock_mutex(&globalLock);
4539    if (layer_data_map.empty()) {
4540        // Release mutex when destroying last instance.
4541        loader_platform_thread_delete_mutex(&globalLock);
4542        globalLockInitialized = 0;
4543    }
4544}
4545
4546static void createDeviceRegisterExtensions(const VkDeviceCreateInfo *pCreateInfo, VkDevice device) {
4547    uint32_t i;
4548    // TBD: Need any locking, in case this function is called at the same time
4549    // by more than one thread?
4550    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
4551    dev_data->device_extensions.wsi_enabled = false;
4552
4553    VkLayerDispatchTable *pDisp = dev_data->device_dispatch_table;
4554    PFN_vkGetDeviceProcAddr gpa = pDisp->GetDeviceProcAddr;
4555    pDisp->CreateSwapchainKHR = (PFN_vkCreateSwapchainKHR)gpa(device, "vkCreateSwapchainKHR");
4556    pDisp->DestroySwapchainKHR = (PFN_vkDestroySwapchainKHR)gpa(device, "vkDestroySwapchainKHR");
4557    pDisp->GetSwapchainImagesKHR = (PFN_vkGetSwapchainImagesKHR)gpa(device, "vkGetSwapchainImagesKHR");
4558    pDisp->AcquireNextImageKHR = (PFN_vkAcquireNextImageKHR)gpa(device, "vkAcquireNextImageKHR");
4559    pDisp->QueuePresentKHR = (PFN_vkQueuePresentKHR)gpa(device, "vkQueuePresentKHR");
4560
4561    for (i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
4562        if (strcmp(pCreateInfo->ppEnabledExtensionNames[i], VK_KHR_SWAPCHAIN_EXTENSION_NAME) == 0)
4563            dev_data->device_extensions.wsi_enabled = true;
4564    }
4565}
4566
4567VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo *pCreateInfo,
4568                                                              const VkAllocationCallbacks *pAllocator, VkDevice *pDevice) {
4569    VkLayerDeviceCreateInfo *chain_info = get_chain_info(pCreateInfo, VK_LAYER_LINK_INFO);
4570
4571    assert(chain_info->u.pLayerInfo);
4572    PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr = chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr;
4573    PFN_vkGetDeviceProcAddr fpGetDeviceProcAddr = chain_info->u.pLayerInfo->pfnNextGetDeviceProcAddr;
4574    PFN_vkCreateDevice fpCreateDevice = (PFN_vkCreateDevice)fpGetInstanceProcAddr(NULL, "vkCreateDevice");
4575    if (fpCreateDevice == NULL) {
4576        return VK_ERROR_INITIALIZATION_FAILED;
4577    }
4578
4579    // Advance the link info for the next element on the chain
4580    chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext;
4581
4582    VkResult result = fpCreateDevice(gpu, pCreateInfo, pAllocator, pDevice);
4583    if (result != VK_SUCCESS) {
4584        return result;
4585    }
4586
4587    loader_platform_thread_lock_mutex(&globalLock);
4588    layer_data *my_instance_data = get_my_data_ptr(get_dispatch_key(gpu), layer_data_map);
4589    layer_data *my_device_data = get_my_data_ptr(get_dispatch_key(*pDevice), layer_data_map);
4590
4591    // Setup device dispatch table
4592    my_device_data->device_dispatch_table = new VkLayerDispatchTable;
4593    layer_init_device_dispatch_table(*pDevice, my_device_data->device_dispatch_table, fpGetDeviceProcAddr);
4594    my_device_data->device = *pDevice;
4595
4596    my_device_data->report_data = layer_debug_report_create_device(my_instance_data->report_data, *pDevice);
4597    createDeviceRegisterExtensions(pCreateInfo, *pDevice);
4598    // Get physical device limits for this device
4599    my_instance_data->instance_dispatch_table->GetPhysicalDeviceProperties(gpu, &(my_device_data->phys_dev_properties.properties));
4600    uint32_t count;
4601    my_instance_data->instance_dispatch_table->GetPhysicalDeviceQueueFamilyProperties(gpu, &count, nullptr);
4602    my_device_data->phys_dev_properties.queue_family_properties.resize(count);
4603    my_instance_data->instance_dispatch_table->GetPhysicalDeviceQueueFamilyProperties(
4604        gpu, &count, &my_device_data->phys_dev_properties.queue_family_properties[0]);
4605    // TODO: device limits should make sure these are compatible
4606    if (pCreateInfo->pEnabledFeatures) {
4607        my_device_data->phys_dev_properties.features = *pCreateInfo->pEnabledFeatures;
4608    } else {
4609        memset(&my_device_data->phys_dev_properties.features, 0, sizeof(VkPhysicalDeviceFeatures));
4610    }
4611    // Store physical device mem limits into device layer_data struct
4612    my_instance_data->instance_dispatch_table->GetPhysicalDeviceMemoryProperties(gpu, &my_device_data->phys_dev_mem_props);
4613    loader_platform_thread_unlock_mutex(&globalLock);
4614
4615    ValidateLayerOrdering(*pCreateInfo);
4616
4617    return result;
4618}
4619
4620// prototype
4621static void deleteRenderPasses(layer_data *);
4622VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkDestroyDevice(VkDevice device, const VkAllocationCallbacks *pAllocator) {
4623    // TODOSC : Shouldn't need any customization here
4624    dispatch_key key = get_dispatch_key(device);
4625    layer_data *dev_data = get_my_data_ptr(key, layer_data_map);
4626    // Free all the memory
4627    loader_platform_thread_lock_mutex(&globalLock);
4628    deletePipelines(dev_data);
4629    deleteRenderPasses(dev_data);
4630    deleteCommandBuffers(dev_data);
4631    deletePools(dev_data);
4632    deleteLayouts(dev_data);
4633    dev_data->imageViewMap.clear();
4634    dev_data->imageMap.clear();
4635    dev_data->imageSubresourceMap.clear();
4636    dev_data->imageLayoutMap.clear();
4637    dev_data->bufferViewMap.clear();
4638    dev_data->bufferMap.clear();
4639    // Queues persist until device is destroyed
4640    dev_data->queueMap.clear();
4641    loader_platform_thread_unlock_mutex(&globalLock);
4642#if MTMERGESOURCE
4643    bool skipCall = false;
4644    loader_platform_thread_lock_mutex(&globalLock);
4645    log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
4646            (uint64_t)device, __LINE__, MEMTRACK_NONE, "MEM", "Printing List details prior to vkDestroyDevice()");
4647    log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
4648            (uint64_t)device, __LINE__, MEMTRACK_NONE, "MEM", "================================================");
4649    print_mem_list(dev_data);
4650    printCBList(dev_data);
4651    // Report any memory leaks
4652    DEVICE_MEM_INFO *pInfo = NULL;
4653    if (!dev_data->memObjMap.empty()) {
4654        for (auto ii = dev_data->memObjMap.begin(); ii != dev_data->memObjMap.end(); ++ii) {
4655            pInfo = &(*ii).second;
4656            if (pInfo->allocInfo.allocationSize != 0) {
4657                // Valid Usage: All child objects created on device must have been destroyed prior to destroying device
4658                skipCall |=
4659                    log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
4660                            VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, (uint64_t)pInfo->mem, __LINE__, MEMTRACK_MEMORY_LEAK,
4661                            "MEM", "Mem Object %" PRIu64 " has not been freed. You should clean up this memory by calling "
4662                                   "vkFreeMemory(%" PRIu64 ") prior to vkDestroyDevice().",
4663                            (uint64_t)(pInfo->mem), (uint64_t)(pInfo->mem));
4664            }
4665        }
4666    }
4667    layer_debug_report_destroy_device(device);
4668    loader_platform_thread_unlock_mutex(&globalLock);
4669
4670#if DISPATCH_MAP_DEBUG
4671    fprintf(stderr, "Device: %p, key: %p\n", device, key);
4672#endif
4673    VkLayerDispatchTable *pDisp = dev_data->device_dispatch_table;
4674    if (!skipCall) {
4675        pDisp->DestroyDevice(device, pAllocator);
4676    }
4677#else
4678    dev_data->device_dispatch_table->DestroyDevice(device, pAllocator);
4679#endif
4680    delete dev_data->device_dispatch_table;
4681    layer_data_map.erase(key);
4682}
4683
4684static const VkExtensionProperties instance_extensions[] = {{VK_EXT_DEBUG_REPORT_EXTENSION_NAME, VK_EXT_DEBUG_REPORT_SPEC_VERSION}};
4685
4686VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
4687vkEnumerateInstanceExtensionProperties(const char *pLayerName, uint32_t *pCount, VkExtensionProperties *pProperties) {
4688    return util_GetExtensionProperties(1, instance_extensions, pCount, pProperties);
4689}
4690
4691VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
4692vkEnumerateInstanceLayerProperties(uint32_t *pCount, VkLayerProperties *pProperties) {
4693    return util_GetLayerProperties(ARRAY_SIZE(cv_global_layers), cv_global_layers, pCount, pProperties);
4694}
4695
4696// TODO: Why does this exist - can we just use global?
4697static const VkLayerProperties cv_device_layers[] = {{
4698    "VK_LAYER_LUNARG_core_validation", VK_LAYER_API_VERSION, 1, "LunarG Validation Layer",
4699}};
4700
4701VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateDeviceExtensionProperties(VkPhysicalDevice physicalDevice,
4702                                                                                    const char *pLayerName, uint32_t *pCount,
4703                                                                                    VkExtensionProperties *pProperties) {
4704    if (pLayerName == NULL) {
4705        dispatch_key key = get_dispatch_key(physicalDevice);
4706        layer_data *my_data = get_my_data_ptr(key, layer_data_map);
4707        return my_data->instance_dispatch_table->EnumerateDeviceExtensionProperties(physicalDevice, NULL, pCount, pProperties);
4708    } else {
4709        return util_GetExtensionProperties(0, NULL, pCount, pProperties);
4710    }
4711}
4712
4713VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
4714vkEnumerateDeviceLayerProperties(VkPhysicalDevice physicalDevice, uint32_t *pCount, VkLayerProperties *pProperties) {
4715    /* draw_state physical device layers are the same as global */
4716    return util_GetLayerProperties(ARRAY_SIZE(cv_device_layers), cv_device_layers, pCount, pProperties);
4717}
4718
4719// This validates that the initial layout specified in the command buffer for
4720// the IMAGE is the same
4721// as the global IMAGE layout
4722static bool ValidateCmdBufImageLayouts(VkCommandBuffer cmdBuffer) {
4723    bool skip_call = false;
4724    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(cmdBuffer), layer_data_map);
4725    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, cmdBuffer);
4726    for (auto cb_image_data : pCB->imageLayoutMap) {
4727        VkImageLayout imageLayout;
4728        if (!FindLayout(dev_data, cb_image_data.first, imageLayout)) {
4729            skip_call |=
4730                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0,
4731                        __LINE__, DRAWSTATE_INVALID_IMAGE_LAYOUT, "DS", "Cannot submit cmd buffer using deleted image %" PRIu64 ".",
4732                        reinterpret_cast<const uint64_t &>(cb_image_data.first));
4733        } else {
4734            if (cb_image_data.second.initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
4735                // TODO: Set memory invalid which is in mem_tracker currently
4736            } else if (imageLayout != cb_image_data.second.initialLayout) {
4737                skip_call |=
4738                    log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
4739                            reinterpret_cast<uint64_t &>(cmdBuffer), __LINE__, DRAWSTATE_INVALID_IMAGE_LAYOUT, "DS",
4740                            "Cannot submit cmd buffer using image (%" PRIx64 ") with layout %s when "
4741                            "first use is %s.",
4742                            reinterpret_cast<const uint64_t &>(cb_image_data.first.image), string_VkImageLayout(imageLayout),
4743                            string_VkImageLayout(cb_image_data.second.initialLayout));
4744            }
4745            SetLayout(dev_data, cb_image_data.first, cb_image_data.second.layout);
4746        }
4747    }
4748    return skip_call;
4749}
4750
4751// Track which resources are in-flight by atomically incrementing their "in_use" count
4752static bool validateAndIncrementResources(layer_data *my_data, GLOBAL_CB_NODE *pCB) {
4753    bool skip_call = false;
4754    for (auto drawDataElement : pCB->drawData) {
4755        for (auto buffer : drawDataElement.buffers) {
4756            auto buffer_data = my_data->bufferMap.find(buffer);
4757            if (buffer_data == my_data->bufferMap.end()) {
4758                skip_call |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
4759                                     (uint64_t)(buffer), __LINE__, DRAWSTATE_INVALID_BUFFER, "DS",
4760                                     "Cannot submit cmd buffer using deleted buffer %" PRIu64 ".", (uint64_t)(buffer));
4761            } else {
4762                buffer_data->second.in_use.fetch_add(1);
4763            }
4764        }
4765    }
4766    for (uint32_t i = 0; i < VK_PIPELINE_BIND_POINT_RANGE_SIZE; ++i) {
4767        for (auto set : pCB->lastBound[i].uniqueBoundSets) {
4768            auto setNode = my_data->setMap.find(set);
4769            if (setNode == my_data->setMap.end()) {
4770                skip_call |=
4771                    log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
4772                            (uint64_t)(set), __LINE__, DRAWSTATE_INVALID_DESCRIPTOR_SET, "DS",
4773                            "Cannot submit cmd buffer using deleted descriptor set %" PRIu64 ".", (uint64_t)(set));
4774            } else {
4775                setNode->second->in_use.fetch_add(1);
4776            }
4777        }
4778    }
4779    for (auto semaphore : pCB->semaphores) {
4780        auto semaphoreNode = my_data->semaphoreMap.find(semaphore);
4781        if (semaphoreNode == my_data->semaphoreMap.end()) {
4782            skip_call |=
4783                log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
4784                        reinterpret_cast<uint64_t &>(semaphore), __LINE__, DRAWSTATE_INVALID_SEMAPHORE, "DS",
4785                        "Cannot submit cmd buffer using deleted semaphore %" PRIu64 ".", reinterpret_cast<uint64_t &>(semaphore));
4786        } else {
4787            semaphoreNode->second.in_use.fetch_add(1);
4788        }
4789    }
4790    for (auto event : pCB->events) {
4791        auto eventNode = my_data->eventMap.find(event);
4792        if (eventNode == my_data->eventMap.end()) {
4793            skip_call |=
4794                log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
4795                        reinterpret_cast<uint64_t &>(event), __LINE__, DRAWSTATE_INVALID_EVENT, "DS",
4796                        "Cannot submit cmd buffer using deleted event %" PRIu64 ".", reinterpret_cast<uint64_t &>(event));
4797        } else {
4798            eventNode->second.in_use.fetch_add(1);
4799        }
4800    }
4801    return skip_call;
4802}
4803
4804static void decrementResources(layer_data *my_data, VkCommandBuffer cmdBuffer) {
4805    GLOBAL_CB_NODE *pCB = getCBNode(my_data, cmdBuffer);
4806    for (auto drawDataElement : pCB->drawData) {
4807        for (auto buffer : drawDataElement.buffers) {
4808            auto buffer_data = my_data->bufferMap.find(buffer);
4809            if (buffer_data != my_data->bufferMap.end()) {
4810                buffer_data->second.in_use.fetch_sub(1);
4811            }
4812        }
4813    }
4814    for (uint32_t i = 0; i < VK_PIPELINE_BIND_POINT_RANGE_SIZE; ++i) {
4815        for (auto set : pCB->lastBound[i].uniqueBoundSets) {
4816            auto setNode = my_data->setMap.find(set);
4817            if (setNode != my_data->setMap.end()) {
4818                setNode->second->in_use.fetch_sub(1);
4819            }
4820        }
4821    }
4822    for (auto semaphore : pCB->semaphores) {
4823        auto semaphoreNode = my_data->semaphoreMap.find(semaphore);
4824        if (semaphoreNode != my_data->semaphoreMap.end()) {
4825            semaphoreNode->second.in_use.fetch_sub(1);
4826        }
4827    }
4828    for (auto event : pCB->events) {
4829        auto eventNode = my_data->eventMap.find(event);
4830        if (eventNode != my_data->eventMap.end()) {
4831            eventNode->second.in_use.fetch_sub(1);
4832        }
4833    }
4834    for (auto queryStatePair : pCB->queryToStateMap) {
4835        my_data->queryToStateMap[queryStatePair.first] = queryStatePair.second;
4836    }
4837    for (auto eventStagePair : pCB->eventToStageMap) {
4838        my_data->eventMap[eventStagePair.first].stageMask = eventStagePair.second;
4839    }
4840}
4841
4842static void decrementResources(layer_data *my_data, uint32_t fenceCount, const VkFence *pFences) {
4843    for (uint32_t i = 0; i < fenceCount; ++i) {
4844        auto fence_data = my_data->fenceMap.find(pFences[i]);
4845        if (fence_data == my_data->fenceMap.end() || !fence_data->second.needsSignaled)
4846            return;
4847        fence_data->second.needsSignaled = false;
4848        fence_data->second.in_use.fetch_sub(1);
4849        decrementResources(my_data, static_cast<uint32_t>(fence_data->second.priorFences.size()),
4850                           fence_data->second.priorFences.data());
4851        for (auto cmdBuffer : fence_data->second.cmdBuffers) {
4852            decrementResources(my_data, cmdBuffer);
4853        }
4854    }
4855}
4856
4857static void decrementResources(layer_data *my_data, VkQueue queue) {
4858    auto queue_data = my_data->queueMap.find(queue);
4859    if (queue_data != my_data->queueMap.end()) {
4860        for (auto cmdBuffer : queue_data->second.untrackedCmdBuffers) {
4861            decrementResources(my_data, cmdBuffer);
4862        }
4863        queue_data->second.untrackedCmdBuffers.clear();
4864        decrementResources(my_data, static_cast<uint32_t>(queue_data->second.lastFences.size()),
4865                           queue_data->second.lastFences.data());
4866    }
4867}
4868
4869static void updateTrackedCommandBuffers(layer_data *dev_data, VkQueue queue, VkQueue other_queue, VkFence fence) {
4870    if (queue == other_queue) {
4871        return;
4872    }
4873    auto queue_data = dev_data->queueMap.find(queue);
4874    auto other_queue_data = dev_data->queueMap.find(other_queue);
4875    if (queue_data == dev_data->queueMap.end() || other_queue_data == dev_data->queueMap.end()) {
4876        return;
4877    }
4878    for (auto fenceInner : other_queue_data->second.lastFences) {
4879        queue_data->second.lastFences.push_back(fenceInner);
4880    }
4881    if (fence != VK_NULL_HANDLE) {
4882        auto fence_data = dev_data->fenceMap.find(fence);
4883        if (fence_data == dev_data->fenceMap.end()) {
4884            return;
4885        }
4886        for (auto cmdbuffer : other_queue_data->second.untrackedCmdBuffers) {
4887            fence_data->second.cmdBuffers.push_back(cmdbuffer);
4888        }
4889        other_queue_data->second.untrackedCmdBuffers.clear();
4890    } else {
4891        for (auto cmdbuffer : other_queue_data->second.untrackedCmdBuffers) {
4892            queue_data->second.untrackedCmdBuffers.push_back(cmdbuffer);
4893        }
4894        other_queue_data->second.untrackedCmdBuffers.clear();
4895    }
4896    for (auto eventStagePair : other_queue_data->second.eventToStageMap) {
4897        queue_data->second.eventToStageMap[eventStagePair.first] = eventStagePair.second;
4898    }
4899}
4900
4901static void trackCommandBuffers(layer_data *my_data, VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits,
4902                                VkFence fence) {
4903    auto queue_data = my_data->queueMap.find(queue);
4904    if (fence != VK_NULL_HANDLE) {
4905        vector<VkFence> prior_fences;
4906        auto fence_data = my_data->fenceMap.find(fence);
4907        if (fence_data == my_data->fenceMap.end()) {
4908            return;
4909        }
4910        if (queue_data != my_data->queueMap.end()) {
4911            prior_fences = queue_data->second.lastFences;
4912            queue_data->second.lastFences.clear();
4913            queue_data->second.lastFences.push_back(fence);
4914            for (auto cmdbuffer : queue_data->second.untrackedCmdBuffers) {
4915                fence_data->second.cmdBuffers.push_back(cmdbuffer);
4916            }
4917            queue_data->second.untrackedCmdBuffers.clear();
4918        }
4919        fence_data->second.cmdBuffers.clear();
4920        fence_data->second.priorFences = prior_fences;
4921        fence_data->second.needsSignaled = true;
4922        fence_data->second.queue = queue;
4923        fence_data->second.in_use.fetch_add(1);
4924        for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) {
4925            const VkSubmitInfo *submit = &pSubmits[submit_idx];
4926            for (uint32_t i = 0; i < submit->commandBufferCount; ++i) {
4927                for (auto secondaryCmdBuffer : my_data->commandBufferMap[submit->pCommandBuffers[i]]->secondaryCommandBuffers) {
4928                    fence_data->second.cmdBuffers.push_back(secondaryCmdBuffer);
4929                }
4930                fence_data->second.cmdBuffers.push_back(submit->pCommandBuffers[i]);
4931            }
4932        }
4933    } else {
4934        if (queue_data != my_data->queueMap.end()) {
4935            for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) {
4936                const VkSubmitInfo *submit = &pSubmits[submit_idx];
4937                for (uint32_t i = 0; i < submit->commandBufferCount; ++i) {
4938                    for (auto secondaryCmdBuffer : my_data->commandBufferMap[submit->pCommandBuffers[i]]->secondaryCommandBuffers) {
4939                        queue_data->second.untrackedCmdBuffers.push_back(secondaryCmdBuffer);
4940                    }
4941                    queue_data->second.untrackedCmdBuffers.push_back(submit->pCommandBuffers[i]);
4942                }
4943            }
4944        }
4945    }
4946    if (queue_data != my_data->queueMap.end()) {
4947        for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) {
4948            const VkSubmitInfo *submit = &pSubmits[submit_idx];
4949            for (uint32_t i = 0; i < submit->commandBufferCount; ++i) {
4950                // Add cmdBuffers to both the global set and queue set
4951                for (auto secondaryCmdBuffer : my_data->commandBufferMap[submit->pCommandBuffers[i]]->secondaryCommandBuffers) {
4952                    my_data->globalInFlightCmdBuffers.insert(secondaryCmdBuffer);
4953                    queue_data->second.inFlightCmdBuffers.insert(secondaryCmdBuffer);
4954                }
4955                my_data->globalInFlightCmdBuffers.insert(submit->pCommandBuffers[i]);
4956                queue_data->second.inFlightCmdBuffers.insert(submit->pCommandBuffers[i]);
4957            }
4958        }
4959    }
4960}
4961
4962static bool validateCommandBufferSimultaneousUse(layer_data *dev_data, GLOBAL_CB_NODE *pCB) {
4963    bool skip_call = false;
4964    if (dev_data->globalInFlightCmdBuffers.count(pCB->commandBuffer) &&
4965        !(pCB->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT)) {
4966        skip_call |=
4967            log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0,
4968                    __LINE__, DRAWSTATE_INVALID_CB_SIMULTANEOUS_USE, "DS",
4969                    "Command Buffer %#" PRIx64 " is already in use and is not marked for simultaneous use.",
4970                    reinterpret_cast<uint64_t>(pCB->commandBuffer));
4971    }
4972    return skip_call;
4973}
4974
4975static bool validateCommandBufferState(layer_data *dev_data, GLOBAL_CB_NODE *pCB) {
4976    bool skipCall = false;
4977    // Validate that cmd buffers have been updated
4978    if (CB_RECORDED != pCB->state) {
4979        if (CB_INVALID == pCB->state) {
4980            // Inform app of reason CB invalid
4981            bool causeReported = false;
4982            if (!pCB->destroyedSets.empty()) {
4983                std::stringstream set_string;
4984                for (auto set : pCB->destroyedSets)
4985                    set_string << " " << set;
4986
4987                skipCall |=
4988                    log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
4989                            (uint64_t)(pCB->commandBuffer), __LINE__, DRAWSTATE_INVALID_COMMAND_BUFFER, "DS",
4990                            "You are submitting command buffer %#" PRIxLEAST64
4991                            " that is invalid because it had the following bound descriptor set(s) destroyed: %s",
4992                            (uint64_t)(pCB->commandBuffer), set_string.str().c_str());
4993                causeReported = true;
4994            }
4995            if (!pCB->updatedSets.empty()) {
4996                std::stringstream set_string;
4997                for (auto set : pCB->updatedSets)
4998                    set_string << " " << set;
4999
5000                skipCall |=
5001                    log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
5002                            (uint64_t)(pCB->commandBuffer), __LINE__, DRAWSTATE_INVALID_COMMAND_BUFFER, "DS",
5003                            "You are submitting command buffer %#" PRIxLEAST64
5004                            " that is invalid because it had the following bound descriptor set(s) updated: %s",
5005                            (uint64_t)(pCB->commandBuffer), set_string.str().c_str());
5006                causeReported = true;
5007            }
5008            if (!pCB->destroyedFramebuffers.empty()) {
5009                std::stringstream fb_string;
5010                for (auto fb : pCB->destroyedFramebuffers)
5011                    fb_string << " " << fb;
5012
5013                skipCall |=
5014                    log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
5015                            reinterpret_cast<uint64_t &>(pCB->commandBuffer), __LINE__, DRAWSTATE_INVALID_COMMAND_BUFFER, "DS",
5016                            "You are submitting command buffer %#" PRIxLEAST64 " that is invalid because it had the following "
5017                            "referenced framebuffers destroyed: %s",
5018                            reinterpret_cast<uint64_t &>(pCB->commandBuffer), fb_string.str().c_str());
5019                causeReported = true;
5020            }
5021            // TODO : This is defensive programming to make sure an error is
5022            //  flagged if we hit this INVALID cmd buffer case and none of the
5023            //  above cases are hit. As the number of INVALID cases grows, this
5024            //  code should be updated to seemlessly handle all the cases.
5025            if (!causeReported) {
5026                skipCall |= log_msg(
5027                    dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
5028                    reinterpret_cast<uint64_t &>(pCB->commandBuffer), __LINE__, DRAWSTATE_INVALID_COMMAND_BUFFER, "DS",
5029                    "You are submitting command buffer %#" PRIxLEAST64 " that is invalid due to an unknown cause. Validation "
5030                    "should "
5031                    "be improved to report the exact cause.",
5032                    reinterpret_cast<uint64_t &>(pCB->commandBuffer));
5033            }
5034        } else { // Flag error for using CB w/o vkEndCommandBuffer() called
5035            skipCall |=
5036                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
5037                        (uint64_t)(pCB->commandBuffer), __LINE__, DRAWSTATE_NO_END_COMMAND_BUFFER, "DS",
5038                        "You must call vkEndCommandBuffer() on CB %#" PRIxLEAST64 " before this call to vkQueueSubmit()!",
5039                        (uint64_t)(pCB->commandBuffer));
5040        }
5041    }
5042    return skipCall;
5043}
5044
5045static bool validatePrimaryCommandBufferState(layer_data *dev_data, GLOBAL_CB_NODE *pCB) {
5046    // Track in-use for resources off of primary and any secondary CBs
5047    bool skipCall = validateAndIncrementResources(dev_data, pCB);
5048    if (!pCB->secondaryCommandBuffers.empty()) {
5049        for (auto secondaryCmdBuffer : pCB->secondaryCommandBuffers) {
5050            skipCall |= validateAndIncrementResources(dev_data, dev_data->commandBufferMap[secondaryCmdBuffer]);
5051            GLOBAL_CB_NODE *pSubCB = getCBNode(dev_data, secondaryCmdBuffer);
5052            if (pSubCB->primaryCommandBuffer != pCB->commandBuffer) {
5053                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0,
5054                        __LINE__, DRAWSTATE_COMMAND_BUFFER_SINGLE_SUBMIT_VIOLATION, "DS",
5055                        "CB %#" PRIxLEAST64 " was submitted with secondary buffer %#" PRIxLEAST64
5056                        " but that buffer has subsequently been bound to "
5057                        "primary cmd buffer %#" PRIxLEAST64 ".",
5058                        reinterpret_cast<uint64_t>(pCB->commandBuffer), reinterpret_cast<uint64_t>(secondaryCmdBuffer),
5059                        reinterpret_cast<uint64_t>(pSubCB->primaryCommandBuffer));
5060            }
5061        }
5062    }
5063    // TODO : Verify if this also needs to be checked for secondary command
5064    //  buffers. If so, this block of code can move to
5065    //   validateCommandBufferState() function. vulkan GL106 filed to clarify
5066    if ((pCB->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && (pCB->submitCount > 1)) {
5067        skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0,
5068                            __LINE__, DRAWSTATE_COMMAND_BUFFER_SINGLE_SUBMIT_VIOLATION, "DS",
5069                            "CB %#" PRIxLEAST64 " was begun w/ VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT "
5070                            "set, but has been submitted %#" PRIxLEAST64 " times.",
5071                            (uint64_t)(pCB->commandBuffer), pCB->submitCount);
5072    }
5073    skipCall |= validateCommandBufferState(dev_data, pCB);
5074    // If USAGE_SIMULTANEOUS_USE_BIT not set then CB cannot already be executing
5075    // on device
5076    skipCall |= validateCommandBufferSimultaneousUse(dev_data, pCB);
5077    return skipCall;
5078}
5079
5080VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
5081vkQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence) {
5082    bool skipCall = false;
5083    GLOBAL_CB_NODE *pCBNode = NULL;
5084    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(queue), layer_data_map);
5085    VkResult result = VK_ERROR_VALIDATION_FAILED_EXT;
5086    loader_platform_thread_lock_mutex(&globalLock);
5087    // First verify that fence is not in use
5088    if ((fence != VK_NULL_HANDLE) && (submitCount != 0) && dev_data->fenceMap[fence].in_use.load()) {
5089        skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT,
5090                            (uint64_t)(fence), __LINE__, DRAWSTATE_INVALID_FENCE, "DS",
5091                            "Fence %#" PRIx64 " is already in use by another submission.", (uint64_t)(fence));
5092    }
5093    uint64_t fenceId = 0;
5094    skipCall = add_fence_info(dev_data, fence, queue, &fenceId);
5095    // TODO : Review these old print functions and clean up as appropriate
5096    print_mem_list(dev_data);
5097    printCBList(dev_data);
5098    // Now verify each individual submit
5099    std::unordered_set<VkQueue> processed_other_queues;
5100    for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) {
5101        const VkSubmitInfo *submit = &pSubmits[submit_idx];
5102        vector<VkSemaphore> semaphoreList;
5103        for (uint32_t i = 0; i < submit->waitSemaphoreCount; ++i) {
5104            const VkSemaphore &semaphore = submit->pWaitSemaphores[i];
5105            semaphoreList.push_back(semaphore);
5106            if (dev_data->semaphoreMap.find(semaphore) != dev_data->semaphoreMap.end()) {
5107                if (dev_data->semaphoreMap[semaphore].signaled) {
5108                    dev_data->semaphoreMap[semaphore].signaled = false;
5109                } else {
5110                    skipCall |=
5111                        log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT,
5112                                reinterpret_cast<const uint64_t &>(semaphore), __LINE__, DRAWSTATE_QUEUE_FORWARD_PROGRESS, "DS",
5113                                "Queue %#" PRIx64 " is waiting on semaphore %#" PRIx64 " that has no way to be signaled.",
5114                                reinterpret_cast<uint64_t &>(queue), reinterpret_cast<const uint64_t &>(semaphore));
5115                }
5116                const VkQueue &other_queue = dev_data->semaphoreMap[semaphore].queue;
5117                if (other_queue != VK_NULL_HANDLE && !processed_other_queues.count(other_queue)) {
5118                    updateTrackedCommandBuffers(dev_data, queue, other_queue, fence);
5119                    processed_other_queues.insert(other_queue);
5120                }
5121            }
5122        }
5123        for (uint32_t i = 0; i < submit->signalSemaphoreCount; ++i) {
5124            const VkSemaphore &semaphore = submit->pSignalSemaphores[i];
5125            if (dev_data->semaphoreMap.find(semaphore) != dev_data->semaphoreMap.end()) {
5126                semaphoreList.push_back(semaphore);
5127                if (dev_data->semaphoreMap[semaphore].signaled) {
5128                    skipCall |=
5129                        log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT,
5130                                reinterpret_cast<const uint64_t &>(semaphore), __LINE__, DRAWSTATE_QUEUE_FORWARD_PROGRESS, "DS",
5131                                "Queue %#" PRIx64 " is signaling semaphore %#" PRIx64
5132                                " that has already been signaled but not waited on by queue %#" PRIx64 ".",
5133                                reinterpret_cast<uint64_t &>(queue), reinterpret_cast<const uint64_t &>(semaphore),
5134                                reinterpret_cast<uint64_t &>(dev_data->semaphoreMap[semaphore].queue));
5135                } else {
5136                    dev_data->semaphoreMap[semaphore].signaled = true;
5137                    dev_data->semaphoreMap[semaphore].queue = queue;
5138                }
5139            }
5140        }
5141        for (uint32_t i = 0; i < submit->commandBufferCount; i++) {
5142            skipCall |= ValidateCmdBufImageLayouts(submit->pCommandBuffers[i]);
5143            pCBNode = getCBNode(dev_data, submit->pCommandBuffers[i]);
5144            if (pCBNode) {
5145                pCBNode->semaphores = semaphoreList;
5146                pCBNode->submitCount++; // increment submit count
5147                pCBNode->fenceId = fenceId;
5148                pCBNode->lastSubmittedFence = fence;
5149                pCBNode->lastSubmittedQueue = queue;
5150                skipCall |= validatePrimaryCommandBufferState(dev_data, pCBNode);
5151                // Call submit-time functions to validate/update state
5152                for (auto &function : pCBNode->validate_functions) {
5153                    skipCall |= function();
5154                }
5155                for (auto &function : pCBNode->eventUpdates) {
5156                    skipCall |= function(queue);
5157                }
5158            }
5159        }
5160    }
5161    // Update cmdBuffer-related data structs and mark fence in-use
5162    trackCommandBuffers(dev_data, queue, submitCount, pSubmits, fence);
5163    loader_platform_thread_unlock_mutex(&globalLock);
5164    if (!skipCall)
5165        result = dev_data->device_dispatch_table->QueueSubmit(queue, submitCount, pSubmits, fence);
5166
5167    return result;
5168}
5169
5170#if MTMERGESOURCE
5171VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkAllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo,
5172                                                                const VkAllocationCallbacks *pAllocator, VkDeviceMemory *pMemory) {
5173    layer_data *my_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5174    VkResult result = my_data->device_dispatch_table->AllocateMemory(device, pAllocateInfo, pAllocator, pMemory);
5175    // TODO : Track allocations and overall size here
5176    loader_platform_thread_lock_mutex(&globalLock);
5177    add_mem_obj_info(my_data, device, *pMemory, pAllocateInfo);
5178    print_mem_list(my_data);
5179    loader_platform_thread_unlock_mutex(&globalLock);
5180    return result;
5181}
5182
5183VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
5184vkFreeMemory(VkDevice device, VkDeviceMemory mem, const VkAllocationCallbacks *pAllocator) {
5185    layer_data *my_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5186
5187    // From spec : A memory object is freed by calling vkFreeMemory() when it is no longer needed.
5188    // Before freeing a memory object, an application must ensure the memory object is no longer
5189    // in use by the device—for example by command buffers queued for execution. The memory need
5190    // not yet be unbound from all images and buffers, but any further use of those images or
5191    // buffers (on host or device) for anything other than destroying those objects will result in
5192    // undefined behavior.
5193
5194    loader_platform_thread_lock_mutex(&globalLock);
5195    freeMemObjInfo(my_data, device, mem, false);
5196    print_mem_list(my_data);
5197    printCBList(my_data);
5198    loader_platform_thread_unlock_mutex(&globalLock);
5199    my_data->device_dispatch_table->FreeMemory(device, mem, pAllocator);
5200}
5201
5202static bool validateMemRange(layer_data *my_data, VkDeviceMemory mem, VkDeviceSize offset, VkDeviceSize size) {
5203    bool skipCall = false;
5204
5205    if (size == 0) {
5206        // TODO: a size of 0 is not listed as an invalid use in the spec, should it be?
5207        skipCall = log_msg(my_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
5208                           (uint64_t)mem, __LINE__, MEMTRACK_INVALID_MAP, "MEM",
5209                           "VkMapMemory: Attempting to map memory range of size zero");
5210    }
5211
5212    auto mem_element = my_data->memObjMap.find(mem);
5213    if (mem_element != my_data->memObjMap.end()) {
5214        // It is an application error to call VkMapMemory on an object that is already mapped
5215        if (mem_element->second.memRange.size != 0) {
5216            skipCall = log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
5217                               (uint64_t)mem, __LINE__, MEMTRACK_INVALID_MAP, "MEM",
5218                               "VkMapMemory: Attempting to map memory on an already-mapped object %#" PRIxLEAST64, (uint64_t)mem);
5219        }
5220
5221        // Validate that offset + size is within object's allocationSize
5222        if (size == VK_WHOLE_SIZE) {
5223            if (offset >= mem_element->second.allocInfo.allocationSize) {
5224                skipCall = log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
5225                                   VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, (uint64_t)mem, __LINE__, MEMTRACK_INVALID_MAP,
5226                                   "MEM", "Mapping Memory from %" PRIu64 " to %" PRIu64 " with total array size %" PRIu64, offset,
5227                                   mem_element->second.allocInfo.allocationSize, mem_element->second.allocInfo.allocationSize);
5228            }
5229        } else {
5230            if ((offset + size) > mem_element->second.allocInfo.allocationSize) {
5231                skipCall = log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
5232                                   VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, (uint64_t)mem, __LINE__, MEMTRACK_INVALID_MAP,
5233                                   "MEM", "Mapping Memory from %" PRIu64 " to %" PRIu64 " with total array size %" PRIu64, offset,
5234                                   size + offset, mem_element->second.allocInfo.allocationSize);
5235            }
5236        }
5237    }
5238    return skipCall;
5239}
5240
5241static void storeMemRanges(layer_data *my_data, VkDeviceMemory mem, VkDeviceSize offset, VkDeviceSize size) {
5242    auto mem_element = my_data->memObjMap.find(mem);
5243    if (mem_element != my_data->memObjMap.end()) {
5244        MemRange new_range;
5245        new_range.offset = offset;
5246        new_range.size = size;
5247        mem_element->second.memRange = new_range;
5248    }
5249}
5250
5251static bool deleteMemRanges(layer_data *my_data, VkDeviceMemory mem) {
5252    bool skipCall = false;
5253    auto mem_element = my_data->memObjMap.find(mem);
5254    if (mem_element != my_data->memObjMap.end()) {
5255        if (!mem_element->second.memRange.size) {
5256            // Valid Usage: memory must currently be mapped
5257            skipCall = log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
5258                               (uint64_t)mem, __LINE__, MEMTRACK_INVALID_MAP, "MEM",
5259                               "Unmapping Memory without memory being mapped: mem obj %#" PRIxLEAST64, (uint64_t)mem);
5260        }
5261        mem_element->second.memRange.size = 0;
5262        if (mem_element->second.pData) {
5263            free(mem_element->second.pData);
5264            mem_element->second.pData = 0;
5265        }
5266    }
5267    return skipCall;
5268}
5269
5270static char NoncoherentMemoryFillValue = 0xb;
5271
5272static void initializeAndTrackMemory(layer_data *dev_data, VkDeviceMemory mem, VkDeviceSize size, void **ppData) {
5273    auto mem_element = dev_data->memObjMap.find(mem);
5274    if (mem_element != dev_data->memObjMap.end()) {
5275        mem_element->second.pDriverData = *ppData;
5276        uint32_t index = mem_element->second.allocInfo.memoryTypeIndex;
5277        if (dev_data->phys_dev_mem_props.memoryTypes[index].propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) {
5278            mem_element->second.pData = 0;
5279        } else {
5280            if (size == VK_WHOLE_SIZE) {
5281                size = mem_element->second.allocInfo.allocationSize;
5282            }
5283            size_t convSize = (size_t)(size);
5284            mem_element->second.pData = malloc(2 * convSize);
5285            memset(mem_element->second.pData, NoncoherentMemoryFillValue, 2 * convSize);
5286            *ppData = static_cast<char *>(mem_element->second.pData) + (convSize / 2);
5287        }
5288    }
5289}
5290#endif
5291// Note: This function assumes that the global lock is held by the calling
5292// thread.
5293static bool cleanInFlightCmdBuffer(layer_data *my_data, VkCommandBuffer cmdBuffer) {
5294    bool skip_call = false;
5295    GLOBAL_CB_NODE *pCB = getCBNode(my_data, cmdBuffer);
5296    if (pCB) {
5297        for (auto queryEventsPair : pCB->waitedEventsBeforeQueryReset) {
5298            for (auto event : queryEventsPair.second) {
5299                if (my_data->eventMap[event].needsSignaled) {
5300                    skip_call |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
5301                                         VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT, 0, 0, DRAWSTATE_INVALID_QUERY, "DS",
5302                                         "Cannot get query results on queryPool %" PRIu64
5303                                         " with index %d which was guarded by unsignaled event %" PRIu64 ".",
5304                                         (uint64_t)(queryEventsPair.first.pool), queryEventsPair.first.index, (uint64_t)(event));
5305                }
5306            }
5307        }
5308    }
5309    return skip_call;
5310}
5311// Remove given cmd_buffer from the global inFlight set.
5312//  Also, if given queue is valid, then remove the cmd_buffer from that queues
5313//  inFlightCmdBuffer set. Finally, check all other queues and if given cmd_buffer
5314//  is still in flight on another queue, add it back into the global set.
5315// Note: This function assumes that the global lock is held by the calling
5316// thread.
5317static inline void removeInFlightCmdBuffer(layer_data *dev_data, VkCommandBuffer cmd_buffer, VkQueue queue) {
5318    // Pull it off of global list initially, but if we find it in any other queue list, add it back in
5319    dev_data->globalInFlightCmdBuffers.erase(cmd_buffer);
5320    if (dev_data->queueMap.find(queue) != dev_data->queueMap.end()) {
5321        dev_data->queueMap[queue].inFlightCmdBuffers.erase(cmd_buffer);
5322        for (auto q : dev_data->queues) {
5323            if ((q != queue) &&
5324                (dev_data->queueMap[q].inFlightCmdBuffers.find(cmd_buffer) != dev_data->queueMap[q].inFlightCmdBuffers.end())) {
5325                dev_data->globalInFlightCmdBuffers.insert(cmd_buffer);
5326                break;
5327            }
5328        }
5329    }
5330}
5331#if MTMERGESOURCE
5332static inline bool verifyFenceStatus(VkDevice device, VkFence fence, const char *apiCall) {
5333    layer_data *my_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5334    bool skipCall = false;
5335    auto pFenceInfo = my_data->fenceMap.find(fence);
5336    if (pFenceInfo != my_data->fenceMap.end()) {
5337        if (!pFenceInfo->second.firstTimeFlag) {
5338            if ((pFenceInfo->second.createInfo.flags & VK_FENCE_CREATE_SIGNALED_BIT) && !pFenceInfo->second.firstTimeFlag) {
5339                skipCall |=
5340                    log_msg(my_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT,
5341                            (uint64_t)fence, __LINE__, MEMTRACK_INVALID_FENCE_STATE, "MEM",
5342                            "%s specified fence %#" PRIxLEAST64 " already in SIGNALED state.", apiCall, (uint64_t)fence);
5343            }
5344            if (!pFenceInfo->second.queue && !pFenceInfo->second.swapchain) { // Checking status of unsubmitted fence
5345                skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT,
5346                                    reinterpret_cast<uint64_t &>(fence), __LINE__, MEMTRACK_INVALID_FENCE_STATE, "MEM",
5347                                    "%s called for fence %#" PRIxLEAST64 " which has not been submitted on a Queue or during "
5348                                    "acquire next image.",
5349                                    apiCall, reinterpret_cast<uint64_t &>(fence));
5350            }
5351        } else {
5352            pFenceInfo->second.firstTimeFlag = false;
5353        }
5354    }
5355    return skipCall;
5356}
5357#endif
5358VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
5359vkWaitForFences(VkDevice device, uint32_t fenceCount, const VkFence *pFences, VkBool32 waitAll, uint64_t timeout) {
5360    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5361    bool skip_call = false;
5362#if MTMERGESOURCE
5363    // Verify fence status of submitted fences
5364    loader_platform_thread_lock_mutex(&globalLock);
5365    for (uint32_t i = 0; i < fenceCount; i++) {
5366        skip_call |= verifyFenceStatus(device, pFences[i], "vkWaitForFences");
5367    }
5368    loader_platform_thread_unlock_mutex(&globalLock);
5369    if (skip_call)
5370        return VK_ERROR_VALIDATION_FAILED_EXT;
5371#endif
5372    VkResult result = dev_data->device_dispatch_table->WaitForFences(device, fenceCount, pFences, waitAll, timeout);
5373
5374    if (result == VK_SUCCESS) {
5375        loader_platform_thread_lock_mutex(&globalLock);
5376        // When we know that all fences are complete we can clean/remove their CBs
5377        if (waitAll || fenceCount == 1) {
5378            for (uint32_t i = 0; i < fenceCount; ++i) {
5379#if MTMERGESOURCE
5380                update_fence_tracking(dev_data, pFences[i]);
5381#endif
5382                VkQueue fence_queue = dev_data->fenceMap[pFences[i]].queue;
5383                for (auto cmdBuffer : dev_data->fenceMap[pFences[i]].cmdBuffers) {
5384                    skip_call |= cleanInFlightCmdBuffer(dev_data, cmdBuffer);
5385                    removeInFlightCmdBuffer(dev_data, cmdBuffer, fence_queue);
5386                }
5387            }
5388            decrementResources(dev_data, fenceCount, pFences);
5389        }
5390        // NOTE : Alternate case not handled here is when some fences have completed. In
5391        //  this case for app to guarantee which fences completed it will have to call
5392        //  vkGetFenceStatus() at which point we'll clean/remove their CBs if complete.
5393        loader_platform_thread_unlock_mutex(&globalLock);
5394    }
5395    if (skip_call)
5396        return VK_ERROR_VALIDATION_FAILED_EXT;
5397    return result;
5398}
5399
5400VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkGetFenceStatus(VkDevice device, VkFence fence) {
5401    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5402    bool skipCall = false;
5403    VkResult result = VK_ERROR_VALIDATION_FAILED_EXT;
5404#if MTMERGESOURCE
5405    loader_platform_thread_lock_mutex(&globalLock);
5406    skipCall = verifyFenceStatus(device, fence, "vkGetFenceStatus");
5407    loader_platform_thread_unlock_mutex(&globalLock);
5408    if (skipCall)
5409        return result;
5410#endif
5411    result = dev_data->device_dispatch_table->GetFenceStatus(device, fence);
5412    bool skip_call = false;
5413    loader_platform_thread_lock_mutex(&globalLock);
5414    if (result == VK_SUCCESS) {
5415#if MTMERGESOURCE
5416        update_fence_tracking(dev_data, fence);
5417#endif
5418        auto fence_queue = dev_data->fenceMap[fence].queue;
5419        for (auto cmdBuffer : dev_data->fenceMap[fence].cmdBuffers) {
5420            skip_call |= cleanInFlightCmdBuffer(dev_data, cmdBuffer);
5421            removeInFlightCmdBuffer(dev_data, cmdBuffer, fence_queue);
5422        }
5423        decrementResources(dev_data, 1, &fence);
5424    }
5425    loader_platform_thread_unlock_mutex(&globalLock);
5426    if (skip_call)
5427        return VK_ERROR_VALIDATION_FAILED_EXT;
5428    return result;
5429}
5430
5431VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkGetDeviceQueue(VkDevice device, uint32_t queueFamilyIndex, uint32_t queueIndex,
5432                                                            VkQueue *pQueue) {
5433    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5434    dev_data->device_dispatch_table->GetDeviceQueue(device, queueFamilyIndex, queueIndex, pQueue);
5435    loader_platform_thread_lock_mutex(&globalLock);
5436
5437    // Add queue to tracking set only if it is new
5438    auto result = dev_data->queues.emplace(*pQueue);
5439    if (result.second == true) {
5440        QUEUE_NODE *pQNode = &dev_data->queueMap[*pQueue];
5441        pQNode->device = device;
5442#if MTMERGESOURCE
5443        pQNode->lastRetiredId = 0;
5444        pQNode->lastSubmittedId = 0;
5445#endif
5446    }
5447
5448    loader_platform_thread_unlock_mutex(&globalLock);
5449}
5450
5451VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkQueueWaitIdle(VkQueue queue) {
5452    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(queue), layer_data_map);
5453    decrementResources(dev_data, queue);
5454    bool skip_call = false;
5455    loader_platform_thread_lock_mutex(&globalLock);
5456    // Iterate over local set since we erase set members as we go in for loop
5457    auto local_cb_set = dev_data->queueMap[queue].inFlightCmdBuffers;
5458    for (auto cmdBuffer : local_cb_set) {
5459        skip_call |= cleanInFlightCmdBuffer(dev_data, cmdBuffer);
5460        removeInFlightCmdBuffer(dev_data, cmdBuffer, queue);
5461    }
5462    dev_data->queueMap[queue].inFlightCmdBuffers.clear();
5463    loader_platform_thread_unlock_mutex(&globalLock);
5464    if (skip_call)
5465        return VK_ERROR_VALIDATION_FAILED_EXT;
5466    VkResult result = dev_data->device_dispatch_table->QueueWaitIdle(queue);
5467#if MTMERGESOURCE
5468    if (VK_SUCCESS == result) {
5469        loader_platform_thread_lock_mutex(&globalLock);
5470        retire_queue_fences(dev_data, queue);
5471        loader_platform_thread_unlock_mutex(&globalLock);
5472    }
5473#endif
5474    return result;
5475}
5476
5477VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkDeviceWaitIdle(VkDevice device) {
5478    bool skip_call = false;
5479    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5480    loader_platform_thread_lock_mutex(&globalLock);
5481    for (auto queue : dev_data->queues) {
5482        decrementResources(dev_data, queue);
5483        if (dev_data->queueMap.find(queue) != dev_data->queueMap.end()) {
5484            // Clear all of the queue inFlightCmdBuffers (global set cleared below)
5485            dev_data->queueMap[queue].inFlightCmdBuffers.clear();
5486        }
5487    }
5488    for (auto cmdBuffer : dev_data->globalInFlightCmdBuffers) {
5489        skip_call |= cleanInFlightCmdBuffer(dev_data, cmdBuffer);
5490    }
5491    dev_data->globalInFlightCmdBuffers.clear();
5492    loader_platform_thread_unlock_mutex(&globalLock);
5493    if (skip_call)
5494        return VK_ERROR_VALIDATION_FAILED_EXT;
5495    VkResult result = dev_data->device_dispatch_table->DeviceWaitIdle(device);
5496#if MTMERGESOURCE
5497    if (VK_SUCCESS == result) {
5498        loader_platform_thread_lock_mutex(&globalLock);
5499        retire_device_fences(dev_data, device);
5500        loader_platform_thread_unlock_mutex(&globalLock);
5501    }
5502#endif
5503    return result;
5504}
5505
5506VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkDestroyFence(VkDevice device, VkFence fence, const VkAllocationCallbacks *pAllocator) {
5507    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5508    bool skipCall = false;
5509    loader_platform_thread_lock_mutex(&globalLock);
5510    auto fence_pair = dev_data->fenceMap.find(fence);
5511    if (fence_pair != dev_data->fenceMap.end()) {
5512        if (fence_pair->second.in_use.load()) {
5513            skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT,
5514                                (uint64_t)(fence), __LINE__, DRAWSTATE_INVALID_FENCE, "DS",
5515                                "Fence %#" PRIx64 " is in use by a command buffer.", (uint64_t)(fence));
5516        }
5517        dev_data->fenceMap.erase(fence_pair);
5518    }
5519    loader_platform_thread_unlock_mutex(&globalLock);
5520
5521    if (!skipCall)
5522        dev_data->device_dispatch_table->DestroyFence(device, fence, pAllocator);
5523}
5524
5525VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
5526vkDestroySemaphore(VkDevice device, VkSemaphore semaphore, const VkAllocationCallbacks *pAllocator) {
5527    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5528    dev_data->device_dispatch_table->DestroySemaphore(device, semaphore, pAllocator);
5529    loader_platform_thread_lock_mutex(&globalLock);
5530    auto item = dev_data->semaphoreMap.find(semaphore);
5531    if (item != dev_data->semaphoreMap.end()) {
5532        if (item->second.in_use.load()) {
5533            log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT,
5534                    reinterpret_cast<uint64_t &>(semaphore), __LINE__, DRAWSTATE_INVALID_SEMAPHORE, "DS",
5535                    "Cannot delete semaphore %" PRIx64 " which is in use.", reinterpret_cast<uint64_t &>(semaphore));
5536        }
5537        dev_data->semaphoreMap.erase(semaphore);
5538    }
5539    loader_platform_thread_unlock_mutex(&globalLock);
5540    // TODO : Clean up any internal data structures using this obj.
5541}
5542
5543VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
5544    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5545    bool skip_call = false;
5546    loader_platform_thread_lock_mutex(&globalLock);
5547    auto event_data = dev_data->eventMap.find(event);
5548    if (event_data != dev_data->eventMap.end()) {
5549        if (event_data->second.in_use.load()) {
5550            skip_call |= log_msg(
5551                dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
5552                reinterpret_cast<uint64_t &>(event), __LINE__, DRAWSTATE_INVALID_EVENT, "DS",
5553                "Cannot delete event %" PRIx64 " which is in use by a command buffer.", reinterpret_cast<uint64_t &>(event));
5554        }
5555        dev_data->eventMap.erase(event_data);
5556    }
5557    loader_platform_thread_unlock_mutex(&globalLock);
5558    if (!skip_call)
5559        dev_data->device_dispatch_table->DestroyEvent(device, event, pAllocator);
5560    // TODO : Clean up any internal data structures using this obj.
5561}
5562
5563VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
5564vkDestroyQueryPool(VkDevice device, VkQueryPool queryPool, const VkAllocationCallbacks *pAllocator) {
5565    get_my_data_ptr(get_dispatch_key(device), layer_data_map)
5566        ->device_dispatch_table->DestroyQueryPool(device, queryPool, pAllocator);
5567    // TODO : Clean up any internal data structures using this obj.
5568}
5569
5570VKAPI_ATTR VkResult VKAPI_CALL vkGetQueryPoolResults(VkDevice device, VkQueryPool queryPool, uint32_t firstQuery,
5571                                                     uint32_t queryCount, size_t dataSize, void *pData, VkDeviceSize stride,
5572                                                     VkQueryResultFlags flags) {
5573    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5574    unordered_map<QueryObject, vector<VkCommandBuffer>> queriesInFlight;
5575    GLOBAL_CB_NODE *pCB = nullptr;
5576    loader_platform_thread_lock_mutex(&globalLock);
5577    for (auto cmdBuffer : dev_data->globalInFlightCmdBuffers) {
5578        pCB = getCBNode(dev_data, cmdBuffer);
5579        for (auto queryStatePair : pCB->queryToStateMap) {
5580            queriesInFlight[queryStatePair.first].push_back(cmdBuffer);
5581        }
5582    }
5583    bool skip_call = false;
5584    for (uint32_t i = 0; i < queryCount; ++i) {
5585        QueryObject query = {queryPool, firstQuery + i};
5586        auto queryElement = queriesInFlight.find(query);
5587        auto queryToStateElement = dev_data->queryToStateMap.find(query);
5588        if (queryToStateElement != dev_data->queryToStateMap.end()) {
5589            // Available and in flight
5590            if (queryElement != queriesInFlight.end() && queryToStateElement != dev_data->queryToStateMap.end() &&
5591                queryToStateElement->second) {
5592                for (auto cmdBuffer : queryElement->second) {
5593                    pCB = getCBNode(dev_data, cmdBuffer);
5594                    auto queryEventElement = pCB->waitedEventsBeforeQueryReset.find(query);
5595                    if (queryEventElement == pCB->waitedEventsBeforeQueryReset.end()) {
5596                        skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
5597                                             VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT, 0, __LINE__, DRAWSTATE_INVALID_QUERY, "DS",
5598                                             "Cannot get query results on queryPool %" PRIu64 " with index %d which is in flight.",
5599                                             (uint64_t)(queryPool), firstQuery + i);
5600                    } else {
5601                        for (auto event : queryEventElement->second) {
5602                            dev_data->eventMap[event].needsSignaled = true;
5603                        }
5604                    }
5605                }
5606                // Unavailable and in flight
5607            } else if (queryElement != queriesInFlight.end() && queryToStateElement != dev_data->queryToStateMap.end() &&
5608                       !queryToStateElement->second) {
5609                // TODO : Can there be the same query in use by multiple command buffers in flight?
5610                bool make_available = false;
5611                for (auto cmdBuffer : queryElement->second) {
5612                    pCB = getCBNode(dev_data, cmdBuffer);
5613                    make_available |= pCB->queryToStateMap[query];
5614                }
5615                if (!(((flags & VK_QUERY_RESULT_PARTIAL_BIT) || (flags & VK_QUERY_RESULT_WAIT_BIT)) && make_available)) {
5616                    skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
5617                                         VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT, 0, __LINE__, DRAWSTATE_INVALID_QUERY, "DS",
5618                                         "Cannot get query results on queryPool %" PRIu64 " with index %d which is unavailable.",
5619                                         (uint64_t)(queryPool), firstQuery + i);
5620                }
5621                // Unavailable
5622            } else if (queryToStateElement != dev_data->queryToStateMap.end() && !queryToStateElement->second) {
5623                skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
5624                                     VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT, 0, __LINE__, DRAWSTATE_INVALID_QUERY, "DS",
5625                                     "Cannot get query results on queryPool %" PRIu64 " with index %d which is unavailable.",
5626                                     (uint64_t)(queryPool), firstQuery + i);
5627                // Unitialized
5628            } else if (queryToStateElement == dev_data->queryToStateMap.end()) {
5629                skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
5630                                     VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT, 0, __LINE__, DRAWSTATE_INVALID_QUERY, "DS",
5631                                     "Cannot get query results on queryPool %" PRIu64
5632                                     " with index %d as data has not been collected for this index.",
5633                                     (uint64_t)(queryPool), firstQuery + i);
5634            }
5635        }
5636    }
5637    loader_platform_thread_unlock_mutex(&globalLock);
5638    if (skip_call)
5639        return VK_ERROR_VALIDATION_FAILED_EXT;
5640    return dev_data->device_dispatch_table->GetQueryPoolResults(device, queryPool, firstQuery, queryCount, dataSize, pData, stride,
5641                                                                flags);
5642}
5643
5644static bool validateIdleBuffer(const layer_data *my_data, VkBuffer buffer) {
5645    bool skip_call = false;
5646    auto buffer_data = my_data->bufferMap.find(buffer);
5647    if (buffer_data == my_data->bufferMap.end()) {
5648        skip_call |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
5649                             (uint64_t)(buffer), __LINE__, DRAWSTATE_DOUBLE_DESTROY, "DS",
5650                             "Cannot free buffer %" PRIxLEAST64 " that has not been allocated.", (uint64_t)(buffer));
5651    } else {
5652        if (buffer_data->second.in_use.load()) {
5653            skip_call |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
5654                                 (uint64_t)(buffer), __LINE__, DRAWSTATE_OBJECT_INUSE, "DS",
5655                                 "Cannot free buffer %" PRIxLEAST64 " that is in use by a command buffer.", (uint64_t)(buffer));
5656        }
5657    }
5658    return skip_call;
5659}
5660
5661VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
5662vkDestroyBuffer(VkDevice device, VkBuffer buffer, const VkAllocationCallbacks *pAllocator) {
5663    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5664    bool skipCall = false;
5665    loader_platform_thread_lock_mutex(&globalLock);
5666    if (!validateIdleBuffer(dev_data, buffer) && !skipCall) {
5667        loader_platform_thread_unlock_mutex(&globalLock);
5668        dev_data->device_dispatch_table->DestroyBuffer(device, buffer, pAllocator);
5669        loader_platform_thread_lock_mutex(&globalLock);
5670    }
5671    dev_data->bufferMap.erase(buffer);
5672    loader_platform_thread_unlock_mutex(&globalLock);
5673}
5674
5675VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
5676vkDestroyBufferView(VkDevice device, VkBufferView bufferView, const VkAllocationCallbacks *pAllocator) {
5677    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5678    dev_data->device_dispatch_table->DestroyBufferView(device, bufferView, pAllocator);
5679    loader_platform_thread_lock_mutex(&globalLock);
5680    auto item = dev_data->bufferViewMap.find(bufferView);
5681    if (item != dev_data->bufferViewMap.end()) {
5682        dev_data->bufferViewMap.erase(item);
5683    }
5684    loader_platform_thread_unlock_mutex(&globalLock);
5685}
5686
5687VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
5688    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5689    bool skipCall = false;
5690    if (!skipCall)
5691        dev_data->device_dispatch_table->DestroyImage(device, image, pAllocator);
5692
5693    loader_platform_thread_lock_mutex(&globalLock);
5694    const auto& entry = dev_data->imageMap.find(image);
5695    if (entry != dev_data->imageMap.end()) {
5696        // Clear any memory mapping for this image
5697        auto mem_entry = dev_data->memObjMap.find(entry->second.mem);
5698        if (mem_entry != dev_data->memObjMap.end())
5699            mem_entry->second.image = VK_NULL_HANDLE;
5700
5701        // Remove image from imageMap
5702        dev_data->imageMap.erase(entry);
5703    }
5704    const auto& subEntry = dev_data->imageSubresourceMap.find(image);
5705    if (subEntry != dev_data->imageSubresourceMap.end()) {
5706        for (const auto& pair : subEntry->second) {
5707            dev_data->imageLayoutMap.erase(pair);
5708        }
5709        dev_data->imageSubresourceMap.erase(subEntry);
5710    }
5711    loader_platform_thread_unlock_mutex(&globalLock);
5712}
5713#if MTMERGESOURCE
5714static bool print_memory_range_error(layer_data *dev_data, const uint64_t object_handle, const uint64_t other_handle,
5715                                     VkDebugReportObjectTypeEXT object_type) {
5716    if (object_type == VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT) {
5717        return log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, object_type, object_handle, 0,
5718                       MEMTRACK_INVALID_ALIASING, "MEM", "Buffer %" PRIx64 " is alised with image %" PRIx64, object_handle,
5719                       other_handle);
5720    } else {
5721        return log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, object_type, object_handle, 0,
5722                       MEMTRACK_INVALID_ALIASING, "MEM", "Image %" PRIx64 " is alised with buffer %" PRIx64, object_handle,
5723                       other_handle);
5724    }
5725}
5726
5727static bool validate_memory_range(layer_data *dev_data, const vector<MEMORY_RANGE> &ranges, const MEMORY_RANGE &new_range,
5728                                  VkDebugReportObjectTypeEXT object_type) {
5729    bool skip_call = false;
5730
5731    for (auto range : ranges) {
5732        if ((range.end & ~(dev_data->phys_dev_properties.properties.limits.bufferImageGranularity - 1)) <
5733            (new_range.start & ~(dev_data->phys_dev_properties.properties.limits.bufferImageGranularity - 1)))
5734            continue;
5735        if ((range.start & ~(dev_data->phys_dev_properties.properties.limits.bufferImageGranularity - 1)) >
5736            (new_range.end & ~(dev_data->phys_dev_properties.properties.limits.bufferImageGranularity - 1)))
5737            continue;
5738        skip_call |= print_memory_range_error(dev_data, new_range.handle, range.handle, object_type);
5739    }
5740    return skip_call;
5741}
5742
5743static bool validate_buffer_image_aliasing(layer_data *dev_data, uint64_t handle, VkDeviceMemory mem, VkDeviceSize memoryOffset,
5744                                           VkMemoryRequirements memRequirements, vector<MEMORY_RANGE> &ranges,
5745                                           const vector<MEMORY_RANGE> &other_ranges, VkDebugReportObjectTypeEXT object_type) {
5746    MEMORY_RANGE range;
5747    range.handle = handle;
5748    range.memory = mem;
5749    range.start = memoryOffset;
5750    range.end = memoryOffset + memRequirements.size - 1;
5751    ranges.push_back(range);
5752    return validate_memory_range(dev_data, other_ranges, range, object_type);
5753}
5754
5755VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
5756vkBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory mem, VkDeviceSize memoryOffset) {
5757    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5758    VkResult result = VK_ERROR_VALIDATION_FAILED_EXT;
5759    loader_platform_thread_lock_mutex(&globalLock);
5760    // Track objects tied to memory
5761    uint64_t buffer_handle = (uint64_t)(buffer);
5762    bool skipCall =
5763        set_mem_binding(dev_data, mem, buffer_handle, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, "vkBindBufferMemory");
5764    auto buffer_node = dev_data->bufferMap.find(buffer);
5765    if (buffer_node != dev_data->bufferMap.end()) {
5766        buffer_node->second.mem = mem;
5767        VkMemoryRequirements memRequirements;
5768        dev_data->device_dispatch_table->GetBufferMemoryRequirements(device, buffer, &memRequirements);
5769        skipCall |= validate_buffer_image_aliasing(dev_data, buffer_handle, mem, memoryOffset, memRequirements,
5770                                                   dev_data->memObjMap[mem].bufferRanges, dev_data->memObjMap[mem].imageRanges,
5771                                                   VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT);
5772        // Validate memory requirements alignment
5773        if (vk_safe_modulo(memoryOffset, memRequirements.alignment) != 0) {
5774            skipCall |=
5775                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT, 0,
5776                        __LINE__, DRAWSTATE_INVALID_BUFFER_MEMORY_OFFSET, "DS",
5777                        "vkBindBufferMemory(): memoryOffset is %#" PRIxLEAST64 " but must be an integer multiple of the "
5778                        "VkMemoryRequirements::alignment value %#" PRIxLEAST64
5779                        ", returned from a call to vkGetBufferMemoryRequirements with buffer",
5780                        memoryOffset, memRequirements.alignment);
5781        }
5782        // Validate device limits alignments
5783        VkBufferUsageFlags usage = dev_data->bufferMap[buffer].createInfo.usage;
5784        if (usage & (VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT)) {
5785            if (vk_safe_modulo(memoryOffset, dev_data->phys_dev_properties.properties.limits.minTexelBufferOffsetAlignment) != 0) {
5786                skipCall |=
5787                    log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT,
5788                            0, __LINE__, DRAWSTATE_INVALID_TEXEL_BUFFER_OFFSET, "DS",
5789                            "vkBindBufferMemory(): memoryOffset is %#" PRIxLEAST64 " but must be a multiple of "
5790                            "device limit minTexelBufferOffsetAlignment %#" PRIxLEAST64,
5791                            memoryOffset, dev_data->phys_dev_properties.properties.limits.minTexelBufferOffsetAlignment);
5792            }
5793        }
5794        if (usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT) {
5795            if (vk_safe_modulo(memoryOffset, dev_data->phys_dev_properties.properties.limits.minUniformBufferOffsetAlignment) !=
5796                0) {
5797                skipCall |=
5798                    log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT,
5799                            0, __LINE__, DRAWSTATE_INVALID_UNIFORM_BUFFER_OFFSET, "DS",
5800                            "vkBindBufferMemory(): memoryOffset is %#" PRIxLEAST64 " but must be a multiple of "
5801                            "device limit minUniformBufferOffsetAlignment %#" PRIxLEAST64,
5802                            memoryOffset, dev_data->phys_dev_properties.properties.limits.minUniformBufferOffsetAlignment);
5803            }
5804        }
5805        if (usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) {
5806            if (vk_safe_modulo(memoryOffset, dev_data->phys_dev_properties.properties.limits.minStorageBufferOffsetAlignment) !=
5807                0) {
5808                skipCall |=
5809                    log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT,
5810                            0, __LINE__, DRAWSTATE_INVALID_STORAGE_BUFFER_OFFSET, "DS",
5811                            "vkBindBufferMemory(): memoryOffset is %#" PRIxLEAST64 " but must be a multiple of "
5812                            "device limit minStorageBufferOffsetAlignment %#" PRIxLEAST64,
5813                            memoryOffset, dev_data->phys_dev_properties.properties.limits.minStorageBufferOffsetAlignment);
5814            }
5815        }
5816    }
5817    print_mem_list(dev_data);
5818    loader_platform_thread_unlock_mutex(&globalLock);
5819    if (!skipCall) {
5820        result = dev_data->device_dispatch_table->BindBufferMemory(device, buffer, mem, memoryOffset);
5821    }
5822    return result;
5823}
5824
5825VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
5826vkGetBufferMemoryRequirements(VkDevice device, VkBuffer buffer, VkMemoryRequirements *pMemoryRequirements) {
5827    layer_data *my_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5828    // TODO : What to track here?
5829    //   Could potentially save returned mem requirements and validate values passed into BindBufferMemory
5830    my_data->device_dispatch_table->GetBufferMemoryRequirements(device, buffer, pMemoryRequirements);
5831}
5832
5833VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
5834vkGetImageMemoryRequirements(VkDevice device, VkImage image, VkMemoryRequirements *pMemoryRequirements) {
5835    layer_data *my_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5836    // TODO : What to track here?
5837    //   Could potentially save returned mem requirements and validate values passed into BindImageMemory
5838    my_data->device_dispatch_table->GetImageMemoryRequirements(device, image, pMemoryRequirements);
5839}
5840#endif
5841VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
5842vkDestroyImageView(VkDevice device, VkImageView imageView, const VkAllocationCallbacks *pAllocator) {
5843    get_my_data_ptr(get_dispatch_key(device), layer_data_map)
5844        ->device_dispatch_table->DestroyImageView(device, imageView, pAllocator);
5845    // TODO : Clean up any internal data structures using this obj.
5846}
5847
5848VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
5849vkDestroyShaderModule(VkDevice device, VkShaderModule shaderModule, const VkAllocationCallbacks *pAllocator) {
5850    layer_data *my_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5851
5852    loader_platform_thread_lock_mutex(&globalLock);
5853
5854    my_data->shaderModuleMap.erase(shaderModule);
5855
5856    loader_platform_thread_unlock_mutex(&globalLock);
5857
5858    my_data->device_dispatch_table->DestroyShaderModule(device, shaderModule, pAllocator);
5859}
5860
5861VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
5862vkDestroyPipeline(VkDevice device, VkPipeline pipeline, const VkAllocationCallbacks *pAllocator) {
5863    get_my_data_ptr(get_dispatch_key(device), layer_data_map)->device_dispatch_table->DestroyPipeline(device, pipeline, pAllocator);
5864    // TODO : Clean up any internal data structures using this obj.
5865}
5866
5867VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
5868vkDestroyPipelineLayout(VkDevice device, VkPipelineLayout pipelineLayout, const VkAllocationCallbacks *pAllocator) {
5869    get_my_data_ptr(get_dispatch_key(device), layer_data_map)
5870        ->device_dispatch_table->DestroyPipelineLayout(device, pipelineLayout, pAllocator);
5871    // TODO : Clean up any internal data structures using this obj.
5872}
5873
5874VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
5875vkDestroySampler(VkDevice device, VkSampler sampler, const VkAllocationCallbacks *pAllocator) {
5876    get_my_data_ptr(get_dispatch_key(device), layer_data_map)->device_dispatch_table->DestroySampler(device, sampler, pAllocator);
5877    // TODO : Clean up any internal data structures using this obj.
5878}
5879
5880VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
5881vkDestroyDescriptorSetLayout(VkDevice device, VkDescriptorSetLayout descriptorSetLayout, const VkAllocationCallbacks *pAllocator) {
5882    get_my_data_ptr(get_dispatch_key(device), layer_data_map)
5883        ->device_dispatch_table->DestroyDescriptorSetLayout(device, descriptorSetLayout, pAllocator);
5884    // TODO : Clean up any internal data structures using this obj.
5885}
5886
5887VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
5888vkDestroyDescriptorPool(VkDevice device, VkDescriptorPool descriptorPool, const VkAllocationCallbacks *pAllocator) {
5889    get_my_data_ptr(get_dispatch_key(device), layer_data_map)
5890        ->device_dispatch_table->DestroyDescriptorPool(device, descriptorPool, pAllocator);
5891    // TODO : Clean up any internal data structures using this obj.
5892}
5893
5894VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
5895vkFreeCommandBuffers(VkDevice device, VkCommandPool commandPool, uint32_t commandBufferCount, const VkCommandBuffer *pCommandBuffers) {
5896    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5897
5898    bool skip_call = false;
5899    loader_platform_thread_lock_mutex(&globalLock);
5900    for (uint32_t i = 0; i < commandBufferCount; i++) {
5901        if (dev_data->globalInFlightCmdBuffers.count(pCommandBuffers[i])) {
5902            skip_call |=
5903                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
5904                        reinterpret_cast<uint64_t>(pCommandBuffers[i]), __LINE__, DRAWSTATE_INVALID_COMMAND_BUFFER_RESET, "DS",
5905                        "Attempt to free command buffer (%#" PRIxLEAST64 ") which is in use.",
5906                        reinterpret_cast<uint64_t>(pCommandBuffers[i]));
5907        }
5908        // Delete CB information structure, and remove from commandBufferMap
5909        auto cb = dev_data->commandBufferMap.find(pCommandBuffers[i]);
5910        if (cb != dev_data->commandBufferMap.end()) {
5911            // reset prior to delete for data clean-up
5912            resetCB(dev_data, (*cb).second->commandBuffer);
5913            delete (*cb).second;
5914            dev_data->commandBufferMap.erase(cb);
5915        }
5916
5917        // Remove commandBuffer reference from commandPoolMap
5918        dev_data->commandPoolMap[commandPool].commandBuffers.remove(pCommandBuffers[i]);
5919    }
5920#if MTMERGESOURCE
5921    printCBList(dev_data);
5922#endif
5923    loader_platform_thread_unlock_mutex(&globalLock);
5924
5925    if (!skip_call)
5926        dev_data->device_dispatch_table->FreeCommandBuffers(device, commandPool, commandBufferCount, pCommandBuffers);
5927}
5928
5929VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo *pCreateInfo,
5930                                                                   const VkAllocationCallbacks *pAllocator,
5931                                                                   VkCommandPool *pCommandPool) {
5932    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5933
5934    VkResult result = dev_data->device_dispatch_table->CreateCommandPool(device, pCreateInfo, pAllocator, pCommandPool);
5935
5936    if (VK_SUCCESS == result) {
5937        loader_platform_thread_lock_mutex(&globalLock);
5938        dev_data->commandPoolMap[*pCommandPool].createFlags = pCreateInfo->flags;
5939        dev_data->commandPoolMap[*pCommandPool].queueFamilyIndex = pCreateInfo->queueFamilyIndex;
5940        loader_platform_thread_unlock_mutex(&globalLock);
5941    }
5942    return result;
5943}
5944
5945VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkCreateQueryPool(VkDevice device, const VkQueryPoolCreateInfo *pCreateInfo,
5946                                                                 const VkAllocationCallbacks *pAllocator, VkQueryPool *pQueryPool) {
5947
5948    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5949    VkResult result = dev_data->device_dispatch_table->CreateQueryPool(device, pCreateInfo, pAllocator, pQueryPool);
5950    if (result == VK_SUCCESS) {
5951        loader_platform_thread_lock_mutex(&globalLock);
5952        dev_data->queryPoolMap[*pQueryPool].createInfo = *pCreateInfo;
5953        loader_platform_thread_unlock_mutex(&globalLock);
5954    }
5955    return result;
5956}
5957
5958static bool validateCommandBuffersNotInUse(const layer_data *dev_data, VkCommandPool commandPool, const char *action) {
5959    bool skipCall = false;
5960    auto pool_data = dev_data->commandPoolMap.find(commandPool);
5961    if (pool_data != dev_data->commandPoolMap.end()) {
5962        for (auto cmdBuffer : pool_data->second.commandBuffers) {
5963            if (dev_data->globalInFlightCmdBuffers.count(cmdBuffer)) {
5964                skipCall |=
5965                    log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_POOL_EXT,
5966                            (uint64_t)(commandPool), __LINE__, DRAWSTATE_OBJECT_INUSE, "DS",
5967                            "Cannot %s command pool %" PRIx64 " when allocated command buffer %" PRIx64 " is in use.", action,
5968                            reinterpret_cast<const uint64_t &>(commandPool), reinterpret_cast<const uint64_t &>(cmdBuffer));
5969            }
5970        }
5971    }
5972    return skipCall;
5973}
5974
5975// Destroy commandPool along with all of the commandBuffers allocated from that pool
5976VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
5977vkDestroyCommandPool(VkDevice device, VkCommandPool commandPool, const VkAllocationCallbacks *pAllocator) {
5978    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
5979    bool skipCall = false;
5980    loader_platform_thread_lock_mutex(&globalLock);
5981    // Verify that command buffers in pool are complete (not in-flight)
5982    VkBool32 result = validateCommandBuffersNotInUse(dev_data, commandPool, "destroy");
5983    // Must remove cmdpool from cmdpoolmap, after removing all cmdbuffers in its list from the commandPoolMap
5984    if (dev_data->commandPoolMap.find(commandPool) != dev_data->commandPoolMap.end()) {
5985        for (auto poolCb = dev_data->commandPoolMap[commandPool].commandBuffers.begin();
5986             poolCb != dev_data->commandPoolMap[commandPool].commandBuffers.end();) {
5987            clear_cmd_buf_and_mem_references(dev_data, *poolCb);
5988            auto del_cb = dev_data->commandBufferMap.find(*poolCb);
5989            delete (*del_cb).second;                  // delete CB info structure
5990            dev_data->commandBufferMap.erase(del_cb); // Remove this command buffer
5991            poolCb = dev_data->commandPoolMap[commandPool].commandBuffers.erase(
5992                poolCb); // Remove CB reference from commandPoolMap's list
5993        }
5994    }
5995    dev_data->commandPoolMap.erase(commandPool);
5996
5997    loader_platform_thread_unlock_mutex(&globalLock);
5998
5999    if (result)
6000        return;
6001
6002    if (!skipCall)
6003        dev_data->device_dispatch_table->DestroyCommandPool(device, commandPool, pAllocator);
6004}
6005
6006VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
6007vkResetCommandPool(VkDevice device, VkCommandPool commandPool, VkCommandPoolResetFlags flags) {
6008    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6009    bool skipCall = false;
6010    VkResult result = VK_ERROR_VALIDATION_FAILED_EXT;
6011
6012    if (validateCommandBuffersNotInUse(dev_data, commandPool, "reset"))
6013        return VK_ERROR_VALIDATION_FAILED_EXT;
6014
6015    if (!skipCall)
6016        result = dev_data->device_dispatch_table->ResetCommandPool(device, commandPool, flags);
6017
6018    // Reset all of the CBs allocated from this pool
6019    if (VK_SUCCESS == result) {
6020        loader_platform_thread_lock_mutex(&globalLock);
6021        auto it = dev_data->commandPoolMap[commandPool].commandBuffers.begin();
6022        while (it != dev_data->commandPoolMap[commandPool].commandBuffers.end()) {
6023            resetCB(dev_data, (*it));
6024            ++it;
6025        }
6026        loader_platform_thread_unlock_mutex(&globalLock);
6027    }
6028    return result;
6029}
6030
6031VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkResetFences(VkDevice device, uint32_t fenceCount, const VkFence *pFences) {
6032    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6033    VkResult result = VK_ERROR_VALIDATION_FAILED_EXT;
6034    bool skipCall = false;
6035    loader_platform_thread_lock_mutex(&globalLock);
6036    for (uint32_t i = 0; i < fenceCount; ++i) {
6037#if MTMERGESOURCE
6038        // Reset fence state in fenceCreateInfo structure
6039        // MTMTODO : Merge with code below
6040        auto fence_item = dev_data->fenceMap.find(pFences[i]);
6041        if (fence_item != dev_data->fenceMap.end()) {
6042            // Validate fences in SIGNALED state
6043            if (!(fence_item->second.createInfo.flags & VK_FENCE_CREATE_SIGNALED_BIT)) {
6044                // TODO: I don't see a Valid Usage section for ResetFences. This behavior should be documented there.
6045                skipCall = log_msg(dev_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT,
6046                                   (uint64_t)pFences[i], __LINE__, MEMTRACK_INVALID_FENCE_STATE, "MEM",
6047                                   "Fence %#" PRIxLEAST64 " submitted to VkResetFences in UNSIGNALED STATE", (uint64_t)pFences[i]);
6048            } else {
6049                fence_item->second.createInfo.flags =
6050                    static_cast<VkFenceCreateFlags>(fence_item->second.createInfo.flags & ~VK_FENCE_CREATE_SIGNALED_BIT);
6051            }
6052        }
6053#endif
6054        if (dev_data->fenceMap[pFences[i]].in_use.load()) {
6055            skipCall |=
6056                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT,
6057                        reinterpret_cast<const uint64_t &>(pFences[i]), __LINE__, DRAWSTATE_INVALID_FENCE, "DS",
6058                        "Fence %#" PRIx64 " is in use by a command buffer.", reinterpret_cast<const uint64_t &>(pFences[i]));
6059        }
6060    }
6061    loader_platform_thread_unlock_mutex(&globalLock);
6062    if (!skipCall)
6063        result = dev_data->device_dispatch_table->ResetFences(device, fenceCount, pFences);
6064    return result;
6065}
6066
6067VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
6068vkDestroyFramebuffer(VkDevice device, VkFramebuffer framebuffer, const VkAllocationCallbacks *pAllocator) {
6069    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6070    loader_platform_thread_lock_mutex(&globalLock);
6071    auto fbNode = dev_data->frameBufferMap.find(framebuffer);
6072    if (fbNode != dev_data->frameBufferMap.end()) {
6073        for (auto cb : fbNode->second.referencingCmdBuffers) {
6074            auto cbNode = dev_data->commandBufferMap.find(cb);
6075            if (cbNode != dev_data->commandBufferMap.end()) {
6076                // Set CB as invalid and record destroyed framebuffer
6077                cbNode->second->state = CB_INVALID;
6078                cbNode->second->destroyedFramebuffers.insert(framebuffer);
6079            }
6080        }
6081        delete [] fbNode->second.createInfo.pAttachments;
6082        dev_data->frameBufferMap.erase(fbNode);
6083    }
6084    loader_platform_thread_unlock_mutex(&globalLock);
6085    dev_data->device_dispatch_table->DestroyFramebuffer(device, framebuffer, pAllocator);
6086}
6087
6088VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
6089vkDestroyRenderPass(VkDevice device, VkRenderPass renderPass, const VkAllocationCallbacks *pAllocator) {
6090    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6091    dev_data->device_dispatch_table->DestroyRenderPass(device, renderPass, pAllocator);
6092    loader_platform_thread_lock_mutex(&globalLock);
6093    dev_data->renderPassMap.erase(renderPass);
6094    loader_platform_thread_unlock_mutex(&globalLock);
6095}
6096
6097VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkCreateBuffer(VkDevice device, const VkBufferCreateInfo *pCreateInfo,
6098                                                              const VkAllocationCallbacks *pAllocator, VkBuffer *pBuffer) {
6099    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6100
6101    VkResult result = dev_data->device_dispatch_table->CreateBuffer(device, pCreateInfo, pAllocator, pBuffer);
6102
6103    if (VK_SUCCESS == result) {
6104        loader_platform_thread_lock_mutex(&globalLock);
6105        // TODO : This doesn't create deep copy of pQueueFamilyIndices so need to fix that if/when we want that data to be valid
6106        dev_data->bufferMap[*pBuffer].createInfo = *pCreateInfo;
6107        dev_data->bufferMap[*pBuffer].in_use.store(0);
6108        loader_platform_thread_unlock_mutex(&globalLock);
6109    }
6110    return result;
6111}
6112
6113VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkCreateBufferView(VkDevice device, const VkBufferViewCreateInfo *pCreateInfo,
6114                                                                  const VkAllocationCallbacks *pAllocator, VkBufferView *pView) {
6115    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6116    VkResult result = dev_data->device_dispatch_table->CreateBufferView(device, pCreateInfo, pAllocator, pView);
6117    if (VK_SUCCESS == result) {
6118        loader_platform_thread_lock_mutex(&globalLock);
6119        dev_data->bufferViewMap[*pView] = VkBufferViewCreateInfo(*pCreateInfo);
6120#if MTMERGESOURCE
6121        // In order to create a valid buffer view, the buffer must have been created with at least one of the
6122        // following flags:  UNIFORM_TEXEL_BUFFER_BIT or STORAGE_TEXEL_BUFFER_BIT
6123        validate_buffer_usage_flags(dev_data, pCreateInfo->buffer,
6124                                    VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT, false,
6125                                    "vkCreateBufferView()", "VK_BUFFER_USAGE_[STORAGE|UNIFORM]_TEXEL_BUFFER_BIT");
6126#endif
6127        loader_platform_thread_unlock_mutex(&globalLock);
6128    }
6129    return result;
6130}
6131
6132VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkCreateImage(VkDevice device, const VkImageCreateInfo *pCreateInfo,
6133                                                             const VkAllocationCallbacks *pAllocator, VkImage *pImage) {
6134    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6135
6136    VkResult result = dev_data->device_dispatch_table->CreateImage(device, pCreateInfo, pAllocator, pImage);
6137
6138    if (VK_SUCCESS == result) {
6139        loader_platform_thread_lock_mutex(&globalLock);
6140        IMAGE_LAYOUT_NODE image_node;
6141        image_node.layout = pCreateInfo->initialLayout;
6142        image_node.format = pCreateInfo->format;
6143        dev_data->imageMap[*pImage].createInfo = *pCreateInfo;
6144        ImageSubresourcePair subpair = {*pImage, false, VkImageSubresource()};
6145        dev_data->imageSubresourceMap[*pImage].push_back(subpair);
6146        dev_data->imageLayoutMap[subpair] = image_node;
6147        loader_platform_thread_unlock_mutex(&globalLock);
6148    }
6149    return result;
6150}
6151
6152static void ResolveRemainingLevelsLayers(layer_data *dev_data, VkImageSubresourceRange *range, VkImage image) {
6153    /* expects globalLock to be held by caller */
6154
6155    auto image_node_it = dev_data->imageMap.find(image);
6156    if (image_node_it != dev_data->imageMap.end()) {
6157        /* If the caller used the special values VK_REMAINING_MIP_LEVELS and
6158         * VK_REMAINING_ARRAY_LAYERS, resolve them now in our internal state to
6159         * the actual values.
6160         */
6161        if (range->levelCount == VK_REMAINING_MIP_LEVELS) {
6162            range->levelCount = image_node_it->second.createInfo.mipLevels - range->baseMipLevel;
6163        }
6164
6165        if (range->layerCount == VK_REMAINING_ARRAY_LAYERS) {
6166            range->layerCount = image_node_it->second.createInfo.arrayLayers - range->baseArrayLayer;
6167        }
6168    }
6169}
6170
6171// Return the correct layer/level counts if the caller used the special
6172// values VK_REMAINING_MIP_LEVELS or VK_REMAINING_ARRAY_LAYERS.
6173static void ResolveRemainingLevelsLayers(layer_data *dev_data, uint32_t *levels, uint32_t *layers, VkImageSubresourceRange range,
6174                                         VkImage image) {
6175    /* expects globalLock to be held by caller */
6176
6177    *levels = range.levelCount;
6178    *layers = range.layerCount;
6179    auto image_node_it = dev_data->imageMap.find(image);
6180    if (image_node_it != dev_data->imageMap.end()) {
6181        if (range.levelCount == VK_REMAINING_MIP_LEVELS) {
6182            *levels = image_node_it->second.createInfo.mipLevels - range.baseMipLevel;
6183        }
6184        if (range.layerCount == VK_REMAINING_ARRAY_LAYERS) {
6185            *layers = image_node_it->second.createInfo.arrayLayers - range.baseArrayLayer;
6186        }
6187    }
6188}
6189
6190VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkCreateImageView(VkDevice device, const VkImageViewCreateInfo *pCreateInfo,
6191                                                                 const VkAllocationCallbacks *pAllocator, VkImageView *pView) {
6192    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6193    VkResult result = dev_data->device_dispatch_table->CreateImageView(device, pCreateInfo, pAllocator, pView);
6194    if (VK_SUCCESS == result) {
6195        loader_platform_thread_lock_mutex(&globalLock);
6196        VkImageViewCreateInfo localCI = VkImageViewCreateInfo(*pCreateInfo);
6197        ResolveRemainingLevelsLayers(dev_data, &localCI.subresourceRange, pCreateInfo->image);
6198        dev_data->imageViewMap[*pView] = localCI;
6199#if MTMERGESOURCE
6200        // Validate that img has correct usage flags set
6201        validate_image_usage_flags(dev_data, pCreateInfo->image,
6202                                   VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
6203                                       VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
6204                                   false, "vkCreateImageView()", "VK_IMAGE_USAGE_[SAMPLED|STORAGE|COLOR_ATTACHMENT]_BIT");
6205#endif
6206        loader_platform_thread_unlock_mutex(&globalLock);
6207    }
6208    return result;
6209}
6210
6211VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
6212vkCreateFence(VkDevice device, const VkFenceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkFence *pFence) {
6213    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6214    VkResult result = dev_data->device_dispatch_table->CreateFence(device, pCreateInfo, pAllocator, pFence);
6215    if (VK_SUCCESS == result) {
6216        loader_platform_thread_lock_mutex(&globalLock);
6217        FENCE_NODE *pFN = &dev_data->fenceMap[*pFence];
6218#if MTMERGESOURCE
6219        memset(pFN, 0, sizeof(MT_FENCE_INFO));
6220        memcpy(&(pFN->createInfo), pCreateInfo, sizeof(VkFenceCreateInfo));
6221        if (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT) {
6222            pFN->firstTimeFlag = true;
6223        }
6224#endif
6225        pFN->in_use.store(0);
6226        loader_platform_thread_unlock_mutex(&globalLock);
6227    }
6228    return result;
6229}
6230
6231// TODO handle pipeline caches
6232VKAPI_ATTR VkResult VKAPI_CALL vkCreatePipelineCache(VkDevice device, const VkPipelineCacheCreateInfo *pCreateInfo,
6233                                                     const VkAllocationCallbacks *pAllocator, VkPipelineCache *pPipelineCache) {
6234    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6235    VkResult result = dev_data->device_dispatch_table->CreatePipelineCache(device, pCreateInfo, pAllocator, pPipelineCache);
6236    return result;
6237}
6238
6239VKAPI_ATTR void VKAPI_CALL
6240vkDestroyPipelineCache(VkDevice device, VkPipelineCache pipelineCache, const VkAllocationCallbacks *pAllocator) {
6241    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6242    dev_data->device_dispatch_table->DestroyPipelineCache(device, pipelineCache, pAllocator);
6243}
6244
6245VKAPI_ATTR VkResult VKAPI_CALL
6246vkGetPipelineCacheData(VkDevice device, VkPipelineCache pipelineCache, size_t *pDataSize, void *pData) {
6247    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6248    VkResult result = dev_data->device_dispatch_table->GetPipelineCacheData(device, pipelineCache, pDataSize, pData);
6249    return result;
6250}
6251
6252VKAPI_ATTR VkResult VKAPI_CALL
6253vkMergePipelineCaches(VkDevice device, VkPipelineCache dstCache, uint32_t srcCacheCount, const VkPipelineCache *pSrcCaches) {
6254    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6255    VkResult result = dev_data->device_dispatch_table->MergePipelineCaches(device, dstCache, srcCacheCount, pSrcCaches);
6256    return result;
6257}
6258
6259// utility function to set collective state for pipeline
6260void set_pipeline_state(PIPELINE_NODE *pPipe) {
6261    // If any attachment used by this pipeline has blendEnable, set top-level blendEnable
6262    if (pPipe->graphicsPipelineCI.pColorBlendState) {
6263        for (size_t i = 0; i < pPipe->attachments.size(); ++i) {
6264            if (VK_TRUE == pPipe->attachments[i].blendEnable) {
6265                if (((pPipe->attachments[i].dstAlphaBlendFactor >= VK_BLEND_FACTOR_CONSTANT_COLOR) &&
6266                     (pPipe->attachments[i].dstAlphaBlendFactor <= VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA)) ||
6267                    ((pPipe->attachments[i].dstColorBlendFactor >= VK_BLEND_FACTOR_CONSTANT_COLOR) &&
6268                     (pPipe->attachments[i].dstColorBlendFactor <= VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA)) ||
6269                    ((pPipe->attachments[i].srcAlphaBlendFactor >= VK_BLEND_FACTOR_CONSTANT_COLOR) &&
6270                     (pPipe->attachments[i].srcAlphaBlendFactor <= VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA)) ||
6271                    ((pPipe->attachments[i].srcColorBlendFactor >= VK_BLEND_FACTOR_CONSTANT_COLOR) &&
6272                     (pPipe->attachments[i].srcColorBlendFactor <= VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA))) {
6273                    pPipe->blendConstantsEnabled = true;
6274                }
6275            }
6276        }
6277    }
6278}
6279
6280VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
6281vkCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
6282                          const VkGraphicsPipelineCreateInfo *pCreateInfos, const VkAllocationCallbacks *pAllocator,
6283                          VkPipeline *pPipelines) {
6284    VkResult result = VK_SUCCESS;
6285    // TODO What to do with pipelineCache?
6286    // The order of operations here is a little convoluted but gets the job done
6287    //  1. Pipeline create state is first shadowed into PIPELINE_NODE struct
6288    //  2. Create state is then validated (which uses flags setup during shadowing)
6289    //  3. If everything looks good, we'll then create the pipeline and add NODE to pipelineMap
6290    bool skipCall = false;
6291    // TODO : Improve this data struct w/ unique_ptrs so cleanup below is automatic
6292    vector<PIPELINE_NODE *> pPipeNode(count);
6293    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6294
6295    uint32_t i = 0;
6296    loader_platform_thread_lock_mutex(&globalLock);
6297
6298    for (i = 0; i < count; i++) {
6299        pPipeNode[i] = new PIPELINE_NODE;
6300        pPipeNode[i]->initGraphicsPipeline(&pCreateInfos[i]);
6301        skipCall |= verifyPipelineCreateState(dev_data, device, pPipeNode, i);
6302    }
6303
6304    if (!skipCall) {
6305        loader_platform_thread_unlock_mutex(&globalLock);
6306        result = dev_data->device_dispatch_table->CreateGraphicsPipelines(device, pipelineCache, count, pCreateInfos, pAllocator,
6307                                                                          pPipelines);
6308        loader_platform_thread_lock_mutex(&globalLock);
6309        for (i = 0; i < count; i++) {
6310            pPipeNode[i]->pipeline = pPipelines[i];
6311            dev_data->pipelineMap[pPipeNode[i]->pipeline] = pPipeNode[i];
6312        }
6313        loader_platform_thread_unlock_mutex(&globalLock);
6314    } else {
6315        for (i = 0; i < count; i++) {
6316            delete pPipeNode[i];
6317        }
6318        loader_platform_thread_unlock_mutex(&globalLock);
6319        return VK_ERROR_VALIDATION_FAILED_EXT;
6320    }
6321    return result;
6322}
6323
6324VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
6325vkCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
6326                         const VkComputePipelineCreateInfo *pCreateInfos, const VkAllocationCallbacks *pAllocator,
6327                         VkPipeline *pPipelines) {
6328    VkResult result = VK_SUCCESS;
6329    bool skipCall = false;
6330
6331    // TODO : Improve this data struct w/ unique_ptrs so cleanup below is automatic
6332    vector<PIPELINE_NODE *> pPipeNode(count);
6333    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6334
6335    uint32_t i = 0;
6336    loader_platform_thread_lock_mutex(&globalLock);
6337    for (i = 0; i < count; i++) {
6338        // TODO: Verify compute stage bits
6339
6340        // Create and initialize internal tracking data structure
6341        pPipeNode[i] = new PIPELINE_NODE;
6342        pPipeNode[i]->initComputePipeline(&pCreateInfos[i]);
6343        // memcpy(&pPipeNode[i]->computePipelineCI, (const void *)&pCreateInfos[i], sizeof(VkComputePipelineCreateInfo));
6344
6345        // TODO: Add Compute Pipeline Verification
6346        // skipCall |= verifyPipelineCreateState(dev_data, device, pPipeNode[i]);
6347    }
6348
6349    if (!skipCall) {
6350        loader_platform_thread_unlock_mutex(&globalLock);
6351        result = dev_data->device_dispatch_table->CreateComputePipelines(device, pipelineCache, count, pCreateInfos, pAllocator,
6352                                                                         pPipelines);
6353        loader_platform_thread_lock_mutex(&globalLock);
6354        for (i = 0; i < count; i++) {
6355            pPipeNode[i]->pipeline = pPipelines[i];
6356            dev_data->pipelineMap[pPipeNode[i]->pipeline] = pPipeNode[i];
6357        }
6358        loader_platform_thread_unlock_mutex(&globalLock);
6359    } else {
6360        for (i = 0; i < count; i++) {
6361            // Clean up any locally allocated data structures
6362            delete pPipeNode[i];
6363        }
6364        loader_platform_thread_unlock_mutex(&globalLock);
6365        return VK_ERROR_VALIDATION_FAILED_EXT;
6366    }
6367    return result;
6368}
6369
6370VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkCreateSampler(VkDevice device, const VkSamplerCreateInfo *pCreateInfo,
6371                                                               const VkAllocationCallbacks *pAllocator, VkSampler *pSampler) {
6372    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6373    VkResult result = dev_data->device_dispatch_table->CreateSampler(device, pCreateInfo, pAllocator, pSampler);
6374    if (VK_SUCCESS == result) {
6375        loader_platform_thread_lock_mutex(&globalLock);
6376        dev_data->sampleMap[*pSampler] = unique_ptr<SAMPLER_NODE>(new SAMPLER_NODE(pSampler, pCreateInfo));
6377        loader_platform_thread_unlock_mutex(&globalLock);
6378    }
6379    return result;
6380}
6381
6382VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
6383vkCreateDescriptorSetLayout(VkDevice device, const VkDescriptorSetLayoutCreateInfo *pCreateInfo,
6384                            const VkAllocationCallbacks *pAllocator, VkDescriptorSetLayout *pSetLayout) {
6385    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6386    VkResult result = dev_data->device_dispatch_table->CreateDescriptorSetLayout(device, pCreateInfo, pAllocator, pSetLayout);
6387    if (VK_SUCCESS == result) {
6388        // TODOSC : Capture layout bindings set
6389        LAYOUT_NODE *pNewNode = new LAYOUT_NODE;
6390        if (NULL == pNewNode) {
6391            if (log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT,
6392                        (uint64_t)*pSetLayout, __LINE__, DRAWSTATE_OUT_OF_MEMORY, "DS",
6393                        "Out of memory while attempting to allocate LAYOUT_NODE in vkCreateDescriptorSetLayout()"))
6394                return VK_ERROR_VALIDATION_FAILED_EXT;
6395        }
6396        memcpy((void *)&pNewNode->createInfo, pCreateInfo, sizeof(VkDescriptorSetLayoutCreateInfo));
6397        pNewNode->createInfo.pBindings = new VkDescriptorSetLayoutBinding[pCreateInfo->bindingCount];
6398        memcpy((void *)pNewNode->createInfo.pBindings, pCreateInfo->pBindings,
6399               sizeof(VkDescriptorSetLayoutBinding) * pCreateInfo->bindingCount);
6400        // g++ does not like reserve with size 0
6401        if (pCreateInfo->bindingCount)
6402            pNewNode->bindingToIndexMap.reserve(pCreateInfo->bindingCount);
6403        uint32_t totalCount = 0;
6404        for (uint32_t i = 0; i < pCreateInfo->bindingCount; i++) {
6405            if (!pNewNode->bindingToIndexMap.emplace(pCreateInfo->pBindings[i].binding, i).second) {
6406                if (log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
6407                            VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT, (uint64_t)*pSetLayout, __LINE__,
6408                            DRAWSTATE_INVALID_LAYOUT, "DS", "duplicated binding number in "
6409                                                            "VkDescriptorSetLayoutBinding"))
6410                    return VK_ERROR_VALIDATION_FAILED_EXT;
6411            } else {
6412                pNewNode->bindingToIndexMap[pCreateInfo->pBindings[i].binding] = i;
6413            }
6414            totalCount += pCreateInfo->pBindings[i].descriptorCount;
6415            if (pCreateInfo->pBindings[i].pImmutableSamplers) {
6416                VkSampler **ppIS = (VkSampler **)&pNewNode->createInfo.pBindings[i].pImmutableSamplers;
6417                *ppIS = new VkSampler[pCreateInfo->pBindings[i].descriptorCount];
6418                memcpy(*ppIS, pCreateInfo->pBindings[i].pImmutableSamplers,
6419                       pCreateInfo->pBindings[i].descriptorCount * sizeof(VkSampler));
6420            }
6421        }
6422        pNewNode->layout = *pSetLayout;
6423        pNewNode->startIndex = 0;
6424        if (totalCount > 0) {
6425            pNewNode->descriptorTypes.resize(totalCount);
6426            pNewNode->stageFlags.resize(totalCount);
6427            uint32_t offset = 0;
6428            uint32_t j = 0;
6429            VkDescriptorType dType;
6430            for (uint32_t i = 0; i < pCreateInfo->bindingCount; i++) {
6431                dType = pCreateInfo->pBindings[i].descriptorType;
6432                for (j = 0; j < pCreateInfo->pBindings[i].descriptorCount; j++) {
6433                    pNewNode->descriptorTypes[offset + j] = dType;
6434                    pNewNode->stageFlags[offset + j] = pCreateInfo->pBindings[i].stageFlags;
6435                    if ((dType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) ||
6436                        (dType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC)) {
6437                        pNewNode->dynamicDescriptorCount++;
6438                    }
6439                }
6440                offset += j;
6441            }
6442            pNewNode->endIndex = pNewNode->startIndex + totalCount - 1;
6443        } else { // no descriptors
6444            pNewNode->endIndex = 0;
6445        }
6446        // Put new node at Head of global Layer list
6447        loader_platform_thread_lock_mutex(&globalLock);
6448        dev_data->descriptorSetLayoutMap[*pSetLayout] = pNewNode;
6449        loader_platform_thread_unlock_mutex(&globalLock);
6450    }
6451    return result;
6452}
6453
6454static bool validatePushConstantSize(const layer_data *dev_data, const uint32_t offset, const uint32_t size,
6455                                     const char *caller_name) {
6456    bool skipCall = false;
6457    if ((offset + size) > dev_data->phys_dev_properties.properties.limits.maxPushConstantsSize) {
6458        skipCall = log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
6459                           DRAWSTATE_PUSH_CONSTANTS_ERROR, "DS", "%s call has push constants with offset %u and size %u that "
6460                                                                 "exceeds this device's maxPushConstantSize of %u.",
6461                           caller_name, offset, size, dev_data->phys_dev_properties.properties.limits.maxPushConstantsSize);
6462    }
6463    return skipCall;
6464}
6465
6466VKAPI_ATTR VkResult VKAPI_CALL vkCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo *pCreateInfo,
6467                                                      const VkAllocationCallbacks *pAllocator, VkPipelineLayout *pPipelineLayout) {
6468    bool skipCall = false;
6469    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6470    uint32_t i = 0;
6471    for (i = 0; i < pCreateInfo->pushConstantRangeCount; ++i) {
6472        skipCall |= validatePushConstantSize(dev_data, pCreateInfo->pPushConstantRanges[i].offset,
6473                                             pCreateInfo->pPushConstantRanges[i].size, "vkCreatePipelineLayout()");
6474        if ((pCreateInfo->pPushConstantRanges[i].size == 0) || ((pCreateInfo->pPushConstantRanges[i].size & 0x3) != 0)) {
6475            skipCall |=
6476                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
6477                        DRAWSTATE_PUSH_CONSTANTS_ERROR, "DS", "vkCreatePipelineLayout() call has push constant index %u with "
6478                                                              "size %u. Size must be greater than zero and a multiple of 4.",
6479                        i, pCreateInfo->pPushConstantRanges[i].size);
6480        }
6481        // TODO : Add warning if ranges overlap
6482    }
6483    VkResult result = dev_data->device_dispatch_table->CreatePipelineLayout(device, pCreateInfo, pAllocator, pPipelineLayout);
6484    if (VK_SUCCESS == result) {
6485        loader_platform_thread_lock_mutex(&globalLock);
6486        // TODOSC : Merge capture of the setLayouts per pipeline
6487        PIPELINE_LAYOUT_NODE &plNode = dev_data->pipelineLayoutMap[*pPipelineLayout];
6488        plNode.descriptorSetLayouts.resize(pCreateInfo->setLayoutCount);
6489        for (i = 0; i < pCreateInfo->setLayoutCount; ++i) {
6490            plNode.descriptorSetLayouts[i] = pCreateInfo->pSetLayouts[i];
6491        }
6492        plNode.pushConstantRanges.resize(pCreateInfo->pushConstantRangeCount);
6493        for (i = 0; i < pCreateInfo->pushConstantRangeCount; ++i) {
6494            plNode.pushConstantRanges[i] = pCreateInfo->pPushConstantRanges[i];
6495        }
6496        loader_platform_thread_unlock_mutex(&globalLock);
6497    }
6498    return result;
6499}
6500
6501VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
6502vkCreateDescriptorPool(VkDevice device, const VkDescriptorPoolCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator,
6503                       VkDescriptorPool *pDescriptorPool) {
6504    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6505    VkResult result = dev_data->device_dispatch_table->CreateDescriptorPool(device, pCreateInfo, pAllocator, pDescriptorPool);
6506    if (VK_SUCCESS == result) {
6507        // Insert this pool into Global Pool LL at head
6508        if (log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT,
6509                    (uint64_t)*pDescriptorPool, __LINE__, DRAWSTATE_OUT_OF_MEMORY, "DS", "Created Descriptor Pool %#" PRIxLEAST64,
6510                    (uint64_t)*pDescriptorPool))
6511            return VK_ERROR_VALIDATION_FAILED_EXT;
6512        DESCRIPTOR_POOL_NODE *pNewNode = new DESCRIPTOR_POOL_NODE(*pDescriptorPool, pCreateInfo);
6513        if (NULL == pNewNode) {
6514            if (log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT,
6515                        (uint64_t)*pDescriptorPool, __LINE__, DRAWSTATE_OUT_OF_MEMORY, "DS",
6516                        "Out of memory while attempting to allocate DESCRIPTOR_POOL_NODE in vkCreateDescriptorPool()"))
6517                return VK_ERROR_VALIDATION_FAILED_EXT;
6518        } else {
6519            loader_platform_thread_lock_mutex(&globalLock);
6520            dev_data->descriptorPoolMap[*pDescriptorPool] = pNewNode;
6521            loader_platform_thread_unlock_mutex(&globalLock);
6522        }
6523    } else {
6524        // Need to do anything if pool create fails?
6525    }
6526    return result;
6527}
6528
6529VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
6530vkResetDescriptorPool(VkDevice device, VkDescriptorPool descriptorPool, VkDescriptorPoolResetFlags flags) {
6531    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6532    VkResult result = dev_data->device_dispatch_table->ResetDescriptorPool(device, descriptorPool, flags);
6533    if (VK_SUCCESS == result) {
6534        loader_platform_thread_lock_mutex(&globalLock);
6535        clearDescriptorPool(dev_data, device, descriptorPool, flags);
6536        loader_platform_thread_unlock_mutex(&globalLock);
6537    }
6538    return result;
6539}
6540
6541VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
6542vkAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo *pAllocateInfo, VkDescriptorSet *pDescriptorSets) {
6543    bool skipCall = false;
6544    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6545
6546    loader_platform_thread_lock_mutex(&globalLock);
6547    // Verify that requested descriptorSets are available in pool
6548    DESCRIPTOR_POOL_NODE *pPoolNode = getPoolNode(dev_data, pAllocateInfo->descriptorPool);
6549    if (!pPoolNode) {
6550        skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT,
6551                            (uint64_t)pAllocateInfo->descriptorPool, __LINE__, DRAWSTATE_INVALID_POOL, "DS",
6552                            "Unable to find pool node for pool %#" PRIxLEAST64 " specified in vkAllocateDescriptorSets() call",
6553                            (uint64_t)pAllocateInfo->descriptorPool);
6554    } else { // Make sure pool has all the available descriptors before calling down chain
6555        skipCall |= validate_descriptor_availability_in_pool(dev_data, pPoolNode, pAllocateInfo->descriptorSetCount,
6556                                                             pAllocateInfo->pSetLayouts);
6557    }
6558    loader_platform_thread_unlock_mutex(&globalLock);
6559    if (skipCall)
6560        return VK_ERROR_VALIDATION_FAILED_EXT;
6561    VkResult result = dev_data->device_dispatch_table->AllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets);
6562    if (VK_SUCCESS == result) {
6563        loader_platform_thread_lock_mutex(&globalLock);
6564        DESCRIPTOR_POOL_NODE *pPoolNode = getPoolNode(dev_data, pAllocateInfo->descriptorPool);
6565        if (pPoolNode) {
6566            if (pAllocateInfo->descriptorSetCount == 0) {
6567                log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
6568                        pAllocateInfo->descriptorSetCount, __LINE__, DRAWSTATE_NONE, "DS",
6569                        "AllocateDescriptorSets called with 0 count");
6570            }
6571            for (uint32_t i = 0; i < pAllocateInfo->descriptorSetCount; i++) {
6572                log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
6573                        (uint64_t)pDescriptorSets[i], __LINE__, DRAWSTATE_NONE, "DS", "Created Descriptor Set %#" PRIxLEAST64,
6574                        (uint64_t)pDescriptorSets[i]);
6575                // Create new set node and add to head of pool nodes
6576                SET_NODE *pNewNode = new SET_NODE;
6577                if (NULL == pNewNode) {
6578                    if (log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
6579                                VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, (uint64_t)pDescriptorSets[i], __LINE__,
6580                                DRAWSTATE_OUT_OF_MEMORY, "DS",
6581                                "Out of memory while attempting to allocate SET_NODE in vkAllocateDescriptorSets()")) {
6582                        loader_platform_thread_unlock_mutex(&globalLock);
6583                        return VK_ERROR_VALIDATION_FAILED_EXT;
6584                    }
6585                } else {
6586                    // TODO : Pool should store a total count of each type of Descriptor available
6587                    //  When descriptors are allocated, decrement the count and validate here
6588                    //  that the count doesn't go below 0. One reset/free need to bump count back up.
6589                    // Insert set at head of Set LL for this pool
6590                    pNewNode->pNext = pPoolNode->pSets;
6591                    pNewNode->in_use.store(0);
6592                    pPoolNode->pSets = pNewNode;
6593                    LAYOUT_NODE *pLayout = getLayoutNode(dev_data, pAllocateInfo->pSetLayouts[i]);
6594                    if (NULL == pLayout) {
6595                        if (log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
6596                                    VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT, (uint64_t)pAllocateInfo->pSetLayouts[i],
6597                                    __LINE__, DRAWSTATE_INVALID_LAYOUT, "DS",
6598                                    "Unable to find set layout node for layout %#" PRIxLEAST64
6599                                    " specified in vkAllocateDescriptorSets() call",
6600                                    (uint64_t)pAllocateInfo->pSetLayouts[i])) {
6601                            loader_platform_thread_unlock_mutex(&globalLock);
6602                            return VK_ERROR_VALIDATION_FAILED_EXT;
6603                        }
6604                    }
6605                    pNewNode->pLayout = pLayout;
6606                    pNewNode->pool = pAllocateInfo->descriptorPool;
6607                    pNewNode->set = pDescriptorSets[i];
6608                    pNewNode->descriptorCount = (pLayout->createInfo.bindingCount != 0) ? pLayout->endIndex + 1 : 0;
6609                    if (pNewNode->descriptorCount) {
6610                        pNewNode->pDescriptorUpdates.resize(pNewNode->descriptorCount);
6611                    }
6612                    dev_data->setMap[pDescriptorSets[i]] = pNewNode;
6613                }
6614            }
6615        }
6616        loader_platform_thread_unlock_mutex(&globalLock);
6617    }
6618    return result;
6619}
6620
6621VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
6622vkFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t count, const VkDescriptorSet *pDescriptorSets) {
6623    bool skipCall = false;
6624    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6625    // Make sure that no sets being destroyed are in-flight
6626    loader_platform_thread_lock_mutex(&globalLock);
6627    for (uint32_t i = 0; i < count; ++i)
6628        skipCall |= validateIdleDescriptorSet(dev_data, pDescriptorSets[i], "vkFreeDesriptorSets");
6629    DESCRIPTOR_POOL_NODE *pPoolNode = getPoolNode(dev_data, descriptorPool);
6630    if (pPoolNode && !(VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT & pPoolNode->createInfo.flags)) {
6631        // Can't Free from a NON_FREE pool
6632        skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
6633                            (uint64_t)device, __LINE__, DRAWSTATE_CANT_FREE_FROM_NON_FREE_POOL, "DS",
6634                            "It is invalid to call vkFreeDescriptorSets() with a pool created without setting "
6635                            "VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT.");
6636    }
6637    loader_platform_thread_unlock_mutex(&globalLock);
6638    if (skipCall)
6639        return VK_ERROR_VALIDATION_FAILED_EXT;
6640    VkResult result = dev_data->device_dispatch_table->FreeDescriptorSets(device, descriptorPool, count, pDescriptorSets);
6641    if (VK_SUCCESS == result) {
6642        loader_platform_thread_lock_mutex(&globalLock);
6643
6644        // Update available descriptor sets in pool
6645        pPoolNode->availableSets += count;
6646
6647        // For each freed descriptor add it back into the pool as available
6648        for (uint32_t i = 0; i < count; ++i) {
6649            SET_NODE *pSet = dev_data->setMap[pDescriptorSets[i]]; // getSetNode() without locking
6650            invalidateBoundCmdBuffers(dev_data, pSet);
6651            LAYOUT_NODE *pLayout = pSet->pLayout;
6652            uint32_t typeIndex = 0, poolSizeCount = 0;
6653            for (uint32_t j = 0; j < pLayout->createInfo.bindingCount; ++j) {
6654                typeIndex = static_cast<uint32_t>(pLayout->createInfo.pBindings[j].descriptorType);
6655                poolSizeCount = pLayout->createInfo.pBindings[j].descriptorCount;
6656                pPoolNode->availableDescriptorTypeCount[typeIndex] += poolSizeCount;
6657            }
6658        }
6659        loader_platform_thread_unlock_mutex(&globalLock);
6660    }
6661    // TODO : Any other clean-up or book-keeping to do here?
6662    return result;
6663}
6664
6665VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
6666vkUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount, const VkWriteDescriptorSet *pDescriptorWrites,
6667                       uint32_t descriptorCopyCount, const VkCopyDescriptorSet *pDescriptorCopies) {
6668    // dsUpdate will return true only if a bailout error occurs, so we want to call down tree when update returns false
6669    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6670    loader_platform_thread_lock_mutex(&globalLock);
6671    bool rtn = dsUpdate(dev_data, device, descriptorWriteCount, pDescriptorWrites, descriptorCopyCount, pDescriptorCopies);
6672    loader_platform_thread_unlock_mutex(&globalLock);
6673    if (!rtn) {
6674        dev_data->device_dispatch_table->UpdateDescriptorSets(device, descriptorWriteCount, pDescriptorWrites, descriptorCopyCount,
6675                                                              pDescriptorCopies);
6676    }
6677}
6678
6679VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
6680vkAllocateCommandBuffers(VkDevice device, const VkCommandBufferAllocateInfo *pCreateInfo, VkCommandBuffer *pCommandBuffer) {
6681    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
6682    VkResult result = dev_data->device_dispatch_table->AllocateCommandBuffers(device, pCreateInfo, pCommandBuffer);
6683    if (VK_SUCCESS == result) {
6684        loader_platform_thread_lock_mutex(&globalLock);
6685        auto const &cp_it = dev_data->commandPoolMap.find(pCreateInfo->commandPool);
6686        if (cp_it != dev_data->commandPoolMap.end()) {
6687            for (uint32_t i = 0; i < pCreateInfo->commandBufferCount; i++) {
6688                // Add command buffer to its commandPool map
6689                cp_it->second.commandBuffers.push_back(pCommandBuffer[i]);
6690                GLOBAL_CB_NODE *pCB = new GLOBAL_CB_NODE;
6691                // Add command buffer to map
6692                dev_data->commandBufferMap[pCommandBuffer[i]] = pCB;
6693                resetCB(dev_data, pCommandBuffer[i]);
6694                pCB->createInfo = *pCreateInfo;
6695                pCB->device = device;
6696            }
6697        }
6698#if MTMERGESOURCE
6699        printCBList(dev_data);
6700#endif
6701        loader_platform_thread_unlock_mutex(&globalLock);
6702    }
6703    return result;
6704}
6705
6706VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
6707vkBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo) {
6708    bool skipCall = false;
6709    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
6710    loader_platform_thread_lock_mutex(&globalLock);
6711    // Validate command buffer level
6712    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
6713    if (pCB) {
6714        bool commandBufferComplete = false;
6715        // This implicitly resets the Cmd Buffer so make sure any fence is done and then clear memory references
6716        skipCall = checkCBCompleted(dev_data, commandBuffer, &commandBufferComplete);
6717        clear_cmd_buf_and_mem_references(dev_data, pCB);
6718
6719        if (!commandBufferComplete) {
6720            skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
6721                                (uint64_t)commandBuffer, __LINE__, MEMTRACK_RESET_CB_WHILE_IN_FLIGHT, "MEM",
6722                                "Calling vkBeginCommandBuffer() on active CB %p before it has completed. "
6723                                "You must check CB flag before this call.",
6724                                commandBuffer);
6725        }
6726        if (pCB->createInfo.level != VK_COMMAND_BUFFER_LEVEL_PRIMARY) {
6727            // Secondary Command Buffer
6728            const VkCommandBufferInheritanceInfo *pInfo = pBeginInfo->pInheritanceInfo;
6729            if (!pInfo) {
6730                skipCall |=
6731                    log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
6732                            reinterpret_cast<uint64_t>(commandBuffer), __LINE__, DRAWSTATE_BEGIN_CB_INVALID_STATE, "DS",
6733                            "vkBeginCommandBuffer(): Secondary Command Buffer (%p) must have inheritance info.",
6734                            reinterpret_cast<void *>(commandBuffer));
6735            } else {
6736                if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT) {
6737                    if (!pInfo->renderPass) { // renderpass should NOT be null for a Secondary CB
6738                        skipCall |= log_msg(
6739                            dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
6740                            reinterpret_cast<uint64_t>(commandBuffer), __LINE__, DRAWSTATE_BEGIN_CB_INVALID_STATE, "DS",
6741                            "vkBeginCommandBuffer(): Secondary Command Buffers (%p) must specify a valid renderpass parameter.",
6742                            reinterpret_cast<void *>(commandBuffer));
6743                    }
6744                    if (!pInfo->framebuffer) { // framebuffer may be null for a Secondary CB, but this affects perf
6745                        skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT,
6746                                            VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
6747                                            reinterpret_cast<uint64_t>(commandBuffer), __LINE__, DRAWSTATE_BEGIN_CB_INVALID_STATE,
6748                                            "DS", "vkBeginCommandBuffer(): Secondary Command Buffers (%p) may perform better if a "
6749                                                  "valid framebuffer parameter is specified.",
6750                                            reinterpret_cast<void *>(commandBuffer));
6751                    } else {
6752                        string errorString = "";
6753                        auto fbNode = dev_data->frameBufferMap.find(pInfo->framebuffer);
6754                        if (fbNode != dev_data->frameBufferMap.end()) {
6755                            VkRenderPass fbRP = fbNode->second.createInfo.renderPass;
6756                            if (!verify_renderpass_compatibility(dev_data, fbRP, pInfo->renderPass, errorString)) {
6757                                // renderPass that framebuffer was created with must be compatible with local renderPass
6758                                skipCall |=
6759                                    log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
6760                                            VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
6761                                            reinterpret_cast<uint64_t>(commandBuffer), __LINE__, DRAWSTATE_RENDERPASS_INCOMPATIBLE,
6762                                            "DS", "vkBeginCommandBuffer(): Secondary Command "
6763                                                  "Buffer (%p) renderPass (%#" PRIxLEAST64 ") is incompatible w/ framebuffer "
6764                                                  "(%#" PRIxLEAST64 ") w/ render pass (%#" PRIxLEAST64 ") due to: %s",
6765                                            reinterpret_cast<void *>(commandBuffer), (uint64_t)(pInfo->renderPass),
6766                                            (uint64_t)(pInfo->framebuffer), (uint64_t)(fbRP), errorString.c_str());
6767                            }
6768                            // Connect this framebuffer to this cmdBuffer
6769                            fbNode->second.referencingCmdBuffers.insert(pCB->commandBuffer);
6770                        }
6771                    }
6772                }
6773                if ((pInfo->occlusionQueryEnable == VK_FALSE ||
6774                     dev_data->phys_dev_properties.features.occlusionQueryPrecise == VK_FALSE) &&
6775                    (pInfo->queryFlags & VK_QUERY_CONTROL_PRECISE_BIT)) {
6776                    skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
6777                                        VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, reinterpret_cast<uint64_t>(commandBuffer),
6778                                        __LINE__, DRAWSTATE_BEGIN_CB_INVALID_STATE, "DS",
6779                                        "vkBeginCommandBuffer(): Secondary Command Buffer (%p) must not have "
6780                                        "VK_QUERY_CONTROL_PRECISE_BIT if occulusionQuery is disabled or the device does not "
6781                                        "support precise occlusion queries.",
6782                                        reinterpret_cast<void *>(commandBuffer));
6783                }
6784            }
6785            if (pInfo && pInfo->renderPass != VK_NULL_HANDLE) {
6786                auto rp_data = dev_data->renderPassMap.find(pInfo->renderPass);
6787                if (rp_data != dev_data->renderPassMap.end() && rp_data->second && rp_data->second->pCreateInfo) {
6788                    if (pInfo->subpass >= rp_data->second->pCreateInfo->subpassCount) {
6789                        skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
6790                                            VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, (uint64_t)commandBuffer, __LINE__,
6791                                            DRAWSTATE_BEGIN_CB_INVALID_STATE, "DS",
6792                                            "vkBeginCommandBuffer(): Secondary Command Buffers (%p) must has a subpass index (%d) "
6793                                            "that is less than the number of subpasses (%d).",
6794                                            (void *)commandBuffer, pInfo->subpass, rp_data->second->pCreateInfo->subpassCount);
6795                    }
6796                }
6797            }
6798        }
6799        if (CB_RECORDING == pCB->state) {
6800            skipCall |=
6801                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
6802                        (uint64_t)commandBuffer, __LINE__, DRAWSTATE_BEGIN_CB_INVALID_STATE, "DS",
6803                        "vkBeginCommandBuffer(): Cannot call Begin on CB (%#" PRIxLEAST64
6804                        ") in the RECORDING state. Must first call vkEndCommandBuffer().",
6805                        (uint64_t)commandBuffer);
6806        } else if (CB_RECORDED == pCB->state) {
6807            VkCommandPool cmdPool = pCB->createInfo.commandPool;
6808            if (!(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT & dev_data->commandPoolMap[cmdPool].createFlags)) {
6809                skipCall |=
6810                    log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
6811                            (uint64_t)commandBuffer, __LINE__, DRAWSTATE_INVALID_COMMAND_BUFFER_RESET, "DS",
6812                            "Call to vkBeginCommandBuffer() on command buffer (%#" PRIxLEAST64
6813                            ") attempts to implicitly reset cmdBuffer created from command pool (%#" PRIxLEAST64
6814                            ") that does NOT have the VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT bit set.",
6815                            (uint64_t)commandBuffer, (uint64_t)cmdPool);
6816            }
6817            resetCB(dev_data, commandBuffer);
6818        }
6819        // Set updated state here in case implicit reset occurs above
6820        pCB->state = CB_RECORDING;
6821        pCB->beginInfo = *pBeginInfo;
6822        if (pCB->beginInfo.pInheritanceInfo) {
6823            pCB->inheritanceInfo = *(pCB->beginInfo.pInheritanceInfo);
6824            pCB->beginInfo.pInheritanceInfo = &pCB->inheritanceInfo;
6825        }
6826    } else {
6827        skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
6828                            (uint64_t)commandBuffer, __LINE__, DRAWSTATE_INVALID_COMMAND_BUFFER, "DS",
6829                            "In vkBeginCommandBuffer() and unable to find CommandBuffer Node for CB %p!", (void *)commandBuffer);
6830    }
6831    loader_platform_thread_unlock_mutex(&globalLock);
6832    if (skipCall) {
6833        return VK_ERROR_VALIDATION_FAILED_EXT;
6834    }
6835    VkResult result = dev_data->device_dispatch_table->BeginCommandBuffer(commandBuffer, pBeginInfo);
6836
6837    return result;
6838}
6839
6840VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkEndCommandBuffer(VkCommandBuffer commandBuffer) {
6841    bool skipCall = false;
6842    VkResult result = VK_SUCCESS;
6843    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
6844    loader_platform_thread_lock_mutex(&globalLock);
6845    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
6846    if (pCB) {
6847        if (pCB->state != CB_RECORDING) {
6848            skipCall |= report_error_no_cb_begin(dev_data, commandBuffer, "vkEndCommandBuffer()");
6849        }
6850        for (auto query : pCB->activeQueries) {
6851            skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
6852                                DRAWSTATE_INVALID_QUERY, "DS",
6853                                "Ending command buffer with in progress query: queryPool %" PRIu64 ", index %d",
6854                                (uint64_t)(query.pool), query.index);
6855        }
6856    }
6857    if (!skipCall) {
6858        loader_platform_thread_unlock_mutex(&globalLock);
6859        result = dev_data->device_dispatch_table->EndCommandBuffer(commandBuffer);
6860        loader_platform_thread_lock_mutex(&globalLock);
6861        if (VK_SUCCESS == result) {
6862            pCB->state = CB_RECORDED;
6863            // Reset CB status flags
6864            pCB->status = 0;
6865            printCB(dev_data, commandBuffer);
6866        }
6867    } else {
6868        result = VK_ERROR_VALIDATION_FAILED_EXT;
6869    }
6870    loader_platform_thread_unlock_mutex(&globalLock);
6871    return result;
6872}
6873
6874VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
6875vkResetCommandBuffer(VkCommandBuffer commandBuffer, VkCommandBufferResetFlags flags) {
6876    bool skipCall = false;
6877    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
6878    loader_platform_thread_lock_mutex(&globalLock);
6879    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
6880    VkCommandPool cmdPool = pCB->createInfo.commandPool;
6881    if (!(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT & dev_data->commandPoolMap[cmdPool].createFlags)) {
6882        skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
6883                            (uint64_t)commandBuffer, __LINE__, DRAWSTATE_INVALID_COMMAND_BUFFER_RESET, "DS",
6884                            "Attempt to reset command buffer (%#" PRIxLEAST64 ") created from command pool (%#" PRIxLEAST64
6885                            ") that does NOT have the VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT bit set.",
6886                            (uint64_t)commandBuffer, (uint64_t)cmdPool);
6887    }
6888    if (dev_data->globalInFlightCmdBuffers.count(commandBuffer)) {
6889        skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
6890                            (uint64_t)commandBuffer, __LINE__, DRAWSTATE_INVALID_COMMAND_BUFFER_RESET, "DS",
6891                            "Attempt to reset command buffer (%#" PRIxLEAST64 ") which is in use.",
6892                            reinterpret_cast<uint64_t>(commandBuffer));
6893    }
6894    loader_platform_thread_unlock_mutex(&globalLock);
6895    if (skipCall)
6896        return VK_ERROR_VALIDATION_FAILED_EXT;
6897    VkResult result = dev_data->device_dispatch_table->ResetCommandBuffer(commandBuffer, flags);
6898    if (VK_SUCCESS == result) {
6899        loader_platform_thread_lock_mutex(&globalLock);
6900        resetCB(dev_data, commandBuffer);
6901        loader_platform_thread_unlock_mutex(&globalLock);
6902    }
6903    return result;
6904}
6905#if MTMERGESOURCE
6906// TODO : For any vkCmdBind* calls that include an object which has mem bound to it,
6907//    need to account for that mem now having binding to given commandBuffer
6908#endif
6909VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
6910vkCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipeline pipeline) {
6911    bool skipCall = false;
6912    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
6913    loader_platform_thread_lock_mutex(&globalLock);
6914    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
6915    if (pCB) {
6916        skipCall |= addCmd(dev_data, pCB, CMD_BINDPIPELINE, "vkCmdBindPipeline()");
6917        if ((VK_PIPELINE_BIND_POINT_COMPUTE == pipelineBindPoint) && (pCB->activeRenderPass)) {
6918            skipCall |=
6919                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
6920                        (uint64_t)pipeline, __LINE__, DRAWSTATE_INVALID_RENDERPASS_CMD, "DS",
6921                        "Incorrectly binding compute pipeline (%#" PRIxLEAST64 ") during active RenderPass (%#" PRIxLEAST64 ")",
6922                        (uint64_t)pipeline, (uint64_t)pCB->activeRenderPass);
6923        }
6924
6925        PIPELINE_NODE *pPN = getPipeline(dev_data, pipeline);
6926        if (pPN) {
6927            pCB->lastBound[pipelineBindPoint].pipeline = pipeline;
6928            set_cb_pso_status(pCB, pPN);
6929            set_pipeline_state(pPN);
6930            skipCall |= validatePipelineState(dev_data, pCB, pipelineBindPoint, pipeline);
6931        } else {
6932            skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
6933                                (uint64_t)pipeline, __LINE__, DRAWSTATE_INVALID_PIPELINE, "DS",
6934                                "Attempt to bind Pipeline %#" PRIxLEAST64 " that doesn't exist!", (uint64_t)(pipeline));
6935        }
6936    }
6937    loader_platform_thread_unlock_mutex(&globalLock);
6938    if (!skipCall)
6939        dev_data->device_dispatch_table->CmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
6940}
6941
6942VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
6943vkCmdSetViewport(VkCommandBuffer commandBuffer, uint32_t firstViewport, uint32_t viewportCount, const VkViewport *pViewports) {
6944    bool skipCall = false;
6945    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
6946    loader_platform_thread_lock_mutex(&globalLock);
6947    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
6948    if (pCB) {
6949        skipCall |= addCmd(dev_data, pCB, CMD_SETVIEWPORTSTATE, "vkCmdSetViewport()");
6950        pCB->status |= CBSTATUS_VIEWPORT_SET;
6951        pCB->viewports.resize(viewportCount);
6952        memcpy(pCB->viewports.data(), pViewports, viewportCount * sizeof(VkViewport));
6953    }
6954    loader_platform_thread_unlock_mutex(&globalLock);
6955    if (!skipCall)
6956        dev_data->device_dispatch_table->CmdSetViewport(commandBuffer, firstViewport, viewportCount, pViewports);
6957}
6958
6959VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
6960vkCmdSetScissor(VkCommandBuffer commandBuffer, uint32_t firstScissor, uint32_t scissorCount, const VkRect2D *pScissors) {
6961    bool skipCall = false;
6962    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
6963    loader_platform_thread_lock_mutex(&globalLock);
6964    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
6965    if (pCB) {
6966        skipCall |= addCmd(dev_data, pCB, CMD_SETSCISSORSTATE, "vkCmdSetScissor()");
6967        pCB->status |= CBSTATUS_SCISSOR_SET;
6968        pCB->scissors.resize(scissorCount);
6969        memcpy(pCB->scissors.data(), pScissors, scissorCount * sizeof(VkRect2D));
6970    }
6971    loader_platform_thread_unlock_mutex(&globalLock);
6972    if (!skipCall)
6973        dev_data->device_dispatch_table->CmdSetScissor(commandBuffer, firstScissor, scissorCount, pScissors);
6974}
6975
6976VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkCmdSetLineWidth(VkCommandBuffer commandBuffer, float lineWidth) {
6977    bool skipCall = false;
6978    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
6979    loader_platform_thread_lock_mutex(&globalLock);
6980    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
6981    if (pCB) {
6982        skipCall |= addCmd(dev_data, pCB, CMD_SETLINEWIDTHSTATE, "vkCmdSetLineWidth()");
6983        pCB->status |= CBSTATUS_LINE_WIDTH_SET;
6984    }
6985    loader_platform_thread_unlock_mutex(&globalLock);
6986    if (!skipCall)
6987        dev_data->device_dispatch_table->CmdSetLineWidth(commandBuffer, lineWidth);
6988}
6989
6990VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
6991vkCmdSetDepthBias(VkCommandBuffer commandBuffer, float depthBiasConstantFactor, float depthBiasClamp, float depthBiasSlopeFactor) {
6992    bool skipCall = false;
6993    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
6994    loader_platform_thread_lock_mutex(&globalLock);
6995    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
6996    if (pCB) {
6997        skipCall |= addCmd(dev_data, pCB, CMD_SETDEPTHBIASSTATE, "vkCmdSetDepthBias()");
6998        pCB->status |= CBSTATUS_DEPTH_BIAS_SET;
6999    }
7000    loader_platform_thread_unlock_mutex(&globalLock);
7001    if (!skipCall)
7002        dev_data->device_dispatch_table->CmdSetDepthBias(commandBuffer, depthBiasConstantFactor, depthBiasClamp,
7003                                                         depthBiasSlopeFactor);
7004}
7005
7006VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkCmdSetBlendConstants(VkCommandBuffer commandBuffer, const float blendConstants[4]) {
7007    bool skipCall = false;
7008    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7009    loader_platform_thread_lock_mutex(&globalLock);
7010    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7011    if (pCB) {
7012        skipCall |= addCmd(dev_data, pCB, CMD_SETBLENDSTATE, "vkCmdSetBlendConstants()");
7013        pCB->status |= CBSTATUS_BLEND_CONSTANTS_SET;
7014    }
7015    loader_platform_thread_unlock_mutex(&globalLock);
7016    if (!skipCall)
7017        dev_data->device_dispatch_table->CmdSetBlendConstants(commandBuffer, blendConstants);
7018}
7019
7020VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
7021vkCmdSetDepthBounds(VkCommandBuffer commandBuffer, float minDepthBounds, float maxDepthBounds) {
7022    bool skipCall = false;
7023    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7024    loader_platform_thread_lock_mutex(&globalLock);
7025    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7026    if (pCB) {
7027        skipCall |= addCmd(dev_data, pCB, CMD_SETDEPTHBOUNDSSTATE, "vkCmdSetDepthBounds()");
7028        pCB->status |= CBSTATUS_DEPTH_BOUNDS_SET;
7029    }
7030    loader_platform_thread_unlock_mutex(&globalLock);
7031    if (!skipCall)
7032        dev_data->device_dispatch_table->CmdSetDepthBounds(commandBuffer, minDepthBounds, maxDepthBounds);
7033}
7034
7035VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
7036vkCmdSetStencilCompareMask(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, uint32_t compareMask) {
7037    bool skipCall = false;
7038    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7039    loader_platform_thread_lock_mutex(&globalLock);
7040    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7041    if (pCB) {
7042        skipCall |= addCmd(dev_data, pCB, CMD_SETSTENCILREADMASKSTATE, "vkCmdSetStencilCompareMask()");
7043        pCB->status |= CBSTATUS_STENCIL_READ_MASK_SET;
7044    }
7045    loader_platform_thread_unlock_mutex(&globalLock);
7046    if (!skipCall)
7047        dev_data->device_dispatch_table->CmdSetStencilCompareMask(commandBuffer, faceMask, compareMask);
7048}
7049
7050VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
7051vkCmdSetStencilWriteMask(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, uint32_t writeMask) {
7052    bool skipCall = false;
7053    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7054    loader_platform_thread_lock_mutex(&globalLock);
7055    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7056    if (pCB) {
7057        skipCall |= addCmd(dev_data, pCB, CMD_SETSTENCILWRITEMASKSTATE, "vkCmdSetStencilWriteMask()");
7058        pCB->status |= CBSTATUS_STENCIL_WRITE_MASK_SET;
7059    }
7060    loader_platform_thread_unlock_mutex(&globalLock);
7061    if (!skipCall)
7062        dev_data->device_dispatch_table->CmdSetStencilWriteMask(commandBuffer, faceMask, writeMask);
7063}
7064
7065VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
7066vkCmdSetStencilReference(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, uint32_t reference) {
7067    bool skipCall = false;
7068    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7069    loader_platform_thread_lock_mutex(&globalLock);
7070    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7071    if (pCB) {
7072        skipCall |= addCmd(dev_data, pCB, CMD_SETSTENCILREFERENCESTATE, "vkCmdSetStencilReference()");
7073        pCB->status |= CBSTATUS_STENCIL_REFERENCE_SET;
7074    }
7075    loader_platform_thread_unlock_mutex(&globalLock);
7076    if (!skipCall)
7077        dev_data->device_dispatch_table->CmdSetStencilReference(commandBuffer, faceMask, reference);
7078}
7079
7080VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
7081vkCmdBindDescriptorSets(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipelineLayout layout,
7082                        uint32_t firstSet, uint32_t setCount, const VkDescriptorSet *pDescriptorSets, uint32_t dynamicOffsetCount,
7083                        const uint32_t *pDynamicOffsets) {
7084    bool skipCall = false;
7085    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7086    loader_platform_thread_lock_mutex(&globalLock);
7087    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7088    if (pCB) {
7089        if (pCB->state == CB_RECORDING) {
7090            // Track total count of dynamic descriptor types to make sure we have an offset for each one
7091            uint32_t totalDynamicDescriptors = 0;
7092            string errorString = "";
7093            uint32_t lastSetIndex = firstSet + setCount - 1;
7094            if (lastSetIndex >= pCB->lastBound[pipelineBindPoint].boundDescriptorSets.size())
7095                pCB->lastBound[pipelineBindPoint].boundDescriptorSets.resize(lastSetIndex + 1);
7096            VkDescriptorSet oldFinalBoundSet = pCB->lastBound[pipelineBindPoint].boundDescriptorSets[lastSetIndex];
7097            for (uint32_t i = 0; i < setCount; i++) {
7098                SET_NODE *pSet = getSetNode(dev_data, pDescriptorSets[i]);
7099                if (pSet) {
7100                    pCB->lastBound[pipelineBindPoint].uniqueBoundSets.insert(pDescriptorSets[i]);
7101                    pSet->boundCmdBuffers.insert(commandBuffer);
7102                    pCB->lastBound[pipelineBindPoint].pipelineLayout = layout;
7103                    pCB->lastBound[pipelineBindPoint].boundDescriptorSets[i + firstSet] = pDescriptorSets[i];
7104                    skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT,
7105                                        VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, (uint64_t)pDescriptorSets[i], __LINE__,
7106                                        DRAWSTATE_NONE, "DS", "DS %#" PRIxLEAST64 " bound on pipeline %s",
7107                                        (uint64_t)pDescriptorSets[i], string_VkPipelineBindPoint(pipelineBindPoint));
7108                    if (!pSet->pUpdateStructs && (pSet->descriptorCount != 0)) {
7109                        skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT,
7110                                            VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, (uint64_t)pDescriptorSets[i],
7111                                            __LINE__, DRAWSTATE_DESCRIPTOR_SET_NOT_UPDATED, "DS",
7112                                            "DS %#" PRIxLEAST64
7113                                            " bound but it was never updated. You may want to either update it or not bind it.",
7114                                            (uint64_t)pDescriptorSets[i]);
7115                    }
7116                    // Verify that set being bound is compatible with overlapping setLayout of pipelineLayout
7117                    if (!verify_set_layout_compatibility(dev_data, pSet, layout, i + firstSet, errorString)) {
7118                        skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
7119                                            VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, (uint64_t)pDescriptorSets[i],
7120                                            __LINE__, DRAWSTATE_PIPELINE_LAYOUTS_INCOMPATIBLE, "DS",
7121                                            "descriptorSet #%u being bound is not compatible with overlapping layout in "
7122                                            "pipelineLayout due to: %s",
7123                                            i, errorString.c_str());
7124                    }
7125                    if (pSet->pLayout->dynamicDescriptorCount) {
7126                        // First make sure we won't overstep bounds of pDynamicOffsets array
7127                        if ((totalDynamicDescriptors + pSet->pLayout->dynamicDescriptorCount) > dynamicOffsetCount) {
7128                            skipCall |=
7129                                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
7130                                        VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, (uint64_t)pDescriptorSets[i], __LINE__,
7131                                        DRAWSTATE_INVALID_DYNAMIC_OFFSET_COUNT, "DS",
7132                                        "descriptorSet #%u (%#" PRIxLEAST64
7133                                        ") requires %u dynamicOffsets, but only %u dynamicOffsets are left in pDynamicOffsets "
7134                                        "array. There must be one dynamic offset for each dynamic descriptor being bound.",
7135                                        i, (uint64_t)pDescriptorSets[i], pSet->pLayout->dynamicDescriptorCount,
7136                                        (dynamicOffsetCount - totalDynamicDescriptors));
7137                        } else { // Validate and store dynamic offsets with the set
7138                            // Validate Dynamic Offset Minimums
7139                            uint32_t cur_dyn_offset = totalDynamicDescriptors;
7140                            for (uint32_t d = 0; d < pSet->descriptorCount; d++) {
7141                                if (pSet->pLayout->descriptorTypes[d] == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) {
7142                                    if (vk_safe_modulo(
7143                                            pDynamicOffsets[cur_dyn_offset],
7144                                            dev_data->phys_dev_properties.properties.limits.minUniformBufferOffsetAlignment) != 0) {
7145                                        skipCall |= log_msg(
7146                                            dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
7147                                            VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT, 0, __LINE__,
7148                                            DRAWSTATE_INVALID_UNIFORM_BUFFER_OFFSET, "DS",
7149                                            "vkCmdBindDescriptorSets(): pDynamicOffsets[%d] is %d but must be a multiple of "
7150                                            "device limit minUniformBufferOffsetAlignment %#" PRIxLEAST64,
7151                                            cur_dyn_offset, pDynamicOffsets[cur_dyn_offset],
7152                                            dev_data->phys_dev_properties.properties.limits.minUniformBufferOffsetAlignment);
7153                                    }
7154                                    cur_dyn_offset++;
7155                                } else if (pSet->pLayout->descriptorTypes[d] == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC) {
7156                                    if (vk_safe_modulo(
7157                                            pDynamicOffsets[cur_dyn_offset],
7158                                            dev_data->phys_dev_properties.properties.limits.minStorageBufferOffsetAlignment) != 0) {
7159                                        skipCall |= log_msg(
7160                                            dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
7161                                            VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT, 0, __LINE__,
7162                                            DRAWSTATE_INVALID_STORAGE_BUFFER_OFFSET, "DS",
7163                                            "vkCmdBindDescriptorSets(): pDynamicOffsets[%d] is %d but must be a multiple of "
7164                                            "device limit minStorageBufferOffsetAlignment %#" PRIxLEAST64,
7165                                            cur_dyn_offset, pDynamicOffsets[cur_dyn_offset],
7166                                            dev_data->phys_dev_properties.properties.limits.minStorageBufferOffsetAlignment);
7167                                    }
7168                                    cur_dyn_offset++;
7169                                }
7170                            }
7171                            // Keep running total of dynamic descriptor count to verify at the end
7172                            totalDynamicDescriptors += pSet->pLayout->dynamicDescriptorCount;
7173                        }
7174                    }
7175                } else {
7176                    skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
7177                                        VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, (uint64_t)pDescriptorSets[i], __LINE__,
7178                                        DRAWSTATE_INVALID_SET, "DS", "Attempt to bind DS %#" PRIxLEAST64 " that doesn't exist!",
7179                                        (uint64_t)pDescriptorSets[i]);
7180                }
7181                skipCall |= addCmd(dev_data, pCB, CMD_BINDDESCRIPTORSETS, "vkCmdBindDescriptorSets()");
7182                // For any previously bound sets, need to set them to "invalid" if they were disturbed by this update
7183                if (firstSet > 0) { // Check set #s below the first bound set
7184                    for (uint32_t i = 0; i < firstSet; ++i) {
7185                        if (pCB->lastBound[pipelineBindPoint].boundDescriptorSets[i] &&
7186                            !verify_set_layout_compatibility(
7187                                dev_data, dev_data->setMap[pCB->lastBound[pipelineBindPoint].boundDescriptorSets[i]], layout, i,
7188                                errorString)) {
7189                            skipCall |= log_msg(
7190                                dev_data->report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
7191                                VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
7192                                (uint64_t)pCB->lastBound[pipelineBindPoint].boundDescriptorSets[i], __LINE__, DRAWSTATE_NONE, "DS",
7193                                "DescriptorSetDS %#" PRIxLEAST64
7194                                " previously bound as set #%u was disturbed by newly bound pipelineLayout (%#" PRIxLEAST64 ")",
7195                                (uint64_t)pCB->lastBound[pipelineBindPoint].boundDescriptorSets[i], i, (uint64_t)layout);
7196                            pCB->lastBound[pipelineBindPoint].boundDescriptorSets[i] = VK_NULL_HANDLE;
7197                        }
7198                    }
7199                }
7200                // Check if newly last bound set invalidates any remaining bound sets
7201                if ((pCB->lastBound[pipelineBindPoint].boundDescriptorSets.size() - 1) > (lastSetIndex)) {
7202                    if (oldFinalBoundSet &&
7203                        !verify_set_layout_compatibility(dev_data, dev_data->setMap[oldFinalBoundSet], layout, lastSetIndex,
7204                                                         errorString)) {
7205                        skipCall |=
7206                            log_msg(dev_data->report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
7207                                    VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, (uint64_t)oldFinalBoundSet, __LINE__,
7208                                    DRAWSTATE_NONE, "DS", "DescriptorSetDS %#" PRIxLEAST64
7209                                                          " previously bound as set #%u is incompatible with set %#" PRIxLEAST64
7210                                                          " newly bound as set #%u so set #%u and any subsequent sets were "
7211                                                          "disturbed by newly bound pipelineLayout (%#" PRIxLEAST64 ")",
7212                                    (uint64_t)oldFinalBoundSet, lastSetIndex,
7213                                    (uint64_t)pCB->lastBound[pipelineBindPoint].boundDescriptorSets[lastSetIndex], lastSetIndex,
7214                                    lastSetIndex + 1, (uint64_t)layout);
7215                        pCB->lastBound[pipelineBindPoint].boundDescriptorSets.resize(lastSetIndex + 1);
7216                    }
7217                }
7218            }
7219            //  dynamicOffsetCount must equal the total number of dynamic descriptors in the sets being bound
7220            if (totalDynamicDescriptors != dynamicOffsetCount) {
7221                skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
7222                                    VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, (uint64_t)commandBuffer, __LINE__,
7223                                    DRAWSTATE_INVALID_DYNAMIC_OFFSET_COUNT, "DS",
7224                                    "Attempting to bind %u descriptorSets with %u dynamic descriptors, but dynamicOffsetCount "
7225                                    "is %u. It should exactly match the number of dynamic descriptors.",
7226                                    setCount, totalDynamicDescriptors, dynamicOffsetCount);
7227            }
7228            // Save dynamicOffsets bound to this CB
7229            for (uint32_t i = 0; i < dynamicOffsetCount; i++) {
7230                pCB->lastBound[pipelineBindPoint].dynamicOffsets.emplace_back(pDynamicOffsets[i]);
7231            }
7232        } else {
7233            skipCall |= report_error_no_cb_begin(dev_data, commandBuffer, "vkCmdBindDescriptorSets()");
7234        }
7235    }
7236    loader_platform_thread_unlock_mutex(&globalLock);
7237    if (!skipCall)
7238        dev_data->device_dispatch_table->CmdBindDescriptorSets(commandBuffer, pipelineBindPoint, layout, firstSet, setCount,
7239                                                               pDescriptorSets, dynamicOffsetCount, pDynamicOffsets);
7240}
7241
7242VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
7243vkCmdBindIndexBuffer(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkIndexType indexType) {
7244    bool skipCall = false;
7245    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7246    loader_platform_thread_lock_mutex(&globalLock);
7247#if MTMERGESOURCE
7248    VkDeviceMemory mem;
7249    skipCall =
7250        get_mem_binding_from_object(dev_data, (uint64_t)buffer, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, &mem);
7251    auto cb_data = dev_data->commandBufferMap.find(commandBuffer);
7252    if (cb_data != dev_data->commandBufferMap.end()) {
7253        std::function<bool()> function = [=]() { return validate_memory_is_valid(dev_data, mem, "vkCmdBindIndexBuffer()"); };
7254        cb_data->second->validate_functions.push_back(function);
7255    }
7256    // TODO : Somewhere need to verify that IBs have correct usage state flagged
7257#endif
7258    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7259    if (pCB) {
7260        skipCall |= addCmd(dev_data, pCB, CMD_BINDINDEXBUFFER, "vkCmdBindIndexBuffer()");
7261        VkDeviceSize offset_align = 0;
7262        switch (indexType) {
7263        case VK_INDEX_TYPE_UINT16:
7264            offset_align = 2;
7265            break;
7266        case VK_INDEX_TYPE_UINT32:
7267            offset_align = 4;
7268            break;
7269        default:
7270            // ParamChecker should catch bad enum, we'll also throw alignment error below if offset_align stays 0
7271            break;
7272        }
7273        if (!offset_align || (offset % offset_align)) {
7274            skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
7275                                DRAWSTATE_VTX_INDEX_ALIGNMENT_ERROR, "DS",
7276                                "vkCmdBindIndexBuffer() offset (%#" PRIxLEAST64 ") does not fall on alignment (%s) boundary.",
7277                                offset, string_VkIndexType(indexType));
7278        }
7279        pCB->status |= CBSTATUS_INDEX_BUFFER_BOUND;
7280    }
7281    loader_platform_thread_unlock_mutex(&globalLock);
7282    if (!skipCall)
7283        dev_data->device_dispatch_table->CmdBindIndexBuffer(commandBuffer, buffer, offset, indexType);
7284}
7285
7286void updateResourceTracking(GLOBAL_CB_NODE *pCB, uint32_t firstBinding, uint32_t bindingCount, const VkBuffer *pBuffers) {
7287    uint32_t end = firstBinding + bindingCount;
7288    if (pCB->currentDrawData.buffers.size() < end) {
7289        pCB->currentDrawData.buffers.resize(end);
7290    }
7291    for (uint32_t i = 0; i < bindingCount; ++i) {
7292        pCB->currentDrawData.buffers[i + firstBinding] = pBuffers[i];
7293    }
7294}
7295
7296static inline void updateResourceTrackingOnDraw(GLOBAL_CB_NODE *pCB) { pCB->drawData.push_back(pCB->currentDrawData); }
7297
7298VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkCmdBindVertexBuffers(VkCommandBuffer commandBuffer, uint32_t firstBinding,
7299                                                                  uint32_t bindingCount, const VkBuffer *pBuffers,
7300                                                                  const VkDeviceSize *pOffsets) {
7301    bool skipCall = false;
7302    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7303    loader_platform_thread_lock_mutex(&globalLock);
7304#if MTMERGESOURCE
7305    for (uint32_t i = 0; i < bindingCount; ++i) {
7306        VkDeviceMemory mem;
7307        skipCall |= get_mem_binding_from_object(dev_data, (uint64_t)pBuffers[i], VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, &mem);
7308        auto cb_data = dev_data->commandBufferMap.find(commandBuffer);
7309        if (cb_data != dev_data->commandBufferMap.end()) {
7310            std::function<bool()> function = [=]() { return validate_memory_is_valid(dev_data, mem, "vkCmdBindVertexBuffers()"); };
7311            cb_data->second->validate_functions.push_back(function);
7312        }
7313    }
7314    // TODO : Somewhere need to verify that VBs have correct usage state flagged
7315#endif
7316    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7317    if (pCB) {
7318        addCmd(dev_data, pCB, CMD_BINDVERTEXBUFFER, "vkCmdBindVertexBuffer()");
7319        updateResourceTracking(pCB, firstBinding, bindingCount, pBuffers);
7320    } else {
7321        skipCall |= report_error_no_cb_begin(dev_data, commandBuffer, "vkCmdBindVertexBuffer()");
7322    }
7323    loader_platform_thread_unlock_mutex(&globalLock);
7324    if (!skipCall)
7325        dev_data->device_dispatch_table->CmdBindVertexBuffers(commandBuffer, firstBinding, bindingCount, pBuffers, pOffsets);
7326}
7327
7328/* expects globalLock to be held by caller */
7329static bool markStoreImagesAndBuffersAsWritten(layer_data *dev_data, GLOBAL_CB_NODE *pCB) {
7330    bool skip_call = false;
7331
7332    for (auto imageView : pCB->updateImages) {
7333        auto iv_data = dev_data->imageViewMap.find(imageView);
7334        if (iv_data == dev_data->imageViewMap.end())
7335            continue;
7336        VkImage image = iv_data->second.image;
7337        VkDeviceMemory mem;
7338        skip_call |=
7339            get_mem_binding_from_object(dev_data, (uint64_t)image, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, &mem);
7340        std::function<bool()> function = [=]() {
7341            set_memory_valid(dev_data, mem, true, image);
7342            return false;
7343        };
7344        pCB->validate_functions.push_back(function);
7345    }
7346    for (auto buffer : pCB->updateBuffers) {
7347        VkDeviceMemory mem;
7348        skip_call |= get_mem_binding_from_object(dev_data, (uint64_t)buffer,
7349                                                 VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, &mem);
7350        std::function<bool()> function = [=]() {
7351            set_memory_valid(dev_data, mem, true);
7352            return false;
7353        };
7354        pCB->validate_functions.push_back(function);
7355    }
7356    return skip_call;
7357}
7358
7359VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
7360                                                     uint32_t firstVertex, uint32_t firstInstance) {
7361    bool skipCall = false;
7362    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7363    loader_platform_thread_lock_mutex(&globalLock);
7364    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7365    if (pCB) {
7366        skipCall |= addCmd(dev_data, pCB, CMD_DRAW, "vkCmdDraw()");
7367        pCB->drawCount[DRAW]++;
7368        skipCall |= validate_and_update_draw_state(dev_data, pCB, false, VK_PIPELINE_BIND_POINT_GRAPHICS);
7369        skipCall |= markStoreImagesAndBuffersAsWritten(dev_data, pCB);
7370        // TODO : Need to pass commandBuffer as srcObj here
7371        skipCall |=
7372            log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0,
7373                    __LINE__, DRAWSTATE_NONE, "DS", "vkCmdDraw() call #%" PRIu64 ", reporting DS state:", g_drawCount[DRAW]++);
7374        skipCall |= synchAndPrintDSConfig(dev_data, commandBuffer);
7375        if (!skipCall) {
7376            updateResourceTrackingOnDraw(pCB);
7377        }
7378        skipCall |= outsideRenderPass(dev_data, pCB, "vkCmdDraw");
7379    }
7380    loader_platform_thread_unlock_mutex(&globalLock);
7381    if (!skipCall)
7382        dev_data->device_dispatch_table->CmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
7383}
7384
7385VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount,
7386                                                            uint32_t instanceCount, uint32_t firstIndex, int32_t vertexOffset,
7387                                                            uint32_t firstInstance) {
7388    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7389    bool skipCall = false;
7390    loader_platform_thread_lock_mutex(&globalLock);
7391    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7392    if (pCB) {
7393        skipCall |= addCmd(dev_data, pCB, CMD_DRAWINDEXED, "vkCmdDrawIndexed()");
7394        pCB->drawCount[DRAW_INDEXED]++;
7395        skipCall |= validate_and_update_draw_state(dev_data, pCB, true, VK_PIPELINE_BIND_POINT_GRAPHICS);
7396        skipCall |= markStoreImagesAndBuffersAsWritten(dev_data, pCB);
7397        // TODO : Need to pass commandBuffer as srcObj here
7398        skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT,
7399                            VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0, __LINE__, DRAWSTATE_NONE, "DS",
7400                            "vkCmdDrawIndexed() call #%" PRIu64 ", reporting DS state:", g_drawCount[DRAW_INDEXED]++);
7401        skipCall |= synchAndPrintDSConfig(dev_data, commandBuffer);
7402        if (!skipCall) {
7403            updateResourceTrackingOnDraw(pCB);
7404        }
7405        skipCall |= outsideRenderPass(dev_data, pCB, "vkCmdDrawIndexed");
7406    }
7407    loader_platform_thread_unlock_mutex(&globalLock);
7408    if (!skipCall)
7409        dev_data->device_dispatch_table->CmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
7410                                                        firstInstance);
7411}
7412
7413VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
7414vkCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, uint32_t count, uint32_t stride) {
7415    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7416    bool skipCall = false;
7417    loader_platform_thread_lock_mutex(&globalLock);
7418#if MTMERGESOURCE
7419    VkDeviceMemory mem;
7420    // MTMTODO : merge with code below
7421    skipCall =
7422        get_mem_binding_from_object(dev_data, (uint64_t)buffer, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, &mem);
7423    skipCall |= update_cmd_buf_and_mem_references(dev_data, commandBuffer, mem, "vkCmdDrawIndirect");
7424#endif
7425    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7426    if (pCB) {
7427        skipCall |= addCmd(dev_data, pCB, CMD_DRAWINDIRECT, "vkCmdDrawIndirect()");
7428        pCB->drawCount[DRAW_INDIRECT]++;
7429        skipCall |= validate_and_update_draw_state(dev_data, pCB, false, VK_PIPELINE_BIND_POINT_GRAPHICS);
7430        skipCall |= markStoreImagesAndBuffersAsWritten(dev_data, pCB);
7431        // TODO : Need to pass commandBuffer as srcObj here
7432        skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT,
7433                            VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0, __LINE__, DRAWSTATE_NONE, "DS",
7434                            "vkCmdDrawIndirect() call #%" PRIu64 ", reporting DS state:", g_drawCount[DRAW_INDIRECT]++);
7435        skipCall |= synchAndPrintDSConfig(dev_data, commandBuffer);
7436        if (!skipCall) {
7437            updateResourceTrackingOnDraw(pCB);
7438        }
7439        skipCall |= outsideRenderPass(dev_data, pCB, "vkCmdDrawIndirect");
7440    }
7441    loader_platform_thread_unlock_mutex(&globalLock);
7442    if (!skipCall)
7443        dev_data->device_dispatch_table->CmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
7444}
7445
7446VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
7447vkCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, uint32_t count, uint32_t stride) {
7448    bool skipCall = false;
7449    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7450    loader_platform_thread_lock_mutex(&globalLock);
7451#if MTMERGESOURCE
7452    VkDeviceMemory mem;
7453    // MTMTODO : merge with code below
7454    skipCall =
7455        get_mem_binding_from_object(dev_data, (uint64_t)buffer, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, &mem);
7456    skipCall |= update_cmd_buf_and_mem_references(dev_data, commandBuffer, mem, "vkCmdDrawIndexedIndirect");
7457#endif
7458    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7459    if (pCB) {
7460        skipCall |= addCmd(dev_data, pCB, CMD_DRAWINDEXEDINDIRECT, "vkCmdDrawIndexedIndirect()");
7461        pCB->drawCount[DRAW_INDEXED_INDIRECT]++;
7462        skipCall |= validate_and_update_draw_state(dev_data, pCB, true, VK_PIPELINE_BIND_POINT_GRAPHICS);
7463        skipCall |= markStoreImagesAndBuffersAsWritten(dev_data, pCB);
7464        // TODO : Need to pass commandBuffer as srcObj here
7465        skipCall |=
7466            log_msg(dev_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0,
7467                    __LINE__, DRAWSTATE_NONE, "DS", "vkCmdDrawIndexedIndirect() call #%" PRIu64 ", reporting DS state:",
7468                    g_drawCount[DRAW_INDEXED_INDIRECT]++);
7469        skipCall |= synchAndPrintDSConfig(dev_data, commandBuffer);
7470        if (!skipCall) {
7471            updateResourceTrackingOnDraw(pCB);
7472        }
7473        skipCall |= outsideRenderPass(dev_data, pCB, "vkCmdDrawIndexedIndirect");
7474    }
7475    loader_platform_thread_unlock_mutex(&globalLock);
7476    if (!skipCall)
7477        dev_data->device_dispatch_table->CmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
7478}
7479
7480VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
7481    bool skipCall = false;
7482    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7483    loader_platform_thread_lock_mutex(&globalLock);
7484    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7485    if (pCB) {
7486        // TODO : Re-enable validate_and_update_draw_state() when it supports compute shaders
7487        // skipCall |= validate_and_update_draw_state(dev_data, pCB, false, VK_PIPELINE_BIND_POINT_COMPUTE);
7488        // TODO : Call below is temporary until call above can be re-enabled
7489        update_shader_storage_images_and_buffers(dev_data, pCB);
7490        skipCall |= markStoreImagesAndBuffersAsWritten(dev_data, pCB);
7491        skipCall |= addCmd(dev_data, pCB, CMD_DISPATCH, "vkCmdDispatch()");
7492        skipCall |= insideRenderPass(dev_data, pCB, "vkCmdDispatch");
7493    }
7494    loader_platform_thread_unlock_mutex(&globalLock);
7495    if (!skipCall)
7496        dev_data->device_dispatch_table->CmdDispatch(commandBuffer, x, y, z);
7497}
7498
7499VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
7500vkCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
7501    bool skipCall = false;
7502    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7503    loader_platform_thread_lock_mutex(&globalLock);
7504#if MTMERGESOURCE
7505    VkDeviceMemory mem;
7506    skipCall =
7507        get_mem_binding_from_object(dev_data, (uint64_t)buffer, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, &mem);
7508    skipCall |= update_cmd_buf_and_mem_references(dev_data, commandBuffer, mem, "vkCmdDispatchIndirect");
7509#endif
7510    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7511    if (pCB) {
7512        // TODO : Re-enable validate_and_update_draw_state() when it supports compute shaders
7513        // skipCall |= validate_and_update_draw_state(dev_data, pCB, false, VK_PIPELINE_BIND_POINT_COMPUTE);
7514        // TODO : Call below is temporary until call above can be re-enabled
7515        update_shader_storage_images_and_buffers(dev_data, pCB);
7516        skipCall |= markStoreImagesAndBuffersAsWritten(dev_data, pCB);
7517        skipCall |= addCmd(dev_data, pCB, CMD_DISPATCHINDIRECT, "vkCmdDispatchIndirect()");
7518        skipCall |= insideRenderPass(dev_data, pCB, "vkCmdDispatchIndirect");
7519    }
7520    loader_platform_thread_unlock_mutex(&globalLock);
7521    if (!skipCall)
7522        dev_data->device_dispatch_table->CmdDispatchIndirect(commandBuffer, buffer, offset);
7523}
7524
7525VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
7526                                                           uint32_t regionCount, const VkBufferCopy *pRegions) {
7527    bool skipCall = false;
7528    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7529    loader_platform_thread_lock_mutex(&globalLock);
7530#if MTMERGESOURCE
7531    VkDeviceMemory mem;
7532    auto cb_data = dev_data->commandBufferMap.find(commandBuffer);
7533    skipCall =
7534        get_mem_binding_from_object(dev_data, (uint64_t)srcBuffer, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, &mem);
7535    if (cb_data != dev_data->commandBufferMap.end()) {
7536        std::function<bool()> function = [=]() { return validate_memory_is_valid(dev_data, mem, "vkCmdCopyBuffer()"); };
7537        cb_data->second->validate_functions.push_back(function);
7538    }
7539    skipCall |= update_cmd_buf_and_mem_references(dev_data, commandBuffer, mem, "vkCmdCopyBuffer");
7540    skipCall |=
7541        get_mem_binding_from_object(dev_data, (uint64_t)dstBuffer, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, &mem);
7542    if (cb_data != dev_data->commandBufferMap.end()) {
7543        std::function<bool()> function = [=]() {
7544            set_memory_valid(dev_data, mem, true);
7545            return false;
7546        };
7547        cb_data->second->validate_functions.push_back(function);
7548    }
7549    skipCall |= update_cmd_buf_and_mem_references(dev_data, commandBuffer, mem, "vkCmdCopyBuffer");
7550    // Validate that SRC & DST buffers have correct usage flags set
7551    skipCall |= validate_buffer_usage_flags(dev_data, srcBuffer, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, true,
7552                                            "vkCmdCopyBuffer()", "VK_BUFFER_USAGE_TRANSFER_SRC_BIT");
7553    skipCall |= validate_buffer_usage_flags(dev_data, dstBuffer, VK_BUFFER_USAGE_TRANSFER_DST_BIT, true,
7554                                            "vkCmdCopyBuffer()", "VK_BUFFER_USAGE_TRANSFER_DST_BIT");
7555#endif
7556    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7557    if (pCB) {
7558        skipCall |= addCmd(dev_data, pCB, CMD_COPYBUFFER, "vkCmdCopyBuffer()");
7559        skipCall |= insideRenderPass(dev_data, pCB, "vkCmdCopyBuffer");
7560    }
7561    loader_platform_thread_unlock_mutex(&globalLock);
7562    if (!skipCall)
7563        dev_data->device_dispatch_table->CmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, regionCount, pRegions);
7564}
7565
7566static bool VerifySourceImageLayout(VkCommandBuffer cmdBuffer, VkImage srcImage, VkImageSubresourceLayers subLayers,
7567                                    VkImageLayout srcImageLayout) {
7568    bool skip_call = false;
7569
7570    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(cmdBuffer), layer_data_map);
7571    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, cmdBuffer);
7572    for (uint32_t i = 0; i < subLayers.layerCount; ++i) {
7573        uint32_t layer = i + subLayers.baseArrayLayer;
7574        VkImageSubresource sub = {subLayers.aspectMask, subLayers.mipLevel, layer};
7575        IMAGE_CMD_BUF_LAYOUT_NODE node;
7576        if (!FindLayout(pCB, srcImage, sub, node)) {
7577            SetLayout(pCB, srcImage, sub, IMAGE_CMD_BUF_LAYOUT_NODE(srcImageLayout, srcImageLayout));
7578            continue;
7579        }
7580        if (node.layout != srcImageLayout) {
7581            // TODO: Improve log message in the next pass
7582            skip_call |=
7583                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0,
7584                        __LINE__, DRAWSTATE_INVALID_IMAGE_LAYOUT, "DS", "Cannot copy from an image whose source layout is %s "
7585                                                                        "and doesn't match the current layout %s.",
7586                        string_VkImageLayout(srcImageLayout), string_VkImageLayout(node.layout));
7587        }
7588    }
7589    if (srcImageLayout != VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) {
7590        if (srcImageLayout == VK_IMAGE_LAYOUT_GENERAL) {
7591            // LAYOUT_GENERAL is allowed, but may not be performance optimal, flag as perf warning.
7592            skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, (VkDebugReportObjectTypeEXT)0,
7593                                 0, __LINE__, DRAWSTATE_INVALID_IMAGE_LAYOUT, "DS",
7594                                 "Layout for input image should be TRANSFER_SRC_OPTIMAL instead of GENERAL.");
7595        } else {
7596            skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
7597                                 DRAWSTATE_INVALID_IMAGE_LAYOUT, "DS", "Layout for input image is %s but can only be "
7598                                                                       "TRANSFER_SRC_OPTIMAL or GENERAL.",
7599                                 string_VkImageLayout(srcImageLayout));
7600        }
7601    }
7602    return skip_call;
7603}
7604
7605static bool VerifyDestImageLayout(VkCommandBuffer cmdBuffer, VkImage destImage, VkImageSubresourceLayers subLayers,
7606                                  VkImageLayout destImageLayout) {
7607    bool skip_call = false;
7608
7609    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(cmdBuffer), layer_data_map);
7610    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, cmdBuffer);
7611    for (uint32_t i = 0; i < subLayers.layerCount; ++i) {
7612        uint32_t layer = i + subLayers.baseArrayLayer;
7613        VkImageSubresource sub = {subLayers.aspectMask, subLayers.mipLevel, layer};
7614        IMAGE_CMD_BUF_LAYOUT_NODE node;
7615        if (!FindLayout(pCB, destImage, sub, node)) {
7616            SetLayout(pCB, destImage, sub, IMAGE_CMD_BUF_LAYOUT_NODE(destImageLayout, destImageLayout));
7617            continue;
7618        }
7619        if (node.layout != destImageLayout) {
7620            skip_call |=
7621                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0,
7622                        __LINE__, DRAWSTATE_INVALID_IMAGE_LAYOUT, "DS", "Cannot copy from an image whose dest layout is %s and "
7623                                                                        "doesn't match the current layout %s.",
7624                        string_VkImageLayout(destImageLayout), string_VkImageLayout(node.layout));
7625        }
7626    }
7627    if (destImageLayout != VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
7628        if (destImageLayout == VK_IMAGE_LAYOUT_GENERAL) {
7629            // LAYOUT_GENERAL is allowed, but may not be performance optimal, flag as perf warning.
7630            skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, (VkDebugReportObjectTypeEXT)0,
7631                                 0, __LINE__, DRAWSTATE_INVALID_IMAGE_LAYOUT, "DS",
7632                                 "Layout for output image should be TRANSFER_DST_OPTIMAL instead of GENERAL.");
7633        } else {
7634            skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
7635                                 DRAWSTATE_INVALID_IMAGE_LAYOUT, "DS", "Layout for output image is %s but can only be "
7636                                                                       "TRANSFER_DST_OPTIMAL or GENERAL.",
7637                                 string_VkImageLayout(destImageLayout));
7638        }
7639    }
7640    return skip_call;
7641}
7642
7643VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
7644vkCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage,
7645               VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageCopy *pRegions) {
7646    bool skipCall = false;
7647    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7648    loader_platform_thread_lock_mutex(&globalLock);
7649#if MTMERGESOURCE
7650    VkDeviceMemory mem;
7651    auto cb_data = dev_data->commandBufferMap.find(commandBuffer);
7652    // Validate that src & dst images have correct usage flags set
7653    skipCall = get_mem_binding_from_object(dev_data, (uint64_t)srcImage, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, &mem);
7654    if (cb_data != dev_data->commandBufferMap.end()) {
7655        std::function<bool()> function = [=]() { return validate_memory_is_valid(dev_data, mem, "vkCmdCopyImage()", srcImage); };
7656        cb_data->second->validate_functions.push_back(function);
7657    }
7658    skipCall |= update_cmd_buf_and_mem_references(dev_data, commandBuffer, mem, "vkCmdCopyImage");
7659    skipCall |=
7660        get_mem_binding_from_object(dev_data, (uint64_t)dstImage, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, &mem);
7661    if (cb_data != dev_data->commandBufferMap.end()) {
7662        std::function<bool()> function = [=]() {
7663            set_memory_valid(dev_data, mem, true, dstImage);
7664            return false;
7665        };
7666        cb_data->second->validate_functions.push_back(function);
7667    }
7668    skipCall |= update_cmd_buf_and_mem_references(dev_data, commandBuffer, mem, "vkCmdCopyImage");
7669    skipCall |= validate_image_usage_flags(dev_data, srcImage, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, true,
7670                                           "vkCmdCopyImage()", "VK_IMAGE_USAGE_TRANSFER_SRC_BIT");
7671    skipCall |= validate_image_usage_flags(dev_data, dstImage, VK_IMAGE_USAGE_TRANSFER_DST_BIT, true,
7672                                           "vkCmdCopyImage()", "VK_IMAGE_USAGE_TRANSFER_DST_BIT");
7673#endif
7674    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7675    if (pCB) {
7676        skipCall |= addCmd(dev_data, pCB, CMD_COPYIMAGE, "vkCmdCopyImage()");
7677        skipCall |= insideRenderPass(dev_data, pCB, "vkCmdCopyImage");
7678        for (uint32_t i = 0; i < regionCount; ++i) {
7679            skipCall |= VerifySourceImageLayout(commandBuffer, srcImage, pRegions[i].srcSubresource, srcImageLayout);
7680            skipCall |= VerifyDestImageLayout(commandBuffer, dstImage, pRegions[i].dstSubresource, dstImageLayout);
7681        }
7682    }
7683    loader_platform_thread_unlock_mutex(&globalLock);
7684    if (!skipCall)
7685        dev_data->device_dispatch_table->CmdCopyImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout,
7686                                                      regionCount, pRegions);
7687}
7688
7689VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
7690vkCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage,
7691               VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageBlit *pRegions, VkFilter filter) {
7692    bool skipCall = false;
7693    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7694    loader_platform_thread_lock_mutex(&globalLock);
7695#if MTMERGESOURCE
7696    VkDeviceMemory mem;
7697    auto cb_data = dev_data->commandBufferMap.find(commandBuffer);
7698    // Validate that src & dst images have correct usage flags set
7699    skipCall = get_mem_binding_from_object(dev_data, (uint64_t)srcImage, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, &mem);
7700    if (cb_data != dev_data->commandBufferMap.end()) {
7701        std::function<bool()> function = [=]() { return validate_memory_is_valid(dev_data, mem, "vkCmdBlitImage()", srcImage); };
7702        cb_data->second->validate_functions.push_back(function);
7703    }
7704    skipCall |= update_cmd_buf_and_mem_references(dev_data, commandBuffer, mem, "vkCmdBlitImage");
7705    skipCall |=
7706        get_mem_binding_from_object(dev_data, (uint64_t)dstImage, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, &mem);
7707    if (cb_data != dev_data->commandBufferMap.end()) {
7708        std::function<bool()> function = [=]() {
7709            set_memory_valid(dev_data, mem, true, dstImage);
7710            return false;
7711        };
7712        cb_data->second->validate_functions.push_back(function);
7713    }
7714    skipCall |= update_cmd_buf_and_mem_references(dev_data, commandBuffer, mem, "vkCmdBlitImage");
7715    skipCall |= validate_image_usage_flags(dev_data, srcImage, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, true,
7716                                           "vkCmdBlitImage()", "VK_IMAGE_USAGE_TRANSFER_SRC_BIT");
7717    skipCall |= validate_image_usage_flags(dev_data, dstImage, VK_IMAGE_USAGE_TRANSFER_DST_BIT, true,
7718                                           "vkCmdBlitImage()", "VK_IMAGE_USAGE_TRANSFER_DST_BIT");
7719#endif
7720    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7721    if (pCB) {
7722        skipCall |= addCmd(dev_data, pCB, CMD_BLITIMAGE, "vkCmdBlitImage()");
7723        skipCall |= insideRenderPass(dev_data, pCB, "vkCmdBlitImage");
7724    }
7725    loader_platform_thread_unlock_mutex(&globalLock);
7726    if (!skipCall)
7727        dev_data->device_dispatch_table->CmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout,
7728                                                      regionCount, pRegions, filter);
7729}
7730
7731VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer,
7732                                                                  VkImage dstImage, VkImageLayout dstImageLayout,
7733                                                                  uint32_t regionCount, const VkBufferImageCopy *pRegions) {
7734    bool skipCall = false;
7735    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7736    loader_platform_thread_lock_mutex(&globalLock);
7737#if MTMERGESOURCE
7738    VkDeviceMemory mem;
7739    auto cb_data = dev_data->commandBufferMap.find(commandBuffer);
7740    skipCall = get_mem_binding_from_object(dev_data, (uint64_t)dstImage, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, &mem);
7741    if (cb_data != dev_data->commandBufferMap.end()) {
7742        std::function<bool()> function = [=]() {
7743            set_memory_valid(dev_data, mem, true, dstImage);
7744            return false;
7745        };
7746        cb_data->second->validate_functions.push_back(function);
7747    }
7748    skipCall |= update_cmd_buf_and_mem_references(dev_data, commandBuffer, mem, "vkCmdCopyBufferToImage");
7749    skipCall |=
7750        get_mem_binding_from_object(dev_data, (uint64_t)srcBuffer, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, &mem);
7751    if (cb_data != dev_data->commandBufferMap.end()) {
7752        std::function<bool()> function = [=]() { return validate_memory_is_valid(dev_data, mem, "vkCmdCopyBufferToImage()"); };
7753        cb_data->second->validate_functions.push_back(function);
7754    }
7755    skipCall |= update_cmd_buf_and_mem_references(dev_data, commandBuffer, mem, "vkCmdCopyBufferToImage");
7756    // Validate that src buff & dst image have correct usage flags set
7757    skipCall |= validate_buffer_usage_flags(dev_data, srcBuffer, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, true,
7758                                            "vkCmdCopyBufferToImage()", "VK_BUFFER_USAGE_TRANSFER_SRC_BIT");
7759    skipCall |= validate_image_usage_flags(dev_data, dstImage, VK_IMAGE_USAGE_TRANSFER_DST_BIT, true,
7760                                           "vkCmdCopyBufferToImage()", "VK_IMAGE_USAGE_TRANSFER_DST_BIT");
7761#endif
7762    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7763    if (pCB) {
7764        skipCall |= addCmd(dev_data, pCB, CMD_COPYBUFFERTOIMAGE, "vkCmdCopyBufferToImage()");
7765        skipCall |= insideRenderPass(dev_data, pCB, "vkCmdCopyBufferToImage");
7766        for (uint32_t i = 0; i < regionCount; ++i) {
7767            skipCall |= VerifyDestImageLayout(commandBuffer, dstImage, pRegions[i].imageSubresource, dstImageLayout);
7768        }
7769    }
7770    loader_platform_thread_unlock_mutex(&globalLock);
7771    if (!skipCall)
7772        dev_data->device_dispatch_table->CmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount,
7773                                                              pRegions);
7774}
7775
7776VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
7777                                                                  VkImageLayout srcImageLayout, VkBuffer dstBuffer,
7778                                                                  uint32_t regionCount, const VkBufferImageCopy *pRegions) {
7779    bool skipCall = false;
7780    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7781    loader_platform_thread_lock_mutex(&globalLock);
7782#if MTMERGESOURCE
7783    VkDeviceMemory mem;
7784    auto cb_data = dev_data->commandBufferMap.find(commandBuffer);
7785    skipCall = get_mem_binding_from_object(dev_data, (uint64_t)srcImage, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, &mem);
7786    if (cb_data != dev_data->commandBufferMap.end()) {
7787        std::function<bool()> function = [=]() {
7788            return validate_memory_is_valid(dev_data, mem, "vkCmdCopyImageToBuffer()", srcImage);
7789        };
7790        cb_data->second->validate_functions.push_back(function);
7791    }
7792    skipCall |= update_cmd_buf_and_mem_references(dev_data, commandBuffer, mem, "vkCmdCopyImageToBuffer");
7793    skipCall |=
7794        get_mem_binding_from_object(dev_data, (uint64_t)dstBuffer, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, &mem);
7795    if (cb_data != dev_data->commandBufferMap.end()) {
7796        std::function<bool()> function = [=]() {
7797            set_memory_valid(dev_data, mem, true);
7798            return false;
7799        };
7800        cb_data->second->validate_functions.push_back(function);
7801    }
7802    skipCall |= update_cmd_buf_and_mem_references(dev_data, commandBuffer, mem, "vkCmdCopyImageToBuffer");
7803    // Validate that dst buff & src image have correct usage flags set
7804    skipCall |= validate_image_usage_flags(dev_data, srcImage, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, true,
7805                                           "vkCmdCopyImageToBuffer()", "VK_IMAGE_USAGE_TRANSFER_SRC_BIT");
7806    skipCall |= validate_buffer_usage_flags(dev_data, dstBuffer, VK_BUFFER_USAGE_TRANSFER_DST_BIT, true,
7807                                            "vkCmdCopyImageToBuffer()", "VK_BUFFER_USAGE_TRANSFER_DST_BIT");
7808#endif
7809    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7810    if (pCB) {
7811        skipCall |= addCmd(dev_data, pCB, CMD_COPYIMAGETOBUFFER, "vkCmdCopyImageToBuffer()");
7812        skipCall |= insideRenderPass(dev_data, pCB, "vkCmdCopyImageToBuffer");
7813        for (uint32_t i = 0; i < regionCount; ++i) {
7814            skipCall |= VerifySourceImageLayout(commandBuffer, srcImage, pRegions[i].imageSubresource, srcImageLayout);
7815        }
7816    }
7817    loader_platform_thread_unlock_mutex(&globalLock);
7818    if (!skipCall)
7819        dev_data->device_dispatch_table->CmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount,
7820                                                              pRegions);
7821}
7822
7823VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer,
7824                                                             VkDeviceSize dstOffset, VkDeviceSize dataSize, const uint32_t *pData) {
7825    bool skipCall = false;
7826    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7827    loader_platform_thread_lock_mutex(&globalLock);
7828#if MTMERGESOURCE
7829    VkDeviceMemory mem;
7830    auto cb_data = dev_data->commandBufferMap.find(commandBuffer);
7831    skipCall =
7832        get_mem_binding_from_object(dev_data, (uint64_t)dstBuffer, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, &mem);
7833    if (cb_data != dev_data->commandBufferMap.end()) {
7834        std::function<bool()> function = [=]() {
7835            set_memory_valid(dev_data, mem, true);
7836            return false;
7837        };
7838        cb_data->second->validate_functions.push_back(function);
7839    }
7840    skipCall |= update_cmd_buf_and_mem_references(dev_data, commandBuffer, mem, "vkCmdUpdateBuffer");
7841    // Validate that dst buff has correct usage flags set
7842    skipCall |= validate_buffer_usage_flags(dev_data, dstBuffer, VK_BUFFER_USAGE_TRANSFER_DST_BIT, true,
7843                                            "vkCmdUpdateBuffer()", "VK_BUFFER_USAGE_TRANSFER_DST_BIT");
7844#endif
7845    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7846    if (pCB) {
7847        skipCall |= addCmd(dev_data, pCB, CMD_UPDATEBUFFER, "vkCmdUpdateBuffer()");
7848        skipCall |= insideRenderPass(dev_data, pCB, "vkCmdCopyUpdateBuffer");
7849    }
7850    loader_platform_thread_unlock_mutex(&globalLock);
7851    if (!skipCall)
7852        dev_data->device_dispatch_table->CmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData);
7853}
7854
7855VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
7856vkCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize size, uint32_t data) {
7857    bool skipCall = false;
7858    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7859    loader_platform_thread_lock_mutex(&globalLock);
7860#if MTMERGESOURCE
7861    VkDeviceMemory mem;
7862    auto cb_data = dev_data->commandBufferMap.find(commandBuffer);
7863    skipCall =
7864        get_mem_binding_from_object(dev_data, (uint64_t)dstBuffer, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, &mem);
7865    if (cb_data != dev_data->commandBufferMap.end()) {
7866        std::function<bool()> function = [=]() {
7867            set_memory_valid(dev_data, mem, true);
7868            return false;
7869        };
7870        cb_data->second->validate_functions.push_back(function);
7871    }
7872    skipCall |= update_cmd_buf_and_mem_references(dev_data, commandBuffer, mem, "vkCmdFillBuffer");
7873    // Validate that dst buff has correct usage flags set
7874    skipCall |= validate_buffer_usage_flags(dev_data, dstBuffer, VK_BUFFER_USAGE_TRANSFER_DST_BIT, true,
7875                                            "vkCmdFillBuffer()", "VK_BUFFER_USAGE_TRANSFER_DST_BIT");
7876#endif
7877    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7878    if (pCB) {
7879        skipCall |= addCmd(dev_data, pCB, CMD_FILLBUFFER, "vkCmdFillBuffer()");
7880        skipCall |= insideRenderPass(dev_data, pCB, "vkCmdCopyFillBuffer");
7881    }
7882    loader_platform_thread_unlock_mutex(&globalLock);
7883    if (!skipCall)
7884        dev_data->device_dispatch_table->CmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data);
7885}
7886
7887VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
7888                                                                 const VkClearAttachment *pAttachments, uint32_t rectCount,
7889                                                                 const VkClearRect *pRects) {
7890    bool skipCall = false;
7891    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7892    loader_platform_thread_lock_mutex(&globalLock);
7893    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7894    if (pCB) {
7895        skipCall |= addCmd(dev_data, pCB, CMD_CLEARATTACHMENTS, "vkCmdClearAttachments()");
7896        // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
7897        if (!hasDrawCmd(pCB) && (pCB->activeRenderPassBeginInfo.renderArea.extent.width == pRects[0].rect.extent.width) &&
7898            (pCB->activeRenderPassBeginInfo.renderArea.extent.height == pRects[0].rect.extent.height)) {
7899            // TODO : commandBuffer should be srcObj
7900            // There are times where app needs to use ClearAttachments (generally when reusing a buffer inside of a render pass)
7901            // Can we make this warning more specific? I'd like to avoid triggering this test if we can tell it's a use that must
7902            // call CmdClearAttachments
7903            // Otherwise this seems more like a performance warning.
7904            skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
7905                                VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0, 0, DRAWSTATE_CLEAR_CMD_BEFORE_DRAW, "DS",
7906                                "vkCmdClearAttachments() issued on CB object 0x%" PRIxLEAST64 " prior to any Draw Cmds."
7907                                " It is recommended you use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
7908                                (uint64_t)(commandBuffer));
7909        }
7910        skipCall |= outsideRenderPass(dev_data, pCB, "vkCmdClearAttachments");
7911    }
7912
7913    // Validate that attachment is in reference list of active subpass
7914    if (pCB->activeRenderPass) {
7915        const VkRenderPassCreateInfo *pRPCI = dev_data->renderPassMap[pCB->activeRenderPass]->pCreateInfo;
7916        const VkSubpassDescription *pSD = &pRPCI->pSubpasses[pCB->activeSubpass];
7917
7918        for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; attachment_idx++) {
7919            const VkClearAttachment *attachment = &pAttachments[attachment_idx];
7920            if (attachment->aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
7921                bool found = false;
7922                for (uint32_t i = 0; i < pSD->colorAttachmentCount; i++) {
7923                    if (attachment->colorAttachment == pSD->pColorAttachments[i].attachment) {
7924                        found = true;
7925                        break;
7926                    }
7927                }
7928                if (!found) {
7929                    skipCall |= log_msg(
7930                        dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
7931                        (uint64_t)commandBuffer, __LINE__, DRAWSTATE_MISSING_ATTACHMENT_REFERENCE, "DS",
7932                        "vkCmdClearAttachments() attachment index %d not found in attachment reference array of active subpass %d",
7933                        attachment->colorAttachment, pCB->activeSubpass);
7934                }
7935            } else if (attachment->aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
7936                if (!pSD->pDepthStencilAttachment || // Says no DS will be used in active subpass
7937                    (pSD->pDepthStencilAttachment->attachment ==
7938                     VK_ATTACHMENT_UNUSED)) { // Says no DS will be used in active subpass
7939
7940                    skipCall |= log_msg(
7941                        dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
7942                        (uint64_t)commandBuffer, __LINE__, DRAWSTATE_MISSING_ATTACHMENT_REFERENCE, "DS",
7943                        "vkCmdClearAttachments() attachment index %d does not match depthStencilAttachment.attachment (%d) found "
7944                        "in active subpass %d",
7945                        attachment->colorAttachment,
7946                        (pSD->pDepthStencilAttachment) ? pSD->pDepthStencilAttachment->attachment : VK_ATTACHMENT_UNUSED,
7947                        pCB->activeSubpass);
7948                }
7949            }
7950        }
7951    }
7952    loader_platform_thread_unlock_mutex(&globalLock);
7953    if (!skipCall)
7954        dev_data->device_dispatch_table->CmdClearAttachments(commandBuffer, attachmentCount, pAttachments, rectCount, pRects);
7955}
7956
7957VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image,
7958                                                                VkImageLayout imageLayout, const VkClearColorValue *pColor,
7959                                                                uint32_t rangeCount, const VkImageSubresourceRange *pRanges) {
7960    bool skipCall = false;
7961    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7962    loader_platform_thread_lock_mutex(&globalLock);
7963#if MTMERGESOURCE
7964    // TODO : Verify memory is in VK_IMAGE_STATE_CLEAR state
7965    VkDeviceMemory mem;
7966    auto cb_data = dev_data->commandBufferMap.find(commandBuffer);
7967    skipCall = get_mem_binding_from_object(dev_data, (uint64_t)image, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, &mem);
7968    if (cb_data != dev_data->commandBufferMap.end()) {
7969        std::function<bool()> function = [=]() {
7970            set_memory_valid(dev_data, mem, true, image);
7971            return false;
7972        };
7973        cb_data->second->validate_functions.push_back(function);
7974    }
7975    skipCall |= update_cmd_buf_and_mem_references(dev_data, commandBuffer, mem, "vkCmdClearColorImage");
7976#endif
7977    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
7978    if (pCB) {
7979        skipCall |= addCmd(dev_data, pCB, CMD_CLEARCOLORIMAGE, "vkCmdClearColorImage()");
7980        skipCall |= insideRenderPass(dev_data, pCB, "vkCmdClearColorImage");
7981    }
7982    loader_platform_thread_unlock_mutex(&globalLock);
7983    if (!skipCall)
7984        dev_data->device_dispatch_table->CmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges);
7985}
7986
7987VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
7988vkCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
7989                            const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
7990                            const VkImageSubresourceRange *pRanges) {
7991    bool skipCall = false;
7992    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
7993    loader_platform_thread_lock_mutex(&globalLock);
7994#if MTMERGESOURCE
7995    // TODO : Verify memory is in VK_IMAGE_STATE_CLEAR state
7996    VkDeviceMemory mem;
7997    auto cb_data = dev_data->commandBufferMap.find(commandBuffer);
7998    skipCall = get_mem_binding_from_object(dev_data, (uint64_t)image, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, &mem);
7999    if (cb_data != dev_data->commandBufferMap.end()) {
8000        std::function<bool()> function = [=]() {
8001            set_memory_valid(dev_data, mem, true, image);
8002            return false;
8003        };
8004        cb_data->second->validate_functions.push_back(function);
8005    }
8006    skipCall |= update_cmd_buf_and_mem_references(dev_data, commandBuffer, mem, "vkCmdClearDepthStencilImage");
8007#endif
8008    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
8009    if (pCB) {
8010        skipCall |= addCmd(dev_data, pCB, CMD_CLEARDEPTHSTENCILIMAGE, "vkCmdClearDepthStencilImage()");
8011        skipCall |= insideRenderPass(dev_data, pCB, "vkCmdClearDepthStencilImage");
8012    }
8013    loader_platform_thread_unlock_mutex(&globalLock);
8014    if (!skipCall)
8015        dev_data->device_dispatch_table->CmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount,
8016                                                                   pRanges);
8017}
8018
8019VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
8020vkCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage,
8021                  VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageResolve *pRegions) {
8022    bool skipCall = false;
8023    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
8024    loader_platform_thread_lock_mutex(&globalLock);
8025#if MTMERGESOURCE
8026    auto cb_data = dev_data->commandBufferMap.find(commandBuffer);
8027    VkDeviceMemory mem;
8028    skipCall = get_mem_binding_from_object(dev_data, (uint64_t)srcImage, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, &mem);
8029    if (cb_data != dev_data->commandBufferMap.end()) {
8030        std::function<bool()> function = [=]() { return validate_memory_is_valid(dev_data, mem, "vkCmdResolveImage()", srcImage); };
8031        cb_data->second->validate_functions.push_back(function);
8032    }
8033    skipCall |= update_cmd_buf_and_mem_references(dev_data, commandBuffer, mem, "vkCmdResolveImage");
8034    skipCall |=
8035        get_mem_binding_from_object(dev_data, (uint64_t)dstImage, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, &mem);
8036    if (cb_data != dev_data->commandBufferMap.end()) {
8037        std::function<bool()> function = [=]() {
8038            set_memory_valid(dev_data, mem, true, dstImage);
8039            return false;
8040        };
8041        cb_data->second->validate_functions.push_back(function);
8042    }
8043    skipCall |= update_cmd_buf_and_mem_references(dev_data, commandBuffer, mem, "vkCmdResolveImage");
8044#endif
8045    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
8046    if (pCB) {
8047        skipCall |= addCmd(dev_data, pCB, CMD_RESOLVEIMAGE, "vkCmdResolveImage()");
8048        skipCall |= insideRenderPass(dev_data, pCB, "vkCmdResolveImage");
8049    }
8050    loader_platform_thread_unlock_mutex(&globalLock);
8051    if (!skipCall)
8052        dev_data->device_dispatch_table->CmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout,
8053                                                         regionCount, pRegions);
8054}
8055
8056bool setEventStageMask(VkQueue queue, VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
8057    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
8058    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
8059    if (pCB) {
8060        pCB->eventToStageMap[event] = stageMask;
8061    }
8062    auto queue_data = dev_data->queueMap.find(queue);
8063    if (queue_data != dev_data->queueMap.end()) {
8064        queue_data->second.eventToStageMap[event] = stageMask;
8065    }
8066    return false;
8067}
8068
8069VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
8070vkCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
8071    bool skipCall = false;
8072    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
8073    loader_platform_thread_lock_mutex(&globalLock);
8074    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
8075    if (pCB) {
8076        skipCall |= addCmd(dev_data, pCB, CMD_SETEVENT, "vkCmdSetEvent()");
8077        skipCall |= insideRenderPass(dev_data, pCB, "vkCmdSetEvent");
8078        pCB->events.push_back(event);
8079        std::function<bool(VkQueue)> eventUpdate =
8080            std::bind(setEventStageMask, std::placeholders::_1, commandBuffer, event, stageMask);
8081        pCB->eventUpdates.push_back(eventUpdate);
8082    }
8083    loader_platform_thread_unlock_mutex(&globalLock);
8084    if (!skipCall)
8085        dev_data->device_dispatch_table->CmdSetEvent(commandBuffer, event, stageMask);
8086}
8087
8088VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
8089vkCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
8090    bool skipCall = false;
8091    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
8092    loader_platform_thread_lock_mutex(&globalLock);
8093    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
8094    if (pCB) {
8095        skipCall |= addCmd(dev_data, pCB, CMD_RESETEVENT, "vkCmdResetEvent()");
8096        skipCall |= insideRenderPass(dev_data, pCB, "vkCmdResetEvent");
8097        pCB->events.push_back(event);
8098        std::function<bool(VkQueue)> eventUpdate =
8099            std::bind(setEventStageMask, std::placeholders::_1, commandBuffer, event, VkPipelineStageFlags(0));
8100        pCB->eventUpdates.push_back(eventUpdate);
8101    }
8102    loader_platform_thread_unlock_mutex(&globalLock);
8103    if (!skipCall)
8104        dev_data->device_dispatch_table->CmdResetEvent(commandBuffer, event, stageMask);
8105}
8106
8107static bool TransitionImageLayouts(VkCommandBuffer cmdBuffer, uint32_t memBarrierCount,
8108                                   const VkImageMemoryBarrier *pImgMemBarriers) {
8109    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(cmdBuffer), layer_data_map);
8110    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, cmdBuffer);
8111    bool skip = false;
8112    uint32_t levelCount = 0;
8113    uint32_t layerCount = 0;
8114
8115    for (uint32_t i = 0; i < memBarrierCount; ++i) {
8116        auto mem_barrier = &pImgMemBarriers[i];
8117        if (!mem_barrier)
8118            continue;
8119        // TODO: Do not iterate over every possibility - consolidate where
8120        // possible
8121        ResolveRemainingLevelsLayers(dev_data, &levelCount, &layerCount, mem_barrier->subresourceRange, mem_barrier->image);
8122
8123        for (uint32_t j = 0; j < levelCount; j++) {
8124            uint32_t level = mem_barrier->subresourceRange.baseMipLevel + j;
8125            for (uint32_t k = 0; k < layerCount; k++) {
8126                uint32_t layer = mem_barrier->subresourceRange.baseArrayLayer + k;
8127                VkImageSubresource sub = {mem_barrier->subresourceRange.aspectMask, level, layer};
8128                IMAGE_CMD_BUF_LAYOUT_NODE node;
8129                if (!FindLayout(pCB, mem_barrier->image, sub, node)) {
8130                    SetLayout(pCB, mem_barrier->image, sub,
8131                              IMAGE_CMD_BUF_LAYOUT_NODE(mem_barrier->oldLayout, mem_barrier->newLayout));
8132                    continue;
8133                }
8134                if (mem_barrier->oldLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
8135                    // TODO: Set memory invalid which is in mem_tracker currently
8136                } else if (node.layout != mem_barrier->oldLayout) {
8137                    skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
8138                                    __LINE__, DRAWSTATE_INVALID_IMAGE_LAYOUT, "DS", "You cannot transition the layout from %s "
8139                                                                                    "when current layout is %s.",
8140                                    string_VkImageLayout(mem_barrier->oldLayout), string_VkImageLayout(node.layout));
8141                }
8142                SetLayout(pCB, mem_barrier->image, sub, mem_barrier->newLayout);
8143            }
8144        }
8145    }
8146    return skip;
8147}
8148
8149// Print readable FlagBits in FlagMask
8150static std::string string_VkAccessFlags(VkAccessFlags accessMask) {
8151    std::string result;
8152    std::string separator;
8153
8154    if (accessMask == 0) {
8155        result = "[None]";
8156    } else {
8157        result = "[";
8158        for (auto i = 0; i < 32; i++) {
8159            if (accessMask & (1 << i)) {
8160                result = result + separator + string_VkAccessFlagBits((VkAccessFlagBits)(1 << i));
8161                separator = " | ";
8162            }
8163        }
8164        result = result + "]";
8165    }
8166    return result;
8167}
8168
8169// AccessFlags MUST have 'required_bit' set, and may have one or more of 'optional_bits' set.
8170// If required_bit is zero, accessMask must have at least one of 'optional_bits' set
8171// TODO: Add tracking to ensure that at least one barrier has been set for these layout transitions
8172static bool ValidateMaskBits(const layer_data *my_data, VkCommandBuffer cmdBuffer, const VkAccessFlags &accessMask,
8173                             const VkImageLayout &layout, VkAccessFlags required_bit, VkAccessFlags optional_bits,
8174                             const char *type) {
8175    bool skip_call = false;
8176
8177    if ((accessMask & required_bit) || (!required_bit && (accessMask & optional_bits))) {
8178        if (accessMask & !(required_bit | optional_bits)) {
8179            // TODO: Verify against Valid Use
8180            skip_call |=
8181                log_msg(my_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8182                        DRAWSTATE_INVALID_BARRIER, "DS", "Additional bits in %s accessMask %d %s are specified when layout is %s.",
8183                        type, accessMask, string_VkAccessFlags(accessMask).c_str(), string_VkImageLayout(layout));
8184        }
8185    } else {
8186        if (!required_bit) {
8187            skip_call |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8188                                 DRAWSTATE_INVALID_BARRIER, "DS", "%s AccessMask %d %s must contain at least one of access bits %d "
8189                                                                  "%s when layout is %s, unless the app has previously added a "
8190                                                                  "barrier for this transition.",
8191                                 type, accessMask, string_VkAccessFlags(accessMask).c_str(), optional_bits,
8192                                 string_VkAccessFlags(optional_bits).c_str(), string_VkImageLayout(layout));
8193        } else {
8194            std::string opt_bits;
8195            if (optional_bits != 0) {
8196                std::stringstream ss;
8197                ss << optional_bits;
8198                opt_bits = "and may have optional bits " + ss.str() + ' ' + string_VkAccessFlags(optional_bits);
8199            }
8200            skip_call |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8201                                 DRAWSTATE_INVALID_BARRIER, "DS", "%s AccessMask %d %s must have required access bit %d %s %s when "
8202                                                                  "layout is %s, unless the app has previously added a barrier for "
8203                                                                  "this transition.",
8204                                 type, accessMask, string_VkAccessFlags(accessMask).c_str(), required_bit,
8205                                 string_VkAccessFlags(required_bit).c_str(), opt_bits.c_str(), string_VkImageLayout(layout));
8206        }
8207    }
8208    return skip_call;
8209}
8210
8211static bool ValidateMaskBitsFromLayouts(const layer_data *my_data, VkCommandBuffer cmdBuffer, const VkAccessFlags &accessMask,
8212                                        const VkImageLayout &layout, const char *type) {
8213    bool skip_call = false;
8214    switch (layout) {
8215    case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: {
8216        skip_call |= ValidateMaskBits(my_data, cmdBuffer, accessMask, layout, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
8217                                      VK_ACCESS_COLOR_ATTACHMENT_READ_BIT, type);
8218        break;
8219    }
8220    case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: {
8221        skip_call |= ValidateMaskBits(my_data, cmdBuffer, accessMask, layout, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
8222                                      VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT, type);
8223        break;
8224    }
8225    case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: {
8226        skip_call |= ValidateMaskBits(my_data, cmdBuffer, accessMask, layout, VK_ACCESS_TRANSFER_WRITE_BIT, 0, type);
8227        break;
8228    }
8229    case VK_IMAGE_LAYOUT_PREINITIALIZED: {
8230        skip_call |= ValidateMaskBits(my_data, cmdBuffer, accessMask, layout, VK_ACCESS_HOST_WRITE_BIT, 0, type);
8231        break;
8232    }
8233    case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL: {
8234        skip_call |= ValidateMaskBits(my_data, cmdBuffer, accessMask, layout, 0,
8235                                      VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_SHADER_READ_BIT, type);
8236        break;
8237    }
8238    case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: {
8239        skip_call |= ValidateMaskBits(my_data, cmdBuffer, accessMask, layout, 0,
8240                                      VK_ACCESS_INPUT_ATTACHMENT_READ_BIT | VK_ACCESS_SHADER_READ_BIT, type);
8241        break;
8242    }
8243    case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: {
8244        skip_call |= ValidateMaskBits(my_data, cmdBuffer, accessMask, layout, VK_ACCESS_TRANSFER_READ_BIT, 0, type);
8245        break;
8246    }
8247    case VK_IMAGE_LAYOUT_UNDEFINED: {
8248        if (accessMask != 0) {
8249            // TODO: Verify against Valid Use section spec
8250            skip_call |=
8251                log_msg(my_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8252                        DRAWSTATE_INVALID_BARRIER, "DS", "Additional bits in %s accessMask %d %s are specified when layout is %s.",
8253                        type, accessMask, string_VkAccessFlags(accessMask).c_str(), string_VkImageLayout(layout));
8254        }
8255        break;
8256    }
8257    case VK_IMAGE_LAYOUT_GENERAL:
8258    default: { break; }
8259    }
8260    return skip_call;
8261}
8262
8263static bool ValidateBarriers(const char *funcName, VkCommandBuffer cmdBuffer, uint32_t memBarrierCount,
8264                             const VkMemoryBarrier *pMemBarriers, uint32_t bufferBarrierCount,
8265                             const VkBufferMemoryBarrier *pBufferMemBarriers, uint32_t imageMemBarrierCount,
8266                             const VkImageMemoryBarrier *pImageMemBarriers) {
8267    bool skip_call = false;
8268    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(cmdBuffer), layer_data_map);
8269    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, cmdBuffer);
8270    if (pCB->activeRenderPass && memBarrierCount) {
8271        if (!dev_data->renderPassMap[pCB->activeRenderPass]->hasSelfDependency[pCB->activeSubpass]) {
8272            skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8273                                 DRAWSTATE_INVALID_BARRIER, "DS", "%s: Barriers cannot be set during subpass %d "
8274                                                                  "with no self dependency specified.",
8275                                 funcName, pCB->activeSubpass);
8276        }
8277    }
8278    for (uint32_t i = 0; i < imageMemBarrierCount; ++i) {
8279        auto mem_barrier = &pImageMemBarriers[i];
8280        auto image_data = dev_data->imageMap.find(mem_barrier->image);
8281        if (image_data != dev_data->imageMap.end()) {
8282            uint32_t src_q_f_index = mem_barrier->srcQueueFamilyIndex;
8283            uint32_t dst_q_f_index = mem_barrier->dstQueueFamilyIndex;
8284            if (image_data->second.createInfo.sharingMode == VK_SHARING_MODE_CONCURRENT) {
8285                // srcQueueFamilyIndex and dstQueueFamilyIndex must both
8286                // be VK_QUEUE_FAMILY_IGNORED
8287                if ((src_q_f_index != VK_QUEUE_FAMILY_IGNORED) || (dst_q_f_index != VK_QUEUE_FAMILY_IGNORED)) {
8288                    skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
8289                                         __LINE__, DRAWSTATE_INVALID_QUEUE_INDEX, "DS",
8290                                         "%s: Image Barrier for image 0x%" PRIx64 " was created with sharingMode of "
8291                                         "VK_SHARING_MODE_CONCURRENT.  Src and dst "
8292                                         " queueFamilyIndices must be VK_QUEUE_FAMILY_IGNORED.",
8293                                         funcName, reinterpret_cast<const uint64_t &>(mem_barrier->image));
8294                }
8295            } else {
8296                // Sharing mode is VK_SHARING_MODE_EXCLUSIVE. srcQueueFamilyIndex and
8297                // dstQueueFamilyIndex must either both be VK_QUEUE_FAMILY_IGNORED,
8298                // or both be a valid queue family
8299                if (((src_q_f_index == VK_QUEUE_FAMILY_IGNORED) || (dst_q_f_index == VK_QUEUE_FAMILY_IGNORED)) &&
8300                    (src_q_f_index != dst_q_f_index)) {
8301                    skip_call |=
8302                        log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8303                                DRAWSTATE_INVALID_QUEUE_INDEX, "DS", "%s: Image 0x%" PRIx64 " was created with sharingMode "
8304                                                                     "of VK_SHARING_MODE_EXCLUSIVE. If one of src- or "
8305                                                                     "dstQueueFamilyIndex is VK_QUEUE_FAMILY_IGNORED, both "
8306                                                                     "must be.",
8307                                funcName, reinterpret_cast<const uint64_t &>(mem_barrier->image));
8308                } else if (((src_q_f_index != VK_QUEUE_FAMILY_IGNORED) && (dst_q_f_index != VK_QUEUE_FAMILY_IGNORED)) &&
8309                           ((src_q_f_index >= dev_data->phys_dev_properties.queue_family_properties.size()) ||
8310                            (dst_q_f_index >= dev_data->phys_dev_properties.queue_family_properties.size()))) {
8311                    skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
8312                                         __LINE__, DRAWSTATE_INVALID_QUEUE_INDEX, "DS",
8313                                         "%s: Image 0x%" PRIx64 " was created with sharingMode "
8314                                         "of VK_SHARING_MODE_EXCLUSIVE, but srcQueueFamilyIndex %d"
8315                                         " or dstQueueFamilyIndex %d is greater than " PRINTF_SIZE_T_SPECIFIER
8316                                         "queueFamilies crated for this device.",
8317                                         funcName, reinterpret_cast<const uint64_t &>(mem_barrier->image), src_q_f_index,
8318                                         dst_q_f_index, dev_data->phys_dev_properties.queue_family_properties.size());
8319                }
8320            }
8321        }
8322
8323        if (mem_barrier) {
8324            skip_call |=
8325                ValidateMaskBitsFromLayouts(dev_data, cmdBuffer, mem_barrier->srcAccessMask, mem_barrier->oldLayout, "Source");
8326            skip_call |=
8327                ValidateMaskBitsFromLayouts(dev_data, cmdBuffer, mem_barrier->dstAccessMask, mem_barrier->newLayout, "Dest");
8328            if (mem_barrier->newLayout == VK_IMAGE_LAYOUT_UNDEFINED || mem_barrier->newLayout == VK_IMAGE_LAYOUT_PREINITIALIZED) {
8329                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8330                        DRAWSTATE_INVALID_BARRIER, "DS", "%s: Image Layout cannot be transitioned to UNDEFINED or "
8331                                                         "PREINITIALIZED.",
8332                        funcName);
8333            }
8334            auto image_data = dev_data->imageMap.find(mem_barrier->image);
8335            VkFormat format = VK_FORMAT_UNDEFINED;
8336            uint32_t arrayLayers = 0, mipLevels = 0;
8337            bool imageFound = false;
8338            if (image_data != dev_data->imageMap.end()) {
8339                format = image_data->second.createInfo.format;
8340                arrayLayers = image_data->second.createInfo.arrayLayers;
8341                mipLevels = image_data->second.createInfo.mipLevels;
8342                imageFound = true;
8343            } else if (dev_data->device_extensions.wsi_enabled) {
8344                auto imageswap_data = dev_data->device_extensions.imageToSwapchainMap.find(mem_barrier->image);
8345                if (imageswap_data != dev_data->device_extensions.imageToSwapchainMap.end()) {
8346                    auto swapchain_data = dev_data->device_extensions.swapchainMap.find(imageswap_data->second);
8347                    if (swapchain_data != dev_data->device_extensions.swapchainMap.end()) {
8348                        format = swapchain_data->second->createInfo.imageFormat;
8349                        arrayLayers = swapchain_data->second->createInfo.imageArrayLayers;
8350                        mipLevels = 1;
8351                        imageFound = true;
8352                    }
8353                }
8354            }
8355            if (imageFound) {
8356                if (vk_format_is_depth_and_stencil(format) &&
8357                    (!(mem_barrier->subresourceRange.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) ||
8358                     !(mem_barrier->subresourceRange.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT))) {
8359                    log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8360                            DRAWSTATE_INVALID_BARRIER, "DS", "%s: Image is a depth and stencil format and thus must "
8361                                                             "have both VK_IMAGE_ASPECT_DEPTH_BIT and "
8362                                                             "VK_IMAGE_ASPECT_STENCIL_BIT set.",
8363                            funcName);
8364                }
8365                int layerCount = (mem_barrier->subresourceRange.layerCount == VK_REMAINING_ARRAY_LAYERS)
8366                                     ? 1
8367                                     : mem_barrier->subresourceRange.layerCount;
8368                if ((mem_barrier->subresourceRange.baseArrayLayer + layerCount) > arrayLayers) {
8369                    log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8370                            DRAWSTATE_INVALID_BARRIER, "DS", "%s: Subresource must have the sum of the "
8371                                                             "baseArrayLayer (%d) and layerCount (%d) be less "
8372                                                             "than or equal to the total number of layers (%d).",
8373                            funcName, mem_barrier->subresourceRange.baseArrayLayer, mem_barrier->subresourceRange.layerCount,
8374                            arrayLayers);
8375                }
8376                int levelCount = (mem_barrier->subresourceRange.levelCount == VK_REMAINING_MIP_LEVELS)
8377                                     ? 1
8378                                     : mem_barrier->subresourceRange.levelCount;
8379                if ((mem_barrier->subresourceRange.baseMipLevel + levelCount) > mipLevels) {
8380                    log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8381                            DRAWSTATE_INVALID_BARRIER, "DS", "%s: Subresource must have the sum of the baseMipLevel "
8382                                                             "(%d) and levelCount (%d) be less than or equal to "
8383                                                             "the total number of levels (%d).",
8384                            funcName, mem_barrier->subresourceRange.baseMipLevel, mem_barrier->subresourceRange.levelCount,
8385                            mipLevels);
8386                }
8387            }
8388        }
8389    }
8390    for (uint32_t i = 0; i < bufferBarrierCount; ++i) {
8391        auto mem_barrier = &pBufferMemBarriers[i];
8392        if (pCB->activeRenderPass) {
8393            skip_call |=
8394                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8395                        DRAWSTATE_INVALID_BARRIER, "DS", "%s: Buffer Barriers cannot be used during a render pass.", funcName);
8396        }
8397        if (!mem_barrier)
8398            continue;
8399
8400        // Validate buffer barrier queue family indices
8401        if ((mem_barrier->srcQueueFamilyIndex != VK_QUEUE_FAMILY_IGNORED &&
8402             mem_barrier->srcQueueFamilyIndex >= dev_data->phys_dev_properties.queue_family_properties.size()) ||
8403            (mem_barrier->dstQueueFamilyIndex != VK_QUEUE_FAMILY_IGNORED &&
8404             mem_barrier->dstQueueFamilyIndex >= dev_data->phys_dev_properties.queue_family_properties.size())) {
8405            skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8406                                 DRAWSTATE_INVALID_QUEUE_INDEX, "DS",
8407                                 "%s: Buffer Barrier 0x%" PRIx64 " has QueueFamilyIndex greater "
8408                                 "than the number of QueueFamilies (" PRINTF_SIZE_T_SPECIFIER ") for this device.",
8409                                 funcName, reinterpret_cast<const uint64_t &>(mem_barrier->buffer),
8410                                 dev_data->phys_dev_properties.queue_family_properties.size());
8411        }
8412
8413        auto buffer_data = dev_data->bufferMap.find(mem_barrier->buffer);
8414        VkDeviceSize buffer_size = (buffer_data->second.createInfo.sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO)
8415                                       ? buffer_data->second.createInfo.size
8416                                       : 0;
8417        if (buffer_data != dev_data->bufferMap.end()) {
8418            if (mem_barrier->offset >= buffer_size) {
8419                skip_call |= log_msg(
8420                    dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8421                    DRAWSTATE_INVALID_BARRIER, "DS",
8422                    "%s: Buffer Barrier 0x%" PRIx64 " has offset %" PRIu64 " which is not less than total size %" PRIu64 ".",
8423                    funcName, reinterpret_cast<const uint64_t &>(mem_barrier->buffer),
8424                    reinterpret_cast<const uint64_t &>(mem_barrier->offset), reinterpret_cast<const uint64_t &>(buffer_size));
8425            } else if (mem_barrier->size != VK_WHOLE_SIZE && (mem_barrier->offset + mem_barrier->size > buffer_size)) {
8426                skip_call |= log_msg(
8427                    dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8428                    DRAWSTATE_INVALID_BARRIER, "DS", "%s: Buffer Barrier 0x%" PRIx64 " has offset %" PRIu64 " and size %" PRIu64
8429                                                     " whose sum is greater than total size %" PRIu64 ".",
8430                    funcName, reinterpret_cast<const uint64_t &>(mem_barrier->buffer),
8431                    reinterpret_cast<const uint64_t &>(mem_barrier->offset), reinterpret_cast<const uint64_t &>(mem_barrier->size),
8432                    reinterpret_cast<const uint64_t &>(buffer_size));
8433            }
8434        }
8435    }
8436    return skip_call;
8437}
8438
8439bool validateEventStageMask(VkQueue queue, GLOBAL_CB_NODE *pCB, uint32_t eventCount, size_t firstEventIndex, VkPipelineStageFlags sourceStageMask) {
8440    bool skip_call = false;
8441    VkPipelineStageFlags stageMask = 0;
8442    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(queue), layer_data_map);
8443    for (uint32_t i = 0; i < eventCount; ++i) {
8444        auto event = pCB->events[firstEventIndex + i];
8445        auto queue_data = dev_data->queueMap.find(queue);
8446        if (queue_data == dev_data->queueMap.end())
8447            return false;
8448        auto event_data = queue_data->second.eventToStageMap.find(event);
8449        if (event_data != queue_data->second.eventToStageMap.end()) {
8450            stageMask |= event_data->second;
8451        } else {
8452            auto global_event_data = dev_data->eventMap.find(event);
8453            if (global_event_data == dev_data->eventMap.end()) {
8454                skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT,
8455                                     reinterpret_cast<const uint64_t &>(event), __LINE__, DRAWSTATE_INVALID_EVENT, "DS",
8456                                     "Event 0x%" PRIx64 " cannot be waited on if it has never been set.",
8457                                     reinterpret_cast<const uint64_t &>(event));
8458            } else {
8459                stageMask |= global_event_data->second.stageMask;
8460            }
8461        }
8462    }
8463    if (sourceStageMask != stageMask) {
8464        skip_call |=
8465            log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8466                    DRAWSTATE_INVALID_EVENT, "DS",
8467                    "Submitting cmdbuffer with call to VkCmdWaitEvents using srcStageMask 0x%x which must be the bitwise OR of the "
8468                    "stageMask parameters used in calls to vkCmdSetEvent and VK_PIPELINE_STAGE_HOST_BIT if used with vkSetEvent.",
8469                    sourceStageMask);
8470    }
8471    return skip_call;
8472}
8473
8474VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
8475vkCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents, VkPipelineStageFlags sourceStageMask,
8476                VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
8477                uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers,
8478                uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers) {
8479    bool skipCall = false;
8480    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
8481    loader_platform_thread_lock_mutex(&globalLock);
8482    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
8483    if (pCB) {
8484        auto firstEventIndex = pCB->events.size();
8485        for (uint32_t i = 0; i < eventCount; ++i) {
8486            pCB->waitedEvents.push_back(pEvents[i]);
8487            pCB->events.push_back(pEvents[i]);
8488        }
8489        std::function<bool(VkQueue)> eventUpdate =
8490            std::bind(validateEventStageMask, std::placeholders::_1, pCB, eventCount, firstEventIndex, sourceStageMask);
8491        pCB->eventUpdates.push_back(eventUpdate);
8492        if (pCB->state == CB_RECORDING) {
8493            skipCall |= addCmd(dev_data, pCB, CMD_WAITEVENTS, "vkCmdWaitEvents()");
8494        } else {
8495            skipCall |= report_error_no_cb_begin(dev_data, commandBuffer, "vkCmdWaitEvents()");
8496        }
8497        skipCall |= TransitionImageLayouts(commandBuffer, imageMemoryBarrierCount, pImageMemoryBarriers);
8498        skipCall |=
8499            ValidateBarriers("vkCmdWaitEvents", commandBuffer, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
8500                             pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
8501    }
8502    loader_platform_thread_unlock_mutex(&globalLock);
8503    if (!skipCall)
8504        dev_data->device_dispatch_table->CmdWaitEvents(commandBuffer, eventCount, pEvents, sourceStageMask, dstStageMask,
8505                                                       memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
8506                                                       pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
8507}
8508
8509VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
8510vkCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
8511                     VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
8512                     uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers,
8513                     uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers) {
8514    bool skipCall = false;
8515    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
8516    loader_platform_thread_lock_mutex(&globalLock);
8517    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
8518    if (pCB) {
8519        skipCall |= addCmd(dev_data, pCB, CMD_PIPELINEBARRIER, "vkCmdPipelineBarrier()");
8520        skipCall |= TransitionImageLayouts(commandBuffer, imageMemoryBarrierCount, pImageMemoryBarriers);
8521        skipCall |=
8522            ValidateBarriers("vkCmdPipelineBarrier", commandBuffer, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
8523                             pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
8524    }
8525    loader_platform_thread_unlock_mutex(&globalLock);
8526    if (!skipCall)
8527        dev_data->device_dispatch_table->CmdPipelineBarrier(commandBuffer, srcStageMask, dstStageMask, dependencyFlags,
8528                                                            memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
8529                                                            pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
8530}
8531
8532VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
8533vkCmdBeginQuery(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t slot, VkFlags flags) {
8534    bool skipCall = false;
8535    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
8536    loader_platform_thread_lock_mutex(&globalLock);
8537    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
8538    if (pCB) {
8539        QueryObject query = {queryPool, slot};
8540        pCB->activeQueries.insert(query);
8541        if (!pCB->startedQueries.count(query)) {
8542            pCB->startedQueries.insert(query);
8543        }
8544        skipCall |= addCmd(dev_data, pCB, CMD_BEGINQUERY, "vkCmdBeginQuery()");
8545    }
8546    loader_platform_thread_unlock_mutex(&globalLock);
8547    if (!skipCall)
8548        dev_data->device_dispatch_table->CmdBeginQuery(commandBuffer, queryPool, slot, flags);
8549}
8550
8551VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkCmdEndQuery(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t slot) {
8552    bool skipCall = false;
8553    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
8554    loader_platform_thread_lock_mutex(&globalLock);
8555    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
8556    if (pCB) {
8557        QueryObject query = {queryPool, slot};
8558        if (!pCB->activeQueries.count(query)) {
8559            skipCall |=
8560                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8561                        DRAWSTATE_INVALID_QUERY, "DS", "Ending a query before it was started: queryPool %" PRIu64 ", index %d",
8562                        (uint64_t)(queryPool), slot);
8563        } else {
8564            pCB->activeQueries.erase(query);
8565        }
8566        pCB->queryToStateMap[query] = 1;
8567        if (pCB->state == CB_RECORDING) {
8568            skipCall |= addCmd(dev_data, pCB, CMD_ENDQUERY, "VkCmdEndQuery()");
8569        } else {
8570            skipCall |= report_error_no_cb_begin(dev_data, commandBuffer, "vkCmdEndQuery()");
8571        }
8572    }
8573    loader_platform_thread_unlock_mutex(&globalLock);
8574    if (!skipCall)
8575        dev_data->device_dispatch_table->CmdEndQuery(commandBuffer, queryPool, slot);
8576}
8577
8578VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
8579vkCmdResetQueryPool(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount) {
8580    bool skipCall = false;
8581    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
8582    loader_platform_thread_lock_mutex(&globalLock);
8583    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
8584    if (pCB) {
8585        for (uint32_t i = 0; i < queryCount; i++) {
8586            QueryObject query = {queryPool, firstQuery + i};
8587            pCB->waitedEventsBeforeQueryReset[query] = pCB->waitedEvents;
8588            pCB->queryToStateMap[query] = 0;
8589        }
8590        if (pCB->state == CB_RECORDING) {
8591            skipCall |= addCmd(dev_data, pCB, CMD_RESETQUERYPOOL, "VkCmdResetQueryPool()");
8592        } else {
8593            skipCall |= report_error_no_cb_begin(dev_data, commandBuffer, "vkCmdResetQueryPool()");
8594        }
8595        skipCall |= insideRenderPass(dev_data, pCB, "vkCmdQueryPool");
8596    }
8597    loader_platform_thread_unlock_mutex(&globalLock);
8598    if (!skipCall)
8599        dev_data->device_dispatch_table->CmdResetQueryPool(commandBuffer, queryPool, firstQuery, queryCount);
8600}
8601
8602VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
8603vkCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount,
8604                          VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize stride, VkQueryResultFlags flags) {
8605    bool skipCall = false;
8606    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
8607    loader_platform_thread_lock_mutex(&globalLock);
8608    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
8609#if MTMERGESOURCE
8610    VkDeviceMemory mem;
8611    auto cb_data = dev_data->commandBufferMap.find(commandBuffer);
8612    skipCall |=
8613        get_mem_binding_from_object(dev_data, (uint64_t)dstBuffer, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, &mem);
8614    if (cb_data != dev_data->commandBufferMap.end()) {
8615        std::function<bool()> function = [=]() {
8616            set_memory_valid(dev_data, mem, true);
8617            return false;
8618        };
8619        cb_data->second->validate_functions.push_back(function);
8620    }
8621    skipCall |= update_cmd_buf_and_mem_references(dev_data, commandBuffer, mem, "vkCmdCopyQueryPoolResults");
8622    // Validate that DST buffer has correct usage flags set
8623    skipCall |= validate_buffer_usage_flags(dev_data, dstBuffer, VK_BUFFER_USAGE_TRANSFER_DST_BIT, true,
8624                                            "vkCmdCopyQueryPoolResults()", "VK_BUFFER_USAGE_TRANSFER_DST_BIT");
8625#endif
8626    if (pCB) {
8627        for (uint32_t i = 0; i < queryCount; i++) {
8628            QueryObject query = {queryPool, firstQuery + i};
8629            if (!pCB->queryToStateMap[query]) {
8630                skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
8631                                    __LINE__, DRAWSTATE_INVALID_QUERY, "DS",
8632                                    "Requesting a copy from query to buffer with invalid query: queryPool %" PRIu64 ", index %d",
8633                                    (uint64_t)(queryPool), firstQuery + i);
8634            }
8635        }
8636        if (pCB->state == CB_RECORDING) {
8637            skipCall |= addCmd(dev_data, pCB, CMD_COPYQUERYPOOLRESULTS, "vkCmdCopyQueryPoolResults()");
8638        } else {
8639            skipCall |= report_error_no_cb_begin(dev_data, commandBuffer, "vkCmdCopyQueryPoolResults()");
8640        }
8641        skipCall |= insideRenderPass(dev_data, pCB, "vkCmdCopyQueryPoolResults");
8642    }
8643    loader_platform_thread_unlock_mutex(&globalLock);
8644    if (!skipCall)
8645        dev_data->device_dispatch_table->CmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer,
8646                                                                 dstOffset, stride, flags);
8647}
8648
8649VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkCmdPushConstants(VkCommandBuffer commandBuffer, VkPipelineLayout layout,
8650                                                              VkShaderStageFlags stageFlags, uint32_t offset, uint32_t size,
8651                                                              const void *pValues) {
8652    bool skipCall = false;
8653    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
8654    loader_platform_thread_lock_mutex(&globalLock);
8655    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
8656    if (pCB) {
8657        if (pCB->state == CB_RECORDING) {
8658            skipCall |= addCmd(dev_data, pCB, CMD_PUSHCONSTANTS, "vkCmdPushConstants()");
8659        } else {
8660            skipCall |= report_error_no_cb_begin(dev_data, commandBuffer, "vkCmdPushConstants()");
8661        }
8662    }
8663    if ((offset + size) > dev_data->phys_dev_properties.properties.limits.maxPushConstantsSize) {
8664        skipCall |= validatePushConstantSize(dev_data, offset, size, "vkCmdPushConstants()");
8665    }
8666    // TODO : Add warning if push constant update doesn't align with range
8667    loader_platform_thread_unlock_mutex(&globalLock);
8668    if (!skipCall)
8669        dev_data->device_dispatch_table->CmdPushConstants(commandBuffer, layout, stageFlags, offset, size, pValues);
8670}
8671
8672VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
8673vkCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage, VkQueryPool queryPool, uint32_t slot) {
8674    bool skipCall = false;
8675    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
8676    loader_platform_thread_lock_mutex(&globalLock);
8677    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
8678    if (pCB) {
8679        QueryObject query = {queryPool, slot};
8680        pCB->queryToStateMap[query] = 1;
8681        if (pCB->state == CB_RECORDING) {
8682            skipCall |= addCmd(dev_data, pCB, CMD_WRITETIMESTAMP, "vkCmdWriteTimestamp()");
8683        } else {
8684            skipCall |= report_error_no_cb_begin(dev_data, commandBuffer, "vkCmdWriteTimestamp()");
8685        }
8686    }
8687    loader_platform_thread_unlock_mutex(&globalLock);
8688    if (!skipCall)
8689        dev_data->device_dispatch_table->CmdWriteTimestamp(commandBuffer, pipelineStage, queryPool, slot);
8690}
8691
8692VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo *pCreateInfo,
8693                                                                   const VkAllocationCallbacks *pAllocator,
8694                                                                   VkFramebuffer *pFramebuffer) {
8695    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
8696    VkResult result = dev_data->device_dispatch_table->CreateFramebuffer(device, pCreateInfo, pAllocator, pFramebuffer);
8697    if (VK_SUCCESS == result) {
8698        // Shadow create info and store in map
8699        loader_platform_thread_lock_mutex(&globalLock);
8700
8701        auto & fbNode = dev_data->frameBufferMap[*pFramebuffer];
8702        fbNode.createInfo = *pCreateInfo;
8703        if (pCreateInfo->pAttachments) {
8704            auto attachments = new VkImageView[pCreateInfo->attachmentCount];
8705            memcpy(attachments,
8706                   pCreateInfo->pAttachments,
8707                   pCreateInfo->attachmentCount * sizeof(VkImageView));
8708            fbNode.createInfo.pAttachments = attachments;
8709        }
8710        for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
8711            VkImageView view = pCreateInfo->pAttachments[i];
8712            auto view_data = dev_data->imageViewMap.find(view);
8713            if (view_data == dev_data->imageViewMap.end()) {
8714                continue;
8715            }
8716            MT_FB_ATTACHMENT_INFO fb_info;
8717            get_mem_binding_from_object(dev_data, (uint64_t)(view_data->second.image), VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
8718                                        &fb_info.mem);
8719            fb_info.image = view_data->second.image;
8720            fbNode.attachments.push_back(fb_info);
8721        }
8722
8723        loader_platform_thread_unlock_mutex(&globalLock);
8724    }
8725    return result;
8726}
8727
8728static bool FindDependency(const int index, const int dependent, const std::vector<DAGNode> &subpass_to_node,
8729                           std::unordered_set<uint32_t> &processed_nodes) {
8730    // If we have already checked this node we have not found a dependency path so return false.
8731    if (processed_nodes.count(index))
8732        return false;
8733    processed_nodes.insert(index);
8734    const DAGNode &node = subpass_to_node[index];
8735    // Look for a dependency path. If one exists return true else recurse on the previous nodes.
8736    if (std::find(node.prev.begin(), node.prev.end(), dependent) == node.prev.end()) {
8737        for (auto elem : node.prev) {
8738            if (FindDependency(elem, dependent, subpass_to_node, processed_nodes))
8739                return true;
8740        }
8741    } else {
8742        return true;
8743    }
8744    return false;
8745}
8746
8747static bool CheckDependencyExists(const layer_data *my_data, const int subpass, const std::vector<uint32_t> &dependent_subpasses,
8748                                  const std::vector<DAGNode> &subpass_to_node, bool &skip_call) {
8749    bool result = true;
8750    // Loop through all subpasses that share the same attachment and make sure a dependency exists
8751    for (uint32_t k = 0; k < dependent_subpasses.size(); ++k) {
8752        if (static_cast<uint32_t>(subpass) == dependent_subpasses[k])
8753            continue;
8754        const DAGNode &node = subpass_to_node[subpass];
8755        // Check for a specified dependency between the two nodes. If one exists we are done.
8756        auto prev_elem = std::find(node.prev.begin(), node.prev.end(), dependent_subpasses[k]);
8757        auto next_elem = std::find(node.next.begin(), node.next.end(), dependent_subpasses[k]);
8758        if (prev_elem == node.prev.end() && next_elem == node.next.end()) {
8759            // If no dependency exits an implicit dependency still might. If so, warn and if not throw an error.
8760            std::unordered_set<uint32_t> processed_nodes;
8761            if (FindDependency(subpass, dependent_subpasses[k], subpass_to_node, processed_nodes) ||
8762                FindDependency(dependent_subpasses[k], subpass, subpass_to_node, processed_nodes)) {
8763                // TODO: Verify against Valid Use section of spec
8764                skip_call |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
8765                                     __LINE__, DRAWSTATE_INVALID_RENDERPASS, "DS",
8766                                     "A dependency between subpasses %d and %d must exist but only an implicit one is specified.",
8767                                     subpass, dependent_subpasses[k]);
8768            } else {
8769                skip_call |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
8770                                     __LINE__, DRAWSTATE_INVALID_RENDERPASS, "DS",
8771                                     "A dependency between subpasses %d and %d must exist but one is not specified.", subpass,
8772                                     dependent_subpasses[k]);
8773                result = false;
8774            }
8775        }
8776    }
8777    return result;
8778}
8779
8780static bool CheckPreserved(const layer_data *my_data, const VkRenderPassCreateInfo *pCreateInfo, const int index,
8781                           const uint32_t attachment, const std::vector<DAGNode> &subpass_to_node, int depth, bool &skip_call) {
8782    const DAGNode &node = subpass_to_node[index];
8783    // If this node writes to the attachment return true as next nodes need to preserve the attachment.
8784    const VkSubpassDescription &subpass = pCreateInfo->pSubpasses[index];
8785    for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) {
8786        if (attachment == subpass.pColorAttachments[j].attachment)
8787            return true;
8788    }
8789    if (subpass.pDepthStencilAttachment && subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
8790        if (attachment == subpass.pDepthStencilAttachment->attachment)
8791            return true;
8792    }
8793    bool result = false;
8794    // Loop through previous nodes and see if any of them write to the attachment.
8795    for (auto elem : node.prev) {
8796        result |= CheckPreserved(my_data, pCreateInfo, elem, attachment, subpass_to_node, depth + 1, skip_call);
8797    }
8798    // If the attachment was written to by a previous node than this node needs to preserve it.
8799    if (result && depth > 0) {
8800        const VkSubpassDescription &subpass = pCreateInfo->pSubpasses[index];
8801        bool has_preserved = false;
8802        for (uint32_t j = 0; j < subpass.preserveAttachmentCount; ++j) {
8803            if (subpass.pPreserveAttachments[j] == attachment) {
8804                has_preserved = true;
8805                break;
8806            }
8807        }
8808        if (!has_preserved) {
8809            skip_call |=
8810                log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8811                        DRAWSTATE_INVALID_RENDERPASS, "DS",
8812                        "Attachment %d is used by a later subpass and must be preserved in subpass %d.", attachment, index);
8813        }
8814    }
8815    return result;
8816}
8817
8818template <class T> bool isRangeOverlapping(T offset1, T size1, T offset2, T size2) {
8819    return (((offset1 + size1) > offset2) && ((offset1 + size1) < (offset2 + size2))) ||
8820           ((offset1 > offset2) && (offset1 < (offset2 + size2)));
8821}
8822
8823bool isRegionOverlapping(VkImageSubresourceRange range1, VkImageSubresourceRange range2) {
8824    return (isRangeOverlapping(range1.baseMipLevel, range1.levelCount, range2.baseMipLevel, range2.levelCount) &&
8825            isRangeOverlapping(range1.baseArrayLayer, range1.layerCount, range2.baseArrayLayer, range2.layerCount));
8826}
8827
8828static bool ValidateDependencies(const layer_data *my_data, const VkRenderPassBeginInfo *pRenderPassBegin,
8829                                 const std::vector<DAGNode> &subpass_to_node) {
8830    bool skip_call = false;
8831    const VkFramebufferCreateInfo *pFramebufferInfo = &my_data->frameBufferMap.at(pRenderPassBegin->framebuffer).createInfo;
8832    const VkRenderPassCreateInfo *pCreateInfo = my_data->renderPassMap.at(pRenderPassBegin->renderPass)->pCreateInfo;
8833    std::vector<std::vector<uint32_t>> output_attachment_to_subpass(pCreateInfo->attachmentCount);
8834    std::vector<std::vector<uint32_t>> input_attachment_to_subpass(pCreateInfo->attachmentCount);
8835    std::vector<std::vector<uint32_t>> overlapping_attachments(pCreateInfo->attachmentCount);
8836    // Find overlapping attachments
8837    for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
8838        for (uint32_t j = i + 1; j < pCreateInfo->attachmentCount; ++j) {
8839            VkImageView viewi = pFramebufferInfo->pAttachments[i];
8840            VkImageView viewj = pFramebufferInfo->pAttachments[j];
8841            if (viewi == viewj) {
8842                overlapping_attachments[i].push_back(j);
8843                overlapping_attachments[j].push_back(i);
8844                continue;
8845            }
8846            auto view_data_i = my_data->imageViewMap.find(viewi);
8847            auto view_data_j = my_data->imageViewMap.find(viewj);
8848            if (view_data_i == my_data->imageViewMap.end() || view_data_j == my_data->imageViewMap.end()) {
8849                continue;
8850            }
8851            if (view_data_i->second.image == view_data_j->second.image &&
8852                isRegionOverlapping(view_data_i->second.subresourceRange, view_data_j->second.subresourceRange)) {
8853                overlapping_attachments[i].push_back(j);
8854                overlapping_attachments[j].push_back(i);
8855                continue;
8856            }
8857            auto image_data_i = my_data->imageMap.find(view_data_i->second.image);
8858            auto image_data_j = my_data->imageMap.find(view_data_j->second.image);
8859            if (image_data_i == my_data->imageMap.end() || image_data_j == my_data->imageMap.end()) {
8860                continue;
8861            }
8862            if (image_data_i->second.mem == image_data_j->second.mem &&
8863                isRangeOverlapping(image_data_i->second.memOffset, image_data_i->second.memSize, image_data_j->second.memOffset,
8864                                   image_data_j->second.memSize)) {
8865                overlapping_attachments[i].push_back(j);
8866                overlapping_attachments[j].push_back(i);
8867            }
8868        }
8869    }
8870    for (uint32_t i = 0; i < overlapping_attachments.size(); ++i) {
8871        uint32_t attachment = i;
8872        for (auto other_attachment : overlapping_attachments[i]) {
8873            if (!(pCreateInfo->pAttachments[attachment].flags & VK_ATTACHMENT_DESCRIPTION_MAY_ALIAS_BIT)) {
8874                skip_call |=
8875                    log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8876                            DRAWSTATE_INVALID_RENDERPASS, "DS", "Attachment %d aliases attachment %d but doesn't "
8877                                                                "set VK_ATTACHMENT_DESCRIPTION_MAY_ALIAS_BIT.",
8878                            attachment, other_attachment);
8879            }
8880            if (!(pCreateInfo->pAttachments[other_attachment].flags & VK_ATTACHMENT_DESCRIPTION_MAY_ALIAS_BIT)) {
8881                skip_call |=
8882                    log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8883                            DRAWSTATE_INVALID_RENDERPASS, "DS", "Attachment %d aliases attachment %d but doesn't "
8884                                                                "set VK_ATTACHMENT_DESCRIPTION_MAY_ALIAS_BIT.",
8885                            other_attachment, attachment);
8886            }
8887        }
8888    }
8889    // Find for each attachment the subpasses that use them.
8890    unordered_set<uint32_t> attachmentIndices;
8891    for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) {
8892        const VkSubpassDescription &subpass = pCreateInfo->pSubpasses[i];
8893        attachmentIndices.clear();
8894        for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) {
8895            uint32_t attachment = subpass.pInputAttachments[j].attachment;
8896            input_attachment_to_subpass[attachment].push_back(i);
8897            for (auto overlapping_attachment : overlapping_attachments[attachment]) {
8898                input_attachment_to_subpass[overlapping_attachment].push_back(i);
8899            }
8900        }
8901        for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) {
8902            uint32_t attachment = subpass.pColorAttachments[j].attachment;
8903            output_attachment_to_subpass[attachment].push_back(i);
8904            for (auto overlapping_attachment : overlapping_attachments[attachment]) {
8905                output_attachment_to_subpass[overlapping_attachment].push_back(i);
8906            }
8907            attachmentIndices.insert(attachment);
8908        }
8909        if (subpass.pDepthStencilAttachment && subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
8910            uint32_t attachment = subpass.pDepthStencilAttachment->attachment;
8911            output_attachment_to_subpass[attachment].push_back(i);
8912            for (auto overlapping_attachment : overlapping_attachments[attachment]) {
8913                output_attachment_to_subpass[overlapping_attachment].push_back(i);
8914            }
8915
8916            if (attachmentIndices.count(attachment)) {
8917                skip_call |=
8918                    log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0,
8919                            0, __LINE__, DRAWSTATE_INVALID_RENDERPASS, "DS",
8920                            "Cannot use same attachment (%u) as both color and depth output in same subpass (%u).",
8921                            attachment, i);
8922            }
8923        }
8924    }
8925    // If there is a dependency needed make sure one exists
8926    for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) {
8927        const VkSubpassDescription &subpass = pCreateInfo->pSubpasses[i];
8928        // If the attachment is an input then all subpasses that output must have a dependency relationship
8929        for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) {
8930            const uint32_t &attachment = subpass.pInputAttachments[j].attachment;
8931            CheckDependencyExists(my_data, i, output_attachment_to_subpass[attachment], subpass_to_node, skip_call);
8932        }
8933        // If the attachment is an output then all subpasses that use the attachment must have a dependency relationship
8934        for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) {
8935            const uint32_t &attachment = subpass.pColorAttachments[j].attachment;
8936            CheckDependencyExists(my_data, i, output_attachment_to_subpass[attachment], subpass_to_node, skip_call);
8937            CheckDependencyExists(my_data, i, input_attachment_to_subpass[attachment], subpass_to_node, skip_call);
8938        }
8939        if (subpass.pDepthStencilAttachment && subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
8940            const uint32_t &attachment = subpass.pDepthStencilAttachment->attachment;
8941            CheckDependencyExists(my_data, i, output_attachment_to_subpass[attachment], subpass_to_node, skip_call);
8942            CheckDependencyExists(my_data, i, input_attachment_to_subpass[attachment], subpass_to_node, skip_call);
8943        }
8944    }
8945    // Loop through implicit dependencies, if this pass reads make sure the attachment is preserved for all passes after it was
8946    // written.
8947    for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) {
8948        const VkSubpassDescription &subpass = pCreateInfo->pSubpasses[i];
8949        for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) {
8950            CheckPreserved(my_data, pCreateInfo, i, subpass.pInputAttachments[j].attachment, subpass_to_node, 0, skip_call);
8951        }
8952    }
8953    return skip_call;
8954}
8955
8956static bool ValidateLayouts(const layer_data *my_data, VkDevice device, const VkRenderPassCreateInfo *pCreateInfo) {
8957    bool skip = false;
8958
8959    for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) {
8960        const VkSubpassDescription &subpass = pCreateInfo->pSubpasses[i];
8961        for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) {
8962            if (subpass.pInputAttachments[j].layout != VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL &&
8963                subpass.pInputAttachments[j].layout != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
8964                if (subpass.pInputAttachments[j].layout == VK_IMAGE_LAYOUT_GENERAL) {
8965                    // TODO: Verify Valid Use in spec. I believe this is allowed (valid) but may not be optimal performance
8966                    skip |= log_msg(my_data->report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
8967                                    (VkDebugReportObjectTypeEXT)0, 0, __LINE__, DRAWSTATE_INVALID_IMAGE_LAYOUT, "DS",
8968                                    "Layout for input attachment is GENERAL but should be READ_ONLY_OPTIMAL.");
8969                } else {
8970                    skip |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8971                                    DRAWSTATE_INVALID_IMAGE_LAYOUT, "DS",
8972                                    "Layout for input attachment is %s but can only be READ_ONLY_OPTIMAL or GENERAL.",
8973                                    string_VkImageLayout(subpass.pInputAttachments[j].layout));
8974                }
8975            }
8976        }
8977        for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) {
8978            if (subpass.pColorAttachments[j].layout != VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) {
8979                if (subpass.pColorAttachments[j].layout == VK_IMAGE_LAYOUT_GENERAL) {
8980                    // TODO: Verify Valid Use in spec. I believe this is allowed (valid) but may not be optimal performance
8981                    skip |= log_msg(my_data->report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
8982                                    (VkDebugReportObjectTypeEXT)0, 0, __LINE__, DRAWSTATE_INVALID_IMAGE_LAYOUT, "DS",
8983                                    "Layout for color attachment is GENERAL but should be COLOR_ATTACHMENT_OPTIMAL.");
8984                } else {
8985                    skip |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
8986                                    DRAWSTATE_INVALID_IMAGE_LAYOUT, "DS",
8987                                    "Layout for color attachment is %s but can only be COLOR_ATTACHMENT_OPTIMAL or GENERAL.",
8988                                    string_VkImageLayout(subpass.pColorAttachments[j].layout));
8989                }
8990            }
8991        }
8992        if ((subpass.pDepthStencilAttachment != NULL) && (subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED)) {
8993            if (subpass.pDepthStencilAttachment->layout != VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
8994                if (subpass.pDepthStencilAttachment->layout == VK_IMAGE_LAYOUT_GENERAL) {
8995                    // TODO: Verify Valid Use in spec. I believe this is allowed (valid) but may not be optimal performance
8996                    skip |= log_msg(my_data->report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
8997                                    (VkDebugReportObjectTypeEXT)0, 0, __LINE__, DRAWSTATE_INVALID_IMAGE_LAYOUT, "DS",
8998                                    "Layout for depth attachment is GENERAL but should be DEPTH_STENCIL_ATTACHMENT_OPTIMAL.");
8999                } else {
9000                    skip |=
9001                        log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
9002                                DRAWSTATE_INVALID_IMAGE_LAYOUT, "DS",
9003                                "Layout for depth attachment is %s but can only be DEPTH_STENCIL_ATTACHMENT_OPTIMAL or GENERAL.",
9004                                string_VkImageLayout(subpass.pDepthStencilAttachment->layout));
9005                }
9006            }
9007        }
9008    }
9009    return skip;
9010}
9011
9012static bool CreatePassDAG(const layer_data *my_data, VkDevice device, const VkRenderPassCreateInfo *pCreateInfo,
9013                          std::vector<DAGNode> &subpass_to_node, std::vector<bool> &has_self_dependency) {
9014    bool skip_call = false;
9015    for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) {
9016        DAGNode &subpass_node = subpass_to_node[i];
9017        subpass_node.pass = i;
9018    }
9019    for (uint32_t i = 0; i < pCreateInfo->dependencyCount; ++i) {
9020        const VkSubpassDependency &dependency = pCreateInfo->pDependencies[i];
9021        if (dependency.srcSubpass > dependency.dstSubpass && dependency.srcSubpass != VK_SUBPASS_EXTERNAL &&
9022            dependency.dstSubpass != VK_SUBPASS_EXTERNAL) {
9023            skip_call |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
9024                                 DRAWSTATE_INVALID_RENDERPASS, "DS",
9025                                 "Depedency graph must be specified such that an earlier pass cannot depend on a later pass.");
9026        } else if (dependency.srcSubpass == VK_SUBPASS_EXTERNAL && dependency.dstSubpass == VK_SUBPASS_EXTERNAL) {
9027            skip_call |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
9028                                 DRAWSTATE_INVALID_RENDERPASS, "DS", "The src and dest subpasses cannot both be external.");
9029        } else if (dependency.srcSubpass == dependency.dstSubpass) {
9030            has_self_dependency[dependency.srcSubpass] = true;
9031        }
9032        if (dependency.dstSubpass != VK_SUBPASS_EXTERNAL) {
9033            subpass_to_node[dependency.dstSubpass].prev.push_back(dependency.srcSubpass);
9034        }
9035        if (dependency.srcSubpass != VK_SUBPASS_EXTERNAL) {
9036            subpass_to_node[dependency.srcSubpass].next.push_back(dependency.dstSubpass);
9037        }
9038    }
9039    return skip_call;
9040}
9041
9042
9043VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
9044                                                                    const VkAllocationCallbacks *pAllocator,
9045                                                                    VkShaderModule *pShaderModule) {
9046    layer_data *my_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
9047    bool skip_call = false;
9048    if (!shader_is_spirv(pCreateInfo)) {
9049        skip_call |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
9050                             /* dev */ 0, __LINE__, SHADER_CHECKER_NON_SPIRV_SHADER, "SC", "Shader is not SPIR-V");
9051    }
9052
9053    if (skip_call)
9054        return VK_ERROR_VALIDATION_FAILED_EXT;
9055
9056    VkResult res = my_data->device_dispatch_table->CreateShaderModule(device, pCreateInfo, pAllocator, pShaderModule);
9057
9058    if (res == VK_SUCCESS) {
9059        loader_platform_thread_lock_mutex(&globalLock);
9060        my_data->shaderModuleMap[*pShaderModule] = unique_ptr<shader_module>(new shader_module(pCreateInfo));
9061        loader_platform_thread_unlock_mutex(&globalLock);
9062    }
9063    return res;
9064}
9065
9066VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo *pCreateInfo,
9067                                                                  const VkAllocationCallbacks *pAllocator,
9068                                                                  VkRenderPass *pRenderPass) {
9069    bool skip_call = false;
9070    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
9071    loader_platform_thread_lock_mutex(&globalLock);
9072    // Create DAG
9073    std::vector<bool> has_self_dependency(pCreateInfo->subpassCount);
9074    std::vector<DAGNode> subpass_to_node(pCreateInfo->subpassCount);
9075    skip_call |= CreatePassDAG(dev_data, device, pCreateInfo, subpass_to_node, has_self_dependency);
9076    // Validate
9077    skip_call |= ValidateLayouts(dev_data, device, pCreateInfo);
9078    if (skip_call) {
9079        loader_platform_thread_unlock_mutex(&globalLock);
9080        return VK_ERROR_VALIDATION_FAILED_EXT;
9081    }
9082    loader_platform_thread_unlock_mutex(&globalLock);
9083    VkResult result = dev_data->device_dispatch_table->CreateRenderPass(device, pCreateInfo, pAllocator, pRenderPass);
9084    if (VK_SUCCESS == result) {
9085        loader_platform_thread_lock_mutex(&globalLock);
9086        // TODOSC : Merge in tracking of renderpass from shader_checker
9087        // Shadow create info and store in map
9088        VkRenderPassCreateInfo *localRPCI = new VkRenderPassCreateInfo(*pCreateInfo);
9089        if (pCreateInfo->pAttachments) {
9090            localRPCI->pAttachments = new VkAttachmentDescription[localRPCI->attachmentCount];
9091            memcpy((void *)localRPCI->pAttachments, pCreateInfo->pAttachments,
9092                   localRPCI->attachmentCount * sizeof(VkAttachmentDescription));
9093        }
9094        if (pCreateInfo->pSubpasses) {
9095            localRPCI->pSubpasses = new VkSubpassDescription[localRPCI->subpassCount];
9096            memcpy((void *)localRPCI->pSubpasses, pCreateInfo->pSubpasses, localRPCI->subpassCount * sizeof(VkSubpassDescription));
9097
9098            for (uint32_t i = 0; i < localRPCI->subpassCount; i++) {
9099                VkSubpassDescription *subpass = (VkSubpassDescription *)&localRPCI->pSubpasses[i];
9100                const uint32_t attachmentCount = subpass->inputAttachmentCount +
9101                                                 subpass->colorAttachmentCount * (1 + (subpass->pResolveAttachments ? 1 : 0)) +
9102                                                 ((subpass->pDepthStencilAttachment) ? 1 : 0) + subpass->preserveAttachmentCount;
9103                VkAttachmentReference *attachments = new VkAttachmentReference[attachmentCount];
9104
9105                memcpy(attachments, subpass->pInputAttachments, sizeof(attachments[0]) * subpass->inputAttachmentCount);
9106                subpass->pInputAttachments = attachments;
9107                attachments += subpass->inputAttachmentCount;
9108
9109                memcpy(attachments, subpass->pColorAttachments, sizeof(attachments[0]) * subpass->colorAttachmentCount);
9110                subpass->pColorAttachments = attachments;
9111                attachments += subpass->colorAttachmentCount;
9112
9113                if (subpass->pResolveAttachments) {
9114                    memcpy(attachments, subpass->pResolveAttachments, sizeof(attachments[0]) * subpass->colorAttachmentCount);
9115                    subpass->pResolveAttachments = attachments;
9116                    attachments += subpass->colorAttachmentCount;
9117                }
9118
9119                if (subpass->pDepthStencilAttachment) {
9120                    memcpy(attachments, subpass->pDepthStencilAttachment, sizeof(attachments[0]) * 1);
9121                    subpass->pDepthStencilAttachment = attachments;
9122                    attachments += 1;
9123                }
9124
9125                memcpy(attachments, subpass->pPreserveAttachments, sizeof(attachments[0]) * subpass->preserveAttachmentCount);
9126                subpass->pPreserveAttachments = &attachments->attachment;
9127            }
9128        }
9129        if (pCreateInfo->pDependencies) {
9130            localRPCI->pDependencies = new VkSubpassDependency[localRPCI->dependencyCount];
9131            memcpy((void *)localRPCI->pDependencies, pCreateInfo->pDependencies,
9132                   localRPCI->dependencyCount * sizeof(VkSubpassDependency));
9133        }
9134        dev_data->renderPassMap[*pRenderPass] = new RENDER_PASS_NODE(localRPCI);
9135        dev_data->renderPassMap[*pRenderPass]->hasSelfDependency = has_self_dependency;
9136        dev_data->renderPassMap[*pRenderPass]->subpassToNode = subpass_to_node;
9137#if MTMERGESOURCE
9138        // MTMTODO : Merge with code from above to eliminate duplication
9139        for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
9140            VkAttachmentDescription desc = pCreateInfo->pAttachments[i];
9141            MT_PASS_ATTACHMENT_INFO pass_info;
9142            pass_info.load_op = desc.loadOp;
9143            pass_info.store_op = desc.storeOp;
9144            pass_info.attachment = i;
9145            dev_data->renderPassMap[*pRenderPass]->attachments.push_back(pass_info);
9146        }
9147        // TODO: Maybe fill list and then copy instead of locking
9148        std::unordered_map<uint32_t, bool> &attachment_first_read = dev_data->renderPassMap[*pRenderPass]->attachment_first_read;
9149        std::unordered_map<uint32_t, VkImageLayout> &attachment_first_layout =
9150            dev_data->renderPassMap[*pRenderPass]->attachment_first_layout;
9151        for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) {
9152            const VkSubpassDescription &subpass = pCreateInfo->pSubpasses[i];
9153            if (subpass.pipelineBindPoint != VK_PIPELINE_BIND_POINT_GRAPHICS) {
9154                skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
9155                                     __LINE__, DRAWSTATE_INVALID_RENDERPASS, "DS",
9156                                     "Pipeline bind point for subpass %d must be VK_PIPELINE_BIND_POINT_GRAPHICS.", i);
9157            }
9158            for (uint32_t j = 0; j < subpass.preserveAttachmentCount; ++j) {
9159                uint32_t attachment = subpass.pPreserveAttachments[j];
9160                if (attachment >= pCreateInfo->attachmentCount) {
9161                    skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
9162                                         __LINE__, DRAWSTATE_INVALID_RENDERPASS, "DS",
9163                                         "Preserve attachment %d cannot be greater than the total number of attachments %d.",
9164                                         attachment, pCreateInfo->attachmentCount);
9165                }
9166            }
9167            for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) {
9168                uint32_t attachment;
9169                if (subpass.pResolveAttachments) {
9170                    attachment = subpass.pResolveAttachments[j].attachment;
9171                    if (attachment >= pCreateInfo->attachmentCount && attachment != VK_ATTACHMENT_UNUSED) {
9172                        skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
9173                                             __LINE__, DRAWSTATE_INVALID_RENDERPASS, "DS",
9174                                             "Color attachment %d cannot be greater than the total number of attachments %d.",
9175                                             attachment, pCreateInfo->attachmentCount);
9176                        continue;
9177                    }
9178                }
9179                attachment = subpass.pColorAttachments[j].attachment;
9180                if (attachment >= pCreateInfo->attachmentCount) {
9181                    skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
9182                                         __LINE__, DRAWSTATE_INVALID_RENDERPASS, "DS",
9183                                         "Color attachment %d cannot be greater than the total number of attachments %d.",
9184                                         attachment, pCreateInfo->attachmentCount);
9185                    continue;
9186                }
9187                if (attachment_first_read.count(attachment))
9188                    continue;
9189                attachment_first_read.insert(std::make_pair(attachment, false));
9190                attachment_first_layout.insert(std::make_pair(attachment, subpass.pColorAttachments[j].layout));
9191            }
9192            if (subpass.pDepthStencilAttachment && subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
9193                uint32_t attachment = subpass.pDepthStencilAttachment->attachment;
9194                if (attachment >= pCreateInfo->attachmentCount) {
9195                    skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
9196                                         __LINE__, DRAWSTATE_INVALID_RENDERPASS, "DS",
9197                                         "Depth stencil attachment %d cannot be greater than the total number of attachments %d.",
9198                                         attachment, pCreateInfo->attachmentCount);
9199                    continue;
9200                }
9201                if (attachment_first_read.count(attachment))
9202                    continue;
9203                attachment_first_read.insert(std::make_pair(attachment, false));
9204                attachment_first_layout.insert(std::make_pair(attachment, subpass.pDepthStencilAttachment->layout));
9205            }
9206            for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) {
9207                uint32_t attachment = subpass.pInputAttachments[j].attachment;
9208                if (attachment >= pCreateInfo->attachmentCount) {
9209                    skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
9210                                         __LINE__, DRAWSTATE_INVALID_RENDERPASS, "DS",
9211                                         "Input attachment %d cannot be greater than the total number of attachments %d.",
9212                                         attachment, pCreateInfo->attachmentCount);
9213                    continue;
9214                }
9215                if (attachment_first_read.count(attachment))
9216                    continue;
9217                attachment_first_read.insert(std::make_pair(attachment, true));
9218                attachment_first_layout.insert(std::make_pair(attachment, subpass.pInputAttachments[j].layout));
9219            }
9220        }
9221#endif
9222        loader_platform_thread_unlock_mutex(&globalLock);
9223    }
9224    return result;
9225}
9226// Free the renderpass shadow
9227static void deleteRenderPasses(layer_data *my_data) {
9228    if (my_data->renderPassMap.size() <= 0)
9229        return;
9230    for (auto ii = my_data->renderPassMap.begin(); ii != my_data->renderPassMap.end(); ++ii) {
9231        const VkRenderPassCreateInfo *pRenderPassInfo = (*ii).second->pCreateInfo;
9232        delete[] pRenderPassInfo->pAttachments;
9233        if (pRenderPassInfo->pSubpasses) {
9234            for (uint32_t i = 0; i < pRenderPassInfo->subpassCount; ++i) {
9235                // Attachements are all allocated in a block, so just need to
9236                //  find the first non-null one to delete
9237                if (pRenderPassInfo->pSubpasses[i].pInputAttachments) {
9238                    delete[] pRenderPassInfo->pSubpasses[i].pInputAttachments;
9239                } else if (pRenderPassInfo->pSubpasses[i].pColorAttachments) {
9240                    delete[] pRenderPassInfo->pSubpasses[i].pColorAttachments;
9241                } else if (pRenderPassInfo->pSubpasses[i].pResolveAttachments) {
9242                    delete[] pRenderPassInfo->pSubpasses[i].pResolveAttachments;
9243                } else if (pRenderPassInfo->pSubpasses[i].pPreserveAttachments) {
9244                    delete[] pRenderPassInfo->pSubpasses[i].pPreserveAttachments;
9245                }
9246            }
9247            delete[] pRenderPassInfo->pSubpasses;
9248        }
9249        delete[] pRenderPassInfo->pDependencies;
9250        delete pRenderPassInfo;
9251        delete (*ii).second;
9252    }
9253    my_data->renderPassMap.clear();
9254}
9255
9256static bool VerifyFramebufferAndRenderPassLayouts(VkCommandBuffer cmdBuffer, const VkRenderPassBeginInfo *pRenderPassBegin) {
9257    bool skip_call = false;
9258    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(cmdBuffer), layer_data_map);
9259    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, cmdBuffer);
9260    const VkRenderPassCreateInfo *pRenderPassInfo = dev_data->renderPassMap[pRenderPassBegin->renderPass]->pCreateInfo;
9261    const VkFramebufferCreateInfo framebufferInfo = dev_data->frameBufferMap[pRenderPassBegin->framebuffer].createInfo;
9262    if (pRenderPassInfo->attachmentCount != framebufferInfo.attachmentCount) {
9263        skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
9264                             DRAWSTATE_INVALID_RENDERPASS, "DS", "You cannot start a render pass using a framebuffer "
9265                                                                 "with a different number of attachments.");
9266    }
9267    for (uint32_t i = 0; i < pRenderPassInfo->attachmentCount; ++i) {
9268        const VkImageView &image_view = framebufferInfo.pAttachments[i];
9269        auto image_data = dev_data->imageViewMap.find(image_view);
9270        assert(image_data != dev_data->imageViewMap.end());
9271        const VkImage &image = image_data->second.image;
9272        const VkImageSubresourceRange &subRange = image_data->second.subresourceRange;
9273        IMAGE_CMD_BUF_LAYOUT_NODE newNode = {pRenderPassInfo->pAttachments[i].initialLayout,
9274                                             pRenderPassInfo->pAttachments[i].initialLayout};
9275        // TODO: Do not iterate over every possibility - consolidate where possible
9276        for (uint32_t j = 0; j < subRange.levelCount; j++) {
9277            uint32_t level = subRange.baseMipLevel + j;
9278            for (uint32_t k = 0; k < subRange.layerCount; k++) {
9279                uint32_t layer = subRange.baseArrayLayer + k;
9280                VkImageSubresource sub = {subRange.aspectMask, level, layer};
9281                IMAGE_CMD_BUF_LAYOUT_NODE node;
9282                if (!FindLayout(pCB, image, sub, node)) {
9283                    SetLayout(pCB, image, sub, newNode);
9284                    continue;
9285                }
9286                if (newNode.layout != node.layout) {
9287                    skip_call |=
9288                        log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
9289                                DRAWSTATE_INVALID_RENDERPASS, "DS", "You cannot start a render pass using attachment %i "
9290                                                                    "where the "
9291                                                                    "initial layout is %s and the layout of the attachment at the "
9292                                                                    "start of the render pass is %s. The layouts must match.",
9293                                i, string_VkImageLayout(newNode.layout), string_VkImageLayout(node.layout));
9294                }
9295            }
9296        }
9297    }
9298    return skip_call;
9299}
9300
9301static void TransitionSubpassLayouts(VkCommandBuffer cmdBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
9302                                     const int subpass_index) {
9303    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(cmdBuffer), layer_data_map);
9304    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, cmdBuffer);
9305    auto render_pass_data = dev_data->renderPassMap.find(pRenderPassBegin->renderPass);
9306    if (render_pass_data == dev_data->renderPassMap.end()) {
9307        return;
9308    }
9309    const VkRenderPassCreateInfo *pRenderPassInfo = render_pass_data->second->pCreateInfo;
9310    auto framebuffer_data = dev_data->frameBufferMap.find(pRenderPassBegin->framebuffer);
9311    if (framebuffer_data == dev_data->frameBufferMap.end()) {
9312        return;
9313    }
9314    const VkFramebufferCreateInfo framebufferInfo = framebuffer_data->second.createInfo;
9315    const VkSubpassDescription &subpass = pRenderPassInfo->pSubpasses[subpass_index];
9316    for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) {
9317        const VkImageView &image_view = framebufferInfo.pAttachments[subpass.pInputAttachments[j].attachment];
9318        SetLayout(dev_data, pCB, image_view, subpass.pInputAttachments[j].layout);
9319    }
9320    for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) {
9321        const VkImageView &image_view = framebufferInfo.pAttachments[subpass.pColorAttachments[j].attachment];
9322        SetLayout(dev_data, pCB, image_view, subpass.pColorAttachments[j].layout);
9323    }
9324    if ((subpass.pDepthStencilAttachment != NULL) && (subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED)) {
9325        const VkImageView &image_view = framebufferInfo.pAttachments[subpass.pDepthStencilAttachment->attachment];
9326        SetLayout(dev_data, pCB, image_view, subpass.pDepthStencilAttachment->layout);
9327    }
9328}
9329
9330static bool validatePrimaryCommandBuffer(const layer_data *my_data, const GLOBAL_CB_NODE *pCB, const std::string &cmd_name) {
9331    bool skip_call = false;
9332    if (pCB->createInfo.level != VK_COMMAND_BUFFER_LEVEL_PRIMARY) {
9333        skip_call |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
9334                             DRAWSTATE_INVALID_COMMAND_BUFFER, "DS", "Cannot execute command %s on a secondary command buffer.",
9335                             cmd_name.c_str());
9336    }
9337    return skip_call;
9338}
9339
9340static void TransitionFinalSubpassLayouts(VkCommandBuffer cmdBuffer, const VkRenderPassBeginInfo *pRenderPassBegin) {
9341    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(cmdBuffer), layer_data_map);
9342    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, cmdBuffer);
9343    auto render_pass_data = dev_data->renderPassMap.find(pRenderPassBegin->renderPass);
9344    if (render_pass_data == dev_data->renderPassMap.end()) {
9345        return;
9346    }
9347    const VkRenderPassCreateInfo *pRenderPassInfo = render_pass_data->second->pCreateInfo;
9348    auto framebuffer_data = dev_data->frameBufferMap.find(pRenderPassBegin->framebuffer);
9349    if (framebuffer_data == dev_data->frameBufferMap.end()) {
9350        return;
9351    }
9352    const VkFramebufferCreateInfo framebufferInfo = framebuffer_data->second.createInfo;
9353    for (uint32_t i = 0; i < pRenderPassInfo->attachmentCount; ++i) {
9354        const VkImageView &image_view = framebufferInfo.pAttachments[i];
9355        SetLayout(dev_data, pCB, image_view, pRenderPassInfo->pAttachments[i].finalLayout);
9356    }
9357}
9358
9359static bool VerifyRenderAreaBounds(const layer_data *my_data, const VkRenderPassBeginInfo *pRenderPassBegin) {
9360    bool skip_call = false;
9361    const VkFramebufferCreateInfo *pFramebufferInfo = &my_data->frameBufferMap.at(pRenderPassBegin->framebuffer).createInfo;
9362    if (pRenderPassBegin->renderArea.offset.x < 0 ||
9363        (pRenderPassBegin->renderArea.offset.x + pRenderPassBegin->renderArea.extent.width) > pFramebufferInfo->width ||
9364        pRenderPassBegin->renderArea.offset.y < 0 ||
9365        (pRenderPassBegin->renderArea.offset.y + pRenderPassBegin->renderArea.extent.height) > pFramebufferInfo->height) {
9366        skip_call |= static_cast<bool>(log_msg(
9367            my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
9368            DRAWSTATE_INVALID_RENDER_AREA, "CORE",
9369            "Cannot execute a render pass with renderArea not within the bound of the "
9370            "framebuffer. RenderArea: x %d, y %d, width %d, height %d. Framebuffer: width %d, "
9371            "height %d.",
9372            pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y, pRenderPassBegin->renderArea.extent.width,
9373            pRenderPassBegin->renderArea.extent.height, pFramebufferInfo->width, pFramebufferInfo->height));
9374    }
9375    return skip_call;
9376}
9377
9378VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
9379vkCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin, VkSubpassContents contents) {
9380    bool skipCall = false;
9381    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
9382    loader_platform_thread_lock_mutex(&globalLock);
9383    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
9384    if (pCB) {
9385        if (pRenderPassBegin && pRenderPassBegin->renderPass) {
9386#if MTMERGE
9387            auto pass_data = dev_data->renderPassMap.find(pRenderPassBegin->renderPass);
9388            if (pass_data != dev_data->renderPassMap.end()) {
9389                RENDER_PASS_NODE* pRPNode = pass_data->second;
9390                pRPNode->fb = pRenderPassBegin->framebuffer;
9391                auto cb_data = dev_data->commandBufferMap.find(commandBuffer);
9392                for (size_t i = 0; i < pRPNode->attachments.size(); ++i) {
9393                    MT_FB_ATTACHMENT_INFO &fb_info = dev_data->frameBufferMap[pRPNode->fb].attachments[i];
9394                    if (pRPNode->attachments[i].load_op == VK_ATTACHMENT_LOAD_OP_CLEAR) {
9395                        if (cb_data != dev_data->commandBufferMap.end()) {
9396                            std::function<bool()> function = [=]() {
9397                                set_memory_valid(dev_data, fb_info.mem, true, fb_info.image);
9398                                return false;
9399                            };
9400                            cb_data->second->validate_functions.push_back(function);
9401                        }
9402                        VkImageLayout &attachment_layout = pRPNode->attachment_first_layout[pRPNode->attachments[i].attachment];
9403                        if (attachment_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL ||
9404                            attachment_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
9405                            skipCall |=
9406                                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
9407                                        VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, (uint64_t)(pRenderPassBegin->renderPass), __LINE__,
9408                                        MEMTRACK_INVALID_LAYOUT, "MEM", "Cannot clear attachment %d with invalid first layout %d.",
9409                                        pRPNode->attachments[i].attachment, attachment_layout);
9410                        }
9411                    } else if (pRPNode->attachments[i].load_op == VK_ATTACHMENT_LOAD_OP_DONT_CARE) {
9412                        if (cb_data != dev_data->commandBufferMap.end()) {
9413                            std::function<bool()> function = [=]() {
9414                                set_memory_valid(dev_data, fb_info.mem, false, fb_info.image);
9415                                return false;
9416                            };
9417                            cb_data->second->validate_functions.push_back(function);
9418                        }
9419                    } else if (pRPNode->attachments[i].load_op == VK_ATTACHMENT_LOAD_OP_LOAD) {
9420                        if (cb_data != dev_data->commandBufferMap.end()) {
9421                            std::function<bool()> function = [=]() {
9422                                return validate_memory_is_valid(dev_data, fb_info.mem, "vkCmdBeginRenderPass()", fb_info.image);
9423                            };
9424                            cb_data->second->validate_functions.push_back(function);
9425                        }
9426                    }
9427                    if (pRPNode->attachment_first_read[pRPNode->attachments[i].attachment]) {
9428                        if (cb_data != dev_data->commandBufferMap.end()) {
9429                            std::function<bool()> function = [=]() {
9430                                return validate_memory_is_valid(dev_data, fb_info.mem, "vkCmdBeginRenderPass()", fb_info.image);
9431                            };
9432                            cb_data->second->validate_functions.push_back(function);
9433                        }
9434                    }
9435                }
9436            }
9437#endif
9438            skipCall |= VerifyRenderAreaBounds(dev_data, pRenderPassBegin);
9439            skipCall |= VerifyFramebufferAndRenderPassLayouts(commandBuffer, pRenderPassBegin);
9440            auto render_pass_data = dev_data->renderPassMap.find(pRenderPassBegin->renderPass);
9441            if (render_pass_data != dev_data->renderPassMap.end()) {
9442                skipCall |= ValidateDependencies(dev_data, pRenderPassBegin, render_pass_data->second->subpassToNode);
9443            }
9444            skipCall |= insideRenderPass(dev_data, pCB, "vkCmdBeginRenderPass");
9445            skipCall |= validatePrimaryCommandBuffer(dev_data, pCB, "vkCmdBeginRenderPass");
9446            skipCall |= addCmd(dev_data, pCB, CMD_BEGINRENDERPASS, "vkCmdBeginRenderPass()");
9447            pCB->activeRenderPass = pRenderPassBegin->renderPass;
9448            // This is a shallow copy as that is all that is needed for now
9449            pCB->activeRenderPassBeginInfo = *pRenderPassBegin;
9450            pCB->activeSubpass = 0;
9451            pCB->activeSubpassContents = contents;
9452            pCB->framebuffer = pRenderPassBegin->framebuffer;
9453            // Connect this framebuffer to this cmdBuffer
9454            dev_data->frameBufferMap[pCB->framebuffer].referencingCmdBuffers.insert(pCB->commandBuffer);
9455        } else {
9456            skipCall |=
9457                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
9458                        DRAWSTATE_INVALID_RENDERPASS, "DS", "You cannot use a NULL RenderPass object in vkCmdBeginRenderPass()");
9459        }
9460    }
9461    loader_platform_thread_unlock_mutex(&globalLock);
9462    if (!skipCall) {
9463        dev_data->device_dispatch_table->CmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
9464    }
9465}
9466
9467VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
9468    bool skipCall = false;
9469    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
9470    loader_platform_thread_lock_mutex(&globalLock);
9471    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
9472    if (pCB) {
9473        skipCall |= validatePrimaryCommandBuffer(dev_data, pCB, "vkCmdNextSubpass");
9474        skipCall |= addCmd(dev_data, pCB, CMD_NEXTSUBPASS, "vkCmdNextSubpass()");
9475        pCB->activeSubpass++;
9476        pCB->activeSubpassContents = contents;
9477        TransitionSubpassLayouts(commandBuffer, &pCB->activeRenderPassBeginInfo, pCB->activeSubpass);
9478        if (pCB->lastBound[VK_PIPELINE_BIND_POINT_GRAPHICS].pipeline) {
9479            skipCall |= validatePipelineState(dev_data, pCB, VK_PIPELINE_BIND_POINT_GRAPHICS,
9480                                              pCB->lastBound[VK_PIPELINE_BIND_POINT_GRAPHICS].pipeline);
9481        }
9482        skipCall |= outsideRenderPass(dev_data, pCB, "vkCmdNextSubpass");
9483    }
9484    loader_platform_thread_unlock_mutex(&globalLock);
9485    if (!skipCall)
9486        dev_data->device_dispatch_table->CmdNextSubpass(commandBuffer, contents);
9487}
9488
9489VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkCmdEndRenderPass(VkCommandBuffer commandBuffer) {
9490    bool skipCall = false;
9491    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
9492    loader_platform_thread_lock_mutex(&globalLock);
9493#if MTMERGESOURCE
9494    auto cb_data = dev_data->commandBufferMap.find(commandBuffer);
9495    if (cb_data != dev_data->commandBufferMap.end()) {
9496        auto pass_data = dev_data->renderPassMap.find(cb_data->second->activeRenderPass);
9497        if (pass_data != dev_data->renderPassMap.end()) {
9498            RENDER_PASS_NODE* pRPNode = pass_data->second;
9499            for (size_t i = 0; i < pRPNode->attachments.size(); ++i) {
9500                MT_FB_ATTACHMENT_INFO &fb_info = dev_data->frameBufferMap[pRPNode->fb].attachments[i];
9501                if (pRPNode->attachments[i].store_op == VK_ATTACHMENT_STORE_OP_STORE) {
9502                    if (cb_data != dev_data->commandBufferMap.end()) {
9503                        std::function<bool()> function = [=]() {
9504                            set_memory_valid(dev_data, fb_info.mem, true, fb_info.image);
9505                            return false;
9506                        };
9507                        cb_data->second->validate_functions.push_back(function);
9508                    }
9509                } else if (pRPNode->attachments[i].store_op == VK_ATTACHMENT_STORE_OP_DONT_CARE) {
9510                    if (cb_data != dev_data->commandBufferMap.end()) {
9511                        std::function<bool()> function = [=]() {
9512                            set_memory_valid(dev_data, fb_info.mem, false, fb_info.image);
9513                            return false;
9514                        };
9515                        cb_data->second->validate_functions.push_back(function);
9516                    }
9517                }
9518            }
9519        }
9520    }
9521#endif
9522    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
9523    if (pCB) {
9524        skipCall |= outsideRenderPass(dev_data, pCB, "vkCmdEndRenderpass");
9525        skipCall |= validatePrimaryCommandBuffer(dev_data, pCB, "vkCmdEndRenderPass");
9526        skipCall |= addCmd(dev_data, pCB, CMD_ENDRENDERPASS, "vkCmdEndRenderPass()");
9527        TransitionFinalSubpassLayouts(commandBuffer, &pCB->activeRenderPassBeginInfo);
9528        pCB->activeRenderPass = 0;
9529        pCB->activeSubpass = 0;
9530    }
9531    loader_platform_thread_unlock_mutex(&globalLock);
9532    if (!skipCall)
9533        dev_data->device_dispatch_table->CmdEndRenderPass(commandBuffer);
9534}
9535
9536static bool logInvalidAttachmentMessage(layer_data *dev_data, VkCommandBuffer secondaryBuffer, VkRenderPass secondaryPass,
9537                                        VkRenderPass primaryPass, uint32_t primaryAttach, uint32_t secondaryAttach,
9538                                        const char *msg) {
9539    return log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
9540                   DRAWSTATE_INVALID_SECONDARY_COMMAND_BUFFER, "DS",
9541                   "vkCmdExecuteCommands() called w/ invalid Cmd Buffer %p which has a render pass %" PRIx64
9542                   " that is not compatible with the current render pass %" PRIx64 "."
9543                   "Attachment %" PRIu32 " is not compatible with %" PRIu32 ". %s",
9544                   (void *)secondaryBuffer, (uint64_t)(secondaryPass), (uint64_t)(primaryPass), primaryAttach, secondaryAttach,
9545                   msg);
9546}
9547
9548static bool validateAttachmentCompatibility(layer_data *dev_data, VkCommandBuffer primaryBuffer, VkRenderPass primaryPass,
9549                                            uint32_t primaryAttach, VkCommandBuffer secondaryBuffer, VkRenderPass secondaryPass,
9550                                            uint32_t secondaryAttach, bool is_multi) {
9551    bool skip_call = false;
9552    auto primary_data = dev_data->renderPassMap.find(primaryPass);
9553    auto secondary_data = dev_data->renderPassMap.find(secondaryPass);
9554    if (primary_data->second->pCreateInfo->attachmentCount <= primaryAttach) {
9555        primaryAttach = VK_ATTACHMENT_UNUSED;
9556    }
9557    if (secondary_data->second->pCreateInfo->attachmentCount <= secondaryAttach) {
9558        secondaryAttach = VK_ATTACHMENT_UNUSED;
9559    }
9560    if (primaryAttach == VK_ATTACHMENT_UNUSED && secondaryAttach == VK_ATTACHMENT_UNUSED) {
9561        return skip_call;
9562    }
9563    if (primaryAttach == VK_ATTACHMENT_UNUSED) {
9564        skip_call |= logInvalidAttachmentMessage(dev_data, secondaryBuffer, secondaryPass, primaryPass, primaryAttach,
9565                                                 secondaryAttach, "The first is unused while the second is not.");
9566        return skip_call;
9567    }
9568    if (secondaryAttach == VK_ATTACHMENT_UNUSED) {
9569        skip_call |= logInvalidAttachmentMessage(dev_data, secondaryBuffer, secondaryPass, primaryPass, primaryAttach,
9570                                                 secondaryAttach, "The second is unused while the first is not.");
9571        return skip_call;
9572    }
9573    if (primary_data->second->pCreateInfo->pAttachments[primaryAttach].format !=
9574        secondary_data->second->pCreateInfo->pAttachments[secondaryAttach].format) {
9575        skip_call |= logInvalidAttachmentMessage(dev_data, secondaryBuffer, secondaryPass, primaryPass, primaryAttach,
9576                                                 secondaryAttach, "They have different formats.");
9577    }
9578    if (primary_data->second->pCreateInfo->pAttachments[primaryAttach].samples !=
9579        secondary_data->second->pCreateInfo->pAttachments[secondaryAttach].samples) {
9580        skip_call |= logInvalidAttachmentMessage(dev_data, secondaryBuffer, secondaryPass, primaryPass, primaryAttach,
9581                                                 secondaryAttach, "They have different samples.");
9582    }
9583    if (is_multi &&
9584        primary_data->second->pCreateInfo->pAttachments[primaryAttach].flags !=
9585            secondary_data->second->pCreateInfo->pAttachments[secondaryAttach].flags) {
9586        skip_call |= logInvalidAttachmentMessage(dev_data, secondaryBuffer, secondaryPass, primaryPass, primaryAttach,
9587                                                 secondaryAttach, "They have different flags.");
9588    }
9589    return skip_call;
9590}
9591
9592static bool validateSubpassCompatibility(layer_data *dev_data, VkCommandBuffer primaryBuffer, VkRenderPass primaryPass,
9593                                         VkCommandBuffer secondaryBuffer, VkRenderPass secondaryPass, const int subpass,
9594                                         bool is_multi) {
9595    bool skip_call = false;
9596    auto primary_data = dev_data->renderPassMap.find(primaryPass);
9597    auto secondary_data = dev_data->renderPassMap.find(secondaryPass);
9598    const VkSubpassDescription &primary_desc = primary_data->second->pCreateInfo->pSubpasses[subpass];
9599    const VkSubpassDescription &secondary_desc = secondary_data->second->pCreateInfo->pSubpasses[subpass];
9600    uint32_t maxInputAttachmentCount = std::max(primary_desc.inputAttachmentCount, secondary_desc.inputAttachmentCount);
9601    for (uint32_t i = 0; i < maxInputAttachmentCount; ++i) {
9602        uint32_t primary_input_attach = VK_ATTACHMENT_UNUSED, secondary_input_attach = VK_ATTACHMENT_UNUSED;
9603        if (i < primary_desc.inputAttachmentCount) {
9604            primary_input_attach = primary_desc.pInputAttachments[i].attachment;
9605        }
9606        if (i < secondary_desc.inputAttachmentCount) {
9607            secondary_input_attach = secondary_desc.pInputAttachments[i].attachment;
9608        }
9609        skip_call |= validateAttachmentCompatibility(dev_data, primaryBuffer, primaryPass, primary_input_attach, secondaryBuffer,
9610                                                     secondaryPass, secondary_input_attach, is_multi);
9611    }
9612    uint32_t maxColorAttachmentCount = std::max(primary_desc.colorAttachmentCount, secondary_desc.colorAttachmentCount);
9613    for (uint32_t i = 0; i < maxColorAttachmentCount; ++i) {
9614        uint32_t primary_color_attach = VK_ATTACHMENT_UNUSED, secondary_color_attach = VK_ATTACHMENT_UNUSED;
9615        if (i < primary_desc.colorAttachmentCount) {
9616            primary_color_attach = primary_desc.pColorAttachments[i].attachment;
9617        }
9618        if (i < secondary_desc.colorAttachmentCount) {
9619            secondary_color_attach = secondary_desc.pColorAttachments[i].attachment;
9620        }
9621        skip_call |= validateAttachmentCompatibility(dev_data, primaryBuffer, primaryPass, primary_color_attach, secondaryBuffer,
9622                                                     secondaryPass, secondary_color_attach, is_multi);
9623        uint32_t primary_resolve_attach = VK_ATTACHMENT_UNUSED, secondary_resolve_attach = VK_ATTACHMENT_UNUSED;
9624        if (i < primary_desc.colorAttachmentCount && primary_desc.pResolveAttachments) {
9625            primary_resolve_attach = primary_desc.pResolveAttachments[i].attachment;
9626        }
9627        if (i < secondary_desc.colorAttachmentCount && secondary_desc.pResolveAttachments) {
9628            secondary_resolve_attach = secondary_desc.pResolveAttachments[i].attachment;
9629        }
9630        skip_call |= validateAttachmentCompatibility(dev_data, primaryBuffer, primaryPass, primary_resolve_attach, secondaryBuffer,
9631                                                     secondaryPass, secondary_resolve_attach, is_multi);
9632    }
9633    uint32_t primary_depthstencil_attach = VK_ATTACHMENT_UNUSED, secondary_depthstencil_attach = VK_ATTACHMENT_UNUSED;
9634    if (primary_desc.pDepthStencilAttachment) {
9635        primary_depthstencil_attach = primary_desc.pDepthStencilAttachment[0].attachment;
9636    }
9637    if (secondary_desc.pDepthStencilAttachment) {
9638        secondary_depthstencil_attach = secondary_desc.pDepthStencilAttachment[0].attachment;
9639    }
9640    skip_call |= validateAttachmentCompatibility(dev_data, primaryBuffer, primaryPass, primary_depthstencil_attach, secondaryBuffer,
9641                                                 secondaryPass, secondary_depthstencil_attach, is_multi);
9642    return skip_call;
9643}
9644
9645static bool validateRenderPassCompatibility(layer_data *dev_data, VkCommandBuffer primaryBuffer, VkRenderPass primaryPass,
9646                                            VkCommandBuffer secondaryBuffer, VkRenderPass secondaryPass) {
9647    bool skip_call = false;
9648    // Early exit if renderPass objects are identical (and therefore compatible)
9649    if (primaryPass == secondaryPass)
9650        return skip_call;
9651    auto primary_data = dev_data->renderPassMap.find(primaryPass);
9652    auto secondary_data = dev_data->renderPassMap.find(secondaryPass);
9653    if (primary_data == dev_data->renderPassMap.end() || primary_data->second == nullptr) {
9654        skip_call |=
9655            log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
9656                    DRAWSTATE_INVALID_SECONDARY_COMMAND_BUFFER, "DS",
9657                    "vkCmdExecuteCommands() called w/ invalid current Cmd Buffer %p which has invalid render pass %" PRIx64 ".",
9658                    (void *)primaryBuffer, (uint64_t)(primaryPass));
9659        return skip_call;
9660    }
9661    if (secondary_data == dev_data->renderPassMap.end() || secondary_data->second == nullptr) {
9662        skip_call |=
9663            log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
9664                    DRAWSTATE_INVALID_SECONDARY_COMMAND_BUFFER, "DS",
9665                    "vkCmdExecuteCommands() called w/ invalid secondary Cmd Buffer %p which has invalid render pass %" PRIx64 ".",
9666                    (void *)secondaryBuffer, (uint64_t)(secondaryPass));
9667        return skip_call;
9668    }
9669    if (primary_data->second->pCreateInfo->subpassCount != secondary_data->second->pCreateInfo->subpassCount) {
9670        skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
9671                             DRAWSTATE_INVALID_SECONDARY_COMMAND_BUFFER, "DS",
9672                             "vkCmdExecuteCommands() called w/ invalid Cmd Buffer %p which has a render pass %" PRIx64
9673                             " that is not compatible with the current render pass %" PRIx64 "."
9674                             "They have a different number of subpasses.",
9675                             (void *)secondaryBuffer, (uint64_t)(secondaryPass), (uint64_t)(primaryPass));
9676        return skip_call;
9677    }
9678    bool is_multi = primary_data->second->pCreateInfo->subpassCount > 1;
9679    for (uint32_t i = 0; i < primary_data->second->pCreateInfo->subpassCount; ++i) {
9680        skip_call |=
9681            validateSubpassCompatibility(dev_data, primaryBuffer, primaryPass, secondaryBuffer, secondaryPass, i, is_multi);
9682    }
9683    return skip_call;
9684}
9685
9686static bool validateFramebuffer(layer_data *dev_data, VkCommandBuffer primaryBuffer, const GLOBAL_CB_NODE *pCB,
9687                                VkCommandBuffer secondaryBuffer, const GLOBAL_CB_NODE *pSubCB) {
9688    bool skip_call = false;
9689    if (!pSubCB->beginInfo.pInheritanceInfo) {
9690        return skip_call;
9691    }
9692    VkFramebuffer primary_fb = pCB->framebuffer;
9693    VkFramebuffer secondary_fb = pSubCB->beginInfo.pInheritanceInfo->framebuffer;
9694    if (secondary_fb != VK_NULL_HANDLE) {
9695        if (primary_fb != secondary_fb) {
9696            skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
9697                                 DRAWSTATE_INVALID_SECONDARY_COMMAND_BUFFER, "DS",
9698                                 "vkCmdExecuteCommands() called w/ invalid Cmd Buffer %p which has a framebuffer %" PRIx64
9699                                 " that is not compatible with the current framebuffer %" PRIx64 ".",
9700                                 (void *)secondaryBuffer, (uint64_t)(secondary_fb), (uint64_t)(primary_fb));
9701        }
9702        auto fb_data = dev_data->frameBufferMap.find(secondary_fb);
9703        if (fb_data == dev_data->frameBufferMap.end()) {
9704            skip_call |=
9705                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
9706                        DRAWSTATE_INVALID_SECONDARY_COMMAND_BUFFER, "DS", "vkCmdExecuteCommands() called w/ invalid Cmd Buffer %p "
9707                                                                          "which has invalid framebuffer %" PRIx64 ".",
9708                        (void *)secondaryBuffer, (uint64_t)(secondary_fb));
9709            return skip_call;
9710        }
9711        skip_call |= validateRenderPassCompatibility(dev_data, secondaryBuffer, fb_data->second.createInfo.renderPass,
9712                                                     secondaryBuffer, pSubCB->beginInfo.pInheritanceInfo->renderPass);
9713    }
9714    return skip_call;
9715}
9716
9717static bool validateSecondaryCommandBufferState(layer_data *dev_data, GLOBAL_CB_NODE *pCB, GLOBAL_CB_NODE *pSubCB) {
9718    bool skipCall = false;
9719    unordered_set<int> activeTypes;
9720    for (auto queryObject : pCB->activeQueries) {
9721        auto queryPoolData = dev_data->queryPoolMap.find(queryObject.pool);
9722        if (queryPoolData != dev_data->queryPoolMap.end()) {
9723            if (queryPoolData->second.createInfo.queryType == VK_QUERY_TYPE_PIPELINE_STATISTICS &&
9724                pSubCB->beginInfo.pInheritanceInfo) {
9725                VkQueryPipelineStatisticFlags cmdBufStatistics = pSubCB->beginInfo.pInheritanceInfo->pipelineStatistics;
9726                if ((cmdBufStatistics & queryPoolData->second.createInfo.pipelineStatistics) != cmdBufStatistics) {
9727                    skipCall |= log_msg(
9728                        dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
9729                        DRAWSTATE_INVALID_SECONDARY_COMMAND_BUFFER, "DS",
9730                        "vkCmdExecuteCommands() called w/ invalid Cmd Buffer %p "
9731                        "which has invalid active query pool %" PRIx64 ". Pipeline statistics is being queried so the command "
9732                        "buffer must have all bits set on the queryPool.",
9733                        reinterpret_cast<void *>(pCB->commandBuffer), reinterpret_cast<const uint64_t &>(queryPoolData->first));
9734                }
9735            }
9736            activeTypes.insert(queryPoolData->second.createInfo.queryType);
9737        }
9738    }
9739    for (auto queryObject : pSubCB->startedQueries) {
9740        auto queryPoolData = dev_data->queryPoolMap.find(queryObject.pool);
9741        if (queryPoolData != dev_data->queryPoolMap.end() && activeTypes.count(queryPoolData->second.createInfo.queryType)) {
9742            skipCall |=
9743                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
9744                        DRAWSTATE_INVALID_SECONDARY_COMMAND_BUFFER, "DS",
9745                        "vkCmdExecuteCommands() called w/ invalid Cmd Buffer %p "
9746                        "which has invalid active query pool %" PRIx64 "of type %d but a query of that type has been started on "
9747                        "secondary Cmd Buffer %p.",
9748                        reinterpret_cast<void *>(pCB->commandBuffer), reinterpret_cast<const uint64_t &>(queryPoolData->first),
9749                        queryPoolData->second.createInfo.queryType, reinterpret_cast<void *>(pSubCB->commandBuffer));
9750        }
9751    }
9752    return skipCall;
9753}
9754
9755VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
9756vkCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBuffersCount, const VkCommandBuffer *pCommandBuffers) {
9757    bool skipCall = false;
9758    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(commandBuffer), layer_data_map);
9759    loader_platform_thread_lock_mutex(&globalLock);
9760    GLOBAL_CB_NODE *pCB = getCBNode(dev_data, commandBuffer);
9761    if (pCB) {
9762        GLOBAL_CB_NODE *pSubCB = NULL;
9763        for (uint32_t i = 0; i < commandBuffersCount; i++) {
9764            pSubCB = getCBNode(dev_data, pCommandBuffers[i]);
9765            if (!pSubCB) {
9766                skipCall |=
9767                    log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0, __LINE__,
9768                            DRAWSTATE_INVALID_SECONDARY_COMMAND_BUFFER, "DS",
9769                            "vkCmdExecuteCommands() called w/ invalid Cmd Buffer %p in element %u of pCommandBuffers array.",
9770                            (void *)pCommandBuffers[i], i);
9771            } else if (VK_COMMAND_BUFFER_LEVEL_PRIMARY == pSubCB->createInfo.level) {
9772                skipCall |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
9773                                    __LINE__, DRAWSTATE_INVALID_SECONDARY_COMMAND_BUFFER, "DS",
9774                                    "vkCmdExecuteCommands() called w/ Primary Cmd Buffer %p in element %u of pCommandBuffers "
9775                                    "array. All cmd buffers in pCommandBuffers array must be secondary.",
9776                                    (void *)pCommandBuffers[i], i);
9777            } else if (pCB->activeRenderPass) { // Secondary CB w/i RenderPass must have *CONTINUE_BIT set
9778                if (!(pSubCB->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT)) {
9779                    skipCall |= log_msg(
9780                        dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
9781                        (uint64_t)pCommandBuffers[i], __LINE__, DRAWSTATE_BEGIN_CB_INVALID_STATE, "DS",
9782                        "vkCmdExecuteCommands(): Secondary Command Buffer (%p) executed within render pass (%#" PRIxLEAST64
9783                        ") must have had vkBeginCommandBuffer() called w/ VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT set.",
9784                        (void *)pCommandBuffers[i], (uint64_t)pCB->activeRenderPass);
9785                } else {
9786                    // Make sure render pass is compatible with parent command buffer pass if has continue
9787                    skipCall |= validateRenderPassCompatibility(dev_data, commandBuffer, pCB->activeRenderPass, pCommandBuffers[i],
9788                                                                pSubCB->beginInfo.pInheritanceInfo->renderPass);
9789                    skipCall |= validateFramebuffer(dev_data, commandBuffer, pCB, pCommandBuffers[i], pSubCB);
9790                }
9791                string errorString = "";
9792                if (!verify_renderpass_compatibility(dev_data, pCB->activeRenderPass,
9793                                                     pSubCB->beginInfo.pInheritanceInfo->renderPass, errorString)) {
9794                    skipCall |= log_msg(
9795                        dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
9796                        (uint64_t)pCommandBuffers[i], __LINE__, DRAWSTATE_RENDERPASS_INCOMPATIBLE, "DS",
9797                        "vkCmdExecuteCommands(): Secondary Command Buffer (%p) w/ render pass (%#" PRIxLEAST64
9798                        ") is incompatible w/ primary command buffer (%p) w/ render pass (%#" PRIxLEAST64 ") due to: %s",
9799                        (void *)pCommandBuffers[i], (uint64_t)pSubCB->beginInfo.pInheritanceInfo->renderPass, (void *)commandBuffer,
9800                        (uint64_t)pCB->activeRenderPass, errorString.c_str());
9801                }
9802                //  If framebuffer for secondary CB is not NULL, then it must match FB from vkCmdBeginRenderPass()
9803                //   that this CB will be executed in AND framebuffer must have been created w/ RP compatible w/ renderpass
9804                if (pSubCB->beginInfo.pInheritanceInfo->framebuffer) {
9805                    if (pSubCB->beginInfo.pInheritanceInfo->framebuffer != pCB->activeRenderPassBeginInfo.framebuffer) {
9806                        skipCall |= log_msg(
9807                            dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
9808                            (uint64_t)pCommandBuffers[i], __LINE__, DRAWSTATE_FRAMEBUFFER_INCOMPATIBLE, "DS",
9809                            "vkCmdExecuteCommands(): Secondary Command Buffer (%p) references framebuffer (%#" PRIxLEAST64
9810                            ") that does not match framebuffer (%#" PRIxLEAST64 ") in active renderpass (%#" PRIxLEAST64 ").",
9811                            (void *)pCommandBuffers[i], (uint64_t)pSubCB->beginInfo.pInheritanceInfo->framebuffer,
9812                            (uint64_t)pCB->activeRenderPassBeginInfo.framebuffer, (uint64_t)pCB->activeRenderPass);
9813                    }
9814                }
9815            }
9816            // TODO(mlentine): Move more logic into this method
9817            skipCall |= validateSecondaryCommandBufferState(dev_data, pCB, pSubCB);
9818            skipCall |= validateCommandBufferState(dev_data, pSubCB);
9819            // Secondary cmdBuffers are considered pending execution starting w/
9820            // being recorded
9821            if (!(pSubCB->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT)) {
9822                if (dev_data->globalInFlightCmdBuffers.find(pSubCB->commandBuffer) != dev_data->globalInFlightCmdBuffers.end()) {
9823                    skipCall |= log_msg(
9824                        dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
9825                        (uint64_t)(pCB->commandBuffer), __LINE__, DRAWSTATE_INVALID_CB_SIMULTANEOUS_USE, "DS",
9826                        "Attempt to simultaneously execute CB %#" PRIxLEAST64 " w/o VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT "
9827                        "set!",
9828                        (uint64_t)(pCB->commandBuffer));
9829                }
9830                if (pCB->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
9831                    // Warn that non-simultaneous secondary cmd buffer renders primary non-simultaneous
9832                    skipCall |= log_msg(
9833                        dev_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
9834                        (uint64_t)(pCommandBuffers[i]), __LINE__, DRAWSTATE_INVALID_CB_SIMULTANEOUS_USE, "DS",
9835                        "vkCmdExecuteCommands(): Secondary Command Buffer (%#" PRIxLEAST64
9836                        ") does not have VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT set and will cause primary command buffer "
9837                        "(%#" PRIxLEAST64 ") to be treated as if it does not have VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT "
9838                                          "set, even though it does.",
9839                        (uint64_t)(pCommandBuffers[i]), (uint64_t)(pCB->commandBuffer));
9840                    pCB->beginInfo.flags &= ~VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
9841                }
9842            }
9843            if (!pCB->activeQueries.empty() && !dev_data->phys_dev_properties.features.inheritedQueries) {
9844                skipCall |=
9845                    log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
9846                            reinterpret_cast<uint64_t>(pCommandBuffers[i]), __LINE__, DRAWSTATE_INVALID_COMMAND_BUFFER, "DS",
9847                            "vkCmdExecuteCommands(): Secondary Command Buffer "
9848                            "(%#" PRIxLEAST64 ") cannot be submitted with a query in "
9849                            "flight and inherited queries not "
9850                            "supported on this device.",
9851                            reinterpret_cast<uint64_t>(pCommandBuffers[i]));
9852            }
9853            pSubCB->primaryCommandBuffer = pCB->commandBuffer;
9854            pCB->secondaryCommandBuffers.insert(pSubCB->commandBuffer);
9855            dev_data->globalInFlightCmdBuffers.insert(pSubCB->commandBuffer);
9856        }
9857        skipCall |= validatePrimaryCommandBuffer(dev_data, pCB, "vkCmdExecuteComands");
9858        skipCall |= addCmd(dev_data, pCB, CMD_EXECUTECOMMANDS, "vkCmdExecuteComands()");
9859    }
9860    loader_platform_thread_unlock_mutex(&globalLock);
9861    if (!skipCall)
9862        dev_data->device_dispatch_table->CmdExecuteCommands(commandBuffer, commandBuffersCount, pCommandBuffers);
9863}
9864
9865static bool ValidateMapImageLayouts(VkDevice device, VkDeviceMemory mem) {
9866    bool skip_call = false;
9867    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
9868    auto mem_data = dev_data->memObjMap.find(mem);
9869    if ((mem_data != dev_data->memObjMap.end()) && (mem_data->second.image != VK_NULL_HANDLE)) {
9870        std::vector<VkImageLayout> layouts;
9871        if (FindLayouts(dev_data, mem_data->second.image, layouts)) {
9872            for (auto layout : layouts) {
9873                if (layout != VK_IMAGE_LAYOUT_PREINITIALIZED && layout != VK_IMAGE_LAYOUT_GENERAL) {
9874                    skip_call |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, (VkDebugReportObjectTypeEXT)0, 0,
9875                                         __LINE__, DRAWSTATE_INVALID_IMAGE_LAYOUT, "DS", "Cannot map an image with layout %s. Only "
9876                                                                                         "GENERAL or PREINITIALIZED are supported.",
9877                                         string_VkImageLayout(layout));
9878                }
9879            }
9880        }
9881    }
9882    return skip_call;
9883}
9884
9885VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
9886vkMapMemory(VkDevice device, VkDeviceMemory mem, VkDeviceSize offset, VkDeviceSize size, VkFlags flags, void **ppData) {
9887    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
9888
9889    bool skip_call = false;
9890    VkResult result = VK_ERROR_VALIDATION_FAILED_EXT;
9891    loader_platform_thread_lock_mutex(&globalLock);
9892#if MTMERGESOURCE
9893    DEVICE_MEM_INFO *pMemObj = get_mem_obj_info(dev_data, mem);
9894    if (pMemObj) {
9895        pMemObj->valid = true;
9896        if ((dev_data->phys_dev_mem_props.memoryTypes[pMemObj->allocInfo.memoryTypeIndex].propertyFlags &
9897             VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0) {
9898            skip_call =
9899                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
9900                        (uint64_t)mem, __LINE__, MEMTRACK_INVALID_STATE, "MEM",
9901                        "Mapping Memory without VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT set: mem obj %#" PRIxLEAST64, (uint64_t)mem);
9902        }
9903    }
9904    skip_call |= validateMemRange(dev_data, mem, offset, size);
9905    storeMemRanges(dev_data, mem, offset, size);
9906#endif
9907    skip_call |= ValidateMapImageLayouts(device, mem);
9908    loader_platform_thread_unlock_mutex(&globalLock);
9909
9910    if (!skip_call) {
9911        result = dev_data->device_dispatch_table->MapMemory(device, mem, offset, size, flags, ppData);
9912#if MTMERGESOURCE
9913        loader_platform_thread_lock_mutex(&globalLock);
9914        initializeAndTrackMemory(dev_data, mem, size, ppData);
9915        loader_platform_thread_unlock_mutex(&globalLock);
9916#endif
9917    }
9918    return result;
9919}
9920
9921#if MTMERGESOURCE
9922VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkUnmapMemory(VkDevice device, VkDeviceMemory mem) {
9923    layer_data *my_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
9924    bool skipCall = false;
9925
9926    loader_platform_thread_lock_mutex(&globalLock);
9927    skipCall |= deleteMemRanges(my_data, mem);
9928    loader_platform_thread_unlock_mutex(&globalLock);
9929    if (!skipCall) {
9930        my_data->device_dispatch_table->UnmapMemory(device, mem);
9931    }
9932}
9933
9934static bool validateMemoryIsMapped(layer_data *my_data, const char *funcName, uint32_t memRangeCount,
9935                                   const VkMappedMemoryRange *pMemRanges) {
9936    bool skipCall = false;
9937    for (uint32_t i = 0; i < memRangeCount; ++i) {
9938        auto mem_element = my_data->memObjMap.find(pMemRanges[i].memory);
9939        if (mem_element != my_data->memObjMap.end()) {
9940            if (mem_element->second.memRange.offset > pMemRanges[i].offset) {
9941                skipCall |= log_msg(
9942                    my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
9943                    (uint64_t)pMemRanges[i].memory, __LINE__, MEMTRACK_INVALID_MAP, "MEM",
9944                    "%s: Flush/Invalidate offset (" PRINTF_SIZE_T_SPECIFIER ") is less than Memory Object's offset "
9945                    "(" PRINTF_SIZE_T_SPECIFIER ").",
9946                    funcName, static_cast<size_t>(pMemRanges[i].offset), static_cast<size_t>(mem_element->second.memRange.offset));
9947            }
9948            if ((mem_element->second.memRange.size != VK_WHOLE_SIZE) &&
9949                ((mem_element->second.memRange.offset + mem_element->second.memRange.size) <
9950                 (pMemRanges[i].offset + pMemRanges[i].size))) {
9951                skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
9952                                    VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, (uint64_t)pMemRanges[i].memory, __LINE__,
9953                                    MEMTRACK_INVALID_MAP, "MEM", "%s: Flush/Invalidate upper-bound (" PRINTF_SIZE_T_SPECIFIER
9954                                                                 ") exceeds the Memory Object's upper-bound "
9955                                                                 "(" PRINTF_SIZE_T_SPECIFIER ").",
9956                                    funcName, static_cast<size_t>(pMemRanges[i].offset + pMemRanges[i].size),
9957                                    static_cast<size_t>(mem_element->second.memRange.offset + mem_element->second.memRange.size));
9958            }
9959        }
9960    }
9961    return skipCall;
9962}
9963
9964static bool validateAndCopyNoncoherentMemoryToDriver(layer_data *my_data, uint32_t memRangeCount,
9965                                                     const VkMappedMemoryRange *pMemRanges) {
9966    bool skipCall = false;
9967    for (uint32_t i = 0; i < memRangeCount; ++i) {
9968        auto mem_element = my_data->memObjMap.find(pMemRanges[i].memory);
9969        if (mem_element != my_data->memObjMap.end()) {
9970            if (mem_element->second.pData) {
9971                VkDeviceSize size = mem_element->second.memRange.size;
9972                VkDeviceSize half_size = (size / 2);
9973                char *data = static_cast<char *>(mem_element->second.pData);
9974                for (auto j = 0; j < half_size; ++j) {
9975                    if (data[j] != NoncoherentMemoryFillValue) {
9976                        skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
9977                                            VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, (uint64_t)pMemRanges[i].memory, __LINE__,
9978                                            MEMTRACK_INVALID_MAP, "MEM", "Memory overflow was detected on mem obj %" PRIxLEAST64,
9979                                            (uint64_t)pMemRanges[i].memory);
9980                    }
9981                }
9982                for (auto j = size + half_size; j < 2 * size; ++j) {
9983                    if (data[j] != NoncoherentMemoryFillValue) {
9984                        skipCall |= log_msg(my_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
9985                                            VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, (uint64_t)pMemRanges[i].memory, __LINE__,
9986                                            MEMTRACK_INVALID_MAP, "MEM", "Memory overflow was detected on mem obj %" PRIxLEAST64,
9987                                            (uint64_t)pMemRanges[i].memory);
9988                    }
9989                }
9990                memcpy(mem_element->second.pDriverData, static_cast<void *>(data + (size_t)(half_size)), (size_t)(size));
9991            }
9992        }
9993    }
9994    return skipCall;
9995}
9996
9997VK_LAYER_EXPORT VkResult VKAPI_CALL
9998vkFlushMappedMemoryRanges(VkDevice device, uint32_t memRangeCount, const VkMappedMemoryRange *pMemRanges) {
9999    VkResult result = VK_ERROR_VALIDATION_FAILED_EXT;
10000    bool skipCall = false;
10001    layer_data *my_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
10002
10003    loader_platform_thread_lock_mutex(&globalLock);
10004    skipCall |= validateAndCopyNoncoherentMemoryToDriver(my_data, memRangeCount, pMemRanges);
10005    skipCall |= validateMemoryIsMapped(my_data, "vkFlushMappedMemoryRanges", memRangeCount, pMemRanges);
10006    loader_platform_thread_unlock_mutex(&globalLock);
10007    if (!skipCall) {
10008        result = my_data->device_dispatch_table->FlushMappedMemoryRanges(device, memRangeCount, pMemRanges);
10009    }
10010    return result;
10011}
10012
10013VK_LAYER_EXPORT VkResult VKAPI_CALL
10014vkInvalidateMappedMemoryRanges(VkDevice device, uint32_t memRangeCount, const VkMappedMemoryRange *pMemRanges) {
10015    VkResult result = VK_ERROR_VALIDATION_FAILED_EXT;
10016    bool skipCall = false;
10017    layer_data *my_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
10018
10019    loader_platform_thread_lock_mutex(&globalLock);
10020    skipCall |= validateMemoryIsMapped(my_data, "vkInvalidateMappedMemoryRanges", memRangeCount, pMemRanges);
10021    loader_platform_thread_unlock_mutex(&globalLock);
10022    if (!skipCall) {
10023        result = my_data->device_dispatch_table->InvalidateMappedMemoryRanges(device, memRangeCount, pMemRanges);
10024    }
10025    return result;
10026}
10027#endif
10028
10029VKAPI_ATTR VkResult VKAPI_CALL vkBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory mem, VkDeviceSize memoryOffset) {
10030    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
10031    VkResult result = VK_ERROR_VALIDATION_FAILED_EXT;
10032    bool skipCall = false;
10033    loader_platform_thread_lock_mutex(&globalLock);
10034    auto image_node = dev_data->imageMap.find(image);
10035    if (image_node != dev_data->imageMap.end()) {
10036        // Track objects tied to memory
10037        uint64_t image_handle = reinterpret_cast<uint64_t&>(image);
10038        skipCall = set_mem_binding(dev_data, mem, image_handle, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, "vkBindImageMemory");
10039        VkMemoryRequirements memRequirements;
10040        loader_platform_thread_unlock_mutex(&globalLock);
10041        dev_data->device_dispatch_table->GetImageMemoryRequirements(device, image, &memRequirements);
10042        loader_platform_thread_lock_mutex(&globalLock);
10043        skipCall |= validate_buffer_image_aliasing(dev_data, image_handle, mem, memoryOffset, memRequirements,
10044                                                   dev_data->memObjMap[mem].imageRanges, dev_data->memObjMap[mem].bufferRanges,
10045                                                   VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT);
10046        print_mem_list(dev_data);
10047        loader_platform_thread_unlock_mutex(&globalLock);
10048        if (!skipCall) {
10049            result = dev_data->device_dispatch_table->BindImageMemory(device, image, mem, memoryOffset);
10050            loader_platform_thread_lock_mutex(&globalLock);
10051            dev_data->memObjMap[mem].image = image;
10052            image_node->second.mem = mem;
10053            image_node->second.memOffset = memoryOffset;
10054            image_node->second.memSize = memRequirements.size;
10055            loader_platform_thread_unlock_mutex(&globalLock);
10056        }
10057    } else {
10058        log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
10059                reinterpret_cast<const uint64_t &>(image), __LINE__, MEMTRACK_INVALID_OBJECT, "MT",
10060                "vkBindImageMemory: Cannot find invalid image %" PRIx64 ", has it already been deleted?",
10061                reinterpret_cast<const uint64_t &>(image));
10062    }
10063    return result;
10064}
10065
10066VKAPI_ATTR VkResult VKAPI_CALL vkSetEvent(VkDevice device, VkEvent event) {
10067    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
10068    loader_platform_thread_lock_mutex(&globalLock);
10069    dev_data->eventMap[event].needsSignaled = false;
10070    dev_data->eventMap[event].stageMask = VK_PIPELINE_STAGE_HOST_BIT;
10071    loader_platform_thread_unlock_mutex(&globalLock);
10072    // Host setting event is visible to all queues immediately so update stageMask for any queue that's seen this event
10073    // TODO : For correctness this needs separate fix to verify that app doesn't make incorrect assumptions about the
10074    // ordering of this command in relation to vkCmd[Set|Reset]Events (see GH297)
10075    for (auto queue_data : dev_data->queueMap) {
10076        auto event_entry = queue_data.second.eventToStageMap.find(event);
10077        if (event_entry != queue_data.second.eventToStageMap.end()) {
10078            event_entry->second |= VK_PIPELINE_STAGE_HOST_BIT;
10079        }
10080    }
10081    VkResult result = dev_data->device_dispatch_table->SetEvent(device, event);
10082    return result;
10083}
10084
10085VKAPI_ATTR VkResult VKAPI_CALL
10086vkQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo *pBindInfo, VkFence fence) {
10087    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(queue), layer_data_map);
10088    VkResult result = VK_ERROR_VALIDATION_FAILED_EXT;
10089    bool skip_call = false;
10090    loader_platform_thread_lock_mutex(&globalLock);
10091    for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; ++bindIdx) {
10092        const VkBindSparseInfo &bindInfo = pBindInfo[bindIdx];
10093        // Track objects tied to memory
10094        for (uint32_t j = 0; j < bindInfo.bufferBindCount; j++) {
10095            for (uint32_t k = 0; k < bindInfo.pBufferBinds[j].bindCount; k++) {
10096                if (set_sparse_mem_binding(dev_data, bindInfo.pBufferBinds[j].pBinds[k].memory,
10097                                           (uint64_t)bindInfo.pBufferBinds[j].buffer, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
10098                                           "vkQueueBindSparse"))
10099                    skip_call = true;
10100            }
10101        }
10102        for (uint32_t j = 0; j < bindInfo.imageOpaqueBindCount; j++) {
10103            for (uint32_t k = 0; k < bindInfo.pImageOpaqueBinds[j].bindCount; k++) {
10104                if (set_sparse_mem_binding(dev_data, bindInfo.pImageOpaqueBinds[j].pBinds[k].memory,
10105                                           (uint64_t)bindInfo.pImageOpaqueBinds[j].image, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
10106                                           "vkQueueBindSparse"))
10107                    skip_call = true;
10108            }
10109        }
10110        for (uint32_t j = 0; j < bindInfo.imageBindCount; j++) {
10111            for (uint32_t k = 0; k < bindInfo.pImageBinds[j].bindCount; k++) {
10112                if (set_sparse_mem_binding(dev_data, bindInfo.pImageBinds[j].pBinds[k].memory,
10113                                           (uint64_t)bindInfo.pImageBinds[j].image, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
10114                                           "vkQueueBindSparse"))
10115                    skip_call = true;
10116            }
10117        }
10118        for (uint32_t i = 0; i < bindInfo.waitSemaphoreCount; ++i) {
10119            const VkSemaphore &semaphore = bindInfo.pWaitSemaphores[i];
10120            if (dev_data->semaphoreMap.find(semaphore) != dev_data->semaphoreMap.end()) {
10121                if (dev_data->semaphoreMap[semaphore].signaled) {
10122                    dev_data->semaphoreMap[semaphore].signaled = false;
10123                } else {
10124                    skip_call |=
10125                        log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT,
10126                                reinterpret_cast<const uint64_t &>(semaphore), __LINE__, DRAWSTATE_QUEUE_FORWARD_PROGRESS, "DS",
10127                                "vkQueueBindSparse: Queue %#" PRIx64 " is waiting on semaphore %#" PRIx64
10128                                " that has no way to be signaled.",
10129                                reinterpret_cast<const uint64_t &>(queue), reinterpret_cast<const uint64_t &>(semaphore));
10130                }
10131            }
10132        }
10133        for (uint32_t i = 0; i < bindInfo.signalSemaphoreCount; ++i) {
10134            const VkSemaphore &semaphore = bindInfo.pSignalSemaphores[i];
10135            if (dev_data->semaphoreMap.find(semaphore) != dev_data->semaphoreMap.end()) {
10136                if (dev_data->semaphoreMap[semaphore].signaled) {
10137                    skip_call =
10138                        log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT,
10139                                reinterpret_cast<const uint64_t &>(semaphore), __LINE__, DRAWSTATE_QUEUE_FORWARD_PROGRESS, "DS",
10140                                "vkQueueBindSparse: Queue %#" PRIx64 " is signaling semaphore %#" PRIx64
10141                                ", but that semaphore is already signaled.",
10142                                reinterpret_cast<const uint64_t &>(queue), reinterpret_cast<const uint64_t &>(semaphore));
10143                }
10144                dev_data->semaphoreMap[semaphore].signaled = true;
10145            }
10146        }
10147    }
10148    print_mem_list(dev_data);
10149    loader_platform_thread_unlock_mutex(&globalLock);
10150
10151    if (!skip_call)
10152        return dev_data->device_dispatch_table->QueueBindSparse(queue, bindInfoCount, pBindInfo, fence);
10153
10154    return result;
10155}
10156
10157VKAPI_ATTR VkResult VKAPI_CALL vkCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo *pCreateInfo,
10158                                                 const VkAllocationCallbacks *pAllocator, VkSemaphore *pSemaphore) {
10159    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
10160    VkResult result = dev_data->device_dispatch_table->CreateSemaphore(device, pCreateInfo, pAllocator, pSemaphore);
10161    if (result == VK_SUCCESS) {
10162        loader_platform_thread_lock_mutex(&globalLock);
10163        SEMAPHORE_NODE* sNode = &dev_data->semaphoreMap[*pSemaphore];
10164        sNode->signaled = false;
10165        sNode->queue = VK_NULL_HANDLE;
10166        sNode->in_use.store(0);
10167        loader_platform_thread_unlock_mutex(&globalLock);
10168    }
10169    return result;
10170}
10171
10172VKAPI_ATTR VkResult VKAPI_CALL
10173vkCreateEvent(VkDevice device, const VkEventCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkEvent *pEvent) {
10174    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
10175    VkResult result = dev_data->device_dispatch_table->CreateEvent(device, pCreateInfo, pAllocator, pEvent);
10176    if (result == VK_SUCCESS) {
10177        loader_platform_thread_lock_mutex(&globalLock);
10178        dev_data->eventMap[*pEvent].needsSignaled = false;
10179        dev_data->eventMap[*pEvent].in_use.store(0);
10180        dev_data->eventMap[*pEvent].stageMask = VkPipelineStageFlags(0);
10181        loader_platform_thread_unlock_mutex(&globalLock);
10182    }
10183    return result;
10184}
10185
10186VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR *pCreateInfo,
10187                                                                    const VkAllocationCallbacks *pAllocator,
10188                                                                    VkSwapchainKHR *pSwapchain) {
10189    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
10190    VkResult result = dev_data->device_dispatch_table->CreateSwapchainKHR(device, pCreateInfo, pAllocator, pSwapchain);
10191
10192    if (VK_SUCCESS == result) {
10193        SWAPCHAIN_NODE *psc_node = new SWAPCHAIN_NODE(pCreateInfo);
10194        loader_platform_thread_lock_mutex(&globalLock);
10195        dev_data->device_extensions.swapchainMap[*pSwapchain] = psc_node;
10196        loader_platform_thread_unlock_mutex(&globalLock);
10197    }
10198
10199    return result;
10200}
10201
10202VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
10203vkDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain, const VkAllocationCallbacks *pAllocator) {
10204    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
10205    bool skipCall = false;
10206
10207    loader_platform_thread_lock_mutex(&globalLock);
10208    auto swapchain_data = dev_data->device_extensions.swapchainMap.find(swapchain);
10209    if (swapchain_data != dev_data->device_extensions.swapchainMap.end()) {
10210        if (swapchain_data->second->images.size() > 0) {
10211            for (auto swapchain_image : swapchain_data->second->images) {
10212                auto image_sub = dev_data->imageSubresourceMap.find(swapchain_image);
10213                if (image_sub != dev_data->imageSubresourceMap.end()) {
10214                    for (auto imgsubpair : image_sub->second) {
10215                        auto image_item = dev_data->imageLayoutMap.find(imgsubpair);
10216                        if (image_item != dev_data->imageLayoutMap.end()) {
10217                            dev_data->imageLayoutMap.erase(image_item);
10218                        }
10219                    }
10220                    dev_data->imageSubresourceMap.erase(image_sub);
10221                }
10222                skipCall = clear_object_binding(dev_data, (uint64_t)swapchain_image,
10223                                                VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT);
10224                dev_data->imageMap.erase(swapchain_image);
10225            }
10226        }
10227        delete swapchain_data->second;
10228        dev_data->device_extensions.swapchainMap.erase(swapchain);
10229    }
10230    loader_platform_thread_unlock_mutex(&globalLock);
10231    if (!skipCall)
10232        dev_data->device_dispatch_table->DestroySwapchainKHR(device, swapchain, pAllocator);
10233}
10234
10235VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
10236vkGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t *pCount, VkImage *pSwapchainImages) {
10237    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
10238    VkResult result = dev_data->device_dispatch_table->GetSwapchainImagesKHR(device, swapchain, pCount, pSwapchainImages);
10239
10240    if (result == VK_SUCCESS && pSwapchainImages != NULL) {
10241        // This should never happen and is checked by param checker.
10242        if (!pCount)
10243            return result;
10244        loader_platform_thread_lock_mutex(&globalLock);
10245        const size_t count = *pCount;
10246        auto swapchain_node = dev_data->device_extensions.swapchainMap[swapchain];
10247        if (!swapchain_node->images.empty()) {
10248            // TODO : Not sure I like the memcmp here, but it works
10249            const bool mismatch = (swapchain_node->images.size() != count ||
10250                                   memcmp(&swapchain_node->images[0], pSwapchainImages, sizeof(swapchain_node->images[0]) * count));
10251            if (mismatch) {
10252                // TODO: Verify against Valid Usage section of extension
10253                log_msg(dev_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT,
10254                        (uint64_t)swapchain, __LINE__, MEMTRACK_NONE, "SWAP_CHAIN",
10255                        "vkGetSwapchainInfoKHR(%" PRIu64
10256                        ", VK_SWAP_CHAIN_INFO_TYPE_PERSISTENT_IMAGES_KHR) returned mismatching data",
10257                        (uint64_t)(swapchain));
10258            }
10259        }
10260        for (uint32_t i = 0; i < *pCount; ++i) {
10261            IMAGE_LAYOUT_NODE image_layout_node;
10262            image_layout_node.layout = VK_IMAGE_LAYOUT_UNDEFINED;
10263            image_layout_node.format = swapchain_node->createInfo.imageFormat;
10264            auto &image_node = dev_data->imageMap[pSwapchainImages[i]];
10265            image_node.createInfo.mipLevels = 1;
10266            image_node.createInfo.arrayLayers = swapchain_node->createInfo.imageArrayLayers;
10267            image_node.createInfo.usage = swapchain_node->createInfo.imageUsage;
10268            image_node.valid = false;
10269            image_node.mem = MEMTRACKER_SWAP_CHAIN_IMAGE_KEY;
10270            swapchain_node->images.push_back(pSwapchainImages[i]);
10271            ImageSubresourcePair subpair = {pSwapchainImages[i], false, VkImageSubresource()};
10272            dev_data->imageSubresourceMap[pSwapchainImages[i]].push_back(subpair);
10273            dev_data->imageLayoutMap[subpair] = image_layout_node;
10274            dev_data->device_extensions.imageToSwapchainMap[pSwapchainImages[i]] = swapchain;
10275        }
10276        loader_platform_thread_unlock_mutex(&globalLock);
10277    }
10278    return result;
10279}
10280
10281VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR *pPresentInfo) {
10282    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(queue), layer_data_map);
10283    VkResult result = VK_ERROR_VALIDATION_FAILED_EXT;
10284    bool skip_call = false;
10285
10286    if (pPresentInfo) {
10287        loader_platform_thread_lock_mutex(&globalLock);
10288        for (uint32_t i = 0; i < pPresentInfo->waitSemaphoreCount; ++i) {
10289            const VkSemaphore &semaphore = pPresentInfo->pWaitSemaphores[i];
10290            if (dev_data->semaphoreMap.find(semaphore) != dev_data->semaphoreMap.end()) {
10291                if (dev_data->semaphoreMap[semaphore].signaled) {
10292                    dev_data->semaphoreMap[semaphore].signaled = false;
10293                } else {
10294                    skip_call |=
10295                        log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT,
10296                                VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0, __LINE__, DRAWSTATE_QUEUE_FORWARD_PROGRESS, "DS",
10297                                "Queue %#" PRIx64 " is waiting on semaphore %#" PRIx64 " that has no way to be signaled.",
10298                                reinterpret_cast<uint64_t &>(queue), reinterpret_cast<const uint64_t &>(semaphore));
10299                }
10300            }
10301        }
10302        VkDeviceMemory mem;
10303        for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
10304            auto swapchain_data = dev_data->device_extensions.swapchainMap.find(pPresentInfo->pSwapchains[i]);
10305            if (swapchain_data != dev_data->device_extensions.swapchainMap.end() &&
10306                pPresentInfo->pImageIndices[i] < swapchain_data->second->images.size()) {
10307                VkImage image = swapchain_data->second->images[pPresentInfo->pImageIndices[i]];
10308#if MTMERGESOURCE
10309                skip_call |=
10310                    get_mem_binding_from_object(dev_data, (uint64_t)(image), VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, &mem);
10311                skip_call |= validate_memory_is_valid(dev_data, mem, "vkQueuePresentKHR()", image);
10312#endif
10313                vector<VkImageLayout> layouts;
10314                if (FindLayouts(dev_data, image, layouts)) {
10315                    for (auto layout : layouts) {
10316                        if (layout != VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) {
10317                            skip_call |=
10318                                log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT,
10319                                        reinterpret_cast<uint64_t &>(queue), __LINE__, DRAWSTATE_INVALID_IMAGE_LAYOUT, "DS",
10320                                        "Images passed to present must be in layout "
10321                                        "PRESENT_SOURCE_KHR but is in %s",
10322                                        string_VkImageLayout(layout));
10323                        }
10324                    }
10325                }
10326            }
10327        }
10328        loader_platform_thread_unlock_mutex(&globalLock);
10329    }
10330
10331    if (!skip_call)
10332        result = dev_data->device_dispatch_table->QueuePresentKHR(queue, pPresentInfo);
10333
10334    return result;
10335}
10336
10337VKAPI_ATTR VkResult VKAPI_CALL vkAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
10338                                                     VkSemaphore semaphore, VkFence fence, uint32_t *pImageIndex) {
10339    layer_data *dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map);
10340    VkResult result = VK_ERROR_VALIDATION_FAILED_EXT;
10341    bool skipCall = false;
10342
10343    loader_platform_thread_lock_mutex(&globalLock);
10344    if (semaphore != VK_NULL_HANDLE &&
10345        dev_data->semaphoreMap.find(semaphore) != dev_data->semaphoreMap.end()) {
10346        if (dev_data->semaphoreMap[semaphore].signaled) {
10347            skipCall = log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT,
10348                               reinterpret_cast<const uint64_t &>(semaphore), __LINE__, DRAWSTATE_QUEUE_FORWARD_PROGRESS, "DS",
10349                               "vkAcquireNextImageKHR: Semaphore must not be currently signaled or in a wait state");
10350        }
10351        dev_data->semaphoreMap[semaphore].signaled = true;
10352    }
10353    auto fence_data = dev_data->fenceMap.find(fence);
10354    if (fence_data != dev_data->fenceMap.end()) {
10355        fence_data->second.swapchain = swapchain;
10356    }
10357    loader_platform_thread_unlock_mutex(&globalLock);
10358
10359    if (!skipCall) {
10360        result =
10361            dev_data->device_dispatch_table->AcquireNextImageKHR(device, swapchain, timeout, semaphore, fence, pImageIndex);
10362    }
10363
10364    return result;
10365}
10366
10367VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
10368vkCreateDebugReportCallbackEXT(VkInstance instance, const VkDebugReportCallbackCreateInfoEXT *pCreateInfo,
10369                               const VkAllocationCallbacks *pAllocator, VkDebugReportCallbackEXT *pMsgCallback) {
10370    layer_data *my_data = get_my_data_ptr(get_dispatch_key(instance), layer_data_map);
10371    VkLayerInstanceDispatchTable *pTable = my_data->instance_dispatch_table;
10372    VkResult res = pTable->CreateDebugReportCallbackEXT(instance, pCreateInfo, pAllocator, pMsgCallback);
10373    if (VK_SUCCESS == res) {
10374        loader_platform_thread_lock_mutex(&globalLock);
10375        res = layer_create_msg_callback(my_data->report_data, pCreateInfo, pAllocator, pMsgCallback);
10376        loader_platform_thread_unlock_mutex(&globalLock);
10377    }
10378    return res;
10379}
10380
10381VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkDestroyDebugReportCallbackEXT(VkInstance instance,
10382                                                                           VkDebugReportCallbackEXT msgCallback,
10383                                                                           const VkAllocationCallbacks *pAllocator) {
10384    layer_data *my_data = get_my_data_ptr(get_dispatch_key(instance), layer_data_map);
10385    VkLayerInstanceDispatchTable *pTable = my_data->instance_dispatch_table;
10386    pTable->DestroyDebugReportCallbackEXT(instance, msgCallback, pAllocator);
10387    loader_platform_thread_lock_mutex(&globalLock);
10388    layer_destroy_msg_callback(my_data->report_data, msgCallback, pAllocator);
10389    loader_platform_thread_unlock_mutex(&globalLock);
10390}
10391
10392VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL
10393vkDebugReportMessageEXT(VkInstance instance, VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objType, uint64_t object,
10394                        size_t location, int32_t msgCode, const char *pLayerPrefix, const char *pMsg) {
10395    layer_data *my_data = get_my_data_ptr(get_dispatch_key(instance), layer_data_map);
10396    my_data->instance_dispatch_table->DebugReportMessageEXT(instance, flags, objType, object, location, msgCode, pLayerPrefix,
10397                                                            pMsg);
10398}
10399
10400VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkDevice dev, const char *funcName) {
10401    if (!strcmp(funcName, "vkGetDeviceProcAddr"))
10402        return (PFN_vkVoidFunction)vkGetDeviceProcAddr;
10403    if (!strcmp(funcName, "vkDestroyDevice"))
10404        return (PFN_vkVoidFunction)vkDestroyDevice;
10405    if (!strcmp(funcName, "vkQueueSubmit"))
10406        return (PFN_vkVoidFunction)vkQueueSubmit;
10407    if (!strcmp(funcName, "vkWaitForFences"))
10408        return (PFN_vkVoidFunction)vkWaitForFences;
10409    if (!strcmp(funcName, "vkGetFenceStatus"))
10410        return (PFN_vkVoidFunction)vkGetFenceStatus;
10411    if (!strcmp(funcName, "vkQueueWaitIdle"))
10412        return (PFN_vkVoidFunction)vkQueueWaitIdle;
10413    if (!strcmp(funcName, "vkDeviceWaitIdle"))
10414        return (PFN_vkVoidFunction)vkDeviceWaitIdle;
10415    if (!strcmp(funcName, "vkGetDeviceQueue"))
10416        return (PFN_vkVoidFunction)vkGetDeviceQueue;
10417    if (!strcmp(funcName, "vkDestroyInstance"))
10418        return (PFN_vkVoidFunction)vkDestroyInstance;
10419    if (!strcmp(funcName, "vkDestroyDevice"))
10420        return (PFN_vkVoidFunction)vkDestroyDevice;
10421    if (!strcmp(funcName, "vkDestroyFence"))
10422        return (PFN_vkVoidFunction)vkDestroyFence;
10423    if (!strcmp(funcName, "vkResetFences"))
10424        return (PFN_vkVoidFunction)vkResetFences;
10425    if (!strcmp(funcName, "vkDestroySemaphore"))
10426        return (PFN_vkVoidFunction)vkDestroySemaphore;
10427    if (!strcmp(funcName, "vkDestroyEvent"))
10428        return (PFN_vkVoidFunction)vkDestroyEvent;
10429    if (!strcmp(funcName, "vkDestroyQueryPool"))
10430        return (PFN_vkVoidFunction)vkDestroyQueryPool;
10431    if (!strcmp(funcName, "vkDestroyBuffer"))
10432        return (PFN_vkVoidFunction)vkDestroyBuffer;
10433    if (!strcmp(funcName, "vkDestroyBufferView"))
10434        return (PFN_vkVoidFunction)vkDestroyBufferView;
10435    if (!strcmp(funcName, "vkDestroyImage"))
10436        return (PFN_vkVoidFunction)vkDestroyImage;
10437    if (!strcmp(funcName, "vkDestroyImageView"))
10438        return (PFN_vkVoidFunction)vkDestroyImageView;
10439    if (!strcmp(funcName, "vkDestroyShaderModule"))
10440        return (PFN_vkVoidFunction)vkDestroyShaderModule;
10441    if (!strcmp(funcName, "vkDestroyPipeline"))
10442        return (PFN_vkVoidFunction)vkDestroyPipeline;
10443    if (!strcmp(funcName, "vkDestroyPipelineLayout"))
10444        return (PFN_vkVoidFunction)vkDestroyPipelineLayout;
10445    if (!strcmp(funcName, "vkDestroySampler"))
10446        return (PFN_vkVoidFunction)vkDestroySampler;
10447    if (!strcmp(funcName, "vkDestroyDescriptorSetLayout"))
10448        return (PFN_vkVoidFunction)vkDestroyDescriptorSetLayout;
10449    if (!strcmp(funcName, "vkDestroyDescriptorPool"))
10450        return (PFN_vkVoidFunction)vkDestroyDescriptorPool;
10451    if (!strcmp(funcName, "vkDestroyFramebuffer"))
10452        return (PFN_vkVoidFunction)vkDestroyFramebuffer;
10453    if (!strcmp(funcName, "vkDestroyRenderPass"))
10454        return (PFN_vkVoidFunction)vkDestroyRenderPass;
10455    if (!strcmp(funcName, "vkCreateBuffer"))
10456        return (PFN_vkVoidFunction)vkCreateBuffer;
10457    if (!strcmp(funcName, "vkCreateBufferView"))
10458        return (PFN_vkVoidFunction)vkCreateBufferView;
10459    if (!strcmp(funcName, "vkCreateImage"))
10460        return (PFN_vkVoidFunction)vkCreateImage;
10461    if (!strcmp(funcName, "vkCreateImageView"))
10462        return (PFN_vkVoidFunction)vkCreateImageView;
10463    if (!strcmp(funcName, "vkCreateFence"))
10464        return (PFN_vkVoidFunction)vkCreateFence;
10465    if (!strcmp(funcName, "CreatePipelineCache"))
10466        return (PFN_vkVoidFunction)vkCreatePipelineCache;
10467    if (!strcmp(funcName, "DestroyPipelineCache"))
10468        return (PFN_vkVoidFunction)vkDestroyPipelineCache;
10469    if (!strcmp(funcName, "GetPipelineCacheData"))
10470        return (PFN_vkVoidFunction)vkGetPipelineCacheData;
10471    if (!strcmp(funcName, "MergePipelineCaches"))
10472        return (PFN_vkVoidFunction)vkMergePipelineCaches;
10473    if (!strcmp(funcName, "vkCreateGraphicsPipelines"))
10474        return (PFN_vkVoidFunction)vkCreateGraphicsPipelines;
10475    if (!strcmp(funcName, "vkCreateComputePipelines"))
10476        return (PFN_vkVoidFunction)vkCreateComputePipelines;
10477    if (!strcmp(funcName, "vkCreateSampler"))
10478        return (PFN_vkVoidFunction)vkCreateSampler;
10479    if (!strcmp(funcName, "vkCreateDescriptorSetLayout"))
10480        return (PFN_vkVoidFunction)vkCreateDescriptorSetLayout;
10481    if (!strcmp(funcName, "vkCreatePipelineLayout"))
10482        return (PFN_vkVoidFunction)vkCreatePipelineLayout;
10483    if (!strcmp(funcName, "vkCreateDescriptorPool"))
10484        return (PFN_vkVoidFunction)vkCreateDescriptorPool;
10485    if (!strcmp(funcName, "vkResetDescriptorPool"))
10486        return (PFN_vkVoidFunction)vkResetDescriptorPool;
10487    if (!strcmp(funcName, "vkAllocateDescriptorSets"))
10488        return (PFN_vkVoidFunction)vkAllocateDescriptorSets;
10489    if (!strcmp(funcName, "vkFreeDescriptorSets"))
10490        return (PFN_vkVoidFunction)vkFreeDescriptorSets;
10491    if (!strcmp(funcName, "vkUpdateDescriptorSets"))
10492        return (PFN_vkVoidFunction)vkUpdateDescriptorSets;
10493    if (!strcmp(funcName, "vkCreateCommandPool"))
10494        return (PFN_vkVoidFunction)vkCreateCommandPool;
10495    if (!strcmp(funcName, "vkDestroyCommandPool"))
10496        return (PFN_vkVoidFunction)vkDestroyCommandPool;
10497    if (!strcmp(funcName, "vkResetCommandPool"))
10498        return (PFN_vkVoidFunction)vkResetCommandPool;
10499    if (!strcmp(funcName, "vkCreateQueryPool"))
10500        return (PFN_vkVoidFunction)vkCreateQueryPool;
10501    if (!strcmp(funcName, "vkAllocateCommandBuffers"))
10502        return (PFN_vkVoidFunction)vkAllocateCommandBuffers;
10503    if (!strcmp(funcName, "vkFreeCommandBuffers"))
10504        return (PFN_vkVoidFunction)vkFreeCommandBuffers;
10505    if (!strcmp(funcName, "vkBeginCommandBuffer"))
10506        return (PFN_vkVoidFunction)vkBeginCommandBuffer;
10507    if (!strcmp(funcName, "vkEndCommandBuffer"))
10508        return (PFN_vkVoidFunction)vkEndCommandBuffer;
10509    if (!strcmp(funcName, "vkResetCommandBuffer"))
10510        return (PFN_vkVoidFunction)vkResetCommandBuffer;
10511    if (!strcmp(funcName, "vkCmdBindPipeline"))
10512        return (PFN_vkVoidFunction)vkCmdBindPipeline;
10513    if (!strcmp(funcName, "vkCmdSetViewport"))
10514        return (PFN_vkVoidFunction)vkCmdSetViewport;
10515    if (!strcmp(funcName, "vkCmdSetScissor"))
10516        return (PFN_vkVoidFunction)vkCmdSetScissor;
10517    if (!strcmp(funcName, "vkCmdSetLineWidth"))
10518        return (PFN_vkVoidFunction)vkCmdSetLineWidth;
10519    if (!strcmp(funcName, "vkCmdSetDepthBias"))
10520        return (PFN_vkVoidFunction)vkCmdSetDepthBias;
10521    if (!strcmp(funcName, "vkCmdSetBlendConstants"))
10522        return (PFN_vkVoidFunction)vkCmdSetBlendConstants;
10523    if (!strcmp(funcName, "vkCmdSetDepthBounds"))
10524        return (PFN_vkVoidFunction)vkCmdSetDepthBounds;
10525    if (!strcmp(funcName, "vkCmdSetStencilCompareMask"))
10526        return (PFN_vkVoidFunction)vkCmdSetStencilCompareMask;
10527    if (!strcmp(funcName, "vkCmdSetStencilWriteMask"))
10528        return (PFN_vkVoidFunction)vkCmdSetStencilWriteMask;
10529    if (!strcmp(funcName, "vkCmdSetStencilReference"))
10530        return (PFN_vkVoidFunction)vkCmdSetStencilReference;
10531    if (!strcmp(funcName, "vkCmdBindDescriptorSets"))
10532        return (PFN_vkVoidFunction)vkCmdBindDescriptorSets;
10533    if (!strcmp(funcName, "vkCmdBindVertexBuffers"))
10534        return (PFN_vkVoidFunction)vkCmdBindVertexBuffers;
10535    if (!strcmp(funcName, "vkCmdBindIndexBuffer"))
10536        return (PFN_vkVoidFunction)vkCmdBindIndexBuffer;
10537    if (!strcmp(funcName, "vkCmdDraw"))
10538        return (PFN_vkVoidFunction)vkCmdDraw;
10539    if (!strcmp(funcName, "vkCmdDrawIndexed"))
10540        return (PFN_vkVoidFunction)vkCmdDrawIndexed;
10541    if (!strcmp(funcName, "vkCmdDrawIndirect"))
10542        return (PFN_vkVoidFunction)vkCmdDrawIndirect;
10543    if (!strcmp(funcName, "vkCmdDrawIndexedIndirect"))
10544        return (PFN_vkVoidFunction)vkCmdDrawIndexedIndirect;
10545    if (!strcmp(funcName, "vkCmdDispatch"))
10546        return (PFN_vkVoidFunction)vkCmdDispatch;
10547    if (!strcmp(funcName, "vkCmdDispatchIndirect"))
10548        return (PFN_vkVoidFunction)vkCmdDispatchIndirect;
10549    if (!strcmp(funcName, "vkCmdCopyBuffer"))
10550        return (PFN_vkVoidFunction)vkCmdCopyBuffer;
10551    if (!strcmp(funcName, "vkCmdCopyImage"))
10552        return (PFN_vkVoidFunction)vkCmdCopyImage;
10553    if (!strcmp(funcName, "vkCmdBlitImage"))
10554        return (PFN_vkVoidFunction)vkCmdBlitImage;
10555    if (!strcmp(funcName, "vkCmdCopyBufferToImage"))
10556        return (PFN_vkVoidFunction)vkCmdCopyBufferToImage;
10557    if (!strcmp(funcName, "vkCmdCopyImageToBuffer"))
10558        return (PFN_vkVoidFunction)vkCmdCopyImageToBuffer;
10559    if (!strcmp(funcName, "vkCmdUpdateBuffer"))
10560        return (PFN_vkVoidFunction)vkCmdUpdateBuffer;
10561    if (!strcmp(funcName, "vkCmdFillBuffer"))
10562        return (PFN_vkVoidFunction)vkCmdFillBuffer;
10563    if (!strcmp(funcName, "vkCmdClearColorImage"))
10564        return (PFN_vkVoidFunction)vkCmdClearColorImage;
10565    if (!strcmp(funcName, "vkCmdClearDepthStencilImage"))
10566        return (PFN_vkVoidFunction)vkCmdClearDepthStencilImage;
10567    if (!strcmp(funcName, "vkCmdClearAttachments"))
10568        return (PFN_vkVoidFunction)vkCmdClearAttachments;
10569    if (!strcmp(funcName, "vkCmdResolveImage"))
10570        return (PFN_vkVoidFunction)vkCmdResolveImage;
10571    if (!strcmp(funcName, "vkCmdSetEvent"))
10572        return (PFN_vkVoidFunction)vkCmdSetEvent;
10573    if (!strcmp(funcName, "vkCmdResetEvent"))
10574        return (PFN_vkVoidFunction)vkCmdResetEvent;
10575    if (!strcmp(funcName, "vkCmdWaitEvents"))
10576        return (PFN_vkVoidFunction)vkCmdWaitEvents;
10577    if (!strcmp(funcName, "vkCmdPipelineBarrier"))
10578        return (PFN_vkVoidFunction)vkCmdPipelineBarrier;
10579    if (!strcmp(funcName, "vkCmdBeginQuery"))
10580        return (PFN_vkVoidFunction)vkCmdBeginQuery;
10581    if (!strcmp(funcName, "vkCmdEndQuery"))
10582        return (PFN_vkVoidFunction)vkCmdEndQuery;
10583    if (!strcmp(funcName, "vkCmdResetQueryPool"))
10584        return (PFN_vkVoidFunction)vkCmdResetQueryPool;
10585    if (!strcmp(funcName, "vkCmdCopyQueryPoolResults"))
10586        return (PFN_vkVoidFunction)vkCmdCopyQueryPoolResults;
10587    if (!strcmp(funcName, "vkCmdPushConstants"))
10588        return (PFN_vkVoidFunction)vkCmdPushConstants;
10589    if (!strcmp(funcName, "vkCmdWriteTimestamp"))
10590        return (PFN_vkVoidFunction)vkCmdWriteTimestamp;
10591    if (!strcmp(funcName, "vkCreateFramebuffer"))
10592        return (PFN_vkVoidFunction)vkCreateFramebuffer;
10593    if (!strcmp(funcName, "vkCreateShaderModule"))
10594        return (PFN_vkVoidFunction)vkCreateShaderModule;
10595    if (!strcmp(funcName, "vkCreateRenderPass"))
10596        return (PFN_vkVoidFunction)vkCreateRenderPass;
10597    if (!strcmp(funcName, "vkCmdBeginRenderPass"))
10598        return (PFN_vkVoidFunction)vkCmdBeginRenderPass;
10599    if (!strcmp(funcName, "vkCmdNextSubpass"))
10600        return (PFN_vkVoidFunction)vkCmdNextSubpass;
10601    if (!strcmp(funcName, "vkCmdEndRenderPass"))
10602        return (PFN_vkVoidFunction)vkCmdEndRenderPass;
10603    if (!strcmp(funcName, "vkCmdExecuteCommands"))
10604        return (PFN_vkVoidFunction)vkCmdExecuteCommands;
10605    if (!strcmp(funcName, "vkSetEvent"))
10606        return (PFN_vkVoidFunction)vkSetEvent;
10607    if (!strcmp(funcName, "vkMapMemory"))
10608        return (PFN_vkVoidFunction)vkMapMemory;
10609#if MTMERGESOURCE
10610    if (!strcmp(funcName, "vkUnmapMemory"))
10611        return (PFN_vkVoidFunction)vkUnmapMemory;
10612    if (!strcmp(funcName, "vkAllocateMemory"))
10613        return (PFN_vkVoidFunction)vkAllocateMemory;
10614    if (!strcmp(funcName, "vkFreeMemory"))
10615        return (PFN_vkVoidFunction)vkFreeMemory;
10616    if (!strcmp(funcName, "vkFlushMappedMemoryRanges"))
10617        return (PFN_vkVoidFunction)vkFlushMappedMemoryRanges;
10618    if (!strcmp(funcName, "vkInvalidateMappedMemoryRanges"))
10619        return (PFN_vkVoidFunction)vkInvalidateMappedMemoryRanges;
10620    if (!strcmp(funcName, "vkBindBufferMemory"))
10621        return (PFN_vkVoidFunction)vkBindBufferMemory;
10622    if (!strcmp(funcName, "vkGetBufferMemoryRequirements"))
10623        return (PFN_vkVoidFunction)vkGetBufferMemoryRequirements;
10624    if (!strcmp(funcName, "vkGetImageMemoryRequirements"))
10625        return (PFN_vkVoidFunction)vkGetImageMemoryRequirements;
10626#endif
10627    if (!strcmp(funcName, "vkGetQueryPoolResults"))
10628        return (PFN_vkVoidFunction)vkGetQueryPoolResults;
10629    if (!strcmp(funcName, "vkBindImageMemory"))
10630        return (PFN_vkVoidFunction)vkBindImageMemory;
10631    if (!strcmp(funcName, "vkQueueBindSparse"))
10632        return (PFN_vkVoidFunction)vkQueueBindSparse;
10633    if (!strcmp(funcName, "vkCreateSemaphore"))
10634        return (PFN_vkVoidFunction)vkCreateSemaphore;
10635    if (!strcmp(funcName, "vkCreateEvent"))
10636        return (PFN_vkVoidFunction)vkCreateEvent;
10637
10638    if (dev == NULL)
10639        return NULL;
10640
10641    layer_data *dev_data;
10642    dev_data = get_my_data_ptr(get_dispatch_key(dev), layer_data_map);
10643
10644    if (dev_data->device_extensions.wsi_enabled) {
10645        if (!strcmp(funcName, "vkCreateSwapchainKHR"))
10646            return (PFN_vkVoidFunction)vkCreateSwapchainKHR;
10647        if (!strcmp(funcName, "vkDestroySwapchainKHR"))
10648            return (PFN_vkVoidFunction)vkDestroySwapchainKHR;
10649        if (!strcmp(funcName, "vkGetSwapchainImagesKHR"))
10650            return (PFN_vkVoidFunction)vkGetSwapchainImagesKHR;
10651        if (!strcmp(funcName, "vkAcquireNextImageKHR"))
10652            return (PFN_vkVoidFunction)vkAcquireNextImageKHR;
10653        if (!strcmp(funcName, "vkQueuePresentKHR"))
10654            return (PFN_vkVoidFunction)vkQueuePresentKHR;
10655    }
10656
10657    VkLayerDispatchTable *pTable = dev_data->device_dispatch_table;
10658    {
10659        if (pTable->GetDeviceProcAddr == NULL)
10660            return NULL;
10661        return pTable->GetDeviceProcAddr(dev, funcName);
10662    }
10663}
10664
10665VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr(VkInstance instance, const char *funcName) {
10666    if (!strcmp(funcName, "vkGetInstanceProcAddr"))
10667        return (PFN_vkVoidFunction)vkGetInstanceProcAddr;
10668    if (!strcmp(funcName, "vkGetDeviceProcAddr"))
10669        return (PFN_vkVoidFunction)vkGetDeviceProcAddr;
10670    if (!strcmp(funcName, "vkCreateInstance"))
10671        return (PFN_vkVoidFunction)vkCreateInstance;
10672    if (!strcmp(funcName, "vkCreateDevice"))
10673        return (PFN_vkVoidFunction)vkCreateDevice;
10674    if (!strcmp(funcName, "vkDestroyInstance"))
10675        return (PFN_vkVoidFunction)vkDestroyInstance;
10676    if (!strcmp(funcName, "vkEnumerateInstanceLayerProperties"))
10677        return (PFN_vkVoidFunction)vkEnumerateInstanceLayerProperties;
10678    if (!strcmp(funcName, "vkEnumerateInstanceExtensionProperties"))
10679        return (PFN_vkVoidFunction)vkEnumerateInstanceExtensionProperties;
10680    if (!strcmp(funcName, "vkEnumerateDeviceLayerProperties"))
10681        return (PFN_vkVoidFunction)vkEnumerateDeviceLayerProperties;
10682    if (!strcmp(funcName, "vkEnumerateDeviceExtensionProperties"))
10683        return (PFN_vkVoidFunction)vkEnumerateDeviceExtensionProperties;
10684
10685    if (instance == NULL)
10686        return NULL;
10687
10688    PFN_vkVoidFunction fptr;
10689
10690    layer_data *my_data;
10691    my_data = get_my_data_ptr(get_dispatch_key(instance), layer_data_map);
10692    fptr = debug_report_get_instance_proc_addr(my_data->report_data, funcName);
10693    if (fptr)
10694        return fptr;
10695
10696    VkLayerInstanceDispatchTable *pTable = my_data->instance_dispatch_table;
10697    if (pTable->GetInstanceProcAddr == NULL)
10698        return NULL;
10699    return pTable->GetInstanceProcAddr(instance, funcName);
10700}
10701