• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (c) 2015-2019 The Khronos Group Inc.
2  * Copyright (c) 2015-2019 Valve Corporation
3  * Copyright (c) 2015-2019 LunarG, Inc.
4  * Copyright (C) 2015-2019 Google Inc.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * Author: Mark Lobodzinski <mark@lunarg.com>
19  * Author: Dave Houlton <daveh@lunarg.com>
20  * Shannon McPherson <shannon@lunarg.com>
21  */
22 
23 // Allow use of STL min and max functions in Windows
24 #define NOMINMAX
25 
26 #include <cmath>
27 #include <set>
28 #include <sstream>
29 #include <string>
30 
31 #include "vk_enum_string_helper.h"
32 #include "vk_format_utils.h"
33 #include "vk_layer_data.h"
34 #include "vk_layer_utils.h"
35 #include "vk_layer_logging.h"
36 #include "vk_typemap_helper.h"
37 
38 #include "chassis.h"
39 #include "core_validation.h"
40 #include "shader_validation.h"
41 #include "descriptor_sets.h"
42 #include "buffer_validation.h"
43 
44 // Transfer VkImageSubresourceLayers into VkImageSubresourceRange struct
RangeFromLayers(const VkImageSubresourceLayers & subresource_layers)45 static VkImageSubresourceRange RangeFromLayers(const VkImageSubresourceLayers &subresource_layers) {
46     VkImageSubresourceRange subresource_range;
47     subresource_range.aspectMask = subresource_layers.aspectMask;
48     subresource_range.baseArrayLayer = subresource_layers.baseArrayLayer;
49     subresource_range.layerCount = subresource_layers.layerCount;
50     subresource_range.baseMipLevel = subresource_layers.mipLevel;
51     subresource_range.levelCount = 1;
52     return subresource_range;
53 }
54 
IMAGE_STATE(VkImage img,const VkImageCreateInfo * pCreateInfo)55 IMAGE_STATE::IMAGE_STATE(VkImage img, const VkImageCreateInfo *pCreateInfo)
56     : image(img),
57       createInfo(*pCreateInfo),
58       valid(false),
59       acquired(false),
60       shared_presentable(false),
61       layout_locked(false),
62       get_sparse_reqs_called(false),
63       sparse_metadata_required(false),
64       sparse_metadata_bound(false),
65       imported_ahb(false),
66       has_ahb_format(false),
67       ahb_format(0),
68       full_range{},
69       create_from_swapchain(VK_NULL_HANDLE),
70       bind_swapchain(VK_NULL_HANDLE),
71       bind_swapchain_imageIndex(0),
72       sparse_requirements{} {
73     if ((createInfo.sharingMode == VK_SHARING_MODE_CONCURRENT) && (createInfo.queueFamilyIndexCount > 0)) {
74         uint32_t *pQueueFamilyIndices = new uint32_t[createInfo.queueFamilyIndexCount];
75         for (uint32_t i = 0; i < createInfo.queueFamilyIndexCount; i++) {
76             pQueueFamilyIndices[i] = pCreateInfo->pQueueFamilyIndices[i];
77         }
78         createInfo.pQueueFamilyIndices = pQueueFamilyIndices;
79     }
80 
81     if (createInfo.flags & VK_IMAGE_CREATE_SPARSE_BINDING_BIT) {
82         sparse = true;
83     }
84     const auto format = createInfo.format;
85     VkImageSubresourceRange init_range{0, 0, VK_REMAINING_MIP_LEVELS, 0, VK_REMAINING_ARRAY_LAYERS};
86     if (FormatIsColor(format) || FormatIsMultiplane(format)) {
87         init_range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;  // Normalization will expand this for multiplane
88     } else {
89         init_range.aspectMask =
90             (FormatHasDepth(format) ? VK_IMAGE_ASPECT_DEPTH_BIT : 0) | (FormatHasStencil(format) ? VK_IMAGE_ASPECT_STENCIL_BIT : 0);
91     }
92     full_range = NormalizeSubresourceRange(*this, init_range);
93 
94 #ifdef VK_USE_PLATFORM_ANDROID_KHR
95     auto external_format = lvl_find_in_chain<VkExternalFormatANDROID>(createInfo.pNext);
96     if (external_format) {
97         external_format_android = external_format->externalFormat;
98     } else {
99         // If externalFormat is zero, the effect is as if the VkExternalFormatANDROID structure was not present.
100         external_format_android = 0;
101     }
102 #endif  // VK_USE_PLATFORM_ANDROID_KHR
103 }
104 
IMAGE_VIEW_STATE(const IMAGE_STATE * image_state,VkImageView iv,const VkImageViewCreateInfo * ci)105 IMAGE_VIEW_STATE::IMAGE_VIEW_STATE(const IMAGE_STATE *image_state, VkImageView iv, const VkImageViewCreateInfo *ci)
106     : image_view(iv), create_info(*ci), normalized_subresource_range(ci->subresourceRange), samplerConversion(VK_NULL_HANDLE) {
107     auto *conversionInfo = lvl_find_in_chain<VkSamplerYcbcrConversionInfo>(create_info.pNext);
108     if (conversionInfo) samplerConversion = conversionInfo->conversion;
109     if (image_state) {
110         // A light normalization of the createInfo range
111         auto &sub_res_range = create_info.subresourceRange;
112         sub_res_range.levelCount = ResolveRemainingLevels(&sub_res_range, image_state->createInfo.mipLevels);
113         sub_res_range.layerCount = ResolveRemainingLayers(&sub_res_range, image_state->createInfo.arrayLayers);
114 
115         // Cache a full normalization (for "full image/whole image" comparisons)
116         normalized_subresource_range = NormalizeSubresourceRange(*image_state, ci->subresourceRange);
117         samples = image_state->createInfo.samples;
118         descriptor_format_bits = DescriptorRequirementsBitsFromFormat(create_info.format);
119     }
120 }
121 
FullMipChainLevels(uint32_t height,uint32_t width,uint32_t depth)122 uint32_t FullMipChainLevels(uint32_t height, uint32_t width, uint32_t depth) {
123     // uint cast applies floor()
124     return 1u + (uint32_t)log2(std::max({height, width, depth}));
125 }
126 
FullMipChainLevels(VkExtent3D extent)127 uint32_t FullMipChainLevels(VkExtent3D extent) { return FullMipChainLevels(extent.height, extent.width, extent.depth); }
128 
FullMipChainLevels(VkExtent2D extent)129 uint32_t FullMipChainLevels(VkExtent2D extent) { return FullMipChainLevels(extent.height, extent.width); }
130 
NormalizeSubresourceRange(const IMAGE_STATE & image_state,const VkImageSubresourceRange & range)131 VkImageSubresourceRange NormalizeSubresourceRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &range) {
132     const VkImageCreateInfo &image_create_info = image_state.createInfo;
133     VkImageSubresourceRange norm = range;
134     norm.levelCount = ResolveRemainingLevels(&range, image_create_info.mipLevels);
135 
136     // Special case for 3D images with VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR flag bit, where <extent.depth> and
137     // <arrayLayers> can potentially alias.
138     uint32_t layer_limit = (0 != (image_create_info.flags & VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR))
139                                ? image_create_info.extent.depth
140                                : image_create_info.arrayLayers;
141     norm.layerCount = ResolveRemainingLayers(&range, layer_limit);
142 
143     // For multiplanar formats, IMAGE_ASPECT_COLOR is equivalent to adding the aspect of the individual planes
144     VkImageAspectFlags &aspect_mask = norm.aspectMask;
145     if (FormatIsMultiplane(image_create_info.format)) {
146         if (aspect_mask & VK_IMAGE_ASPECT_COLOR_BIT) {
147             aspect_mask &= ~VK_IMAGE_ASPECT_COLOR_BIT;
148             aspect_mask |= (VK_IMAGE_ASPECT_PLANE_0_BIT | VK_IMAGE_ASPECT_PLANE_1_BIT);
149             if (FormatPlaneCount(image_create_info.format) > 2) {
150                 aspect_mask |= VK_IMAGE_ASPECT_PLANE_2_BIT;
151             }
152         }
153     }
154     return norm;
155 }
156 
157 template <class OBJECT, class LAYOUT>
SetLayout(OBJECT * pObject,VkImage image,VkImageSubresource range,const LAYOUT & layout)158 void CoreChecks::SetLayout(OBJECT *pObject, VkImage image, VkImageSubresource range, const LAYOUT &layout) {
159     ImageSubresourcePair imgpair = {image, true, range};
160     SetLayout(pObject, imgpair, layout, VK_IMAGE_ASPECT_COLOR_BIT);
161     SetLayout(pObject, imgpair, layout, VK_IMAGE_ASPECT_DEPTH_BIT);
162     SetLayout(pObject, imgpair, layout, VK_IMAGE_ASPECT_STENCIL_BIT);
163     SetLayout(pObject, imgpair, layout, VK_IMAGE_ASPECT_METADATA_BIT);
164     if (device_extensions.vk_khr_sampler_ycbcr_conversion) {
165         SetLayout(pObject, imgpair, layout, VK_IMAGE_ASPECT_PLANE_0_BIT_KHR);
166         SetLayout(pObject, imgpair, layout, VK_IMAGE_ASPECT_PLANE_1_BIT_KHR);
167         SetLayout(pObject, imgpair, layout, VK_IMAGE_ASPECT_PLANE_2_BIT_KHR);
168     }
169 }
170 
171 template <class OBJECT, class LAYOUT>
SetLayout(OBJECT * pObject,ImageSubresourcePair imgpair,const LAYOUT & layout,VkImageAspectFlags aspectMask)172 void CoreChecks::SetLayout(OBJECT *pObject, ImageSubresourcePair imgpair, const LAYOUT &layout, VkImageAspectFlags aspectMask) {
173     if (imgpair.subresource.aspectMask & aspectMask) {
174         imgpair.subresource.aspectMask = aspectMask;
175         SetLayout(pObject, imgpair, layout);
176     }
177 }
178 
179 // Set the layout in supplied map
SetLayout(ImageSubresPairLayoutMap & imageLayoutMap,ImageSubresourcePair imgpair,VkImageLayout layout)180 void CoreChecks::SetLayout(ImageSubresPairLayoutMap &imageLayoutMap, ImageSubresourcePair imgpair, VkImageLayout layout) {
181     auto it = imageLayoutMap.find(imgpair);
182     if (it != imageLayoutMap.end()) {
183         it->second.layout = layout;  // Update
184     } else {
185         imageLayoutMap[imgpair].layout = layout;  // Insert
186     }
187 }
188 
FindLayoutVerifyLayout(ImageSubresourcePair imgpair,VkImageLayout & layout,const VkImageAspectFlags aspectMask)189 bool CoreChecks::FindLayoutVerifyLayout(ImageSubresourcePair imgpair, VkImageLayout &layout, const VkImageAspectFlags aspectMask) {
190     if (!(imgpair.subresource.aspectMask & aspectMask)) {
191         return false;
192     }
193     VkImageAspectFlags oldAspectMask = imgpair.subresource.aspectMask;
194     imgpair.subresource.aspectMask = aspectMask;
195     auto imgsubIt = imageLayoutMap.find(imgpair);
196     if (imgsubIt == imageLayoutMap.end()) {
197         return false;
198     }
199     if (layout != VK_IMAGE_LAYOUT_MAX_ENUM && layout != imgsubIt->second.layout) {
200         log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(imgpair.image),
201                 kVUID_Core_DrawState_InvalidLayout,
202                 "Cannot query for %s layout when combined aspect mask %d has multiple layout types: %s and %s",
203                 report_data->FormatHandle(imgpair.image).c_str(), oldAspectMask, string_VkImageLayout(layout),
204                 string_VkImageLayout(imgsubIt->second.layout));
205     }
206     layout = imgsubIt->second.layout;
207     return true;
208 }
209 
210 // Find layout(s) on the global level
FindGlobalLayout(ImageSubresourcePair imgpair,VkImageLayout & layout)211 bool CoreChecks::FindGlobalLayout(ImageSubresourcePair imgpair, VkImageLayout &layout) {
212     layout = VK_IMAGE_LAYOUT_MAX_ENUM;
213     FindLayoutVerifyLayout(imgpair, layout, VK_IMAGE_ASPECT_COLOR_BIT);
214     FindLayoutVerifyLayout(imgpair, layout, VK_IMAGE_ASPECT_DEPTH_BIT);
215     FindLayoutVerifyLayout(imgpair, layout, VK_IMAGE_ASPECT_STENCIL_BIT);
216     FindLayoutVerifyLayout(imgpair, layout, VK_IMAGE_ASPECT_METADATA_BIT);
217     if (device_extensions.vk_khr_sampler_ycbcr_conversion) {
218         FindLayoutVerifyLayout(imgpair, layout, VK_IMAGE_ASPECT_PLANE_0_BIT_KHR);
219         FindLayoutVerifyLayout(imgpair, layout, VK_IMAGE_ASPECT_PLANE_1_BIT_KHR);
220         FindLayoutVerifyLayout(imgpair, layout, VK_IMAGE_ASPECT_PLANE_2_BIT_KHR);
221     }
222     if (layout == VK_IMAGE_LAYOUT_MAX_ENUM) {
223         imgpair = {imgpair.image, false, VkImageSubresource()};
224         auto imgsubIt = imageLayoutMap.find(imgpair);
225         if (imgsubIt == imageLayoutMap.end()) return false;
226         layout = imgsubIt->second.layout;
227     }
228     return true;
229 }
230 
FindLayouts(VkImage image,std::vector<VkImageLayout> & layouts)231 bool CoreChecks::FindLayouts(VkImage image, std::vector<VkImageLayout> &layouts) {
232     auto sub_data = imageSubresourceMap.find(image);
233     if (sub_data == imageSubresourceMap.end()) return false;
234     auto image_state = GetImageState(image);
235     if (!image_state) return false;
236     bool ignoreGlobal = false;
237     // TODO: Make this robust for >1 aspect mask. Now it will just say ignore potential errors in this case.
238     if (sub_data->second.size() >= (image_state->createInfo.arrayLayers * image_state->createInfo.mipLevels + 1)) {
239         ignoreGlobal = true;
240     }
241     for (auto imgsubpair : sub_data->second) {
242         if (ignoreGlobal && !imgsubpair.hasSubresource) continue;
243         auto img_data = imageLayoutMap.find(imgsubpair);
244         if (img_data != imageLayoutMap.end()) {
245             layouts.push_back(img_data->second.layout);
246         }
247     }
248     return true;
249 }
250 
FindLayout(const ImageSubresPairLayoutMap & imageLayoutMap,ImageSubresourcePair imgpair,VkImageLayout & layout,const VkImageAspectFlags aspectMask)251 bool CoreChecks::FindLayout(const ImageSubresPairLayoutMap &imageLayoutMap, ImageSubresourcePair imgpair, VkImageLayout &layout,
252                             const VkImageAspectFlags aspectMask) {
253     if (!(imgpair.subresource.aspectMask & aspectMask)) {
254         return false;
255     }
256     imgpair.subresource.aspectMask = aspectMask;
257     auto imgsubIt = imageLayoutMap.find(imgpair);
258     if (imgsubIt == imageLayoutMap.end()) {
259         return false;
260     }
261     layout = imgsubIt->second.layout;
262     return true;
263 }
264 
265 // find layout in supplied map
FindLayout(const ImageSubresPairLayoutMap & imageLayoutMap,ImageSubresourcePair imgpair,VkImageLayout & layout) const266 bool CoreChecks::FindLayout(const ImageSubresPairLayoutMap &imageLayoutMap, ImageSubresourcePair imgpair,
267                             VkImageLayout &layout) const {
268     layout = VK_IMAGE_LAYOUT_MAX_ENUM;
269     FindLayout(imageLayoutMap, imgpair, layout, VK_IMAGE_ASPECT_COLOR_BIT);
270     FindLayout(imageLayoutMap, imgpair, layout, VK_IMAGE_ASPECT_DEPTH_BIT);
271     FindLayout(imageLayoutMap, imgpair, layout, VK_IMAGE_ASPECT_STENCIL_BIT);
272     FindLayout(imageLayoutMap, imgpair, layout, VK_IMAGE_ASPECT_METADATA_BIT);
273     if (device_extensions.vk_khr_sampler_ycbcr_conversion) {
274         FindLayout(imageLayoutMap, imgpair, layout, VK_IMAGE_ASPECT_PLANE_0_BIT_KHR);
275         FindLayout(imageLayoutMap, imgpair, layout, VK_IMAGE_ASPECT_PLANE_1_BIT_KHR);
276         FindLayout(imageLayoutMap, imgpair, layout, VK_IMAGE_ASPECT_PLANE_2_BIT_KHR);
277     }
278     // Image+subresource not found, look for image handle w/o subresource
279     if (layout == VK_IMAGE_LAYOUT_MAX_ENUM) {
280         imgpair = {imgpair.image, false, VkImageSubresource()};
281         auto imgsubIt = imageLayoutMap.find(imgpair);
282         if (imgsubIt == imageLayoutMap.end()) return false;
283         layout = imgsubIt->second.layout;
284     }
285     return true;
286 }
287 
288 // Set the layout on the global level
SetGlobalLayout(ImageSubresourcePair imgpair,const VkImageLayout & layout)289 void CoreChecks::SetGlobalLayout(ImageSubresourcePair imgpair, const VkImageLayout &layout) {
290     VkImage &image = imgpair.image;
291     auto data = imageLayoutMap.find(imgpair);
292     if (data != imageLayoutMap.end()) {
293         data->second.layout = layout;  // Update
294     } else {
295         imageLayoutMap[imgpair].layout = layout;  // Insert
296     }
297     auto &image_subresources = imageSubresourceMap[image];
298     auto subresource = std::find(image_subresources.begin(), image_subresources.end(), imgpair);
299     if (subresource == image_subresources.end()) {
300         image_subresources.push_back(imgpair);
301     }
302 }
303 
304 // Set image layout for given VkImageSubresourceRange struct
SetImageLayout(CMD_BUFFER_STATE * cb_node,const IMAGE_STATE & image_state,const VkImageSubresourceRange & image_subresource_range,VkImageLayout layout,VkImageLayout expected_layout)305 void CoreChecks::SetImageLayout(CMD_BUFFER_STATE *cb_node, const IMAGE_STATE &image_state,
306                                 const VkImageSubresourceRange &image_subresource_range, VkImageLayout layout,
307                                 VkImageLayout expected_layout) {
308     auto *subresource_map = GetImageSubresourceLayoutMap(cb_node, image_state);
309     assert(subresource_map);  // the non-const getter must return a valid pointer
310     if (subresource_map->SetSubresourceRangeLayout(*cb_node, image_subresource_range, layout, expected_layout)) {
311         cb_node->image_layout_change_count++;  // Change the version of this data to force revalidation
312     }
313 }
314 
315 // Set the initial image layout for all slices of an image view
SetImageViewInitialLayout(CMD_BUFFER_STATE * cb_node,const IMAGE_VIEW_STATE & view_state,VkImageLayout layout)316 void CoreChecks::SetImageViewInitialLayout(CMD_BUFFER_STATE *cb_node, const IMAGE_VIEW_STATE &view_state, VkImageLayout layout) {
317     if (disabled.image_layout_validation) {
318         return;
319     }
320     IMAGE_STATE *image_state = GetImageState(view_state.create_info.image);
321     if (image_state) {
322         auto *subresource_map = GetImageSubresourceLayoutMap(cb_node, *image_state);
323         subresource_map->SetSubresourceRangeInitialLayout(*cb_node, view_state.normalized_subresource_range, layout, &view_state);
324     }
325 }
326 
327 // Set the initial image layout for a passed non-normalized subresource range
SetImageInitialLayout(CMD_BUFFER_STATE * cb_node,const IMAGE_STATE & image_state,const VkImageSubresourceRange & range,VkImageLayout layout)328 void CoreChecks::SetImageInitialLayout(CMD_BUFFER_STATE *cb_node, const IMAGE_STATE &image_state,
329                                        const VkImageSubresourceRange &range, VkImageLayout layout) {
330     auto *subresource_map = GetImageSubresourceLayoutMap(cb_node, image_state);
331     assert(subresource_map);
332     subresource_map->SetSubresourceRangeInitialLayout(*cb_node, NormalizeSubresourceRange(image_state, range), layout);
333 }
334 
SetImageInitialLayout(CMD_BUFFER_STATE * cb_node,VkImage image,const VkImageSubresourceRange & range,VkImageLayout layout)335 void CoreChecks::SetImageInitialLayout(CMD_BUFFER_STATE *cb_node, VkImage image, const VkImageSubresourceRange &range,
336                                        VkImageLayout layout) {
337     const IMAGE_STATE *image_state = GetImageState(image);
338     if (!image_state) return;
339     SetImageInitialLayout(cb_node, *image_state, range, layout);
340 };
341 
SetImageInitialLayout(CMD_BUFFER_STATE * cb_node,const IMAGE_STATE & image_state,const VkImageSubresourceLayers & layers,VkImageLayout layout)342 void CoreChecks::SetImageInitialLayout(CMD_BUFFER_STATE *cb_node, const IMAGE_STATE &image_state,
343                                        const VkImageSubresourceLayers &layers, VkImageLayout layout) {
344     SetImageInitialLayout(cb_node, image_state, RangeFromLayers(layers), layout);
345 }
346 
347 // Set image layout for all slices of an image view
SetImageViewLayout(CMD_BUFFER_STATE * cb_node,const IMAGE_VIEW_STATE & view_state,VkImageLayout layout)348 void CoreChecks::SetImageViewLayout(CMD_BUFFER_STATE *cb_node, const IMAGE_VIEW_STATE &view_state, VkImageLayout layout) {
349     IMAGE_STATE *image_state = GetImageState(view_state.create_info.image);
350     if (!image_state) return;  // TODO: track/report stale image references
351 
352     VkImageSubresourceRange sub_range = view_state.normalized_subresource_range;
353     // When changing the layout of a 3D image subresource via a 2D or 2D_ARRRAY image view, all depth slices of
354     // the subresource mip level(s) are transitioned, ignoring any layers restriction in the subresource info.
355     if ((image_state->createInfo.imageType == VK_IMAGE_TYPE_3D) && (view_state.create_info.viewType != VK_IMAGE_VIEW_TYPE_3D)) {
356         sub_range.baseArrayLayer = 0;
357         sub_range.layerCount = image_state->createInfo.extent.depth;
358     }
359 
360     SetImageLayout(cb_node, *image_state, sub_range, layout);
361 }
362 
ValidateRenderPassLayoutAgainstFramebufferImageUsage(RenderPassCreateVersion rp_version,VkImageLayout layout,VkImage image,VkImageView image_view,VkFramebuffer framebuffer,VkRenderPass renderpass,uint32_t attachment_index,const char * variable_name) const363 bool CoreChecks::ValidateRenderPassLayoutAgainstFramebufferImageUsage(RenderPassCreateVersion rp_version, VkImageLayout layout,
364                                                                       VkImage image, VkImageView image_view,
365                                                                       VkFramebuffer framebuffer, VkRenderPass renderpass,
366                                                                       uint32_t attachment_index, const char *variable_name) const {
367     bool skip = false;
368     auto image_state = GetImageState(image);
369     const char *vuid;
370     const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2);
371 
372     if (!image_state) {
373         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(image),
374                         "VUID-VkRenderPassBeginInfo-framebuffer-parameter",
375                         "Render Pass begin with %s uses %s where pAttachments[%" PRIu32 "] = %s, which refers to an invalid image",
376                         report_data->FormatHandle(renderpass).c_str(), report_data->FormatHandle(framebuffer).c_str(),
377                         attachment_index, report_data->FormatHandle(image_view).c_str());
378         return skip;
379     }
380 
381     auto image_usage = image_state->createInfo.usage;
382 
383     // Check for layouts that mismatch image usages in the framebuffer
384     if (layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL && !(image_usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT)) {
385         vuid = use_rp2 ? "VUID-vkCmdBeginRenderPass2KHR-initialLayout-03094" : "VUID-vkCmdBeginRenderPass-initialLayout-00895";
386         skip |=
387             log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(image), vuid,
388                     "Layout/usage mismatch for attachment %u in %s"
389                     " - the %s is %s but the image attached to %s via %s"
390                     " was not created with VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT",
391                     attachment_index, report_data->FormatHandle(renderpass).c_str(), variable_name, string_VkImageLayout(layout),
392                     report_data->FormatHandle(framebuffer).c_str(), report_data->FormatHandle(image_view).c_str());
393     }
394 
395     if (layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL &&
396         !(image_usage & (VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT))) {
397         vuid = use_rp2 ? "VUID-vkCmdBeginRenderPass2KHR-initialLayout-03097" : "VUID-vkCmdBeginRenderPass-initialLayout-00897";
398         skip |=
399             log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(image), vuid,
400                     "Layout/usage mismatch for attachment %u in %s"
401                     " - the %s is %s but the image attached to %s via %s"
402                     " was not created with VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT or VK_IMAGE_USAGE_SAMPLED_BIT",
403                     attachment_index, report_data->FormatHandle(renderpass).c_str(), variable_name, string_VkImageLayout(layout),
404                     report_data->FormatHandle(framebuffer).c_str(), report_data->FormatHandle(image_view).c_str());
405     }
406 
407     if (layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL && !(image_usage & VK_IMAGE_USAGE_TRANSFER_SRC_BIT)) {
408         vuid = use_rp2 ? "VUID-vkCmdBeginRenderPass2KHR-initialLayout-03098" : "VUID-vkCmdBeginRenderPass-initialLayout-00898";
409         skip |=
410             log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(image), vuid,
411                     "Layout/usage mismatch for attachment %u in %s"
412                     " - the %s is %s but the image attached to %s via %s"
413                     " was not created with VK_IMAGE_USAGE_TRANSFER_SRC_BIT",
414                     attachment_index, report_data->FormatHandle(renderpass).c_str(), variable_name, string_VkImageLayout(layout),
415                     report_data->FormatHandle(framebuffer).c_str(), report_data->FormatHandle(image_view).c_str());
416     }
417 
418     if (layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && !(image_usage & VK_IMAGE_USAGE_TRANSFER_DST_BIT)) {
419         vuid = use_rp2 ? "VUID-vkCmdBeginRenderPass2KHR-initialLayout-03099" : "VUID-vkCmdBeginRenderPass-initialLayout-00899";
420         skip |=
421             log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(image), vuid,
422                     "Layout/usage mismatch for attachment %u in %s"
423                     " - the %s is %s but the image attached to %s via %s"
424                     " was not created with VK_IMAGE_USAGE_TRANSFER_DST_BIT",
425                     attachment_index, report_data->FormatHandle(renderpass).c_str(), variable_name, string_VkImageLayout(layout),
426                     report_data->FormatHandle(framebuffer).c_str(), report_data->FormatHandle(image_view).c_str());
427     }
428 
429     if (device_extensions.vk_khr_maintenance2) {
430         if ((layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL ||
431              layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL ||
432              layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
433              layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL) &&
434             !(image_usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
435             vuid = use_rp2 ? "VUID-vkCmdBeginRenderPass2KHR-initialLayout-03096" : "VUID-vkCmdBeginRenderPass-initialLayout-01758";
436             skip |= log_msg(
437                 report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(image), vuid,
438                 "Layout/usage mismatch for attachment %u in %s"
439                 " - the %s is %s but the image attached to %s via %s"
440                 " was not created with VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT",
441                 attachment_index, report_data->FormatHandle(renderpass).c_str(), variable_name, string_VkImageLayout(layout),
442                 report_data->FormatHandle(framebuffer).c_str(), report_data->FormatHandle(image_view).c_str());
443         }
444     } else {
445         // The create render pass 2 extension requires maintenance 2 (the previous branch), so no vuid switch needed here.
446         if ((layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
447              layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL) &&
448             !(image_usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
449             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
450                             HandleToUint64(image), "VUID-vkCmdBeginRenderPass-initialLayout-00896",
451                             "Layout/usage mismatch for attachment %u in %s"
452                             " - the %s is %s but the image attached to %s via %s"
453                             " was not created with VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT",
454                             attachment_index, report_data->FormatHandle(renderpass).c_str(), variable_name,
455                             string_VkImageLayout(layout), report_data->FormatHandle(framebuffer).c_str(),
456                             report_data->FormatHandle(image_view).c_str());
457         }
458     }
459     return skip;
460 }
461 
VerifyFramebufferAndRenderPassLayouts(RenderPassCreateVersion rp_version,const CMD_BUFFER_STATE * pCB,const VkRenderPassBeginInfo * pRenderPassBegin,const FRAMEBUFFER_STATE * framebuffer_state) const462 bool CoreChecks::VerifyFramebufferAndRenderPassLayouts(RenderPassCreateVersion rp_version, const CMD_BUFFER_STATE *pCB,
463                                                        const VkRenderPassBeginInfo *pRenderPassBegin,
464                                                        const FRAMEBUFFER_STATE *framebuffer_state) const {
465     bool skip = false;
466     auto const pRenderPassInfo = GetRenderPassState(pRenderPassBegin->renderPass)->createInfo.ptr();
467     auto const &framebufferInfo = framebuffer_state->createInfo;
468     const VkImageView *attachments = framebufferInfo.pAttachments;
469 
470     auto render_pass = GetRenderPassState(pRenderPassBegin->renderPass)->renderPass;
471     auto framebuffer = framebuffer_state->framebuffer;
472 
473     if (pRenderPassInfo->attachmentCount != framebufferInfo.attachmentCount) {
474         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
475                         HandleToUint64(pCB->commandBuffer), kVUID_Core_DrawState_InvalidRenderpass,
476                         "You cannot start a render pass using a framebuffer with a different number of attachments.");
477     }
478 
479     const auto *attachmentInfo = lvl_find_in_chain<VkRenderPassAttachmentBeginInfoKHR>(pRenderPassBegin->pNext);
480     if (((framebufferInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR) != 0) && attachmentInfo != nullptr) {
481         attachments = attachmentInfo->pAttachments;
482     }
483 
484     if (attachments != nullptr) {
485         const auto *const_pCB = static_cast<const CMD_BUFFER_STATE *>(pCB);
486         for (uint32_t i = 0; i < pRenderPassInfo->attachmentCount; ++i) {
487             auto image_view = attachments[i];
488             auto view_state = GetImageViewState(image_view);
489 
490             if (!view_state) {
491                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT,
492                                 HandleToUint64(pRenderPassBegin->renderPass), "VUID-VkRenderPassBeginInfo-framebuffer-parameter",
493                                 "vkCmdBeginRenderPass(): %s pAttachments[%" PRIu32 "] = %s is not a valid VkImageView handle",
494                                 report_data->FormatHandle(framebuffer_state->framebuffer).c_str(), i,
495                                 report_data->FormatHandle(image_view).c_str());
496                 continue;
497             }
498 
499             const VkImage image = view_state->create_info.image;
500             const IMAGE_STATE *image_state = GetImageState(image);
501 
502             if (!image_state) {
503                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT,
504                                 HandleToUint64(pRenderPassBegin->renderPass), "VUID-VkRenderPassBeginInfo-framebuffer-parameter",
505                                 "vkCmdBeginRenderPass(): %s pAttachments[%" PRIu32 "] =  %s references non-extant %s.",
506                                 report_data->FormatHandle(framebuffer_state->framebuffer).c_str(), i,
507                                 report_data->FormatHandle(image_view).c_str(), report_data->FormatHandle(image).c_str());
508                 continue;
509             }
510             auto attachment_initial_layout = pRenderPassInfo->pAttachments[i].initialLayout;
511             auto final_layout = pRenderPassInfo->pAttachments[i].finalLayout;
512 
513             // Cast pCB to const because we don't want to create entries that don't exist here (in case the key changes to something
514             // in common with the non-const version.)
515             const ImageSubresourceLayoutMap *subresource_map =
516                 (attachment_initial_layout != VK_IMAGE_LAYOUT_UNDEFINED) ? GetImageSubresourceLayoutMap(const_pCB, image) : nullptr;
517 
518             if (subresource_map) {  // If no layout information for image yet, will be checked at QueueSubmit time
519                 LayoutUseCheckAndMessage layout_check(subresource_map);
520                 bool subres_skip = false;
521                 auto subresource_cb = [this, i, attachment_initial_layout, &layout_check, &subres_skip](
522                                           const VkImageSubresource &subres, VkImageLayout layout, VkImageLayout initial_layout) {
523                     if (!layout_check.Check(subres, attachment_initial_layout, layout, initial_layout)) {
524                         subres_skip |=
525                             log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
526                                     kVUID_Core_DrawState_InvalidRenderpass,
527                                     "You cannot start a render pass using attachment %u where the render pass initial layout is %s "
528                                     "and the %s layout of the attachment is %s. The layouts must match, or the render "
529                                     "pass initial layout for the attachment must be VK_IMAGE_LAYOUT_UNDEFINED",
530                                     i, string_VkImageLayout(attachment_initial_layout), layout_check.message,
531                                     string_VkImageLayout(layout_check.layout));
532                     }
533                     return !subres_skip;  // quit checking subresources once we fail once
534                 };
535 
536                 subresource_map->ForRange(view_state->normalized_subresource_range, subresource_cb);
537                 skip |= subres_skip;
538             }
539 
540             ValidateRenderPassLayoutAgainstFramebufferImageUsage(rp_version, attachment_initial_layout, image, image_view,
541                                                                  framebuffer, render_pass, i, "initial layout");
542 
543             ValidateRenderPassLayoutAgainstFramebufferImageUsage(rp_version, final_layout, image, image_view, framebuffer,
544                                                                  render_pass, i, "final layout");
545         }
546 
547         for (uint32_t j = 0; j < pRenderPassInfo->subpassCount; ++j) {
548             auto &subpass = pRenderPassInfo->pSubpasses[j];
549             for (uint32_t k = 0; k < pRenderPassInfo->pSubpasses[j].inputAttachmentCount; ++k) {
550                 auto &attachment_ref = subpass.pInputAttachments[k];
551                 if (attachment_ref.attachment != VK_ATTACHMENT_UNUSED) {
552                     auto image_view = attachments[attachment_ref.attachment];
553                     auto view_state = GetImageViewState(image_view);
554 
555                     if (view_state) {
556                         auto image = view_state->create_info.image;
557                         ValidateRenderPassLayoutAgainstFramebufferImageUsage(rp_version, attachment_ref.layout, image, image_view,
558                                                                              framebuffer, render_pass, attachment_ref.attachment,
559                                                                              "input attachment layout");
560                     }
561                 }
562             }
563 
564             for (uint32_t k = 0; k < pRenderPassInfo->pSubpasses[j].colorAttachmentCount; ++k) {
565                 auto &attachment_ref = subpass.pColorAttachments[k];
566                 if (attachment_ref.attachment != VK_ATTACHMENT_UNUSED) {
567                     auto image_view = attachments[attachment_ref.attachment];
568                     auto view_state = GetImageViewState(image_view);
569 
570                     if (view_state) {
571                         auto image = view_state->create_info.image;
572                         ValidateRenderPassLayoutAgainstFramebufferImageUsage(rp_version, attachment_ref.layout, image, image_view,
573                                                                              framebuffer, render_pass, attachment_ref.attachment,
574                                                                              "color attachment layout");
575                         if (subpass.pResolveAttachments) {
576                             ValidateRenderPassLayoutAgainstFramebufferImageUsage(
577                                 rp_version, attachment_ref.layout, image, image_view, framebuffer, render_pass,
578                                 attachment_ref.attachment, "resolve attachment layout");
579                         }
580                     }
581                 }
582             }
583 
584             if (pRenderPassInfo->pSubpasses[j].pDepthStencilAttachment) {
585                 auto &attachment_ref = *subpass.pDepthStencilAttachment;
586                 if (attachment_ref.attachment != VK_ATTACHMENT_UNUSED) {
587                     auto image_view = attachments[attachment_ref.attachment];
588                     auto view_state = GetImageViewState(image_view);
589 
590                     if (view_state) {
591                         auto image = view_state->create_info.image;
592                         ValidateRenderPassLayoutAgainstFramebufferImageUsage(rp_version, attachment_ref.layout, image, image_view,
593                                                                              framebuffer, render_pass, attachment_ref.attachment,
594                                                                              "input attachment layout");
595                     }
596                 }
597             }
598         }
599     }
600     return skip;
601 }
602 
TransitionAttachmentRefLayout(CMD_BUFFER_STATE * pCB,FRAMEBUFFER_STATE * pFramebuffer,const safe_VkAttachmentReference2KHR & ref)603 void CoreChecks::TransitionAttachmentRefLayout(CMD_BUFFER_STATE *pCB, FRAMEBUFFER_STATE *pFramebuffer,
604                                                const safe_VkAttachmentReference2KHR &ref) {
605     if (ref.attachment != VK_ATTACHMENT_UNUSED) {
606         auto image_view = GetAttachmentImageViewState(pFramebuffer, ref.attachment);
607         if (image_view) {
608             SetImageViewLayout(pCB, *image_view, ref.layout);
609         }
610     }
611 }
612 
TransitionSubpassLayouts(CMD_BUFFER_STATE * pCB,const RENDER_PASS_STATE * render_pass_state,const int subpass_index,FRAMEBUFFER_STATE * framebuffer_state)613 void CoreChecks::TransitionSubpassLayouts(CMD_BUFFER_STATE *pCB, const RENDER_PASS_STATE *render_pass_state,
614                                           const int subpass_index, FRAMEBUFFER_STATE *framebuffer_state) {
615     assert(render_pass_state);
616 
617     if (framebuffer_state) {
618         auto const &subpass = render_pass_state->createInfo.pSubpasses[subpass_index];
619         for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) {
620             TransitionAttachmentRefLayout(pCB, framebuffer_state, subpass.pInputAttachments[j]);
621         }
622         for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) {
623             TransitionAttachmentRefLayout(pCB, framebuffer_state, subpass.pColorAttachments[j]);
624         }
625         if (subpass.pDepthStencilAttachment) {
626             TransitionAttachmentRefLayout(pCB, framebuffer_state, *subpass.pDepthStencilAttachment);
627         }
628     }
629 }
630 
631 // Transition the layout state for renderpass attachments based on the BeginRenderPass() call. This includes:
632 // 1. Transition into initialLayout state
633 // 2. Transition from initialLayout to layout used in subpass 0
TransitionBeginRenderPassLayouts(CMD_BUFFER_STATE * cb_state,const RENDER_PASS_STATE * render_pass_state,FRAMEBUFFER_STATE * framebuffer_state)634 void CoreChecks::TransitionBeginRenderPassLayouts(CMD_BUFFER_STATE *cb_state, const RENDER_PASS_STATE *render_pass_state,
635                                                   FRAMEBUFFER_STATE *framebuffer_state) {
636     // First transition into initialLayout
637     auto const rpci = render_pass_state->createInfo.ptr();
638     for (uint32_t i = 0; i < rpci->attachmentCount; ++i) {
639         auto view_state = GetAttachmentImageViewState(framebuffer_state, i);
640         if (view_state) {
641             SetImageViewLayout(cb_state, *view_state, rpci->pAttachments[i].initialLayout);
642         }
643     }
644     // Now transition for first subpass (index 0)
645     TransitionSubpassLayouts(cb_state, render_pass_state, 0, framebuffer_state);
646 }
647 
VerifyAspectsPresent(VkImageAspectFlags aspect_mask,VkFormat format)648 bool VerifyAspectsPresent(VkImageAspectFlags aspect_mask, VkFormat format) {
649     if ((aspect_mask & VK_IMAGE_ASPECT_COLOR_BIT) != 0) {
650         if (!(FormatIsColor(format) || FormatIsMultiplane(format))) return false;
651     }
652     if ((aspect_mask & VK_IMAGE_ASPECT_DEPTH_BIT) != 0) {
653         if (!FormatHasDepth(format)) return false;
654     }
655     if ((aspect_mask & VK_IMAGE_ASPECT_STENCIL_BIT) != 0) {
656         if (!FormatHasStencil(format)) return false;
657     }
658     if (0 !=
659         (aspect_mask & (VK_IMAGE_ASPECT_PLANE_0_BIT_KHR | VK_IMAGE_ASPECT_PLANE_1_BIT_KHR | VK_IMAGE_ASPECT_PLANE_2_BIT_KHR))) {
660         if (FormatPlaneCount(format) == 1) return false;
661     }
662     return true;
663 }
664 
665 // Verify an ImageMemoryBarrier's old/new ImageLayouts are compatible with the Image's ImageUsageFlags.
ValidateBarrierLayoutToImageUsage(const VkImageMemoryBarrier & img_barrier,bool new_not_old,VkImageUsageFlags usage_flags,const char * func_name,const char * barrier_pname)666 bool CoreChecks::ValidateBarrierLayoutToImageUsage(const VkImageMemoryBarrier &img_barrier, bool new_not_old,
667                                                    VkImageUsageFlags usage_flags, const char *func_name,
668                                                    const char *barrier_pname) {
669     bool skip = false;
670     const VkImageLayout layout = (new_not_old) ? img_barrier.newLayout : img_barrier.oldLayout;
671     const char *msg_code = kVUIDUndefined;  // sentinel value meaning "no error"
672 
673     switch (layout) {
674         case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
675             if ((usage_flags & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) == 0) {
676                 msg_code = "VUID-VkImageMemoryBarrier-oldLayout-01208";
677             }
678             break;
679         case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
680             if ((usage_flags & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) == 0) {
681                 msg_code = "VUID-VkImageMemoryBarrier-oldLayout-01209";
682             }
683             break;
684         case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL:
685             if ((usage_flags & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) == 0) {
686                 msg_code = "VUID-VkImageMemoryBarrier-oldLayout-01210";
687             }
688             break;
689         case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
690             if ((usage_flags & (VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT)) == 0) {
691                 msg_code = "VUID-VkImageMemoryBarrier-oldLayout-01211";
692             }
693             break;
694         case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
695             if ((usage_flags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) == 0) {
696                 msg_code = "VUID-VkImageMemoryBarrier-oldLayout-01212";
697             }
698             break;
699         case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
700             if ((usage_flags & VK_IMAGE_USAGE_TRANSFER_DST_BIT) == 0) {
701                 msg_code = "VUID-VkImageMemoryBarrier-oldLayout-01213";
702             }
703             break;
704         case VK_IMAGE_LAYOUT_SHADING_RATE_OPTIMAL_NV:
705             if ((usage_flags & VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV) == 0) {
706                 msg_code = "VUID-VkImageMemoryBarrier-oldLayout-02088";
707             }
708             break;
709         default:
710             // Other VkImageLayout values do not have VUs defined in this context.
711             break;
712     }
713 
714     if (msg_code != kVUIDUndefined) {
715         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
716                         HandleToUint64(img_barrier.image), msg_code,
717                         "%s: Image barrier %s %s Layout=%s is not compatible with %s usage flags 0x%" PRIx32 ".", func_name,
718                         barrier_pname, ((new_not_old) ? "new" : "old"), string_VkImageLayout(layout),
719                         report_data->FormatHandle(img_barrier.image).c_str(), usage_flags);
720     }
721     return skip;
722 }
723 
724 // Verify image barriers are compatible with the images they reference.
ValidateBarriersToImages(CMD_BUFFER_STATE const * cb_state,uint32_t imageMemoryBarrierCount,const VkImageMemoryBarrier * pImageMemoryBarriers,const char * func_name)725 bool CoreChecks::ValidateBarriersToImages(CMD_BUFFER_STATE const *cb_state, uint32_t imageMemoryBarrierCount,
726                                           const VkImageMemoryBarrier *pImageMemoryBarriers, const char *func_name) {
727     bool skip = false;
728 
729     // Scoreboard for checking for duplicate and inconsistent barriers to images
730     struct ImageBarrierScoreboardEntry {
731         uint32_t index;
732         // This is designed for temporary storage within the scope of the API call.  If retained storage of the barriers is
733         // required, copies should be made and smart or unique pointers used in some other stucture (or this one refactored)
734         const VkImageMemoryBarrier *barrier;
735     };
736     using ImageBarrierScoreboardSubresMap = std::unordered_map<VkImageSubresourceRange, ImageBarrierScoreboardEntry>;
737     using ImageBarrierScoreboardImageMap = std::unordered_map<VkImage, ImageBarrierScoreboardSubresMap>;
738 
739     // Scoreboard for duplicate layout transition barriers within the list
740     // Pointers retained in the scoreboard only have the lifetime of *this* call (i.e. within the scope of the API call)
741     ImageBarrierScoreboardImageMap layout_transitions;
742 
743     for (uint32_t i = 0; i < imageMemoryBarrierCount; ++i) {
744         const auto &img_barrier = pImageMemoryBarriers[i];
745         const std::string barrier_pname = "pImageMemoryBarrier[" + std::to_string(i) + "]";
746 
747         // Update the scoreboard of layout transitions and check for barriers affecting the same image and subresource
748         // TODO: a higher precision could be gained by adapting the command_buffer image_layout_map logic looking for conflicts
749         // at a per sub-resource level
750         if (img_barrier.oldLayout != img_barrier.newLayout) {
751             const ImageBarrierScoreboardEntry new_entry{i, &img_barrier};
752             const auto image_it = layout_transitions.find(img_barrier.image);
753             if (image_it != layout_transitions.end()) {
754                 auto &subres_map = image_it->second;
755                 auto subres_it = subres_map.find(img_barrier.subresourceRange);
756                 if (subres_it != subres_map.end()) {
757                     auto &entry = subres_it->second;
758                     if ((entry.barrier->newLayout != img_barrier.oldLayout) &&
759                         (img_barrier.oldLayout != VK_IMAGE_LAYOUT_UNDEFINED)) {
760                         const VkImageSubresourceRange &range = img_barrier.subresourceRange;
761                         skip = log_msg(
762                             report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
763                             HandleToUint64(cb_state->commandBuffer), "VUID-VkImageMemoryBarrier-oldLayout-01197",
764                             "%s: %s conflicts with earlier entry pImageMemoryBarrier[%u]. %s"
765                             " subresourceRange: aspectMask=%u baseMipLevel=%u levelCount=%u, baseArrayLayer=%u, layerCount=%u; "
766                             "conflicting barrier transitions image layout from %s when earlier barrier transitioned to layout %s.",
767                             func_name, barrier_pname.c_str(), entry.index, report_data->FormatHandle(img_barrier.image).c_str(),
768                             range.aspectMask, range.baseMipLevel, range.levelCount, range.baseArrayLayer, range.layerCount,
769                             string_VkImageLayout(img_barrier.oldLayout), string_VkImageLayout(entry.barrier->newLayout));
770                     }
771                     entry = new_entry;
772                 } else {
773                     subres_map[img_barrier.subresourceRange] = new_entry;
774                 }
775             } else {
776                 layout_transitions[img_barrier.image][img_barrier.subresourceRange] = new_entry;
777             }
778         }
779 
780         auto image_state = GetImageState(img_barrier.image);
781         if (image_state) {
782             VkImageUsageFlags usage_flags = image_state->createInfo.usage;
783             skip |= ValidateBarrierLayoutToImageUsage(img_barrier, false, usage_flags, func_name, barrier_pname.c_str());
784             skip |= ValidateBarrierLayoutToImageUsage(img_barrier, true, usage_flags, func_name, barrier_pname.c_str());
785 
786             // Make sure layout is able to be transitioned, currently only presented shared presentable images are locked
787             if (image_state->layout_locked) {
788                 // TODO: Add unique id for error when available
789                 skip |= log_msg(
790                     report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
791                     HandleToUint64(img_barrier.image), 0,
792                     "Attempting to transition shared presentable %s"
793                     " from layout %s to layout %s, but image has already been presented and cannot have its layout transitioned.",
794                     report_data->FormatHandle(img_barrier.image).c_str(), string_VkImageLayout(img_barrier.oldLayout),
795                     string_VkImageLayout(img_barrier.newLayout));
796             }
797 
798             VkImageCreateInfo *image_create_info = &image_state->createInfo;
799             // For a Depth/Stencil image both aspects MUST be set
800             if (FormatIsDepthAndStencil(image_create_info->format)) {
801                 auto const aspect_mask = img_barrier.subresourceRange.aspectMask;
802                 auto const ds_mask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
803                 if ((aspect_mask & ds_mask) != (ds_mask)) {
804                     skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
805                                     HandleToUint64(img_barrier.image), "VUID-VkImageMemoryBarrier-image-01207",
806                                     "%s: Image barrier %s references %s of format %s that must have the depth and stencil "
807                                     "aspects set, but its aspectMask is 0x%" PRIx32 ".",
808                                     func_name, barrier_pname.c_str(), report_data->FormatHandle(img_barrier.image).c_str(),
809                                     string_VkFormat(image_create_info->format), aspect_mask);
810                 }
811             }
812 
813             const auto *subresource_map = GetImageSubresourceLayoutMap(cb_state, img_barrier.image);
814             if (img_barrier.oldLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
815                 // TODO: Set memory invalid which is in mem_tracker currently
816                 // Not sure if this needs to be in the ForRange traversal, pulling it out as it is currently invariant with
817                 // subresource.
818             } else if (subresource_map) {
819                 bool subres_skip = false;
820                 LayoutUseCheckAndMessage layout_check(subresource_map);
821                 VkImageSubresourceRange normalized_isr = NormalizeSubresourceRange(*image_state, img_barrier.subresourceRange);
822                 auto subres_callback = [this, img_barrier, cb_state, &layout_check, &subres_skip](
823                                            const VkImageSubresource &subres, VkImageLayout layout, VkImageLayout initial_layout) {
824                     if (!layout_check.Check(subres, img_barrier.oldLayout, layout, initial_layout)) {
825                         subres_skip =
826                             log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
827                                     HandleToUint64(cb_state->commandBuffer), "VUID-VkImageMemoryBarrier-oldLayout-01197",
828                                     "For %s you cannot transition the layout of aspect=%d level=%d layer=%d from %s when the "
829                                     "%s layout is %s.",
830                                     report_data->FormatHandle(img_barrier.image).c_str(), subres.aspectMask, subres.mipLevel,
831                                     subres.arrayLayer, string_VkImageLayout(img_barrier.oldLayout), layout_check.message,
832                                     string_VkImageLayout(layout_check.layout));
833                     }
834                     return !subres_skip;
835                 };
836                 subresource_map->ForRange(normalized_isr, subres_callback);
837                 skip |= subres_skip;
838             }
839         }
840     }
841     return skip;
842 }
843 
IsReleaseOp(CMD_BUFFER_STATE * cb_state,const VkImageMemoryBarrier & barrier) const844 bool CoreChecks::IsReleaseOp(CMD_BUFFER_STATE *cb_state, const VkImageMemoryBarrier &barrier) const {
845     if (!IsTransferOp(&barrier)) return false;
846 
847     auto pool = GetCommandPoolState(cb_state->createInfo.commandPool);
848     return pool && TempIsReleaseOp<VkImageMemoryBarrier, true>(pool, &barrier);
849 }
850 
851 template <typename Barrier>
ValidateQFOTransferBarrierUniqueness(const char * func_name,CMD_BUFFER_STATE * cb_state,uint32_t barrier_count,const Barrier * barriers)852 bool CoreChecks::ValidateQFOTransferBarrierUniqueness(const char *func_name, CMD_BUFFER_STATE *cb_state, uint32_t barrier_count,
853                                                       const Barrier *barriers) {
854     using BarrierRecord = QFOTransferBarrier<Barrier>;
855     bool skip = false;
856     auto pool = GetCommandPoolState(cb_state->createInfo.commandPool);
857     auto &barrier_sets = GetQFOBarrierSets(cb_state, typename BarrierRecord::Tag());
858     const char *barrier_name = BarrierRecord::BarrierName();
859     const char *handle_name = BarrierRecord::HandleName();
860     const char *transfer_type = nullptr;
861     for (uint32_t b = 0; b < barrier_count; b++) {
862         if (!IsTransferOp(&barriers[b])) continue;
863         const BarrierRecord *barrier_record = nullptr;
864         if (TempIsReleaseOp<Barrier, true /* Assume IsTransfer */>(pool, &barriers[b]) &&
865             !IsSpecial(barriers[b].dstQueueFamilyIndex)) {
866             const auto found = barrier_sets.release.find(barriers[b]);
867             if (found != barrier_sets.release.cend()) {
868                 barrier_record = &(*found);
869                 transfer_type = "releasing";
870             }
871         } else if (IsAcquireOp<Barrier, true /*Assume IsTransfer */>(pool, &barriers[b]) &&
872                    !IsSpecial(barriers[b].srcQueueFamilyIndex)) {
873             const auto found = barrier_sets.acquire.find(barriers[b]);
874             if (found != barrier_sets.acquire.cend()) {
875                 barrier_record = &(*found);
876                 transfer_type = "acquiring";
877             }
878         }
879         if (barrier_record != nullptr) {
880             skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
881                             HandleToUint64(cb_state->commandBuffer), BarrierRecord::ErrMsgDuplicateQFOInCB(),
882                             "%s: %s at index %" PRIu32 " %s queue ownership of %s (%s), from srcQueueFamilyIndex %" PRIu32
883                             " to dstQueueFamilyIndex %" PRIu32 " duplicates existing barrier recorded in this command buffer.",
884                             func_name, barrier_name, b, transfer_type, handle_name,
885                             report_data->FormatHandle(barrier_record->handle).c_str(), barrier_record->srcQueueFamilyIndex,
886                             barrier_record->dstQueueFamilyIndex);
887         }
888     }
889     return skip;
890 }
891 
892 template <typename Barrier>
RecordQFOTransferBarriers(CMD_BUFFER_STATE * cb_state,uint32_t barrier_count,const Barrier * barriers)893 void CoreChecks::RecordQFOTransferBarriers(CMD_BUFFER_STATE *cb_state, uint32_t barrier_count, const Barrier *barriers) {
894     auto pool = GetCommandPoolState(cb_state->createInfo.commandPool);
895     auto &barrier_sets = GetQFOBarrierSets(cb_state, typename QFOTransferBarrier<Barrier>::Tag());
896     for (uint32_t b = 0; b < barrier_count; b++) {
897         if (!IsTransferOp(&barriers[b])) continue;
898         if (TempIsReleaseOp<Barrier, true /* Assume IsTransfer*/>(pool, &barriers[b]) &&
899             !IsSpecial(barriers[b].dstQueueFamilyIndex)) {
900             barrier_sets.release.emplace(barriers[b]);
901         } else if (IsAcquireOp<Barrier, true /*Assume IsTransfer */>(pool, &barriers[b]) &&
902                    !IsSpecial(barriers[b].srcQueueFamilyIndex)) {
903             barrier_sets.acquire.emplace(barriers[b]);
904         }
905     }
906 }
907 
ValidateBarriersQFOTransferUniqueness(const char * func_name,CMD_BUFFER_STATE * cb_state,uint32_t bufferBarrierCount,const VkBufferMemoryBarrier * pBufferMemBarriers,uint32_t imageMemBarrierCount,const VkImageMemoryBarrier * pImageMemBarriers)908 bool CoreChecks::ValidateBarriersQFOTransferUniqueness(const char *func_name, CMD_BUFFER_STATE *cb_state,
909                                                        uint32_t bufferBarrierCount, const VkBufferMemoryBarrier *pBufferMemBarriers,
910                                                        uint32_t imageMemBarrierCount,
911                                                        const VkImageMemoryBarrier *pImageMemBarriers) {
912     bool skip = false;
913     skip |= ValidateQFOTransferBarrierUniqueness(func_name, cb_state, bufferBarrierCount, pBufferMemBarriers);
914     skip |= ValidateQFOTransferBarrierUniqueness(func_name, cb_state, imageMemBarrierCount, pImageMemBarriers);
915     return skip;
916 }
917 
RecordBarriersQFOTransfers(CMD_BUFFER_STATE * cb_state,uint32_t bufferBarrierCount,const VkBufferMemoryBarrier * pBufferMemBarriers,uint32_t imageMemBarrierCount,const VkImageMemoryBarrier * pImageMemBarriers)918 void CoreChecks::RecordBarriersQFOTransfers(CMD_BUFFER_STATE *cb_state, uint32_t bufferBarrierCount,
919                                             const VkBufferMemoryBarrier *pBufferMemBarriers, uint32_t imageMemBarrierCount,
920                                             const VkImageMemoryBarrier *pImageMemBarriers) {
921     RecordQFOTransferBarriers(cb_state, bufferBarrierCount, pBufferMemBarriers);
922     RecordQFOTransferBarriers(cb_state, imageMemBarrierCount, pImageMemBarriers);
923 }
924 
925 template <typename BarrierRecord, typename Scoreboard>
ValidateAndUpdateQFOScoreboard(const debug_report_data * report_data,const CMD_BUFFER_STATE * cb_state,const char * operation,const BarrierRecord & barrier,Scoreboard * scoreboard) const926 bool CoreChecks::ValidateAndUpdateQFOScoreboard(const debug_report_data *report_data, const CMD_BUFFER_STATE *cb_state,
927                                                 const char *operation, const BarrierRecord &barrier, Scoreboard *scoreboard) const {
928     // Record to the scoreboard or report that we have a duplication
929     bool skip = false;
930     auto inserted = scoreboard->insert(std::make_pair(barrier, cb_state));
931     if (!inserted.second && inserted.first->second != cb_state) {
932         // This is a duplication (but don't report duplicates from the same CB, as we do that at record time
933         skip = log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
934                        HandleToUint64(cb_state->commandBuffer), BarrierRecord::ErrMsgDuplicateQFOInSubmit(),
935                        "%s: %s %s queue ownership of %s (%s), from srcQueueFamilyIndex %" PRIu32 " to dstQueueFamilyIndex %" PRIu32
936                        " duplicates existing barrier submitted in this batch from %s.",
937                        "vkQueueSubmit()", BarrierRecord::BarrierName(), operation, BarrierRecord::HandleName(),
938                        report_data->FormatHandle(barrier.handle).c_str(), barrier.srcQueueFamilyIndex, barrier.dstQueueFamilyIndex,
939                        report_data->FormatHandle(inserted.first->second->commandBuffer).c_str());
940     }
941     return skip;
942 }
943 
944 template <typename Barrier>
ValidateQueuedQFOTransferBarriers(const CMD_BUFFER_STATE * cb_state,QFOTransferCBScoreboards<Barrier> * scoreboards) const945 bool CoreChecks::ValidateQueuedQFOTransferBarriers(const CMD_BUFFER_STATE *cb_state,
946                                                    QFOTransferCBScoreboards<Barrier> *scoreboards) const {
947     using BarrierRecord = QFOTransferBarrier<Barrier>;
948     using TypeTag = typename BarrierRecord::Tag;
949     bool skip = false;
950     const auto &cb_barriers = GetQFOBarrierSets(cb_state, TypeTag());
951     const GlobalQFOTransferBarrierMap<Barrier> &global_release_barriers = GetGlobalQFOReleaseBarrierMap(TypeTag());
952     const char *barrier_name = BarrierRecord::BarrierName();
953     const char *handle_name = BarrierRecord::HandleName();
954     // No release should have an extant duplicate (WARNING)
955     for (const auto &release : cb_barriers.release) {
956         // Check the global pending release barriers
957         const auto set_it = global_release_barriers.find(release.handle);
958         if (set_it != global_release_barriers.cend()) {
959             const QFOTransferBarrierSet<Barrier> &set_for_handle = set_it->second;
960             const auto found = set_for_handle.find(release);
961             if (found != set_for_handle.cend()) {
962                 skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
963                                 HandleToUint64(cb_state->commandBuffer), BarrierRecord::ErrMsgDuplicateQFOSubmitted(),
964                                 "%s: %s releasing queue ownership of %s (%s), from srcQueueFamilyIndex %" PRIu32
965                                 " to dstQueueFamilyIndex %" PRIu32
966                                 " duplicates existing barrier queued for execution, without intervening acquire operation.",
967                                 "vkQueueSubmit()", barrier_name, handle_name, report_data->FormatHandle(found->handle).c_str(),
968                                 found->srcQueueFamilyIndex, found->dstQueueFamilyIndex);
969             }
970         }
971         skip |= ValidateAndUpdateQFOScoreboard(report_data, cb_state, "releasing", release, &scoreboards->release);
972     }
973     // Each acquire must have a matching release (ERROR)
974     for (const auto &acquire : cb_barriers.acquire) {
975         const auto set_it = global_release_barriers.find(acquire.handle);
976         bool matching_release_found = false;
977         if (set_it != global_release_barriers.cend()) {
978             const QFOTransferBarrierSet<Barrier> &set_for_handle = set_it->second;
979             matching_release_found = set_for_handle.find(acquire) != set_for_handle.cend();
980         }
981         if (!matching_release_found) {
982             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
983                             HandleToUint64(cb_state->commandBuffer), BarrierRecord::ErrMsgMissingQFOReleaseInSubmit(),
984                             "%s: in submitted command buffer %s acquiring ownership of %s (%s), from srcQueueFamilyIndex %" PRIu32
985                             " to dstQueueFamilyIndex %" PRIu32 " has no matching release barrier queued for execution.",
986                             "vkQueueSubmit()", barrier_name, handle_name, report_data->FormatHandle(acquire.handle).c_str(),
987                             acquire.srcQueueFamilyIndex, acquire.dstQueueFamilyIndex);
988         }
989         skip |= ValidateAndUpdateQFOScoreboard(report_data, cb_state, "acquiring", acquire, &scoreboards->acquire);
990     }
991     return skip;
992 }
993 
ValidateQueuedQFOTransfers(const CMD_BUFFER_STATE * cb_state,QFOTransferCBScoreboards<VkImageMemoryBarrier> * qfo_image_scoreboards,QFOTransferCBScoreboards<VkBufferMemoryBarrier> * qfo_buffer_scoreboards) const994 bool CoreChecks::ValidateQueuedQFOTransfers(const CMD_BUFFER_STATE *cb_state,
995                                             QFOTransferCBScoreboards<VkImageMemoryBarrier> *qfo_image_scoreboards,
996                                             QFOTransferCBScoreboards<VkBufferMemoryBarrier> *qfo_buffer_scoreboards) const {
997     bool skip = false;
998     skip |= ValidateQueuedQFOTransferBarriers<VkImageMemoryBarrier>(cb_state, qfo_image_scoreboards);
999     skip |= ValidateQueuedQFOTransferBarriers<VkBufferMemoryBarrier>(cb_state, qfo_buffer_scoreboards);
1000     return skip;
1001 }
1002 
1003 template <typename Barrier>
RecordQueuedQFOTransferBarriers(CMD_BUFFER_STATE * cb_state)1004 void CoreChecks::RecordQueuedQFOTransferBarriers(CMD_BUFFER_STATE *cb_state) {
1005     using BarrierRecord = QFOTransferBarrier<Barrier>;
1006     using TypeTag = typename BarrierRecord::Tag;
1007     const auto &cb_barriers = GetQFOBarrierSets(cb_state, TypeTag());
1008     GlobalQFOTransferBarrierMap<Barrier> &global_release_barriers = GetGlobalQFOReleaseBarrierMap(TypeTag());
1009 
1010     // Add release barriers from this submit to the global map
1011     for (const auto &release : cb_barriers.release) {
1012         // the global barrier list is mapped by resource handle to allow cleanup on resource destruction
1013         // NOTE: We're using [] because creation of a Set is a needed side effect for new handles
1014         global_release_barriers[release.handle].insert(release);
1015     }
1016 
1017     // Erase acquired barriers from this submit from the global map -- essentially marking releases as consumed
1018     for (const auto &acquire : cb_barriers.acquire) {
1019         // NOTE: We're not using [] because we don't want to create entries for missing releases
1020         auto set_it = global_release_barriers.find(acquire.handle);
1021         if (set_it != global_release_barriers.end()) {
1022             QFOTransferBarrierSet<Barrier> &set_for_handle = set_it->second;
1023             set_for_handle.erase(acquire);
1024             if (set_for_handle.size() == 0) {  // Clean up empty sets
1025                 global_release_barriers.erase(set_it);
1026             }
1027         }
1028     }
1029 }
1030 
RecordQueuedQFOTransfers(CMD_BUFFER_STATE * cb_state)1031 void CoreChecks::RecordQueuedQFOTransfers(CMD_BUFFER_STATE *cb_state) {
1032     RecordQueuedQFOTransferBarriers<VkImageMemoryBarrier>(cb_state);
1033     RecordQueuedQFOTransferBarriers<VkBufferMemoryBarrier>(cb_state);
1034 }
1035 
1036 // Avoid making the template globally visible by exporting the one instance of it we need.
EraseQFOImageRelaseBarriers(const VkImage & image)1037 void CoreChecks::EraseQFOImageRelaseBarriers(const VkImage &image) { EraseQFOReleaseBarriers<VkImageMemoryBarrier>(image); }
1038 
TransitionImageLayouts(CMD_BUFFER_STATE * cb_state,uint32_t memBarrierCount,const VkImageMemoryBarrier * pImgMemBarriers)1039 void CoreChecks::TransitionImageLayouts(CMD_BUFFER_STATE *cb_state, uint32_t memBarrierCount,
1040                                         const VkImageMemoryBarrier *pImgMemBarriers) {
1041     for (uint32_t i = 0; i < memBarrierCount; ++i) {
1042         const auto &mem_barrier = pImgMemBarriers[i];
1043 
1044         // For ownership transfers, the barrier is specified twice; as a release
1045         // operation on the yielding queue family, and as an acquire operation
1046         // on the acquiring queue family. This barrier may also include a layout
1047         // transition, which occurs 'between' the two operations. For validation
1048         // purposes it doesn't seem important which side performs the layout
1049         // transition, but it must not be performed twice. We'll arbitrarily
1050         // choose to perform it as part of the acquire operation.
1051         if (IsReleaseOp(cb_state, mem_barrier)) {
1052             continue;
1053         }
1054 
1055         auto *image_state = GetImageState(mem_barrier.image);
1056         if (!image_state) continue;
1057 
1058         VkImageSubresourceRange normalized_isr = NormalizeSubresourceRange(*image_state, mem_barrier.subresourceRange);
1059         const auto &image_create_info = image_state->createInfo;
1060 
1061         // Special case for 3D images with VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR flag bit, where <extent.depth> and
1062         // <arrayLayers> can potentially alias. When recording layout for the entire image, pre-emptively record layouts
1063         // for all (potential) layer sub_resources.
1064         if (0 != (image_create_info.flags & VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR)) {
1065             normalized_isr.baseArrayLayer = 0;
1066             normalized_isr.layerCount = image_create_info.extent.depth;  // Treat each depth slice as a layer subresource
1067         }
1068 
1069         SetImageLayout(cb_state, *image_state, normalized_isr, mem_barrier.newLayout, mem_barrier.oldLayout);
1070     }
1071 }
1072 
VerifyImageLayout(const CMD_BUFFER_STATE * cb_node,const IMAGE_STATE * image_state,const VkImageSubresourceRange & range,VkImageAspectFlags aspect_mask,VkImageLayout explicit_layout,VkImageLayout optimal_layout,const char * caller,const char * layout_invalid_msg_code,const char * layout_mismatch_msg_code,bool * error) const1073 bool CoreChecks::VerifyImageLayout(const CMD_BUFFER_STATE *cb_node, const IMAGE_STATE *image_state,
1074                                    const VkImageSubresourceRange &range, VkImageAspectFlags aspect_mask,
1075                                    VkImageLayout explicit_layout, VkImageLayout optimal_layout, const char *caller,
1076                                    const char *layout_invalid_msg_code, const char *layout_mismatch_msg_code, bool *error) const {
1077     if (disabled.image_layout_validation) return false;
1078     assert(cb_node);
1079     assert(image_state);
1080     const auto image = image_state->image;
1081     bool skip = false;
1082 
1083     const auto *subresource_map = GetImageSubresourceLayoutMap(cb_node, image);
1084     if (subresource_map) {
1085         bool subres_skip = false;
1086         LayoutUseCheckAndMessage layout_check(subresource_map, aspect_mask);
1087         auto subresource_cb = [this, explicit_layout, cb_node, layout_mismatch_msg_code, caller, image, &layout_check, &error,
1088                                &subres_skip](const VkImageSubresource &subres, VkImageLayout layout, VkImageLayout initial_layout) {
1089             if (!layout_check.Check(subres, explicit_layout, layout, initial_layout)) {
1090                 *error = true;
1091                 subres_skip |=
1092                     log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
1093                             HandleToUint64(cb_node->commandBuffer), layout_mismatch_msg_code,
1094                             "%s: Cannot use %s (layer=%u mip=%u) with specific layout %s that doesn't match the "
1095                             "%s layout %s.",
1096                             caller, report_data->FormatHandle(image).c_str(), subres.arrayLayer, subres.mipLevel,
1097                             string_VkImageLayout(explicit_layout), layout_check.message, string_VkImageLayout(layout_check.layout));
1098             }
1099             return !subres_skip;
1100         };
1101         subresource_map->ForRange(range, subresource_cb);
1102         skip |= subres_skip;
1103     }
1104 
1105     // If optimal_layout is not UNDEFINED, check that layout matches optimal for this case
1106     if ((VK_IMAGE_LAYOUT_UNDEFINED != optimal_layout) && (explicit_layout != optimal_layout)) {
1107         if (VK_IMAGE_LAYOUT_GENERAL == explicit_layout) {
1108             if (image_state->createInfo.tiling != VK_IMAGE_TILING_LINEAR) {
1109                 // LAYOUT_GENERAL is allowed, but may not be performance optimal, flag as perf warning.
1110                 skip |= log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
1111                                 VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_node->commandBuffer),
1112                                 kVUID_Core_DrawState_InvalidImageLayout,
1113                                 "%s: For optimal performance %s layout should be %s instead of GENERAL.", caller,
1114                                 report_data->FormatHandle(image).c_str(), string_VkImageLayout(optimal_layout));
1115             }
1116         } else if (device_extensions.vk_khr_shared_presentable_image) {
1117             if (image_state->shared_presentable) {
1118                 if (VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR != explicit_layout) {
1119                     skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1120                                     layout_invalid_msg_code,
1121                                     "Layout for shared presentable image is %s but must be VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR.",
1122                                     string_VkImageLayout(optimal_layout));
1123                 }
1124             }
1125         } else {
1126             *error = true;
1127             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
1128                             HandleToUint64(cb_node->commandBuffer), layout_invalid_msg_code,
1129                             "%s: Layout for %s is %s but can only be %s or VK_IMAGE_LAYOUT_GENERAL.", caller,
1130                             report_data->FormatHandle(image).c_str(), string_VkImageLayout(explicit_layout),
1131                             string_VkImageLayout(optimal_layout));
1132         }
1133     }
1134     return skip;
1135 }
VerifyImageLayout(const CMD_BUFFER_STATE * cb_node,const IMAGE_STATE * image_state,const VkImageSubresourceLayers & subLayers,VkImageLayout explicit_layout,VkImageLayout optimal_layout,const char * caller,const char * layout_invalid_msg_code,const char * layout_mismatch_msg_code,bool * error) const1136 bool CoreChecks::VerifyImageLayout(const CMD_BUFFER_STATE *cb_node, const IMAGE_STATE *image_state,
1137                                    const VkImageSubresourceLayers &subLayers, VkImageLayout explicit_layout,
1138                                    VkImageLayout optimal_layout, const char *caller, const char *layout_invalid_msg_code,
1139                                    const char *layout_mismatch_msg_code, bool *error) const {
1140     return VerifyImageLayout(cb_node, image_state, RangeFromLayers(subLayers), explicit_layout, optimal_layout, caller,
1141                              layout_invalid_msg_code, layout_mismatch_msg_code, error);
1142 }
1143 
TransitionFinalSubpassLayouts(CMD_BUFFER_STATE * pCB,const VkRenderPassBeginInfo * pRenderPassBegin,FRAMEBUFFER_STATE * framebuffer_state)1144 void CoreChecks::TransitionFinalSubpassLayouts(CMD_BUFFER_STATE *pCB, const VkRenderPassBeginInfo *pRenderPassBegin,
1145                                                FRAMEBUFFER_STATE *framebuffer_state) {
1146     auto renderPass = GetRenderPassState(pRenderPassBegin->renderPass);
1147     if (!renderPass) return;
1148 
1149     const VkRenderPassCreateInfo2KHR *pRenderPassInfo = renderPass->createInfo.ptr();
1150     if (framebuffer_state) {
1151         for (uint32_t i = 0; i < pRenderPassInfo->attachmentCount; ++i) {
1152             auto view_state = GetAttachmentImageViewState(framebuffer_state, i);
1153             if (view_state) {
1154                 SetImageViewLayout(pCB, *view_state, pRenderPassInfo->pAttachments[i].finalLayout);
1155             }
1156         }
1157     }
1158 }
1159 
1160 #ifdef VK_USE_PLATFORM_ANDROID_KHR
1161 // Android-specific validation that uses types defined only with VK_USE_PLATFORM_ANDROID_KHR
1162 // This could also move into a seperate core_validation_android.cpp file... ?
1163 
1164 //
1165 // AHB-specific validation within non-AHB APIs
1166 //
ValidateCreateImageANDROID(const debug_report_data * report_data,const VkImageCreateInfo * create_info)1167 bool CoreChecks::ValidateCreateImageANDROID(const debug_report_data *report_data, const VkImageCreateInfo *create_info) {
1168     bool skip = false;
1169 
1170     const VkExternalFormatANDROID *ext_fmt_android = lvl_find_in_chain<VkExternalFormatANDROID>(create_info->pNext);
1171     if (ext_fmt_android) {
1172         if (0 != ext_fmt_android->externalFormat) {
1173             if (VK_FORMAT_UNDEFINED != create_info->format) {
1174                 skip |=
1175                     log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1176                             "VUID-VkImageCreateInfo-pNext-01974",
1177                             "vkCreateImage(): VkImageCreateInfo struct has a chained VkExternalFormatANDROID struct with non-zero "
1178                             "externalFormat, but the VkImageCreateInfo's format is not VK_FORMAT_UNDEFINED.");
1179             }
1180 
1181             if (0 != (VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT & create_info->flags)) {
1182                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1183                                 "VUID-VkImageCreateInfo-pNext-02396",
1184                                 "vkCreateImage(): VkImageCreateInfo struct has a chained VkExternalFormatANDROID struct with "
1185                                 "non-zero externalFormat, but flags include VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT.");
1186             }
1187 
1188             if (0 != (~VK_IMAGE_USAGE_SAMPLED_BIT & create_info->usage)) {
1189                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1190                                 "VUID-VkImageCreateInfo-pNext-02397",
1191                                 "vkCreateImage(): VkImageCreateInfo struct has a chained VkExternalFormatANDROID struct with "
1192                                 "non-zero externalFormat, but usage includes bits other than VK_IMAGE_USAGE_SAMPLED_BIT.");
1193             }
1194 
1195             if (VK_IMAGE_TILING_OPTIMAL != create_info->tiling) {
1196                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1197                                 "VUID-VkImageCreateInfo-pNext-02398",
1198                                 "vkCreateImage(): VkImageCreateInfo struct has a chained VkExternalFormatANDROID struct with "
1199                                 "non-zero externalFormat, but layout is not VK_IMAGE_TILING_OPTIMAL.");
1200             }
1201         }
1202 
1203         if ((0 != ext_fmt_android->externalFormat) && (0 == ahb_ext_formats_set.count(ext_fmt_android->externalFormat))) {
1204             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1205                             "VUID-VkExternalFormatANDROID-externalFormat-01894",
1206                             "vkCreateImage(): Chained VkExternalFormatANDROID struct contains a non-zero externalFormat which has "
1207                             "not been previously retrieved by vkGetAndroidHardwareBufferPropertiesANDROID().");
1208         }
1209     }
1210 
1211     if ((nullptr == ext_fmt_android) || (0 == ext_fmt_android->externalFormat)) {
1212         if (VK_FORMAT_UNDEFINED == create_info->format) {
1213             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1214                             "VUID-VkImageCreateInfo-pNext-01975",
1215                             "vkCreateImage(): VkImageCreateInfo struct's format is VK_FORMAT_UNDEFINED, but either does not have a "
1216                             "chained VkExternalFormatANDROID struct or the struct exists but has an externalFormat of 0.");
1217         }
1218     }
1219 
1220     const VkExternalMemoryImageCreateInfo *emici = lvl_find_in_chain<VkExternalMemoryImageCreateInfo>(create_info->pNext);
1221     if (emici && (emici->handleTypes & VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID)) {
1222         if (create_info->imageType != VK_IMAGE_TYPE_2D) {
1223             skip |=
1224                 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1225                         "VUID-VkImageCreateInfo-pNext-02393",
1226                         "vkCreateImage(): VkImageCreateInfo struct with imageType %s has chained VkExternalMemoryImageCreateInfo "
1227                         "struct with handleType VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID.",
1228                         string_VkImageType(create_info->imageType));
1229         }
1230 
1231         if ((create_info->mipLevels != 1) && (create_info->mipLevels != FullMipChainLevels(create_info->extent))) {
1232             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1233                             "VUID-VkImageCreateInfo-pNext-02394",
1234                             "vkCreateImage(): VkImageCreateInfo struct with chained VkExternalMemoryImageCreateInfo struct of "
1235                             "handleType VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID "
1236                             "specifies mipLevels = %" PRId32 " (full chain mipLevels are %" PRId32 ").",
1237                             create_info->mipLevels, FullMipChainLevels(create_info->extent));
1238         }
1239     }
1240 
1241     return skip;
1242 }
1243 
RecordCreateImageANDROID(const VkImageCreateInfo * create_info,IMAGE_STATE * is_node)1244 void ValidationStateTracker::RecordCreateImageANDROID(const VkImageCreateInfo *create_info, IMAGE_STATE *is_node) {
1245     const VkExternalMemoryImageCreateInfo *emici = lvl_find_in_chain<VkExternalMemoryImageCreateInfo>(create_info->pNext);
1246     if (emici && (emici->handleTypes & VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID)) {
1247         is_node->imported_ahb = true;
1248     }
1249     const VkExternalFormatANDROID *ext_fmt_android = lvl_find_in_chain<VkExternalFormatANDROID>(create_info->pNext);
1250     if (ext_fmt_android && (0 != ext_fmt_android->externalFormat)) {
1251         is_node->has_ahb_format = true;
1252         is_node->ahb_format = ext_fmt_android->externalFormat;
1253     }
1254 }
1255 
ValidateCreateImageViewANDROID(const VkImageViewCreateInfo * create_info)1256 bool CoreChecks::ValidateCreateImageViewANDROID(const VkImageViewCreateInfo *create_info) {
1257     bool skip = false;
1258     IMAGE_STATE *image_state = GetImageState(create_info->image);
1259 
1260     if (image_state->has_ahb_format) {
1261         if (VK_FORMAT_UNDEFINED != create_info->format) {
1262             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
1263                             HandleToUint64(create_info->image), "VUID-VkImageViewCreateInfo-image-02399",
1264                             "vkCreateImageView(): VkImageViewCreateInfo struct has a chained VkExternalFormatANDROID struct, but "
1265                             "format member is %s.",
1266                             string_VkFormat(create_info->format));
1267         }
1268 
1269         // Chain must include a compatible ycbcr conversion
1270         bool conv_found = false;
1271         uint64_t external_format = 0;
1272         const VkSamplerYcbcrConversionInfo *ycbcr_conv_info = lvl_find_in_chain<VkSamplerYcbcrConversionInfo>(create_info->pNext);
1273         if (ycbcr_conv_info != nullptr) {
1274             VkSamplerYcbcrConversion conv_handle = ycbcr_conv_info->conversion;
1275             if (ycbcr_conversion_ahb_fmt_map.find(conv_handle) != ycbcr_conversion_ahb_fmt_map.end()) {
1276                 conv_found = true;
1277                 external_format = ycbcr_conversion_ahb_fmt_map.at(conv_handle);
1278             }
1279         }
1280         if ((!conv_found) || (external_format != image_state->ahb_format)) {
1281             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
1282                             HandleToUint64(create_info->image), "VUID-VkImageViewCreateInfo-image-02400",
1283                             "vkCreateImageView(): VkImageViewCreateInfo struct has a chained VkExternalFormatANDROID struct, but "
1284                             "without a chained VkSamplerYcbcrConversionInfo struct with the same external format.");
1285         }
1286 
1287         // Errors in create_info swizzles
1288         if ((create_info->components.r != VK_COMPONENT_SWIZZLE_IDENTITY) ||
1289             (create_info->components.g != VK_COMPONENT_SWIZZLE_IDENTITY) ||
1290             (create_info->components.b != VK_COMPONENT_SWIZZLE_IDENTITY) ||
1291             (create_info->components.a != VK_COMPONENT_SWIZZLE_IDENTITY)) {
1292             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
1293                             HandleToUint64(create_info->image), "VUID-VkImageViewCreateInfo-image-02401",
1294                             "vkCreateImageView(): VkImageViewCreateInfo struct has a chained VkExternalFormatANDROID struct, but "
1295                             "includes one or more non-identity component swizzles.");
1296         }
1297     }
1298 
1299     return skip;
1300 }
1301 
ValidateGetImageSubresourceLayoutANDROID(const VkImage image) const1302 bool CoreChecks::ValidateGetImageSubresourceLayoutANDROID(const VkImage image) const {
1303     bool skip = false;
1304 
1305     const IMAGE_STATE *image_state = GetImageState(image);
1306     if (image_state->imported_ahb && (0 == image_state->GetBoundMemory().size())) {
1307         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(image),
1308                         "VUID-vkGetImageSubresourceLayout-image-01895",
1309                         "vkGetImageSubresourceLayout(): Attempt to query layout from an image created with "
1310                         "VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID handleType which has not yet been "
1311                         "bound to memory.");
1312     }
1313     return skip;
1314 }
1315 
1316 #else
1317 
ValidateCreateImageANDROID(const debug_report_data * report_data,const VkImageCreateInfo * create_info)1318 bool CoreChecks::ValidateCreateImageANDROID(const debug_report_data *report_data, const VkImageCreateInfo *create_info) {
1319     return false;
1320 }
1321 
RecordCreateImageANDROID(const VkImageCreateInfo * create_info,IMAGE_STATE * is_node)1322 void ValidationStateTracker::RecordCreateImageANDROID(const VkImageCreateInfo *create_info, IMAGE_STATE *is_node) {}
1323 
ValidateCreateImageViewANDROID(const VkImageViewCreateInfo * create_info)1324 bool CoreChecks::ValidateCreateImageViewANDROID(const VkImageViewCreateInfo *create_info) { return false; }
1325 
ValidateGetImageSubresourceLayoutANDROID(const VkImage image) const1326 bool CoreChecks::ValidateGetImageSubresourceLayoutANDROID(const VkImage image) const { return false; }
1327 
1328 #endif  // VK_USE_PLATFORM_ANDROID_KHR
1329 
PreCallValidateCreateImage(VkDevice device,const VkImageCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkImage * pImage)1330 bool CoreChecks::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo *pCreateInfo,
1331                                             const VkAllocationCallbacks *pAllocator, VkImage *pImage) {
1332     bool skip = false;
1333 
1334     if (device_extensions.vk_android_external_memory_android_hardware_buffer) {
1335         skip |= ValidateCreateImageANDROID(report_data, pCreateInfo);
1336     } else {  // These checks are omitted or replaced when Android HW Buffer extension is active
1337         if (pCreateInfo->format == VK_FORMAT_UNDEFINED) {
1338             return log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1339                            "VUID-VkImageCreateInfo-format-00943",
1340                            "vkCreateImage(): VkFormat for image must not be VK_FORMAT_UNDEFINED.");
1341         }
1342     }
1343 
1344     if (pCreateInfo->flags & VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT) {
1345         if (VK_IMAGE_TYPE_2D != pCreateInfo->imageType) {
1346             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1347                             "VUID-VkImageCreateInfo-flags-00949",
1348                             "vkCreateImage(): Image type must be VK_IMAGE_TYPE_2D when VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT "
1349                             "flag bit is set");
1350         }
1351 
1352         if ((pCreateInfo->extent.width != pCreateInfo->extent.height) || (pCreateInfo->arrayLayers < 6)) {
1353             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1354                             "VUID-VkImageCreateInfo-imageType-00954",
1355                             "vkCreateImage(): If VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT flag bit is set, width (%d) must equal "
1356                             "height (%d) and arrayLayers (%d) must be >= 6.",
1357                             pCreateInfo->extent.width, pCreateInfo->extent.height, pCreateInfo->arrayLayers);
1358         }
1359     }
1360 
1361     const VkPhysicalDeviceLimits *device_limits = &phys_dev_props.limits;
1362     VkImageUsageFlags attach_flags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT |
1363                                      VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
1364     if ((pCreateInfo->usage & attach_flags) && (pCreateInfo->extent.width > device_limits->maxFramebufferWidth)) {
1365         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1366                         "VUID-VkImageCreateInfo-usage-00964",
1367                         "vkCreateImage(): Image usage flags include a frame buffer attachment bit and image width exceeds device "
1368                         "maxFramebufferWidth.");
1369     }
1370 
1371     if ((pCreateInfo->usage & attach_flags) && (pCreateInfo->extent.height > device_limits->maxFramebufferHeight)) {
1372         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1373                         "VUID-VkImageCreateInfo-usage-00965",
1374                         "vkCreateImage(): Image usage flags include a frame buffer attachment bit and image height exceeds device "
1375                         "maxFramebufferHeight");
1376     }
1377 
1378     if (device_extensions.vk_ext_fragment_density_map) {
1379         uint32_t ceiling_width =
1380             (uint32_t)ceil((float)device_limits->maxFramebufferWidth /
1381                            std::max((float)phys_dev_ext_props.fragment_density_map_props.minFragmentDensityTexelSize.width, 1.0f));
1382         if ((pCreateInfo->usage & VK_IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT) && (pCreateInfo->extent.width > ceiling_width)) {
1383             skip |=
1384                 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1385                         "VUID-VkImageCreateInfo-usage-02559",
1386                         "vkCreateImage(): Image usage flags include a fragment density map bit and image width (%u) exceeds the "
1387                         "ceiling of device "
1388                         "maxFramebufferWidth (%u) / minFragmentDensityTexelSize.width (%u). The ceiling value: %u",
1389                         pCreateInfo->extent.width, device_limits->maxFramebufferWidth,
1390                         phys_dev_ext_props.fragment_density_map_props.minFragmentDensityTexelSize.width, ceiling_width);
1391         }
1392 
1393         uint32_t ceiling_height =
1394             (uint32_t)ceil((float)device_limits->maxFramebufferHeight /
1395                            std::max((float)phys_dev_ext_props.fragment_density_map_props.minFragmentDensityTexelSize.height, 1.0f));
1396         if ((pCreateInfo->usage & VK_IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT) && (pCreateInfo->extent.height > ceiling_height)) {
1397             skip |=
1398                 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1399                         "VUID-VkImageCreateInfo-usage-02560",
1400                         "vkCreateImage(): Image usage flags include a fragment density map bit and image height (%u) exceeds the "
1401                         "ceiling of device "
1402                         "maxFramebufferHeight (%u) / minFragmentDensityTexelSize.height (%u). The ceiling value: %u",
1403                         pCreateInfo->extent.height, device_limits->maxFramebufferHeight,
1404                         phys_dev_ext_props.fragment_density_map_props.minFragmentDensityTexelSize.height, ceiling_height);
1405         }
1406     }
1407 
1408     VkImageFormatProperties format_limits = {};
1409     VkResult res = GetPDImageFormatProperties(pCreateInfo, &format_limits);
1410     if (res == VK_ERROR_FORMAT_NOT_SUPPORTED) {
1411 #ifdef VK_USE_PLATFORM_ANDROID_KHR
1412         if (!lvl_find_in_chain<VkExternalFormatANDROID>(pCreateInfo->pNext))
1413 #endif  // VK_USE_PLATFORM_ANDROID_KHR
1414             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUIDUndefined,
1415                             "vkCreateImage(): Format %s is not supported for this combination of parameters.",
1416                             string_VkFormat(pCreateInfo->format));
1417     } else {
1418         if (pCreateInfo->mipLevels > format_limits.maxMipLevels) {
1419             const char *format_string = string_VkFormat(pCreateInfo->format);
1420             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1421                             "VUID-VkImageCreateInfo-mipLevels-02255",
1422                             "vkCreateImage(): Image mip levels=%d exceed image format maxMipLevels=%d for format %s.",
1423                             pCreateInfo->mipLevels, format_limits.maxMipLevels, format_string);
1424         }
1425 
1426         uint64_t texel_count = (uint64_t)pCreateInfo->extent.width * (uint64_t)pCreateInfo->extent.height *
1427                                (uint64_t)pCreateInfo->extent.depth * (uint64_t)pCreateInfo->arrayLayers *
1428                                (uint64_t)pCreateInfo->samples;
1429         uint64_t total_size = (uint64_t)std::ceil(FormatTexelSize(pCreateInfo->format) * texel_count);
1430 
1431         // Round up to imageGranularity boundary
1432         VkDeviceSize imageGranularity = phys_dev_props.limits.bufferImageGranularity;
1433         uint64_t ig_mask = imageGranularity - 1;
1434         total_size = (total_size + ig_mask) & ~ig_mask;
1435 
1436         if (total_size > format_limits.maxResourceSize) {
1437             skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, 0,
1438                             kVUID_Core_Image_InvalidFormatLimitsViolation,
1439                             "vkCreateImage(): resource size exceeds allowable maximum Image resource size = 0x%" PRIxLEAST64
1440                             ", maximum resource size = 0x%" PRIxLEAST64 " ",
1441                             total_size, format_limits.maxResourceSize);
1442         }
1443 
1444         if (pCreateInfo->arrayLayers > format_limits.maxArrayLayers) {
1445             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, 0,
1446                             "VUID-VkImageCreateInfo-arrayLayers-02256",
1447                             "vkCreateImage(): arrayLayers=%d exceeds allowable maximum supported by format of %d.",
1448                             pCreateInfo->arrayLayers, format_limits.maxArrayLayers);
1449         }
1450 
1451         if (device_extensions.vk_khr_sampler_ycbcr_conversion && FormatRequiresYcbcrConversion(pCreateInfo->format) &&
1452             !device_extensions.vk_ext_ycbcr_image_arrays && pCreateInfo->arrayLayers > 1) {
1453             skip |= log_msg(
1454                 report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, 0,
1455                 "VUID-VkImageCreateInfo-format-02653",
1456                 "vkCreateImage(): arrayLayers=%d exceeds the maximum allowed of 1 for formats requiring sampler ycbcr conversion",
1457                 pCreateInfo->arrayLayers);
1458         }
1459 
1460         if ((pCreateInfo->samples & format_limits.sampleCounts) == 0) {
1461             skip |=
1462                 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, 0,
1463                         "VUID-VkImageCreateInfo-samples-02258", "vkCreateImage(): samples %s is not supported by format 0x%.8X.",
1464                         string_VkSampleCountFlagBits(pCreateInfo->samples), format_limits.sampleCounts);
1465         }
1466     }
1467 
1468     if ((pCreateInfo->flags & VK_IMAGE_CREATE_SPARSE_ALIASED_BIT) && (!enabled_features.core.sparseResidencyAliased)) {
1469         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
1470                         "VUID-VkImageCreateInfo-flags-01924",
1471                         "vkCreateImage(): the sparseResidencyAliased device feature is disabled: Images cannot be created with the "
1472                         "VK_IMAGE_CREATE_SPARSE_ALIASED_BIT set.");
1473     }
1474 
1475     if (device_extensions.vk_khr_maintenance2) {
1476         if (pCreateInfo->flags & VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT_KHR) {
1477             if (!(FormatIsCompressed_BC(pCreateInfo->format) || FormatIsCompressed_ASTC_LDR(pCreateInfo->format) ||
1478                   FormatIsCompressed_ETC2_EAC(pCreateInfo->format))) {
1479                 // TODO: Add Maintenance2 VUID
1480                 skip |=
1481                     log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUIDUndefined,
1482                             "vkCreateImage(): If pCreateInfo->flags contains VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT_KHR, "
1483                             "format must be block, ETC or ASTC compressed, but is %s",
1484                             string_VkFormat(pCreateInfo->format));
1485             }
1486             if (!(pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
1487                 // TODO: Add Maintenance2 VUID
1488                 skip |=
1489                     log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUIDUndefined,
1490                             "vkCreateImage(): If pCreateInfo->flags contains VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT_KHR, "
1491                             "flags must also contain VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT.");
1492             }
1493         }
1494     }
1495 
1496     if (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT && pCreateInfo->pQueueFamilyIndices) {
1497         skip |= ValidateQueueFamilies(pCreateInfo->queueFamilyIndexCount, pCreateInfo->pQueueFamilyIndices, "vkCreateImage",
1498                                       "pCreateInfo->pQueueFamilyIndices", "VUID-VkImageCreateInfo-sharingMode-01420",
1499                                       "VUID-VkImageCreateInfo-sharingMode-01420", false);
1500     }
1501 
1502     return skip;
1503 }
1504 
PostCallRecordCreateImage(VkDevice device,const VkImageCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkImage * pImage,VkResult result)1505 void ValidationStateTracker::PostCallRecordCreateImage(VkDevice device, const VkImageCreateInfo *pCreateInfo,
1506                                                        const VkAllocationCallbacks *pAllocator, VkImage *pImage, VkResult result) {
1507     if (VK_SUCCESS != result) return;
1508     std::unique_ptr<IMAGE_STATE> is_node(new IMAGE_STATE(*pImage, pCreateInfo));
1509     if (device_extensions.vk_android_external_memory_android_hardware_buffer) {
1510         RecordCreateImageANDROID(pCreateInfo, is_node.get());
1511     }
1512     const auto swapchain_info = lvl_find_in_chain<VkImageSwapchainCreateInfoKHR>(pCreateInfo->pNext);
1513     if (swapchain_info) {
1514         is_node->create_from_swapchain = swapchain_info->swapchain;
1515     }
1516 
1517     bool pre_fetch_memory_reqs = true;
1518 #ifdef VK_USE_PLATFORM_ANDROID_KHR
1519     if (is_node->external_format_android) {
1520         // Do not fetch requirements for external memory images
1521         pre_fetch_memory_reqs = false;
1522     }
1523 #endif
1524     // Record the memory requirements in case they won't be queried
1525     if (pre_fetch_memory_reqs) {
1526         DispatchGetImageMemoryRequirements(device, *pImage, &is_node->requirements);
1527     }
1528     imageMap.insert(std::make_pair(*pImage, std::move(is_node)));
1529 }
1530 
PostCallRecordCreateImage(VkDevice device,const VkImageCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkImage * pImage,VkResult result)1531 void CoreChecks::PostCallRecordCreateImage(VkDevice device, const VkImageCreateInfo *pCreateInfo,
1532                                            const VkAllocationCallbacks *pAllocator, VkImage *pImage, VkResult result) {
1533     if (VK_SUCCESS != result) return;
1534 
1535     StateTracker::PostCallRecordCreateImage(device, pCreateInfo, pAllocator, pImage, result);
1536 
1537     IMAGE_LAYOUT_STATE image_state;
1538     image_state.layout = pCreateInfo->initialLayout;
1539     image_state.format = pCreateInfo->format;
1540     ImageSubresourcePair subpair{*pImage, false, VkImageSubresource()};
1541     imageSubresourceMap[*pImage].push_back(subpair);
1542     imageLayoutMap[subpair] = image_state;
1543 }
1544 
PreCallValidateDestroyImage(VkDevice device,VkImage image,const VkAllocationCallbacks * pAllocator)1545 bool CoreChecks::PreCallValidateDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
1546     IMAGE_STATE *image_state = GetImageState(image);
1547     const VulkanTypedHandle obj_struct(image, kVulkanObjectTypeImage);
1548     bool skip = false;
1549     if (image_state) {
1550         skip |= ValidateObjectNotInUse(image_state, obj_struct, "vkDestroyImage", "VUID-vkDestroyImage-image-01000");
1551     }
1552     return skip;
1553 }
1554 
PreCallRecordDestroyImage(VkDevice device,VkImage image,const VkAllocationCallbacks * pAllocator)1555 void ValidationStateTracker::PreCallRecordDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
1556     if (!image) return;
1557     IMAGE_STATE *image_state = GetImageState(image);
1558     const VulkanTypedHandle obj_struct(image, kVulkanObjectTypeImage);
1559     InvalidateCommandBuffers(image_state->cb_bindings, obj_struct);
1560     // Clean up memory mapping, bindings and range references for image
1561     for (auto mem_binding : image_state->GetBoundMemory()) {
1562         auto mem_info = GetDevMemState(mem_binding);
1563         if (mem_info) {
1564             RemoveImageMemoryRange(obj_struct.handle, mem_info);
1565         }
1566     }
1567     ClearMemoryObjectBindings(obj_struct);
1568     // Remove image from imageMap
1569     imageMap.erase(image);
1570 }
1571 
PreCallRecordDestroyImage(VkDevice device,VkImage image,const VkAllocationCallbacks * pAllocator)1572 void CoreChecks::PreCallRecordDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
1573     // Clean up validation specific data
1574     EraseQFOReleaseBarriers<VkImageMemoryBarrier>(image);
1575 
1576     const auto &sub_entry = imageSubresourceMap.find(image);
1577     if (sub_entry != imageSubresourceMap.end()) {
1578         for (const auto &pair : sub_entry->second) {
1579             imageLayoutMap.erase(pair);
1580         }
1581         imageSubresourceMap.erase(sub_entry);
1582     }
1583 
1584     // Clean up generic image state
1585     StateTracker::PreCallRecordDestroyImage(device, image, pAllocator);
1586 }
1587 
ValidateImageAttributes(const IMAGE_STATE * image_state,const VkImageSubresourceRange & range) const1588 bool CoreChecks::ValidateImageAttributes(const IMAGE_STATE *image_state, const VkImageSubresourceRange &range) const {
1589     bool skip = false;
1590 
1591     if (range.aspectMask != VK_IMAGE_ASPECT_COLOR_BIT) {
1592         char const str[] = "vkCmdClearColorImage aspectMasks for all subresource ranges must be set to VK_IMAGE_ASPECT_COLOR_BIT";
1593         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
1594                         HandleToUint64(image_state->image), kVUID_Core_DrawState_InvalidImageAspect, str);
1595     }
1596 
1597     if (FormatIsDepthOrStencil(image_state->createInfo.format)) {
1598         char const str[] = "vkCmdClearColorImage called with depth/stencil image.";
1599         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
1600                         HandleToUint64(image_state->image), "VUID-vkCmdClearColorImage-image-00007", "%s.", str);
1601     } else if (FormatIsCompressed(image_state->createInfo.format)) {
1602         char const str[] = "vkCmdClearColorImage called with compressed image.";
1603         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
1604                         HandleToUint64(image_state->image), "VUID-vkCmdClearColorImage-image-00007", "%s.", str);
1605     }
1606 
1607     if (!(image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSFER_DST_BIT)) {
1608         char const str[] = "vkCmdClearColorImage called with image created without VK_IMAGE_USAGE_TRANSFER_DST_BIT.";
1609         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
1610                         HandleToUint64(image_state->image), "VUID-vkCmdClearColorImage-image-00002", "%s.", str);
1611     }
1612     return skip;
1613 }
1614 
ResolveRemainingLevels(const VkImageSubresourceRange * range,uint32_t mip_levels)1615 uint32_t ResolveRemainingLevels(const VkImageSubresourceRange *range, uint32_t mip_levels) {
1616     // Return correct number of mip levels taking into account VK_REMAINING_MIP_LEVELS
1617     uint32_t mip_level_count = range->levelCount;
1618     if (range->levelCount == VK_REMAINING_MIP_LEVELS) {
1619         mip_level_count = mip_levels - range->baseMipLevel;
1620     }
1621     return mip_level_count;
1622 }
1623 
ResolveRemainingLayers(const VkImageSubresourceRange * range,uint32_t layers)1624 uint32_t ResolveRemainingLayers(const VkImageSubresourceRange *range, uint32_t layers) {
1625     // Return correct number of layers taking into account VK_REMAINING_ARRAY_LAYERS
1626     uint32_t array_layer_count = range->layerCount;
1627     if (range->layerCount == VK_REMAINING_ARRAY_LAYERS) {
1628         array_layer_count = layers - range->baseArrayLayer;
1629     }
1630     return array_layer_count;
1631 }
1632 
VerifyClearImageLayout(const CMD_BUFFER_STATE * cb_node,const IMAGE_STATE * image_state,const VkImageSubresourceRange & range,VkImageLayout dest_image_layout,const char * func_name) const1633 bool CoreChecks::VerifyClearImageLayout(const CMD_BUFFER_STATE *cb_node, const IMAGE_STATE *image_state,
1634                                         const VkImageSubresourceRange &range, VkImageLayout dest_image_layout,
1635                                         const char *func_name) const {
1636     bool skip = false;
1637 
1638     if (dest_image_layout != VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
1639         if (dest_image_layout == VK_IMAGE_LAYOUT_GENERAL) {
1640             if (image_state->createInfo.tiling != VK_IMAGE_TILING_LINEAR) {
1641                 // LAYOUT_GENERAL is allowed, but may not be performance optimal, flag as perf warning.
1642                 skip |= log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
1643                                 HandleToUint64(image_state->image), kVUID_Core_DrawState_InvalidImageLayout,
1644                                 "%s: Layout for cleared image should be TRANSFER_DST_OPTIMAL instead of GENERAL.", func_name);
1645             }
1646         } else if (VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR == dest_image_layout) {
1647             if (!device_extensions.vk_khr_shared_presentable_image) {
1648                 // TODO: Add unique error id when available.
1649                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
1650                                 HandleToUint64(image_state->image), 0,
1651                                 "Must enable VK_KHR_shared_presentable_image extension before creating images with a layout type "
1652                                 "of VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR.");
1653 
1654             } else {
1655                 if (image_state->shared_presentable) {
1656                     skip |= log_msg(
1657                         report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
1658                         HandleToUint64(image_state->image), 0,
1659                         "Layout for shared presentable cleared image is %s but can only be VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR.",
1660                         string_VkImageLayout(dest_image_layout));
1661                 }
1662             }
1663         } else {
1664             const char *error_code = "VUID-vkCmdClearColorImage-imageLayout-00005";
1665             if (strcmp(func_name, "vkCmdClearDepthStencilImage()") == 0) {
1666                 error_code = "VUID-vkCmdClearDepthStencilImage-imageLayout-00012";
1667             } else {
1668                 assert(strcmp(func_name, "vkCmdClearColorImage()") == 0);
1669             }
1670             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
1671                             HandleToUint64(image_state->image), error_code,
1672                             "%s: Layout for cleared image is %s but can only be TRANSFER_DST_OPTIMAL or GENERAL.", func_name,
1673                             string_VkImageLayout(dest_image_layout));
1674         }
1675     }
1676 
1677     // Cast to const to prevent creation at validate time.
1678     const auto *subresource_map = GetImageSubresourceLayoutMap(cb_node, image_state->image);
1679     if (subresource_map) {
1680         bool subres_skip = false;
1681         LayoutUseCheckAndMessage layout_check(subresource_map);
1682         VkImageSubresourceRange normalized_isr = NormalizeSubresourceRange(*image_state, range);
1683         auto subres_callback = [this, cb_node, dest_image_layout, func_name, &layout_check, &subres_skip](
1684                                    const VkImageSubresource &subres, VkImageLayout layout, VkImageLayout initial_layout) {
1685             if (!layout_check.Check(subres, dest_image_layout, layout, initial_layout)) {
1686                 const char *error_code = "VUID-vkCmdClearColorImage-imageLayout-00004";
1687                 if (strcmp(func_name, "vkCmdClearDepthStencilImage()") == 0) {
1688                     error_code = "VUID-vkCmdClearDepthStencilImage-imageLayout-00011";
1689                 } else {
1690                     assert(strcmp(func_name, "vkCmdClearColorImage()") == 0);
1691                 }
1692                 subres_skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
1693                                        HandleToUint64(cb_node->commandBuffer), error_code,
1694                                        "%s: Cannot clear an image whose layout is %s and doesn't match the %s layout %s.",
1695                                        func_name, string_VkImageLayout(dest_image_layout), layout_check.message,
1696                                        string_VkImageLayout(layout_check.layout));
1697             }
1698             return !subres_skip;
1699         };
1700         subresource_map->ForRange(normalized_isr, subres_callback);
1701         skip |= subres_skip;
1702     }
1703 
1704     return skip;
1705 }
1706 
PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer,VkImage image,VkImageLayout imageLayout,const VkClearColorValue * pColor,uint32_t rangeCount,const VkImageSubresourceRange * pRanges)1707 bool CoreChecks::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
1708                                                    const VkClearColorValue *pColor, uint32_t rangeCount,
1709                                                    const VkImageSubresourceRange *pRanges) {
1710     bool skip = false;
1711     // TODO : Verify memory is in VK_IMAGE_STATE_CLEAR state
1712     const auto *cb_node = GetCBState(commandBuffer);
1713     const auto *image_state = GetImageState(image);
1714     if (cb_node && image_state) {
1715         skip |= ValidateMemoryIsBoundToImage(image_state, "vkCmdClearColorImage()", "VUID-vkCmdClearColorImage-image-00003");
1716         skip |= ValidateCmdQueueFlags(cb_node, "vkCmdClearColorImage()", VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT,
1717                                       "VUID-vkCmdClearColorImage-commandBuffer-cmdpool");
1718         skip |= ValidateCmd(cb_node, CMD_CLEARCOLORIMAGE, "vkCmdClearColorImage()");
1719         if (api_version >= VK_API_VERSION_1_1 || device_extensions.vk_khr_maintenance1) {
1720             skip |=
1721                 ValidateImageFormatFeatureFlags(image_state, VK_FORMAT_FEATURE_TRANSFER_DST_BIT, "vkCmdClearColorImage",
1722                                                 "VUID-vkCmdClearColorImage-image-01993", "VUID-vkCmdClearColorImage-image-01993");
1723         }
1724         skip |= InsideRenderPass(cb_node, "vkCmdClearColorImage()", "VUID-vkCmdClearColorImage-renderpass");
1725         for (uint32_t i = 0; i < rangeCount; ++i) {
1726             std::string param_name = "pRanges[" + std::to_string(i) + "]";
1727             skip |= ValidateCmdClearColorSubresourceRange(image_state, pRanges[i], param_name.c_str());
1728             skip |= ValidateImageAttributes(image_state, pRanges[i]);
1729             skip |= VerifyClearImageLayout(cb_node, image_state, pRanges[i], imageLayout, "vkCmdClearColorImage()");
1730         }
1731     }
1732     return skip;
1733 }
1734 
PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer,VkImage image,VkImageLayout imageLayout,const VkClearColorValue * pColor,uint32_t rangeCount,const VkImageSubresourceRange * pRanges)1735 void ValidationStateTracker::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image,
1736                                                              VkImageLayout imageLayout, const VkClearColorValue *pColor,
1737                                                              uint32_t rangeCount, const VkImageSubresourceRange *pRanges) {
1738     auto cb_node = GetCBState(commandBuffer);
1739     auto image_state = GetImageState(image);
1740     if (cb_node && image_state) {
1741         AddCommandBufferBindingImage(cb_node, image_state);
1742     }
1743 }
1744 
PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer,VkImage image,VkImageLayout imageLayout,const VkClearColorValue * pColor,uint32_t rangeCount,const VkImageSubresourceRange * pRanges)1745 void CoreChecks::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
1746                                                  const VkClearColorValue *pColor, uint32_t rangeCount,
1747                                                  const VkImageSubresourceRange *pRanges) {
1748     StateTracker::PreCallRecordCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges);
1749 
1750     auto cb_node = GetCBState(commandBuffer);
1751     auto image_state = GetImageState(image);
1752     if (cb_node && image_state) {
1753         for (uint32_t i = 0; i < rangeCount; ++i) {
1754             SetImageInitialLayout(cb_node, image, pRanges[i], imageLayout);
1755         }
1756     }
1757 }
1758 
PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer,VkImage image,VkImageLayout imageLayout,const VkClearDepthStencilValue * pDepthStencil,uint32_t rangeCount,const VkImageSubresourceRange * pRanges)1759 bool CoreChecks::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
1760                                                           const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
1761                                                           const VkImageSubresourceRange *pRanges) {
1762     bool skip = false;
1763 
1764     // TODO : Verify memory is in VK_IMAGE_STATE_CLEAR state
1765     const auto *cb_node = GetCBState(commandBuffer);
1766     const auto *image_state = GetImageState(image);
1767     if (cb_node && image_state) {
1768         skip |= ValidateMemoryIsBoundToImage(image_state, "vkCmdClearDepthStencilImage()",
1769                                              "VUID-vkCmdClearDepthStencilImage-image-00010");
1770         skip |= ValidateCmdQueueFlags(cb_node, "vkCmdClearDepthStencilImage()", VK_QUEUE_GRAPHICS_BIT,
1771                                       "VUID-vkCmdClearDepthStencilImage-commandBuffer-cmdpool");
1772         skip |= ValidateCmd(cb_node, CMD_CLEARDEPTHSTENCILIMAGE, "vkCmdClearDepthStencilImage()");
1773         if (api_version >= VK_API_VERSION_1_1 || device_extensions.vk_khr_maintenance1) {
1774             skip |= ValidateImageFormatFeatureFlags(image_state, VK_FORMAT_FEATURE_TRANSFER_DST_BIT, "vkCmdClearDepthStencilImage",
1775                                                     "VUID-vkCmdClearDepthStencilImage-image-01994",
1776                                                     "VUID-vkCmdClearDepthStencilImage-image-01994");
1777         }
1778         skip |= InsideRenderPass(cb_node, "vkCmdClearDepthStencilImage()", "VUID-vkCmdClearDepthStencilImage-renderpass");
1779         for (uint32_t i = 0; i < rangeCount; ++i) {
1780             std::string param_name = "pRanges[" + std::to_string(i) + "]";
1781             skip |= ValidateCmdClearDepthSubresourceRange(image_state, pRanges[i], param_name.c_str());
1782             skip |= VerifyClearImageLayout(cb_node, image_state, pRanges[i], imageLayout, "vkCmdClearDepthStencilImage()");
1783             // Image aspect must be depth or stencil or both
1784             VkImageAspectFlags valid_aspects = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
1785             if (((pRanges[i].aspectMask & valid_aspects) == 0) || ((pRanges[i].aspectMask & ~valid_aspects) != 0)) {
1786                 char const str[] =
1787                     "vkCmdClearDepthStencilImage aspectMasks for all subresource ranges must be set to VK_IMAGE_ASPECT_DEPTH_BIT "
1788                     "and/or VK_IMAGE_ASPECT_STENCIL_BIT";
1789                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
1790                                 HandleToUint64(commandBuffer), kVUID_Core_DrawState_InvalidImageAspect, str);
1791             }
1792         }
1793         if (image_state && !FormatIsDepthOrStencil(image_state->createInfo.format)) {
1794             char const str[] = "vkCmdClearDepthStencilImage called without a depth/stencil image.";
1795             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
1796                             HandleToUint64(image), "VUID-vkCmdClearDepthStencilImage-image-00014", "%s.", str);
1797         }
1798         if (VK_IMAGE_USAGE_TRANSFER_DST_BIT != (VK_IMAGE_USAGE_TRANSFER_DST_BIT & image_state->createInfo.usage)) {
1799             char const str[] =
1800                 "vkCmdClearDepthStencilImage() called with an image that was not created with the VK_IMAGE_USAGE_TRANSFER_DST_BIT "
1801                 "set.";
1802             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
1803                             HandleToUint64(image), "VUID-vkCmdClearDepthStencilImage-image-00009", "%s.", str);
1804         }
1805     }
1806     return skip;
1807 }
1808 
PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer,VkImage image,VkImageLayout imageLayout,const VkClearDepthStencilValue * pDepthStencil,uint32_t rangeCount,const VkImageSubresourceRange * pRanges)1809 void ValidationStateTracker::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
1810                                                                     VkImageLayout imageLayout,
1811                                                                     const VkClearDepthStencilValue *pDepthStencil,
1812                                                                     uint32_t rangeCount, const VkImageSubresourceRange *pRanges) {
1813     auto cb_node = GetCBState(commandBuffer);
1814     auto image_state = GetImageState(image);
1815     if (cb_node && image_state) {
1816         AddCommandBufferBindingImage(cb_node, image_state);
1817     }
1818 }
1819 
PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer,VkImage image,VkImageLayout imageLayout,const VkClearDepthStencilValue * pDepthStencil,uint32_t rangeCount,const VkImageSubresourceRange * pRanges)1820 void CoreChecks::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
1821                                                         const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
1822                                                         const VkImageSubresourceRange *pRanges) {
1823     StateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges);
1824     auto cb_node = GetCBState(commandBuffer);
1825     auto image_state = GetImageState(image);
1826     if (cb_node && image_state) {
1827         for (uint32_t i = 0; i < rangeCount; ++i) {
1828             SetImageInitialLayout(cb_node, image, pRanges[i], imageLayout);
1829         }
1830     }
1831 }
1832 
1833 // Returns true if [x, xoffset] and [y, yoffset] overlap
RangesIntersect(int32_t start,uint32_t start_offset,int32_t end,uint32_t end_offset)1834 static bool RangesIntersect(int32_t start, uint32_t start_offset, int32_t end, uint32_t end_offset) {
1835     bool result = false;
1836     uint32_t intersection_min = std::max(static_cast<uint32_t>(start), static_cast<uint32_t>(end));
1837     uint32_t intersection_max = std::min(static_cast<uint32_t>(start) + start_offset, static_cast<uint32_t>(end) + end_offset);
1838 
1839     if (intersection_max > intersection_min) {
1840         result = true;
1841     }
1842     return result;
1843 }
1844 
1845 // Returns true if source area of first copy region intersects dest area of second region
1846 // It is assumed that these are copy regions within a single image (otherwise no possibility of collision)
RegionIntersects(const VkImageCopy * rgn0,const VkImageCopy * rgn1,VkImageType type,bool is_multiplane)1847 static bool RegionIntersects(const VkImageCopy *rgn0, const VkImageCopy *rgn1, VkImageType type, bool is_multiplane) {
1848     bool result = false;
1849 
1850     // Separate planes within a multiplane image cannot intersect
1851     if (is_multiplane && (rgn0->srcSubresource.aspectMask != rgn1->dstSubresource.aspectMask)) {
1852         return result;
1853     }
1854 
1855     if ((rgn0->srcSubresource.mipLevel == rgn1->dstSubresource.mipLevel) &&
1856         (RangesIntersect(rgn0->srcSubresource.baseArrayLayer, rgn0->srcSubresource.layerCount, rgn1->dstSubresource.baseArrayLayer,
1857                          rgn1->dstSubresource.layerCount))) {
1858         result = true;
1859         switch (type) {
1860             case VK_IMAGE_TYPE_3D:
1861                 result &= RangesIntersect(rgn0->srcOffset.z, rgn0->extent.depth, rgn1->dstOffset.z, rgn1->extent.depth);
1862                 // fall through
1863             case VK_IMAGE_TYPE_2D:
1864                 result &= RangesIntersect(rgn0->srcOffset.y, rgn0->extent.height, rgn1->dstOffset.y, rgn1->extent.height);
1865                 // fall through
1866             case VK_IMAGE_TYPE_1D:
1867                 result &= RangesIntersect(rgn0->srcOffset.x, rgn0->extent.width, rgn1->dstOffset.x, rgn1->extent.width);
1868                 break;
1869             default:
1870                 // Unrecognized or new IMAGE_TYPE enums will be caught in parameter_validation
1871                 assert(false);
1872         }
1873     }
1874     return result;
1875 }
1876 
1877 // Returns non-zero if offset and extent exceed image extents
1878 static const uint32_t x_bit = 1;
1879 static const uint32_t y_bit = 2;
1880 static const uint32_t z_bit = 4;
ExceedsBounds(const VkOffset3D * offset,const VkExtent3D * extent,const VkExtent3D * image_extent)1881 static uint32_t ExceedsBounds(const VkOffset3D *offset, const VkExtent3D *extent, const VkExtent3D *image_extent) {
1882     uint32_t result = 0;
1883     // Extents/depths cannot be negative but checks left in for clarity
1884     if ((offset->z + extent->depth > image_extent->depth) || (offset->z < 0) ||
1885         ((offset->z + static_cast<int32_t>(extent->depth)) < 0)) {
1886         result |= z_bit;
1887     }
1888     if ((offset->y + extent->height > image_extent->height) || (offset->y < 0) ||
1889         ((offset->y + static_cast<int32_t>(extent->height)) < 0)) {
1890         result |= y_bit;
1891     }
1892     if ((offset->x + extent->width > image_extent->width) || (offset->x < 0) ||
1893         ((offset->x + static_cast<int32_t>(extent->width)) < 0)) {
1894         result |= x_bit;
1895     }
1896     return result;
1897 }
1898 
1899 // Test if two VkExtent3D structs are equivalent
IsExtentEqual(const VkExtent3D * extent,const VkExtent3D * other_extent)1900 static inline bool IsExtentEqual(const VkExtent3D *extent, const VkExtent3D *other_extent) {
1901     bool result = true;
1902     if ((extent->width != other_extent->width) || (extent->height != other_extent->height) ||
1903         (extent->depth != other_extent->depth)) {
1904         result = false;
1905     }
1906     return result;
1907 }
1908 
1909 // For image copies between compressed/uncompressed formats, the extent is provided in source image texels
1910 // Destination image texel extents must be adjusted by block size for the dest validation checks
GetAdjustedDestImageExtent(VkFormat src_format,VkFormat dst_format,VkExtent3D extent)1911 VkExtent3D GetAdjustedDestImageExtent(VkFormat src_format, VkFormat dst_format, VkExtent3D extent) {
1912     VkExtent3D adjusted_extent = extent;
1913     if ((FormatIsCompressed(src_format) && (!FormatIsCompressed(dst_format)))) {
1914         VkExtent3D block_size = FormatTexelBlockExtent(src_format);
1915         adjusted_extent.width /= block_size.width;
1916         adjusted_extent.height /= block_size.height;
1917         adjusted_extent.depth /= block_size.depth;
1918     } else if ((!FormatIsCompressed(src_format) && (FormatIsCompressed(dst_format)))) {
1919         VkExtent3D block_size = FormatTexelBlockExtent(dst_format);
1920         adjusted_extent.width *= block_size.width;
1921         adjusted_extent.height *= block_size.height;
1922         adjusted_extent.depth *= block_size.depth;
1923     }
1924     return adjusted_extent;
1925 }
1926 
1927 // Returns the effective extent of an image subresource, adjusted for mip level and array depth.
GetImageSubresourceExtent(const IMAGE_STATE * img,const VkImageSubresourceLayers * subresource)1928 static inline VkExtent3D GetImageSubresourceExtent(const IMAGE_STATE *img, const VkImageSubresourceLayers *subresource) {
1929     const uint32_t mip = subresource->mipLevel;
1930 
1931     // Return zero extent if mip level doesn't exist
1932     if (mip >= img->createInfo.mipLevels) {
1933         return VkExtent3D{0, 0, 0};
1934     }
1935 
1936     // Don't allow mip adjustment to create 0 dim, but pass along a 0 if that's what subresource specified
1937     VkExtent3D extent = img->createInfo.extent;
1938 
1939     // If multi-plane, adjust per-plane extent
1940     if (FormatIsMultiplane(img->createInfo.format)) {
1941         VkExtent2D divisors = FindMultiplaneExtentDivisors(img->createInfo.format, subresource->aspectMask);
1942         extent.width /= divisors.width;
1943         extent.height /= divisors.height;
1944     }
1945 
1946     if (img->createInfo.flags & VK_IMAGE_CREATE_CORNER_SAMPLED_BIT_NV) {
1947         extent.width = (0 == extent.width ? 0 : std::max(2U, 1 + ((extent.width - 1) >> mip)));
1948         extent.height = (0 == extent.height ? 0 : std::max(2U, 1 + ((extent.height - 1) >> mip)));
1949         extent.depth = (0 == extent.depth ? 0 : std::max(2U, 1 + ((extent.depth - 1) >> mip)));
1950     } else {
1951         extent.width = (0 == extent.width ? 0 : std::max(1U, extent.width >> mip));
1952         extent.height = (0 == extent.height ? 0 : std::max(1U, extent.height >> mip));
1953         extent.depth = (0 == extent.depth ? 0 : std::max(1U, extent.depth >> mip));
1954     }
1955 
1956     // Image arrays have an effective z extent that isn't diminished by mip level
1957     if (VK_IMAGE_TYPE_3D != img->createInfo.imageType) {
1958         extent.depth = img->createInfo.arrayLayers;
1959     }
1960 
1961     return extent;
1962 }
1963 
1964 // Test if the extent argument has all dimensions set to 0.
IsExtentAllZeroes(const VkExtent3D * extent)1965 static inline bool IsExtentAllZeroes(const VkExtent3D *extent) {
1966     return ((extent->width == 0) && (extent->height == 0) && (extent->depth == 0));
1967 }
1968 
1969 // Test if the extent argument has any dimensions set to 0.
IsExtentSizeZero(const VkExtent3D * extent)1970 static inline bool IsExtentSizeZero(const VkExtent3D *extent) {
1971     return ((extent->width == 0) || (extent->height == 0) || (extent->depth == 0));
1972 }
1973 
1974 // Returns the image transfer granularity for a specific image scaled by compressed block size if necessary.
GetScaledItg(const CMD_BUFFER_STATE * cb_node,const IMAGE_STATE * img) const1975 VkExtent3D CoreChecks::GetScaledItg(const CMD_BUFFER_STATE *cb_node, const IMAGE_STATE *img) const {
1976     // Default to (0, 0, 0) granularity in case we can't find the real granularity for the physical device.
1977     VkExtent3D granularity = {0, 0, 0};
1978     auto pPool = GetCommandPoolState(cb_node->createInfo.commandPool);
1979     if (pPool) {
1980         granularity = GetPhysicalDeviceState()->queue_family_properties[pPool->queueFamilyIndex].minImageTransferGranularity;
1981         if (FormatIsCompressed(img->createInfo.format)) {
1982             auto block_size = FormatTexelBlockExtent(img->createInfo.format);
1983             granularity.width *= block_size.width;
1984             granularity.height *= block_size.height;
1985         }
1986     }
1987     return granularity;
1988 }
1989 
1990 // Test elements of a VkExtent3D structure against alignment constraints contained in another VkExtent3D structure
IsExtentAligned(const VkExtent3D * extent,const VkExtent3D * granularity)1991 static inline bool IsExtentAligned(const VkExtent3D *extent, const VkExtent3D *granularity) {
1992     bool valid = true;
1993     if ((SafeModulo(extent->depth, granularity->depth) != 0) || (SafeModulo(extent->width, granularity->width) != 0) ||
1994         (SafeModulo(extent->height, granularity->height) != 0)) {
1995         valid = false;
1996     }
1997     return valid;
1998 }
1999 
2000 // Check elements of a VkOffset3D structure against a queue family's Image Transfer Granularity values
CheckItgOffset(const CMD_BUFFER_STATE * cb_node,const VkOffset3D * offset,const VkExtent3D * granularity,const uint32_t i,const char * function,const char * member,const char * vuid) const2001 bool CoreChecks::CheckItgOffset(const CMD_BUFFER_STATE *cb_node, const VkOffset3D *offset, const VkExtent3D *granularity,
2002                                 const uint32_t i, const char *function, const char *member, const char *vuid) const {
2003     bool skip = false;
2004     VkExtent3D offset_extent = {};
2005     offset_extent.width = static_cast<uint32_t>(abs(offset->x));
2006     offset_extent.height = static_cast<uint32_t>(abs(offset->y));
2007     offset_extent.depth = static_cast<uint32_t>(abs(offset->z));
2008     if (IsExtentAllZeroes(granularity)) {
2009         // If the queue family image transfer granularity is (0, 0, 0), then the offset must always be (0, 0, 0)
2010         if (IsExtentAllZeroes(&offset_extent) == false) {
2011             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2012                             HandleToUint64(cb_node->commandBuffer), vuid,
2013                             "%s: pRegion[%d].%s (x=%d, y=%d, z=%d) must be (x=0, y=0, z=0) when the command buffer's queue family "
2014                             "image transfer granularity is (w=0, h=0, d=0).",
2015                             function, i, member, offset->x, offset->y, offset->z);
2016         }
2017     } else {
2018         // If the queue family image transfer granularity is not (0, 0, 0), then the offset dimensions must always be even
2019         // integer multiples of the image transfer granularity.
2020         if (IsExtentAligned(&offset_extent, granularity) == false) {
2021             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2022                             HandleToUint64(cb_node->commandBuffer), vuid,
2023                             "%s: pRegion[%d].%s (x=%d, y=%d, z=%d) dimensions must be even integer multiples of this command "
2024                             "buffer's queue family image transfer granularity (w=%d, h=%d, d=%d).",
2025                             function, i, member, offset->x, offset->y, offset->z, granularity->width, granularity->height,
2026                             granularity->depth);
2027         }
2028     }
2029     return skip;
2030 }
2031 
2032 // Check elements of a VkExtent3D structure against a queue family's Image Transfer Granularity values
CheckItgExtent(const CMD_BUFFER_STATE * cb_node,const VkExtent3D * extent,const VkOffset3D * offset,const VkExtent3D * granularity,const VkExtent3D * subresource_extent,const VkImageType image_type,const uint32_t i,const char * function,const char * member,const char * vuid) const2033 bool CoreChecks::CheckItgExtent(const CMD_BUFFER_STATE *cb_node, const VkExtent3D *extent, const VkOffset3D *offset,
2034                                 const VkExtent3D *granularity, const VkExtent3D *subresource_extent, const VkImageType image_type,
2035                                 const uint32_t i, const char *function, const char *member, const char *vuid) const {
2036     bool skip = false;
2037     if (IsExtentAllZeroes(granularity)) {
2038         // If the queue family image transfer granularity is (0, 0, 0), then the extent must always match the image
2039         // subresource extent.
2040         if (IsExtentEqual(extent, subresource_extent) == false) {
2041             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2042                             HandleToUint64(cb_node->commandBuffer), vuid,
2043                             "%s: pRegion[%d].%s (w=%d, h=%d, d=%d) must match the image subresource extents (w=%d, h=%d, d=%d) "
2044                             "when the command buffer's queue family image transfer granularity is (w=0, h=0, d=0).",
2045                             function, i, member, extent->width, extent->height, extent->depth, subresource_extent->width,
2046                             subresource_extent->height, subresource_extent->depth);
2047         }
2048     } else {
2049         // If the queue family image transfer granularity is not (0, 0, 0), then the extent dimensions must always be even
2050         // integer multiples of the image transfer granularity or the offset + extent dimensions must always match the image
2051         // subresource extent dimensions.
2052         VkExtent3D offset_extent_sum = {};
2053         offset_extent_sum.width = static_cast<uint32_t>(abs(offset->x)) + extent->width;
2054         offset_extent_sum.height = static_cast<uint32_t>(abs(offset->y)) + extent->height;
2055         offset_extent_sum.depth = static_cast<uint32_t>(abs(offset->z)) + extent->depth;
2056         bool x_ok = true;
2057         bool y_ok = true;
2058         bool z_ok = true;
2059         switch (image_type) {
2060             case VK_IMAGE_TYPE_3D:
2061                 z_ok = ((0 == SafeModulo(extent->depth, granularity->depth)) ||
2062                         (subresource_extent->depth == offset_extent_sum.depth));
2063                 // fall through
2064             case VK_IMAGE_TYPE_2D:
2065                 y_ok = ((0 == SafeModulo(extent->height, granularity->height)) ||
2066                         (subresource_extent->height == offset_extent_sum.height));
2067                 // fall through
2068             case VK_IMAGE_TYPE_1D:
2069                 x_ok = ((0 == SafeModulo(extent->width, granularity->width)) ||
2070                         (subresource_extent->width == offset_extent_sum.width));
2071                 break;
2072             default:
2073                 // Unrecognized or new IMAGE_TYPE enums will be caught in parameter_validation
2074                 assert(false);
2075         }
2076         if (!(x_ok && y_ok && z_ok)) {
2077             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2078                             HandleToUint64(cb_node->commandBuffer), vuid,
2079                             "%s: pRegion[%d].%s (w=%d, h=%d, d=%d) dimensions must be even integer multiples of this command "
2080                             "buffer's queue family image transfer granularity (w=%d, h=%d, d=%d) or offset (x=%d, y=%d, z=%d) + "
2081                             "extent (w=%d, h=%d, d=%d) must match the image subresource extents (w=%d, h=%d, d=%d).",
2082                             function, i, member, extent->width, extent->height, extent->depth, granularity->width,
2083                             granularity->height, granularity->depth, offset->x, offset->y, offset->z, extent->width, extent->height,
2084                             extent->depth, subresource_extent->width, subresource_extent->height, subresource_extent->depth);
2085         }
2086     }
2087     return skip;
2088 }
2089 
ValidateImageMipLevel(const CMD_BUFFER_STATE * cb_node,const IMAGE_STATE * img,uint32_t mip_level,const uint32_t i,const char * function,const char * member,const char * vuid) const2090 bool CoreChecks::ValidateImageMipLevel(const CMD_BUFFER_STATE *cb_node, const IMAGE_STATE *img, uint32_t mip_level,
2091                                        const uint32_t i, const char *function, const char *member, const char *vuid) const {
2092     bool skip = false;
2093     if (mip_level >= img->createInfo.mipLevels) {
2094         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2095                         HandleToUint64(cb_node->commandBuffer), vuid,
2096                         "In %s, pRegions[%u].%s.mipLevel is %u, but provided %s has %u mip levels.", function, i, member, mip_level,
2097                         report_data->FormatHandle(img->image).c_str(), img->createInfo.mipLevels);
2098     }
2099     return skip;
2100 }
2101 
ValidateImageArrayLayerRange(const CMD_BUFFER_STATE * cb_node,const IMAGE_STATE * img,const uint32_t base_layer,const uint32_t layer_count,const uint32_t i,const char * function,const char * member,const char * vuid) const2102 bool CoreChecks::ValidateImageArrayLayerRange(const CMD_BUFFER_STATE *cb_node, const IMAGE_STATE *img, const uint32_t base_layer,
2103                                               const uint32_t layer_count, const uint32_t i, const char *function,
2104                                               const char *member, const char *vuid) const {
2105     bool skip = false;
2106     if (base_layer >= img->createInfo.arrayLayers || layer_count > img->createInfo.arrayLayers ||
2107         (base_layer + layer_count) > img->createInfo.arrayLayers) {
2108         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2109                         HandleToUint64(cb_node->commandBuffer), vuid,
2110                         "In %s, pRegions[%u].%s.baseArrayLayer is %u and .layerCount is "
2111                         "%u, but provided %s has %u array layers.",
2112                         function, i, member, base_layer, layer_count, report_data->FormatHandle(img->image).c_str(),
2113                         img->createInfo.arrayLayers);
2114     }
2115     return skip;
2116 }
2117 
2118 // Check valid usage Image Transfer Granularity requirements for elements of a VkBufferImageCopy structure
ValidateCopyBufferImageTransferGranularityRequirements(const CMD_BUFFER_STATE * cb_node,const IMAGE_STATE * img,const VkBufferImageCopy * region,const uint32_t i,const char * function,const char * vuid) const2119 bool CoreChecks::ValidateCopyBufferImageTransferGranularityRequirements(const CMD_BUFFER_STATE *cb_node, const IMAGE_STATE *img,
2120                                                                         const VkBufferImageCopy *region, const uint32_t i,
2121                                                                         const char *function, const char *vuid) const {
2122     bool skip = false;
2123     VkExtent3D granularity = GetScaledItg(cb_node, img);
2124     skip |= CheckItgOffset(cb_node, &region->imageOffset, &granularity, i, function, "imageOffset", vuid);
2125     VkExtent3D subresource_extent = GetImageSubresourceExtent(img, &region->imageSubresource);
2126     skip |= CheckItgExtent(cb_node, &region->imageExtent, &region->imageOffset, &granularity, &subresource_extent,
2127                            img->createInfo.imageType, i, function, "imageExtent", vuid);
2128     return skip;
2129 }
2130 
2131 // Check valid usage Image Transfer Granularity requirements for elements of a VkImageCopy structure
ValidateCopyImageTransferGranularityRequirements(const CMD_BUFFER_STATE * cb_node,const IMAGE_STATE * src_img,const IMAGE_STATE * dst_img,const VkImageCopy * region,const uint32_t i,const char * function) const2132 bool CoreChecks::ValidateCopyImageTransferGranularityRequirements(const CMD_BUFFER_STATE *cb_node, const IMAGE_STATE *src_img,
2133                                                                   const IMAGE_STATE *dst_img, const VkImageCopy *region,
2134                                                                   const uint32_t i, const char *function) const {
2135     bool skip = false;
2136     // Source image checks
2137     VkExtent3D granularity = GetScaledItg(cb_node, src_img);
2138     skip |=
2139         CheckItgOffset(cb_node, &region->srcOffset, &granularity, i, function, "srcOffset", "VUID-vkCmdCopyImage-srcOffset-01783");
2140     VkExtent3D subresource_extent = GetImageSubresourceExtent(src_img, &region->srcSubresource);
2141     const VkExtent3D extent = region->extent;
2142     skip |= CheckItgExtent(cb_node, &extent, &region->srcOffset, &granularity, &subresource_extent, src_img->createInfo.imageType,
2143                            i, function, "extent", "VUID-vkCmdCopyImage-srcOffset-01783");
2144 
2145     // Destination image checks
2146     granularity = GetScaledItg(cb_node, dst_img);
2147     skip |=
2148         CheckItgOffset(cb_node, &region->dstOffset, &granularity, i, function, "dstOffset", "VUID-vkCmdCopyImage-dstOffset-01784");
2149     // Adjust dest extent, if necessary
2150     const VkExtent3D dest_effective_extent =
2151         GetAdjustedDestImageExtent(src_img->createInfo.format, dst_img->createInfo.format, extent);
2152     subresource_extent = GetImageSubresourceExtent(dst_img, &region->dstSubresource);
2153     skip |= CheckItgExtent(cb_node, &dest_effective_extent, &region->dstOffset, &granularity, &subresource_extent,
2154                            dst_img->createInfo.imageType, i, function, "extent", "VUID-vkCmdCopyImage-dstOffset-01784");
2155     return skip;
2156 }
2157 
2158 // Validate contents of a VkImageCopy struct
ValidateImageCopyData(const uint32_t regionCount,const VkImageCopy * ic_regions,const IMAGE_STATE * src_state,const IMAGE_STATE * dst_state) const2159 bool CoreChecks::ValidateImageCopyData(const uint32_t regionCount, const VkImageCopy *ic_regions, const IMAGE_STATE *src_state,
2160                                        const IMAGE_STATE *dst_state) const {
2161     bool skip = false;
2162 
2163     for (uint32_t i = 0; i < regionCount; i++) {
2164         const VkImageCopy region = ic_regions[i];
2165 
2166         // For comp<->uncomp copies, the copy extent for the dest image must be adjusted
2167         const VkExtent3D src_copy_extent = region.extent;
2168         const VkExtent3D dst_copy_extent =
2169             GetAdjustedDestImageExtent(src_state->createInfo.format, dst_state->createInfo.format, region.extent);
2170 
2171         bool slice_override = false;
2172         uint32_t depth_slices = 0;
2173 
2174         // Special case for copying between a 1D/2D array and a 3D image
2175         // TBD: This seems like the only way to reconcile 3 mutually-exclusive VU checks for 2D/3D copies. Heads up.
2176         if ((VK_IMAGE_TYPE_3D == src_state->createInfo.imageType) && (VK_IMAGE_TYPE_3D != dst_state->createInfo.imageType)) {
2177             depth_slices = region.dstSubresource.layerCount;  // Slice count from 2D subresource
2178             slice_override = (depth_slices != 1);
2179         } else if ((VK_IMAGE_TYPE_3D == dst_state->createInfo.imageType) && (VK_IMAGE_TYPE_3D != src_state->createInfo.imageType)) {
2180             depth_slices = region.srcSubresource.layerCount;  // Slice count from 2D subresource
2181             slice_override = (depth_slices != 1);
2182         }
2183 
2184         // Do all checks on source image
2185         //
2186         if (src_state->createInfo.imageType == VK_IMAGE_TYPE_1D) {
2187             if ((0 != region.srcOffset.y) || (1 != src_copy_extent.height)) {
2188                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
2189                                 HandleToUint64(src_state->image), "VUID-VkImageCopy-srcImage-00146",
2190                                 "vkCmdCopyImage(): pRegion[%d] srcOffset.y is %d and extent.height is %d. For 1D images these must "
2191                                 "be 0 and 1, respectively.",
2192                                 i, region.srcOffset.y, src_copy_extent.height);
2193             }
2194         }
2195 
2196         // VUID-VkImageCopy-srcImage-01785
2197         if ((src_state->createInfo.imageType == VK_IMAGE_TYPE_1D) && ((0 != region.srcOffset.z) || (1 != src_copy_extent.depth))) {
2198             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
2199                             HandleToUint64(src_state->image), "VUID-VkImageCopy-srcImage-01785",
2200                             "vkCmdCopyImage(): pRegion[%d] srcOffset.z is %d and extent.depth is %d. For 1D images "
2201                             "these must be 0 and 1, respectively.",
2202                             i, region.srcOffset.z, src_copy_extent.depth);
2203         }
2204 
2205         // VUID-VkImageCopy-srcImage-01787
2206         if ((src_state->createInfo.imageType == VK_IMAGE_TYPE_2D) && (0 != region.srcOffset.z)) {
2207             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
2208                             HandleToUint64(src_state->image), "VUID-VkImageCopy-srcImage-01787",
2209                             "vkCmdCopyImage(): pRegion[%d] srcOffset.z is %d. For 2D images the z-offset must be 0.", i,
2210                             region.srcOffset.z);
2211         }
2212 
2213         if (device_extensions.vk_khr_maintenance1) {
2214             if (src_state->createInfo.imageType == VK_IMAGE_TYPE_3D) {
2215                 if ((0 != region.srcSubresource.baseArrayLayer) || (1 != region.srcSubresource.layerCount)) {
2216                     skip |=
2217                         log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
2218                                 HandleToUint64(src_state->image), "VUID-VkImageCopy-srcImage-00141",
2219                                 "vkCmdCopyImage(): pRegion[%d] srcSubresource.baseArrayLayer is %d and srcSubresource.layerCount "
2220                                 "is %d. For VK_IMAGE_TYPE_3D images these must be 0 and 1, respectively.",
2221                                 i, region.srcSubresource.baseArrayLayer, region.srcSubresource.layerCount);
2222                 }
2223             }
2224         } else {  // Pre maint 1
2225             if (src_state->createInfo.imageType == VK_IMAGE_TYPE_3D || dst_state->createInfo.imageType == VK_IMAGE_TYPE_3D) {
2226                 if ((0 != region.srcSubresource.baseArrayLayer) || (1 != region.srcSubresource.layerCount)) {
2227                     skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
2228                                     HandleToUint64(src_state->image), "VUID-VkImageCopy-srcImage-00141",
2229                                     "vkCmdCopyImage(): pRegion[%d] srcSubresource.baseArrayLayer is %d and "
2230                                     "srcSubresource.layerCount is %d. For copies with either source or dest of type "
2231                                     "VK_IMAGE_TYPE_3D, these must be 0 and 1, respectively.",
2232                                     i, region.srcSubresource.baseArrayLayer, region.srcSubresource.layerCount);
2233                 }
2234             }
2235         }
2236 
2237         // Source checks that apply only to compressed images (or to _422 images if ycbcr enabled)
2238         bool ext_ycbcr = device_extensions.vk_khr_sampler_ycbcr_conversion;
2239         if (FormatIsCompressed(src_state->createInfo.format) ||
2240             (ext_ycbcr && FormatIsSinglePlane_422(src_state->createInfo.format))) {
2241             const VkExtent3D block_size = FormatTexelBlockExtent(src_state->createInfo.format);
2242             //  image offsets must be multiples of block dimensions
2243             if ((SafeModulo(region.srcOffset.x, block_size.width) != 0) ||
2244                 (SafeModulo(region.srcOffset.y, block_size.height) != 0) ||
2245                 (SafeModulo(region.srcOffset.z, block_size.depth) != 0)) {
2246                 const char *vuid = ext_ycbcr ? "VUID-VkImageCopy-srcImage-01727" : "VUID-VkImageCopy-srcOffset-00157";
2247                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
2248                                 HandleToUint64(src_state->image), vuid,
2249                                 "vkCmdCopyImage(): pRegion[%d] srcOffset (%d, %d) must be multiples of the compressed image's "
2250                                 "texel width & height (%d, %d).",
2251                                 i, region.srcOffset.x, region.srcOffset.y, block_size.width, block_size.height);
2252             }
2253 
2254             const VkExtent3D mip_extent = GetImageSubresourceExtent(src_state, &(region.srcSubresource));
2255             if ((SafeModulo(src_copy_extent.width, block_size.width) != 0) &&
2256                 (src_copy_extent.width + region.srcOffset.x != mip_extent.width)) {
2257                 const char *vuid = ext_ycbcr ? "VUID-VkImageCopy-srcImage-01728" : "VUID-VkImageCopy-extent-00158";
2258                 skip |=
2259                     log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
2260                             HandleToUint64(src_state->image), vuid,
2261                             "vkCmdCopyImage(): pRegion[%d] extent width (%d) must be a multiple of the compressed texture block "
2262                             "width (%d), or when added to srcOffset.x (%d) must equal the image subresource width (%d).",
2263                             i, src_copy_extent.width, block_size.width, region.srcOffset.x, mip_extent.width);
2264             }
2265 
2266             // Extent height must be a multiple of block height, or extent+offset height must equal subresource height
2267             if ((SafeModulo(src_copy_extent.height, block_size.height) != 0) &&
2268                 (src_copy_extent.height + region.srcOffset.y != mip_extent.height)) {
2269                 const char *vuid = ext_ycbcr ? "VUID-VkImageCopy-srcImage-01729" : "VUID-VkImageCopy-extent-00159";
2270                 skip |=
2271                     log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
2272                             HandleToUint64(src_state->image), vuid,
2273                             "vkCmdCopyImage(): pRegion[%d] extent height (%d) must be a multiple of the compressed texture block "
2274                             "height (%d), or when added to srcOffset.y (%d) must equal the image subresource height (%d).",
2275                             i, src_copy_extent.height, block_size.height, region.srcOffset.y, mip_extent.height);
2276             }
2277 
2278             // Extent depth must be a multiple of block depth, or extent+offset depth must equal subresource depth
2279             uint32_t copy_depth = (slice_override ? depth_slices : src_copy_extent.depth);
2280             if ((SafeModulo(copy_depth, block_size.depth) != 0) && (copy_depth + region.srcOffset.z != mip_extent.depth)) {
2281                 const char *vuid = ext_ycbcr ? "VUID-VkImageCopy-srcImage-01730" : "VUID-VkImageCopy-extent-00160";
2282                 skip |=
2283                     log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
2284                             HandleToUint64(src_state->image), vuid,
2285                             "vkCmdCopyImage(): pRegion[%d] extent width (%d) must be a multiple of the compressed texture block "
2286                             "depth (%d), or when added to srcOffset.z (%d) must equal the image subresource depth (%d).",
2287                             i, src_copy_extent.depth, block_size.depth, region.srcOffset.z, mip_extent.depth);
2288             }
2289         }  // Compressed
2290 
2291         // Do all checks on dest image
2292         //
2293         if (dst_state->createInfo.imageType == VK_IMAGE_TYPE_1D) {
2294             if ((0 != region.dstOffset.y) || (1 != dst_copy_extent.height)) {
2295                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
2296                                 HandleToUint64(dst_state->image), "VUID-VkImageCopy-dstImage-00152",
2297                                 "vkCmdCopyImage(): pRegion[%d] dstOffset.y is %d and dst_copy_extent.height is %d. For 1D images "
2298                                 "these must be 0 and 1, respectively.",
2299                                 i, region.dstOffset.y, dst_copy_extent.height);
2300             }
2301         }
2302 
2303         // VUID-VkImageCopy-dstImage-01786
2304         if ((dst_state->createInfo.imageType == VK_IMAGE_TYPE_1D) && ((0 != region.dstOffset.z) || (1 != dst_copy_extent.depth))) {
2305             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
2306                             HandleToUint64(dst_state->image), "VUID-VkImageCopy-dstImage-01786",
2307                             "vkCmdCopyImage(): pRegion[%d] dstOffset.z is %d and extent.depth is %d. For 1D images these must be 0 "
2308                             "and 1, respectively.",
2309                             i, region.dstOffset.z, dst_copy_extent.depth);
2310         }
2311 
2312         // VUID-VkImageCopy-dstImage-01788
2313         if ((dst_state->createInfo.imageType == VK_IMAGE_TYPE_2D) && (0 != region.dstOffset.z)) {
2314             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
2315                             HandleToUint64(dst_state->image), "VUID-VkImageCopy-dstImage-01788",
2316                             "vkCmdCopyImage(): pRegion[%d] dstOffset.z is %d. For 2D images the z-offset must be 0.", i,
2317                             region.dstOffset.z);
2318         }
2319 
2320         if (dst_state->createInfo.imageType == VK_IMAGE_TYPE_3D) {
2321             if ((0 != region.dstSubresource.baseArrayLayer) || (1 != region.dstSubresource.layerCount)) {
2322                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
2323                                 HandleToUint64(dst_state->image), "VUID-VkImageCopy-srcImage-00141",
2324                                 "vkCmdCopyImage(): pRegion[%d] dstSubresource.baseArrayLayer is %d and dstSubresource.layerCount "
2325                                 "is %d. For VK_IMAGE_TYPE_3D images these must be 0 and 1, respectively.",
2326                                 i, region.dstSubresource.baseArrayLayer, region.dstSubresource.layerCount);
2327             }
2328         }
2329         // VU01199 changed with mnt1
2330         if (device_extensions.vk_khr_maintenance1) {
2331             if (dst_state->createInfo.imageType == VK_IMAGE_TYPE_3D) {
2332                 if ((0 != region.dstSubresource.baseArrayLayer) || (1 != region.dstSubresource.layerCount)) {
2333                     skip |=
2334                         log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
2335                                 HandleToUint64(dst_state->image), "VUID-VkImageCopy-srcImage-00141",
2336                                 "vkCmdCopyImage(): pRegion[%d] dstSubresource.baseArrayLayer is %d and dstSubresource.layerCount "
2337                                 "is %d. For VK_IMAGE_TYPE_3D images these must be 0 and 1, respectively.",
2338                                 i, region.dstSubresource.baseArrayLayer, region.dstSubresource.layerCount);
2339                 }
2340             }
2341         } else {  // Pre maint 1
2342             if (src_state->createInfo.imageType == VK_IMAGE_TYPE_3D || dst_state->createInfo.imageType == VK_IMAGE_TYPE_3D) {
2343                 if ((0 != region.dstSubresource.baseArrayLayer) || (1 != region.dstSubresource.layerCount)) {
2344                     skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
2345                                     HandleToUint64(dst_state->image), "VUID-VkImageCopy-srcImage-00141",
2346                                     "vkCmdCopyImage(): pRegion[%d] dstSubresource.baseArrayLayer is %d and "
2347                                     "dstSubresource.layerCount is %d. For copies with either source or dest of type "
2348                                     "VK_IMAGE_TYPE_3D, these must be 0 and 1, respectively.",
2349                                     i, region.dstSubresource.baseArrayLayer, region.dstSubresource.layerCount);
2350                 }
2351             }
2352         }
2353 
2354         // Dest checks that apply only to compressed images (or to _422 images if ycbcr enabled)
2355         if (FormatIsCompressed(dst_state->createInfo.format) ||
2356             (ext_ycbcr && FormatIsSinglePlane_422(dst_state->createInfo.format))) {
2357             const VkExtent3D block_size = FormatTexelBlockExtent(dst_state->createInfo.format);
2358 
2359             //  image offsets must be multiples of block dimensions
2360             if ((SafeModulo(region.dstOffset.x, block_size.width) != 0) ||
2361                 (SafeModulo(region.dstOffset.y, block_size.height) != 0) ||
2362                 (SafeModulo(region.dstOffset.z, block_size.depth) != 0)) {
2363                 const char *vuid = ext_ycbcr ? "VUID-VkImageCopy-dstImage-01731" : "VUID-VkImageCopy-dstOffset-00162";
2364                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
2365                                 HandleToUint64(dst_state->image), vuid,
2366                                 "vkCmdCopyImage(): pRegion[%d] dstOffset (%d, %d) must be multiples of the compressed image's "
2367                                 "texel width & height (%d, %d).",
2368                                 i, region.dstOffset.x, region.dstOffset.y, block_size.width, block_size.height);
2369             }
2370 
2371             const VkExtent3D mip_extent = GetImageSubresourceExtent(dst_state, &(region.dstSubresource));
2372             if ((SafeModulo(dst_copy_extent.width, block_size.width) != 0) &&
2373                 (dst_copy_extent.width + region.dstOffset.x != mip_extent.width)) {
2374                 const char *vuid = ext_ycbcr ? "VUID-VkImageCopy-dstImage-01732" : "VUID-VkImageCopy-extent-00163";
2375                 skip |=
2376                     log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
2377                             HandleToUint64(dst_state->image), vuid,
2378                             "vkCmdCopyImage(): pRegion[%d] dst_copy_extent width (%d) must be a multiple of the compressed texture "
2379                             "block width (%d), or when added to dstOffset.x (%d) must equal the image subresource width (%d).",
2380                             i, dst_copy_extent.width, block_size.width, region.dstOffset.x, mip_extent.width);
2381             }
2382 
2383             // Extent height must be a multiple of block height, or dst_copy_extent+offset height must equal subresource height
2384             if ((SafeModulo(dst_copy_extent.height, block_size.height) != 0) &&
2385                 (dst_copy_extent.height + region.dstOffset.y != mip_extent.height)) {
2386                 const char *vuid = ext_ycbcr ? "VUID-VkImageCopy-dstImage-01733" : "VUID-VkImageCopy-extent-00164";
2387                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
2388                                 HandleToUint64(dst_state->image), vuid,
2389                                 "vkCmdCopyImage(): pRegion[%d] dst_copy_extent height (%d) must be a multiple of the compressed "
2390                                 "texture block height (%d), or when added to dstOffset.y (%d) must equal the image subresource "
2391                                 "height (%d).",
2392                                 i, dst_copy_extent.height, block_size.height, region.dstOffset.y, mip_extent.height);
2393             }
2394 
2395             // Extent depth must be a multiple of block depth, or dst_copy_extent+offset depth must equal subresource depth
2396             uint32_t copy_depth = (slice_override ? depth_slices : dst_copy_extent.depth);
2397             if ((SafeModulo(copy_depth, block_size.depth) != 0) && (copy_depth + region.dstOffset.z != mip_extent.depth)) {
2398                 const char *vuid = ext_ycbcr ? "VUID-VkImageCopy-dstImage-01734" : "VUID-VkImageCopy-extent-00165";
2399                 skip |=
2400                     log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
2401                             HandleToUint64(dst_state->image), vuid,
2402                             "vkCmdCopyImage(): pRegion[%d] dst_copy_extent width (%d) must be a multiple of the compressed texture "
2403                             "block depth (%d), or when added to dstOffset.z (%d) must equal the image subresource depth (%d).",
2404                             i, dst_copy_extent.depth, block_size.depth, region.dstOffset.z, mip_extent.depth);
2405             }
2406         }  // Compressed
2407     }
2408     return skip;
2409 }
2410 
2411 // vkCmdCopyImage checks that only apply if the multiplane extension is enabled
CopyImageMultiplaneValidation(VkCommandBuffer command_buffer,const IMAGE_STATE * src_image_state,const IMAGE_STATE * dst_image_state,const VkImageCopy region) const2412 bool CoreChecks::CopyImageMultiplaneValidation(VkCommandBuffer command_buffer, const IMAGE_STATE *src_image_state,
2413                                                const IMAGE_STATE *dst_image_state, const VkImageCopy region) const {
2414     bool skip = false;
2415 
2416     // Neither image is multiplane
2417     if ((!FormatIsMultiplane(src_image_state->createInfo.format)) && (!FormatIsMultiplane(dst_image_state->createInfo.format))) {
2418         // If neither image is multi-plane the aspectMask member of src and dst must match
2419         if (region.srcSubresource.aspectMask != region.dstSubresource.aspectMask) {
2420             std::stringstream ss;
2421             ss << "vkCmdCopyImage(): Copy between non-multiplane images with differing aspectMasks ( 0x" << std::hex
2422                << region.srcSubresource.aspectMask << " and 0x" << region.dstSubresource.aspectMask << " )";
2423             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2424                             HandleToUint64(command_buffer), "VUID-VkImageCopy-srcImage-01551", "%s.", ss.str().c_str());
2425         }
2426     } else {
2427         // Source image multiplane checks
2428         uint32_t planes = FormatPlaneCount(src_image_state->createInfo.format);
2429         VkImageAspectFlags aspect = region.srcSubresource.aspectMask;
2430         if ((2 == planes) && (aspect != VK_IMAGE_ASPECT_PLANE_0_BIT_KHR) && (aspect != VK_IMAGE_ASPECT_PLANE_1_BIT_KHR)) {
2431             std::stringstream ss;
2432             ss << "vkCmdCopyImage(): Source image aspect mask (0x" << std::hex << aspect << ") is invalid for 2-plane format";
2433             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2434                             HandleToUint64(command_buffer), "VUID-VkImageCopy-srcImage-01552", "%s.", ss.str().c_str());
2435         }
2436         if ((3 == planes) && (aspect != VK_IMAGE_ASPECT_PLANE_0_BIT_KHR) && (aspect != VK_IMAGE_ASPECT_PLANE_1_BIT_KHR) &&
2437             (aspect != VK_IMAGE_ASPECT_PLANE_2_BIT_KHR)) {
2438             std::stringstream ss;
2439             ss << "vkCmdCopyImage(): Source image aspect mask (0x" << std::hex << aspect << ") is invalid for 3-plane format";
2440             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2441                             HandleToUint64(command_buffer), "VUID-VkImageCopy-srcImage-01553", "%s.", ss.str().c_str());
2442         }
2443         // Single-plane to multi-plane
2444         if ((!FormatIsMultiplane(src_image_state->createInfo.format)) && (FormatIsMultiplane(dst_image_state->createInfo.format)) &&
2445             (VK_IMAGE_ASPECT_COLOR_BIT != aspect)) {
2446             std::stringstream ss;
2447             ss << "vkCmdCopyImage(): Source image aspect mask (0x" << std::hex << aspect << ") is not VK_IMAGE_ASPECT_COLOR_BIT";
2448             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2449                             HandleToUint64(command_buffer), "VUID-VkImageCopy-dstImage-01557", "%s.", ss.str().c_str());
2450         }
2451 
2452         // Dest image multiplane checks
2453         planes = FormatPlaneCount(dst_image_state->createInfo.format);
2454         aspect = region.dstSubresource.aspectMask;
2455         if ((2 == planes) && (aspect != VK_IMAGE_ASPECT_PLANE_0_BIT_KHR) && (aspect != VK_IMAGE_ASPECT_PLANE_1_BIT_KHR)) {
2456             std::stringstream ss;
2457             ss << "vkCmdCopyImage(): Dest image aspect mask (0x" << std::hex << aspect << ") is invalid for 2-plane format";
2458             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2459                             HandleToUint64(command_buffer), "VUID-VkImageCopy-dstImage-01554", "%s.", ss.str().c_str());
2460         }
2461         if ((3 == planes) && (aspect != VK_IMAGE_ASPECT_PLANE_0_BIT_KHR) && (aspect != VK_IMAGE_ASPECT_PLANE_1_BIT_KHR) &&
2462             (aspect != VK_IMAGE_ASPECT_PLANE_2_BIT_KHR)) {
2463             std::stringstream ss;
2464             ss << "vkCmdCopyImage(): Dest image aspect mask (0x" << std::hex << aspect << ") is invalid for 3-plane format";
2465             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2466                             HandleToUint64(command_buffer), "VUID-VkImageCopy-dstImage-01555", "%s.", ss.str().c_str());
2467         }
2468         // Multi-plane to single-plane
2469         if ((FormatIsMultiplane(src_image_state->createInfo.format)) && (!FormatIsMultiplane(dst_image_state->createInfo.format)) &&
2470             (VK_IMAGE_ASPECT_COLOR_BIT != aspect)) {
2471             std::stringstream ss;
2472             ss << "vkCmdCopyImage(): Dest image aspect mask (0x" << std::hex << aspect << ") is not VK_IMAGE_ASPECT_COLOR_BIT";
2473             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2474                             HandleToUint64(command_buffer), "VUID-VkImageCopy-srcImage-01556", "%s.", ss.str().c_str());
2475         }
2476     }
2477 
2478     return skip;
2479 }
2480 
PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer,VkImage srcImage,VkImageLayout srcImageLayout,VkImage dstImage,VkImageLayout dstImageLayout,uint32_t regionCount,const VkImageCopy * pRegions)2481 bool CoreChecks::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2482                                              VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2483                                              const VkImageCopy *pRegions) {
2484     const auto *cb_node = GetCBState(commandBuffer);
2485     const auto *src_image_state = GetImageState(srcImage);
2486     const auto *dst_image_state = GetImageState(dstImage);
2487     bool skip = false;
2488 
2489     skip = ValidateImageCopyData(regionCount, pRegions, src_image_state, dst_image_state);
2490 
2491     VkCommandBuffer command_buffer = cb_node->commandBuffer;
2492 
2493     for (uint32_t i = 0; i < regionCount; i++) {
2494         const VkImageCopy region = pRegions[i];
2495 
2496         // For comp/uncomp copies, the copy extent for the dest image must be adjusted
2497         VkExtent3D src_copy_extent = region.extent;
2498         VkExtent3D dst_copy_extent =
2499             GetAdjustedDestImageExtent(src_image_state->createInfo.format, dst_image_state->createInfo.format, region.extent);
2500 
2501         bool slice_override = false;
2502         uint32_t depth_slices = 0;
2503 
2504         // Special case for copying between a 1D/2D array and a 3D image
2505         // TBD: This seems like the only way to reconcile 3 mutually-exclusive VU checks for 2D/3D copies. Heads up.
2506         if ((VK_IMAGE_TYPE_3D == src_image_state->createInfo.imageType) &&
2507             (VK_IMAGE_TYPE_3D != dst_image_state->createInfo.imageType)) {
2508             depth_slices = region.dstSubresource.layerCount;  // Slice count from 2D subresource
2509             slice_override = (depth_slices != 1);
2510         } else if ((VK_IMAGE_TYPE_3D == dst_image_state->createInfo.imageType) &&
2511                    (VK_IMAGE_TYPE_3D != src_image_state->createInfo.imageType)) {
2512             depth_slices = region.srcSubresource.layerCount;  // Slice count from 2D subresource
2513             slice_override = (depth_slices != 1);
2514         }
2515 
2516         skip |= ValidateImageSubresourceLayers(cb_node, &region.srcSubresource, "vkCmdCopyImage", "srcSubresource", i);
2517         skip |= ValidateImageSubresourceLayers(cb_node, &region.dstSubresource, "vkCmdCopyImage", "dstSubresource", i);
2518         skip |= ValidateImageMipLevel(cb_node, src_image_state, region.srcSubresource.mipLevel, i, "vkCmdCopyImage",
2519                                       "srcSubresource", "VUID-vkCmdCopyImage-srcSubresource-01696");
2520         skip |= ValidateImageMipLevel(cb_node, dst_image_state, region.dstSubresource.mipLevel, i, "vkCmdCopyImage",
2521                                       "dstSubresource", "VUID-vkCmdCopyImage-dstSubresource-01697");
2522         skip |= ValidateImageArrayLayerRange(cb_node, src_image_state, region.srcSubresource.baseArrayLayer,
2523                                              region.srcSubresource.layerCount, i, "vkCmdCopyImage", "srcSubresource",
2524                                              "VUID-vkCmdCopyImage-srcSubresource-01698");
2525         skip |= ValidateImageArrayLayerRange(cb_node, dst_image_state, region.dstSubresource.baseArrayLayer,
2526                                              region.dstSubresource.layerCount, i, "vkCmdCopyImage", "dstSubresource",
2527                                              "VUID-vkCmdCopyImage-dstSubresource-01699");
2528 
2529         if (device_extensions.vk_khr_maintenance1) {
2530             // No chance of mismatch if we're overriding depth slice count
2531             if (!slice_override) {
2532                 // The number of depth slices in srcSubresource and dstSubresource must match
2533                 // Depth comes from layerCount for 1D,2D resources, from extent.depth for 3D
2534                 uint32_t src_slices =
2535                     (VK_IMAGE_TYPE_3D == src_image_state->createInfo.imageType ? src_copy_extent.depth
2536                                                                                : region.srcSubresource.layerCount);
2537                 uint32_t dst_slices =
2538                     (VK_IMAGE_TYPE_3D == dst_image_state->createInfo.imageType ? dst_copy_extent.depth
2539                                                                                : region.dstSubresource.layerCount);
2540                 if (src_slices != dst_slices) {
2541                     std::stringstream ss;
2542                     ss << "vkCmdCopyImage(): number of depth slices in source and destination subresources for pRegions[" << i
2543                        << "] do not match";
2544                     skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2545                                     HandleToUint64(command_buffer), "VUID-VkImageCopy-extent-00140", "%s.", ss.str().c_str());
2546                 }
2547             }
2548         } else {
2549             // For each region the layerCount member of srcSubresource and dstSubresource must match
2550             if (region.srcSubresource.layerCount != region.dstSubresource.layerCount) {
2551                 std::stringstream ss;
2552                 ss << "vkCmdCopyImage(): number of layers in source and destination subresources for pRegions[" << i
2553                    << "] do not match";
2554                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2555                                 HandleToUint64(command_buffer), "VUID-VkImageCopy-extent-00140", "%s.", ss.str().c_str());
2556             }
2557         }
2558 
2559         // Do multiplane-specific checks, if extension enabled
2560         if (device_extensions.vk_khr_sampler_ycbcr_conversion) {
2561             skip |= CopyImageMultiplaneValidation(command_buffer, src_image_state, dst_image_state, region);
2562         }
2563 
2564         if (!device_extensions.vk_khr_sampler_ycbcr_conversion) {
2565             // not multi-plane, the aspectMask member of srcSubresource and dstSubresource must match
2566             if (region.srcSubresource.aspectMask != region.dstSubresource.aspectMask) {
2567                 char const str[] = "vkCmdCopyImage(): Src and dest aspectMasks for each region must match";
2568                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2569                                 HandleToUint64(command_buffer), "VUID-VkImageCopy-aspectMask-00137", "%s.", str);
2570             }
2571         }
2572 
2573         // For each region, the aspectMask member of srcSubresource must be present in the source image
2574         if (!VerifyAspectsPresent(region.srcSubresource.aspectMask, src_image_state->createInfo.format)) {
2575             std::stringstream ss;
2576             ss << "vkCmdCopyImage(): pRegion[" << i
2577                << "] srcSubresource.aspectMask cannot specify aspects not present in source image";
2578             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2579                             HandleToUint64(command_buffer), "VUID-VkImageCopy-aspectMask-00142", "%s.", ss.str().c_str());
2580         }
2581 
2582         // For each region, the aspectMask member of dstSubresource must be present in the destination image
2583         if (!VerifyAspectsPresent(region.dstSubresource.aspectMask, dst_image_state->createInfo.format)) {
2584             std::stringstream ss;
2585             ss << "vkCmdCopyImage(): pRegion[" << i
2586                << "] dstSubresource.aspectMask cannot specify aspects not present in dest image";
2587             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2588                             HandleToUint64(command_buffer), "VUID-VkImageCopy-aspectMask-00143", "%s.", ss.str().c_str());
2589         }
2590 
2591         // Check region extents for 1D-1D, 2D-2D, and 3D-3D copies
2592         if (src_image_state->createInfo.imageType == dst_image_state->createInfo.imageType) {
2593             // The source region specified by a given element of regions must be a region that is contained within srcImage
2594             VkExtent3D img_extent = GetImageSubresourceExtent(src_image_state, &(region.srcSubresource));
2595             if (0 != ExceedsBounds(&region.srcOffset, &src_copy_extent, &img_extent)) {
2596                 std::stringstream ss;
2597                 ss << "vkCmdCopyImage(): Source pRegion[" << i << "] with mipLevel [ " << region.srcSubresource.mipLevel
2598                    << " ], offset [ " << region.srcOffset.x << ", " << region.srcOffset.y << ", " << region.srcOffset.z
2599                    << " ], extent [ " << src_copy_extent.width << ", " << src_copy_extent.height << ", " << src_copy_extent.depth
2600                    << " ] exceeds the source image dimensions";
2601                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2602                                 HandleToUint64(command_buffer), "VUID-vkCmdCopyImage-pRegions-00122", "%s.", ss.str().c_str());
2603             }
2604 
2605             // The destination region specified by a given element of regions must be a region that is contained within dst_image
2606             img_extent = GetImageSubresourceExtent(dst_image_state, &(region.dstSubresource));
2607             if (0 != ExceedsBounds(&region.dstOffset, &dst_copy_extent, &img_extent)) {
2608                 std::stringstream ss;
2609                 ss << "vkCmdCopyImage(): Dest pRegion[" << i << "] with mipLevel [ " << region.dstSubresource.mipLevel
2610                    << " ], offset [ " << region.dstOffset.x << ", " << region.dstOffset.y << ", " << region.dstOffset.z
2611                    << " ], extent [ " << dst_copy_extent.width << ", " << dst_copy_extent.height << ", " << dst_copy_extent.depth
2612                    << " ] exceeds the destination image dimensions";
2613                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2614                                 HandleToUint64(command_buffer), "VUID-vkCmdCopyImage-pRegions-00123", "%s.", ss.str().c_str());
2615             }
2616         }
2617 
2618         // Each dimension offset + extent limits must fall with image subresource extent
2619         VkExtent3D subresource_extent = GetImageSubresourceExtent(src_image_state, &(region.srcSubresource));
2620         if (slice_override) src_copy_extent.depth = depth_slices;
2621         uint32_t extent_check = ExceedsBounds(&(region.srcOffset), &src_copy_extent, &subresource_extent);
2622         if (extent_check & x_bit) {
2623             skip |=
2624                 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2625                         HandleToUint64(command_buffer), "VUID-VkImageCopy-srcOffset-00144",
2626                         "vkCmdCopyImage(): Source image pRegion %1d x-dimension offset [%1d] + extent [%1d] exceeds subResource "
2627                         "width [%1d].",
2628                         i, region.srcOffset.x, src_copy_extent.width, subresource_extent.width);
2629         }
2630 
2631         if (extent_check & y_bit) {
2632             skip |=
2633                 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2634                         HandleToUint64(command_buffer), "VUID-VkImageCopy-srcOffset-00145",
2635                         "vkCmdCopyImage(): Source image pRegion %1d y-dimension offset [%1d] + extent [%1d] exceeds subResource "
2636                         "height [%1d].",
2637                         i, region.srcOffset.y, src_copy_extent.height, subresource_extent.height);
2638         }
2639         if (extent_check & z_bit) {
2640             skip |=
2641                 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2642                         HandleToUint64(command_buffer), "VUID-VkImageCopy-srcOffset-00147",
2643                         "vkCmdCopyImage(): Source image pRegion %1d z-dimension offset [%1d] + extent [%1d] exceeds subResource "
2644                         "depth [%1d].",
2645                         i, region.srcOffset.z, src_copy_extent.depth, subresource_extent.depth);
2646         }
2647 
2648         // Adjust dest extent if necessary
2649         subresource_extent = GetImageSubresourceExtent(dst_image_state, &(region.dstSubresource));
2650         if (slice_override) dst_copy_extent.depth = depth_slices;
2651 
2652         extent_check = ExceedsBounds(&(region.dstOffset), &dst_copy_extent, &subresource_extent);
2653         if (extent_check & x_bit) {
2654             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2655                             HandleToUint64(command_buffer), "VUID-VkImageCopy-dstOffset-00150",
2656                             "vkCmdCopyImage(): Dest image pRegion %1d x-dimension offset [%1d] + extent [%1d] exceeds subResource "
2657                             "width [%1d].",
2658                             i, region.dstOffset.x, dst_copy_extent.width, subresource_extent.width);
2659         }
2660         if (extent_check & y_bit) {
2661             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2662                             HandleToUint64(command_buffer), "VUID-VkImageCopy-dstOffset-00151",
2663                             "vkCmdCopyImage(): Dest image pRegion %1d y-dimension offset [%1d] + extent [%1d] exceeds subResource "
2664                             "height [%1d].",
2665                             i, region.dstOffset.y, dst_copy_extent.height, subresource_extent.height);
2666         }
2667         if (extent_check & z_bit) {
2668             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2669                             HandleToUint64(command_buffer), "VUID-VkImageCopy-dstOffset-00153",
2670                             "vkCmdCopyImage(): Dest image pRegion %1d z-dimension offset [%1d] + extent [%1d] exceeds subResource "
2671                             "depth [%1d].",
2672                             i, region.dstOffset.z, dst_copy_extent.depth, subresource_extent.depth);
2673         }
2674 
2675         // The union of all source regions, and the union of all destination regions, specified by the elements of regions,
2676         // must not overlap in memory
2677         if (src_image_state->image == dst_image_state->image) {
2678             for (uint32_t j = 0; j < regionCount; j++) {
2679                 if (RegionIntersects(&region, &pRegions[j], src_image_state->createInfo.imageType,
2680                                      FormatIsMultiplane(src_image_state->createInfo.format))) {
2681                     std::stringstream ss;
2682                     ss << "vkCmdCopyImage(): pRegions[" << i << "] src overlaps with pRegions[" << j << "].";
2683                     skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2684                                     HandleToUint64(command_buffer), "VUID-vkCmdCopyImage-pRegions-00124", "%s.", ss.str().c_str());
2685                 }
2686             }
2687         }
2688     }
2689 
2690     // The formats of src_image and dst_image must be compatible. Formats are considered compatible if their texel size in bytes
2691     // is the same between both formats. For example, VK_FORMAT_R8G8B8A8_UNORM is compatible with VK_FORMAT_R32_UINT because
2692     // because both texels are 4 bytes in size. Depth/stencil formats must match exactly.
2693     if (FormatIsDepthOrStencil(src_image_state->createInfo.format) || FormatIsDepthOrStencil(dst_image_state->createInfo.format)) {
2694         if (src_image_state->createInfo.format != dst_image_state->createInfo.format) {
2695             char const str[] = "vkCmdCopyImage called with unmatched source and dest image depth/stencil formats.";
2696             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2697                             HandleToUint64(command_buffer), kVUID_Core_DrawState_MismatchedImageFormat, str);
2698         }
2699     } else {
2700         if (!FormatSizesAreEqual(src_image_state->createInfo.format, dst_image_state->createInfo.format, regionCount, pRegions)) {
2701             char const str[] = "vkCmdCopyImage called with unmatched source and dest image format sizes.";
2702             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2703                             HandleToUint64(command_buffer), "VUID-vkCmdCopyImage-srcImage-00135", "%s.", str);
2704         }
2705     }
2706 
2707     // Source and dest image sample counts must match
2708     if (src_image_state->createInfo.samples != dst_image_state->createInfo.samples) {
2709         char const str[] = "vkCmdCopyImage() called on image pair with non-identical sample counts.";
2710         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2711                         HandleToUint64(command_buffer), "VUID-vkCmdCopyImage-srcImage-00136", "%s", str);
2712     }
2713 
2714     skip |= ValidateMemoryIsBoundToImage(src_image_state, "vkCmdCopyImage()", "VUID-vkCmdCopyImage-srcImage-00127");
2715     skip |= ValidateMemoryIsBoundToImage(dst_image_state, "vkCmdCopyImage()", "VUID-vkCmdCopyImage-dstImage-00132");
2716     // Validate that SRC & DST images have correct usage flags set
2717     skip |= ValidateImageUsageFlags(src_image_state, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, true, "VUID-vkCmdCopyImage-srcImage-00126",
2718                                     "vkCmdCopyImage()", "VK_IMAGE_USAGE_TRANSFER_SRC_BIT");
2719     skip |= ValidateImageUsageFlags(dst_image_state, VK_IMAGE_USAGE_TRANSFER_DST_BIT, true, "VUID-vkCmdCopyImage-dstImage-00131",
2720                                     "vkCmdCopyImage()", "VK_IMAGE_USAGE_TRANSFER_DST_BIT");
2721     if (api_version >= VK_API_VERSION_1_1 || device_extensions.vk_khr_maintenance1) {
2722         skip |= ValidateImageFormatFeatureFlags(src_image_state, VK_FORMAT_FEATURE_TRANSFER_SRC_BIT, "vkCmdCopyImage()",
2723                                                 "VUID-vkCmdCopyImage-srcImage-01995", "VUID-vkCmdCopyImage-srcImage-01995");
2724         skip |= ValidateImageFormatFeatureFlags(dst_image_state, VK_FORMAT_FEATURE_TRANSFER_DST_BIT, "vkCmdCopyImage()",
2725                                                 "VUID-vkCmdCopyImage-dstImage-01996", "VUID-vkCmdCopyImage-dstImage-01996");
2726     }
2727     skip |= ValidateCmdQueueFlags(cb_node, "vkCmdCopyImage()", VK_QUEUE_TRANSFER_BIT | VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT,
2728                                   "VUID-vkCmdCopyImage-commandBuffer-cmdpool");
2729     skip |= ValidateCmd(cb_node, CMD_COPYIMAGE, "vkCmdCopyImage()");
2730     skip |= InsideRenderPass(cb_node, "vkCmdCopyImage()", "VUID-vkCmdCopyImage-renderpass");
2731     bool hit_error = false;
2732     const char *invalid_src_layout_vuid = (src_image_state->shared_presentable && device_extensions.vk_khr_shared_presentable_image)
2733                                               ? "VUID-vkCmdCopyImage-srcImageLayout-01917"
2734                                               : "VUID-vkCmdCopyImage-srcImageLayout-00129";
2735     const char *invalid_dst_layout_vuid = (dst_image_state->shared_presentable && device_extensions.vk_khr_shared_presentable_image)
2736                                               ? "VUID-vkCmdCopyImage-dstImageLayout-01395"
2737                                               : "VUID-vkCmdCopyImage-dstImageLayout-00134";
2738     for (uint32_t i = 0; i < regionCount; ++i) {
2739         skip |= VerifyImageLayout(cb_node, src_image_state, pRegions[i].srcSubresource, srcImageLayout,
2740                                   VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, "vkCmdCopyImage()", invalid_src_layout_vuid,
2741                                   "VUID-vkCmdCopyImage-srcImageLayout-00128", &hit_error);
2742         skip |= VerifyImageLayout(cb_node, dst_image_state, pRegions[i].dstSubresource, dstImageLayout,
2743                                   VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, "vkCmdCopyImage()", invalid_dst_layout_vuid,
2744                                   "VUID-vkCmdCopyImage-dstImageLayout-00133", &hit_error);
2745         skip |= ValidateCopyImageTransferGranularityRequirements(cb_node, src_image_state, dst_image_state, &pRegions[i], i,
2746                                                                  "vkCmdCopyImage()");
2747     }
2748 
2749     return skip;
2750 }
2751 
PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer,VkImage srcImage,VkImageLayout srcImageLayout,VkImage dstImage,VkImageLayout dstImageLayout,uint32_t regionCount,const VkImageCopy * pRegions)2752 void ValidationStateTracker::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage,
2753                                                        VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout,
2754                                                        uint32_t regionCount, const VkImageCopy *pRegions) {
2755     auto cb_node = GetCBState(commandBuffer);
2756     auto src_image_state = GetImageState(srcImage);
2757     auto dst_image_state = GetImageState(dstImage);
2758 
2759     // Update bindings between images and cmd buffer
2760     AddCommandBufferBindingImage(cb_node, src_image_state);
2761     AddCommandBufferBindingImage(cb_node, dst_image_state);
2762 }
2763 
PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer,VkImage srcImage,VkImageLayout srcImageLayout,VkImage dstImage,VkImageLayout dstImageLayout,uint32_t regionCount,const VkImageCopy * pRegions)2764 void CoreChecks::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2765                                            VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2766                                            const VkImageCopy *pRegions) {
2767     StateTracker::PreCallRecordCmdCopyImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
2768                                             pRegions);
2769     auto cb_node = GetCBState(commandBuffer);
2770     auto src_image_state = GetImageState(srcImage);
2771     auto dst_image_state = GetImageState(dstImage);
2772 
2773     // Make sure that all image slices are updated to correct layout
2774     for (uint32_t i = 0; i < regionCount; ++i) {
2775         SetImageInitialLayout(cb_node, *src_image_state, pRegions[i].srcSubresource, srcImageLayout);
2776         SetImageInitialLayout(cb_node, *dst_image_state, pRegions[i].dstSubresource, dstImageLayout);
2777     }
2778 }
2779 
2780 // Returns true if sub_rect is entirely contained within rect
ContainsRect(VkRect2D rect,VkRect2D sub_rect)2781 static inline bool ContainsRect(VkRect2D rect, VkRect2D sub_rect) {
2782     if ((sub_rect.offset.x < rect.offset.x) || (sub_rect.offset.x + sub_rect.extent.width > rect.offset.x + rect.extent.width) ||
2783         (sub_rect.offset.y < rect.offset.y) || (sub_rect.offset.y + sub_rect.extent.height > rect.offset.y + rect.extent.height))
2784         return false;
2785     return true;
2786 }
2787 
ValidateClearAttachmentExtent(VkCommandBuffer command_buffer,uint32_t attachment_index,const FRAMEBUFFER_STATE * framebuffer,uint32_t fb_attachment,const VkRect2D & render_area,uint32_t rect_count,const VkClearRect * clear_rects) const2788 bool CoreChecks::ValidateClearAttachmentExtent(VkCommandBuffer command_buffer, uint32_t attachment_index,
2789                                                const FRAMEBUFFER_STATE *framebuffer, uint32_t fb_attachment,
2790                                                const VkRect2D &render_area, uint32_t rect_count,
2791                                                const VkClearRect *clear_rects) const {
2792     bool skip = false;
2793     const IMAGE_VIEW_STATE *image_view_state = nullptr;
2794     if (framebuffer && (fb_attachment != VK_ATTACHMENT_UNUSED) && (fb_attachment < framebuffer->createInfo.attachmentCount)) {
2795         image_view_state = GetImageViewState(framebuffer->createInfo.pAttachments[fb_attachment]);
2796     }
2797 
2798     for (uint32_t j = 0; j < rect_count; j++) {
2799         if (!ContainsRect(render_area, clear_rects[j].rect)) {
2800             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2801                             HandleToUint64(command_buffer), "VUID-vkCmdClearAttachments-pRects-00016",
2802                             "vkCmdClearAttachments(): The area defined by pRects[%d] is not contained in the area of "
2803                             "the current render pass instance.",
2804                             j);
2805         }
2806 
2807         if (image_view_state) {
2808             // The layers specified by a given element of pRects must be contained within every attachment that
2809             // pAttachments refers to
2810             const auto attachment_layer_count = image_view_state->create_info.subresourceRange.layerCount;
2811             if ((clear_rects[j].baseArrayLayer >= attachment_layer_count) ||
2812                 (clear_rects[j].baseArrayLayer + clear_rects[j].layerCount > attachment_layer_count)) {
2813                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2814                                 HandleToUint64(command_buffer), "VUID-vkCmdClearAttachments-pRects-00017",
2815                                 "vkCmdClearAttachments(): The layers defined in pRects[%d] are not contained in the layers "
2816                                 "of pAttachment[%d].",
2817                                 j, attachment_index);
2818             }
2819         }
2820     }
2821     return skip;
2822 }
2823 
PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer,uint32_t attachmentCount,const VkClearAttachment * pAttachments,uint32_t rectCount,const VkClearRect * pRects)2824 bool CoreChecks::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
2825                                                     const VkClearAttachment *pAttachments, uint32_t rectCount,
2826                                                     const VkClearRect *pRects) {
2827     bool skip = false;
2828     const CMD_BUFFER_STATE *cb_node = GetCBState(commandBuffer);  // TODO: Should be const, and never modified during validation
2829     if (!cb_node) return skip;
2830 
2831     skip |= ValidateCmdQueueFlags(cb_node, "vkCmdClearAttachments()", VK_QUEUE_GRAPHICS_BIT,
2832                                   "VUID-vkCmdClearAttachments-commandBuffer-cmdpool");
2833     skip |= ValidateCmd(cb_node, CMD_CLEARATTACHMENTS, "vkCmdClearAttachments()");
2834     // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
2835     if (!cb_node->hasDrawCmd && (cb_node->activeRenderPassBeginInfo.renderArea.extent.width == pRects[0].rect.extent.width) &&
2836         (cb_node->activeRenderPassBeginInfo.renderArea.extent.height == pRects[0].rect.extent.height)) {
2837         // There are times where app needs to use ClearAttachments (generally when reusing a buffer inside of a render pass)
2838         // This warning should be made more specific. It'd be best to avoid triggering this test if it's a use that must call
2839         // CmdClearAttachments.
2840         skip |= log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2841                         HandleToUint64(commandBuffer), kVUID_Core_DrawState_ClearCmdBeforeDraw,
2842                         "vkCmdClearAttachments() issued on %s prior to any Draw Cmds. It is recommended you "
2843                         "use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
2844                         report_data->FormatHandle(commandBuffer).c_str());
2845     }
2846     skip |= OutsideRenderPass(cb_node, "vkCmdClearAttachments()", "VUID-vkCmdClearAttachments-renderpass");
2847 
2848     // Validate that attachment is in reference list of active subpass
2849     if (cb_node->activeRenderPass) {
2850         const VkRenderPassCreateInfo2KHR *renderpass_create_info = cb_node->activeRenderPass->createInfo.ptr();
2851         const uint32_t renderpass_attachment_count = renderpass_create_info->attachmentCount;
2852         const VkSubpassDescription2KHR *subpass_desc = &renderpass_create_info->pSubpasses[cb_node->activeSubpass];
2853         const auto *framebuffer = GetFramebufferState(cb_node->activeFramebuffer);
2854         const auto &render_area = cb_node->activeRenderPassBeginInfo.renderArea;
2855 
2856         for (uint32_t attachment_index = 0; attachment_index < attachmentCount; attachment_index++) {
2857             auto clear_desc = &pAttachments[attachment_index];
2858             uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
2859 
2860             if (0 == clear_desc->aspectMask) {
2861                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2862                                 HandleToUint64(commandBuffer), "VUID-VkClearAttachment-aspectMask-requiredbitmask", " ");
2863             } else if (clear_desc->aspectMask & VK_IMAGE_ASPECT_METADATA_BIT) {
2864                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2865                                 HandleToUint64(commandBuffer), "VUID-VkClearAttachment-aspectMask-00020", " ");
2866             } else if (clear_desc->aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
2867                 uint32_t color_attachment = VK_ATTACHMENT_UNUSED;
2868                 if (clear_desc->colorAttachment < subpass_desc->colorAttachmentCount) {
2869                     color_attachment = subpass_desc->pColorAttachments[clear_desc->colorAttachment].attachment;
2870                     if ((color_attachment != VK_ATTACHMENT_UNUSED) && (color_attachment >= renderpass_attachment_count)) {
2871                         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2872                                         HandleToUint64(commandBuffer), "VUID-vkCmdClearAttachments-aspectMask-02501",
2873                                         "vkCmdClearAttachments() pAttachments[%u].colorAttachment=%u is not VK_ATTACHMENT_UNUSED "
2874                                         "and not a valid attachment for %s attachmentCount=%u. Subpass %u pColorAttachment[%u]=%u.",
2875                                         attachment_index, clear_desc->colorAttachment,
2876                                         report_data->FormatHandle(cb_node->activeRenderPass->renderPass).c_str(),
2877                                         cb_node->activeSubpass, clear_desc->colorAttachment, color_attachment,
2878                                         renderpass_attachment_count);
2879 
2880                         color_attachment = VK_ATTACHMENT_UNUSED;  // Defensive, prevent lookup past end of renderpass attachment
2881                     }
2882                 } else {
2883                     skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2884                                     HandleToUint64(commandBuffer), "VUID-vkCmdClearAttachments-aspectMask-02501",
2885                                     "vkCmdClearAttachments() pAttachments[%u].colorAttachment=%u out of range for %s"
2886                                     " subpass %u. colorAttachmentCount=%u",
2887                                     attachment_index, clear_desc->colorAttachment,
2888                                     report_data->FormatHandle(cb_node->activeRenderPass->renderPass).c_str(),
2889                                     cb_node->activeSubpass, subpass_desc->colorAttachmentCount);
2890                 }
2891                 fb_attachment = color_attachment;
2892 
2893                 if ((clear_desc->aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) ||
2894                     (clear_desc->aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT)) {
2895                     char const str[] =
2896                         "vkCmdClearAttachments() aspectMask [%d] must set only VK_IMAGE_ASPECT_COLOR_BIT of a color attachment.";
2897                     skip |=
2898                         log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2899                                 HandleToUint64(commandBuffer), "VUID-VkClearAttachment-aspectMask-00019", str, attachment_index);
2900                 }
2901             } else {  // Must be depth and/or stencil
2902                 if (((clear_desc->aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) != VK_IMAGE_ASPECT_DEPTH_BIT) &&
2903                     ((clear_desc->aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) != VK_IMAGE_ASPECT_STENCIL_BIT)) {
2904                     char const str[] = "vkCmdClearAttachments() aspectMask [%d] is not a valid combination of bits.";
2905                     skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2906                                     HandleToUint64(commandBuffer), "VUID-VkClearAttachment-aspectMask-parameter", str,
2907                                     attachment_index);
2908                 }
2909                 if (!subpass_desc->pDepthStencilAttachment ||
2910                     (subpass_desc->pDepthStencilAttachment->attachment == VK_ATTACHMENT_UNUSED)) {
2911                     skip |= log_msg(
2912                         report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
2913                         HandleToUint64(commandBuffer), kVUID_Core_DrawState_MissingAttachmentReference,
2914                         "vkCmdClearAttachments() depth/stencil clear with no depth/stencil attachment in subpass; ignored");
2915                 } else {
2916                     fb_attachment = subpass_desc->pDepthStencilAttachment->attachment;
2917                 }
2918             }
2919             if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_PRIMARY) {
2920                 skip |= ValidateClearAttachmentExtent(commandBuffer, attachment_index, framebuffer, fb_attachment, render_area,
2921                                                       rectCount, pRects);
2922             }
2923         }
2924     }
2925     return skip;
2926 }
2927 
PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,uint32_t attachmentCount,const VkClearAttachment * pAttachments,uint32_t rectCount,const VkClearRect * pRects)2928 void CoreChecks::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
2929                                                   const VkClearAttachment *pAttachments, uint32_t rectCount,
2930                                                   const VkClearRect *pRects) {
2931     auto *cb_node = GetCBState(commandBuffer);
2932     if (cb_node->activeRenderPass && (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY)) {
2933         const VkRenderPassCreateInfo2KHR *renderpass_create_info = cb_node->activeRenderPass->createInfo.ptr();
2934         const VkSubpassDescription2KHR *subpass_desc = &renderpass_create_info->pSubpasses[cb_node->activeSubpass];
2935         std::shared_ptr<std::vector<VkClearRect>> clear_rect_copy;
2936         for (uint32_t attachment_index = 0; attachment_index < attachmentCount; attachment_index++) {
2937             const auto clear_desc = &pAttachments[attachment_index];
2938             uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
2939             if ((clear_desc->aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) &&
2940                 (clear_desc->colorAttachment < subpass_desc->colorAttachmentCount)) {
2941                 fb_attachment = subpass_desc->pColorAttachments[clear_desc->colorAttachment].attachment;
2942             } else if ((clear_desc->aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) &&
2943                        subpass_desc->pDepthStencilAttachment) {
2944                 fb_attachment = subpass_desc->pDepthStencilAttachment->attachment;
2945             }
2946             if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2947                 if (!clear_rect_copy) {
2948                     // We need a copy of the clear rectangles that will persist until the last lambda executes
2949                     // but we want to create it as lazily as possible
2950                     clear_rect_copy.reset(new std::vector<VkClearRect>(pRects, pRects + rectCount));
2951                 }
2952                 // if a secondary level command buffer inherits the framebuffer from the primary command buffer
2953                 // (see VkCommandBufferInheritanceInfo), this validation must be deferred until queue submit time
2954                 auto val_fn = [this, commandBuffer, attachment_index, fb_attachment, rectCount, clear_rect_copy](
2955                                   const CMD_BUFFER_STATE *prim_cb, VkFramebuffer fb) {
2956                     assert(rectCount == clear_rect_copy->size());
2957                     const FRAMEBUFFER_STATE *framebuffer = GetFramebufferState(fb);
2958                     const auto &render_area = prim_cb->activeRenderPassBeginInfo.renderArea;
2959                     bool skip = false;
2960                     skip = ValidateClearAttachmentExtent(commandBuffer, attachment_index, framebuffer, fb_attachment, render_area,
2961                                                          rectCount, clear_rect_copy->data());
2962                     return skip;
2963                 };
2964                 cb_node->cmd_execute_commands_functions.emplace_back(val_fn);
2965             }
2966         }
2967     }
2968 }
2969 
PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer,VkImage srcImage,VkImageLayout srcImageLayout,VkImage dstImage,VkImageLayout dstImageLayout,uint32_t regionCount,const VkImageResolve * pRegions)2970 bool CoreChecks::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2971                                                 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2972                                                 const VkImageResolve *pRegions) {
2973     const auto *cb_node = GetCBState(commandBuffer);
2974     const auto *src_image_state = GetImageState(srcImage);
2975     const auto *dst_image_state = GetImageState(dstImage);
2976 
2977     bool skip = false;
2978     if (cb_node && src_image_state && dst_image_state) {
2979         skip |= ValidateMemoryIsBoundToImage(src_image_state, "vkCmdResolveImage()", "VUID-vkCmdResolveImage-srcImage-00256");
2980         skip |= ValidateMemoryIsBoundToImage(dst_image_state, "vkCmdResolveImage()", "VUID-vkCmdResolveImage-dstImage-00258");
2981         skip |= ValidateCmdQueueFlags(cb_node, "vkCmdResolveImage()", VK_QUEUE_GRAPHICS_BIT,
2982                                       "VUID-vkCmdResolveImage-commandBuffer-cmdpool");
2983         skip |= ValidateCmd(cb_node, CMD_RESOLVEIMAGE, "vkCmdResolveImage()");
2984         skip |= InsideRenderPass(cb_node, "vkCmdResolveImage()", "VUID-vkCmdResolveImage-renderpass");
2985         skip |= ValidateImageFormatFeatureFlags(dst_image_state, VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT, "vkCmdResolveImage()",
2986                                                 "VUID-vkCmdResolveImage-dstImage-02003", "VUID-vkCmdResolveImage-dstImage-02003");
2987 
2988         bool hit_error = false;
2989         const char *invalid_src_layout_vuid =
2990             (src_image_state->shared_presentable && device_extensions.vk_khr_shared_presentable_image)
2991                 ? "VUID-vkCmdResolveImage-srcImageLayout-01400"
2992                 : "VUID-vkCmdResolveImage-srcImageLayout-00261";
2993         const char *invalid_dst_layout_vuid =
2994             (dst_image_state->shared_presentable && device_extensions.vk_khr_shared_presentable_image)
2995                 ? "VUID-vkCmdResolveImage-dstImageLayout-01401"
2996                 : "VUID-vkCmdResolveImage-dstImageLayout-00263";
2997         // For each region, the number of layers in the image subresource should not be zero
2998         // For each region, src and dest image aspect must be color only
2999         for (uint32_t i = 0; i < regionCount; i++) {
3000             skip |=
3001                 ValidateImageSubresourceLayers(cb_node, &pRegions[i].srcSubresource, "vkCmdResolveImage()", "srcSubresource", i);
3002             skip |=
3003                 ValidateImageSubresourceLayers(cb_node, &pRegions[i].dstSubresource, "vkCmdResolveImage()", "dstSubresource", i);
3004             skip |= VerifyImageLayout(cb_node, src_image_state, pRegions[i].srcSubresource, srcImageLayout,
3005                                       VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, "vkCmdResolveImage()", invalid_src_layout_vuid,
3006                                       "VUID-vkCmdResolveImage-srcImageLayout-00260", &hit_error);
3007             skip |= VerifyImageLayout(cb_node, dst_image_state, pRegions[i].dstSubresource, dstImageLayout,
3008                                       VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, "vkCmdResolveImage()", invalid_dst_layout_vuid,
3009                                       "VUID-vkCmdResolveImage-dstImageLayout-00262", &hit_error);
3010             skip |= ValidateImageMipLevel(cb_node, src_image_state, pRegions[i].srcSubresource.mipLevel, i, "vkCmdResolveImage()",
3011                                           "srcSubresource", "VUID-vkCmdResolveImage-srcSubresource-01709");
3012             skip |= ValidateImageMipLevel(cb_node, dst_image_state, pRegions[i].dstSubresource.mipLevel, i, "vkCmdResolveImage()",
3013                                           "dstSubresource", "VUID-vkCmdResolveImage-dstSubresource-01710");
3014             skip |= ValidateImageArrayLayerRange(cb_node, src_image_state, pRegions[i].srcSubresource.baseArrayLayer,
3015                                                  pRegions[i].srcSubresource.layerCount, i, "vkCmdResolveImage()", "srcSubresource",
3016                                                  "VUID-vkCmdResolveImage-srcSubresource-01711");
3017             skip |= ValidateImageArrayLayerRange(cb_node, dst_image_state, pRegions[i].dstSubresource.baseArrayLayer,
3018                                                  pRegions[i].dstSubresource.layerCount, i, "vkCmdResolveImage()", "srcSubresource",
3019                                                  "VUID-vkCmdResolveImage-dstSubresource-01712");
3020 
3021             // layer counts must match
3022             if (pRegions[i].srcSubresource.layerCount != pRegions[i].dstSubresource.layerCount) {
3023                 skip |= log_msg(
3024                     report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3025                     HandleToUint64(cb_node->commandBuffer), "VUID-VkImageResolve-layerCount-00267",
3026                     "vkCmdResolveImage(): layerCount in source and destination subresource of pRegions[%d] does not match.", i);
3027             }
3028             // For each region, src and dest image aspect must be color only
3029             if ((pRegions[i].srcSubresource.aspectMask != VK_IMAGE_ASPECT_COLOR_BIT) ||
3030                 (pRegions[i].dstSubresource.aspectMask != VK_IMAGE_ASPECT_COLOR_BIT)) {
3031                 char const str[] =
3032                     "vkCmdResolveImage(): src and dest aspectMasks for each region must specify only VK_IMAGE_ASPECT_COLOR_BIT";
3033                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3034                                 HandleToUint64(cb_node->commandBuffer), "VUID-VkImageResolve-aspectMask-00266", "%s.", str);
3035             }
3036         }
3037 
3038         if (src_image_state->createInfo.format != dst_image_state->createInfo.format) {
3039             char const str[] = "vkCmdResolveImage called with unmatched source and dest formats.";
3040             skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3041                             HandleToUint64(cb_node->commandBuffer), kVUID_Core_DrawState_MismatchedImageFormat, str);
3042         }
3043         if (src_image_state->createInfo.imageType != dst_image_state->createInfo.imageType) {
3044             char const str[] = "vkCmdResolveImage called with unmatched source and dest image types.";
3045             skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3046                             HandleToUint64(cb_node->commandBuffer), kVUID_Core_DrawState_MismatchedImageType, str);
3047         }
3048         if (src_image_state->createInfo.samples == VK_SAMPLE_COUNT_1_BIT) {
3049             char const str[] = "vkCmdResolveImage called with source sample count less than 2.";
3050             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3051                             HandleToUint64(cb_node->commandBuffer), "VUID-vkCmdResolveImage-srcImage-00257", "%s.", str);
3052         }
3053         if (dst_image_state->createInfo.samples != VK_SAMPLE_COUNT_1_BIT) {
3054             char const str[] = "vkCmdResolveImage called with dest sample count greater than 1.";
3055             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3056                             HandleToUint64(cb_node->commandBuffer), "VUID-vkCmdResolveImage-dstImage-00259", "%s.", str);
3057         }
3058     } else {
3059         assert(0);
3060     }
3061     return skip;
3062 }
3063 
PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer,VkImage srcImage,VkImageLayout srcImageLayout,VkImage dstImage,VkImageLayout dstImageLayout,uint32_t regionCount,const VkImageResolve * pRegions)3064 void ValidationStateTracker::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage,
3065                                                           VkImageLayout srcImageLayout, VkImage dstImage,
3066                                                           VkImageLayout dstImageLayout, uint32_t regionCount,
3067                                                           const VkImageResolve *pRegions) {
3068     auto cb_node = GetCBState(commandBuffer);
3069     auto src_image_state = GetImageState(srcImage);
3070     auto dst_image_state = GetImageState(dstImage);
3071 
3072     // Update bindings between images and cmd buffer
3073     AddCommandBufferBindingImage(cb_node, src_image_state);
3074     AddCommandBufferBindingImage(cb_node, dst_image_state);
3075 }
3076 
PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer,VkImage srcImage,VkImageLayout srcImageLayout,VkImage dstImage,VkImageLayout dstImageLayout,uint32_t regionCount,const VkImageBlit * pRegions,VkFilter filter)3077 bool CoreChecks::PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3078                                              VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3079                                              const VkImageBlit *pRegions, VkFilter filter) {
3080     const auto *cb_node = GetCBState(commandBuffer);
3081     const auto *src_image_state = GetImageState(srcImage);
3082     const auto *dst_image_state = GetImageState(dstImage);
3083 
3084     bool skip = false;
3085     if (cb_node) {
3086         skip |= ValidateCmd(cb_node, CMD_BLITIMAGE, "vkCmdBlitImage()");
3087     }
3088     if (cb_node && src_image_state && dst_image_state) {
3089         skip |= ValidateImageSampleCount(src_image_state, VK_SAMPLE_COUNT_1_BIT, "vkCmdBlitImage(): srcImage",
3090                                          "VUID-vkCmdBlitImage-srcImage-00233");
3091         skip |= ValidateImageSampleCount(dst_image_state, VK_SAMPLE_COUNT_1_BIT, "vkCmdBlitImage(): dstImage",
3092                                          "VUID-vkCmdBlitImage-dstImage-00234");
3093         skip |= ValidateMemoryIsBoundToImage(src_image_state, "vkCmdBlitImage()", "VUID-vkCmdBlitImage-srcImage-00220");
3094         skip |= ValidateMemoryIsBoundToImage(dst_image_state, "vkCmdBlitImage()", "VUID-vkCmdBlitImage-dstImage-00225");
3095         skip |=
3096             ValidateImageUsageFlags(src_image_state, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, true, "VUID-vkCmdBlitImage-srcImage-00219",
3097                                     "vkCmdBlitImage()", "VK_IMAGE_USAGE_TRANSFER_SRC_BIT");
3098         skip |=
3099             ValidateImageUsageFlags(dst_image_state, VK_IMAGE_USAGE_TRANSFER_DST_BIT, true, "VUID-vkCmdBlitImage-dstImage-00224",
3100                                     "vkCmdBlitImage()", "VK_IMAGE_USAGE_TRANSFER_DST_BIT");
3101         skip |=
3102             ValidateCmdQueueFlags(cb_node, "vkCmdBlitImage()", VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdBlitImage-commandBuffer-cmdpool");
3103         skip |= ValidateCmd(cb_node, CMD_BLITIMAGE, "vkCmdBlitImage()");
3104         skip |= InsideRenderPass(cb_node, "vkCmdBlitImage()", "VUID-vkCmdBlitImage-renderpass");
3105         skip |= ValidateImageFormatFeatureFlags(src_image_state, VK_FORMAT_FEATURE_BLIT_SRC_BIT, "vkCmdBlitImage()",
3106                                                 "VUID-vkCmdBlitImage-srcImage-01999", "VUID-vkCmdBlitImage-srcImage-01999");
3107         skip |= ValidateImageFormatFeatureFlags(dst_image_state, VK_FORMAT_FEATURE_BLIT_DST_BIT, "vkCmdBlitImage()",
3108                                                 "VUID-vkCmdBlitImage-dstImage-02000", "VUID-vkCmdBlitImage-dstImage-02000");
3109 
3110         // TODO: Need to validate image layouts, which will include layout validation for shared presentable images
3111 
3112         VkFormat src_format = src_image_state->createInfo.format;
3113         VkFormat dst_format = dst_image_state->createInfo.format;
3114         VkImageType src_type = src_image_state->createInfo.imageType;
3115         VkImageType dst_type = dst_image_state->createInfo.imageType;
3116 
3117         if (VK_FILTER_LINEAR == filter) {
3118             skip |= ValidateImageFormatFeatureFlags(src_image_state, VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT,
3119                                                     "vkCmdBlitImage()", "VUID-vkCmdBlitImage-filter-02001",
3120                                                     "VUID-vkCmdBlitImage-filter-02001");
3121         } else if (VK_FILTER_CUBIC_IMG == filter) {
3122             skip |= ValidateImageFormatFeatureFlags(src_image_state, VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG,
3123                                                     "vkCmdBlitImage()", "VUID-vkCmdBlitImage-filter-02002",
3124                                                     "VUID-vkCmdBlitImage-filter-02002");
3125         }
3126 
3127         if ((VK_FILTER_CUBIC_IMG == filter) && (VK_IMAGE_TYPE_3D != src_type)) {
3128             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3129                             HandleToUint64(cb_node->commandBuffer), "VUID-vkCmdBlitImage-filter-00237",
3130                             "vkCmdBlitImage(): source image type must be VK_IMAGE_TYPE_3D when cubic filtering is specified.");
3131         }
3132 
3133         if ((VK_SAMPLE_COUNT_1_BIT != src_image_state->createInfo.samples) ||
3134             (VK_SAMPLE_COUNT_1_BIT != dst_image_state->createInfo.samples)) {
3135             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3136                             HandleToUint64(cb_node->commandBuffer), "VUID-vkCmdBlitImage-srcImage-00228",
3137                             "vkCmdBlitImage(): source or dest image has sample count other than VK_SAMPLE_COUNT_1_BIT.");
3138         }
3139 
3140         // Validate consistency for unsigned formats
3141         if (FormatIsUInt(src_format) != FormatIsUInt(dst_format)) {
3142             std::stringstream ss;
3143             ss << "vkCmdBlitImage(): If one of srcImage and dstImage images has unsigned integer format, "
3144                << "the other one must also have unsigned integer format.  "
3145                << "Source format is " << string_VkFormat(src_format) << " Destination format is " << string_VkFormat(dst_format);
3146             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3147                             HandleToUint64(cb_node->commandBuffer), "VUID-vkCmdBlitImage-srcImage-00230", "%s.", ss.str().c_str());
3148         }
3149 
3150         // Validate consistency for signed formats
3151         if (FormatIsSInt(src_format) != FormatIsSInt(dst_format)) {
3152             std::stringstream ss;
3153             ss << "vkCmdBlitImage(): If one of srcImage and dstImage images has signed integer format, "
3154                << "the other one must also have signed integer format.  "
3155                << "Source format is " << string_VkFormat(src_format) << " Destination format is " << string_VkFormat(dst_format);
3156             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3157                             HandleToUint64(cb_node->commandBuffer), "VUID-vkCmdBlitImage-srcImage-00229", "%s.", ss.str().c_str());
3158         }
3159 
3160         // Validate filter for Depth/Stencil formats
3161         if (FormatIsDepthOrStencil(src_format) && (filter != VK_FILTER_NEAREST)) {
3162             std::stringstream ss;
3163             ss << "vkCmdBlitImage(): If the format of srcImage is a depth, stencil, or depth stencil "
3164                << "then filter must be VK_FILTER_NEAREST.";
3165             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3166                             HandleToUint64(cb_node->commandBuffer), "VUID-vkCmdBlitImage-srcImage-00232", "%s.", ss.str().c_str());
3167         }
3168 
3169         // Validate aspect bits and formats for depth/stencil images
3170         if (FormatIsDepthOrStencil(src_format) || FormatIsDepthOrStencil(dst_format)) {
3171             if (src_format != dst_format) {
3172                 std::stringstream ss;
3173                 ss << "vkCmdBlitImage(): If one of srcImage and dstImage images has a format of depth, stencil or depth "
3174                    << "stencil, the other one must have exactly the same format.  "
3175                    << "Source format is " << string_VkFormat(src_format) << " Destination format is "
3176                    << string_VkFormat(dst_format);
3177                 skip |=
3178                     log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3179                             HandleToUint64(cb_node->commandBuffer), "VUID-vkCmdBlitImage-srcImage-00231", "%s.", ss.str().c_str());
3180             }
3181         }  // Depth or Stencil
3182 
3183         // Do per-region checks
3184         const char *invalid_src_layout_vuid =
3185             (src_image_state->shared_presentable && device_extensions.vk_khr_shared_presentable_image)
3186                 ? "VUID-vkCmdBlitImage-srcImageLayout-01398"
3187                 : "VUID-vkCmdBlitImage-srcImageLayout-00222";
3188         const char *invalid_dst_layout_vuid =
3189             (dst_image_state->shared_presentable && device_extensions.vk_khr_shared_presentable_image)
3190                 ? "VUID-vkCmdBlitImage-dstImageLayout-01399"
3191                 : "VUID-vkCmdBlitImage-dstImageLayout-00227";
3192         for (uint32_t i = 0; i < regionCount; i++) {
3193             const VkImageBlit rgn = pRegions[i];
3194             bool hit_error = false;
3195             skip |= VerifyImageLayout(cb_node, src_image_state, rgn.srcSubresource, srcImageLayout,
3196                                       VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, "vkCmdBlitImage()", invalid_src_layout_vuid,
3197                                       "VUID-vkCmdBlitImage-srcImageLayout-00221", &hit_error);
3198             skip |= VerifyImageLayout(cb_node, dst_image_state, rgn.dstSubresource, dstImageLayout,
3199                                       VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, "vkCmdBlitImage()", invalid_dst_layout_vuid,
3200                                       "VUID-vkCmdBlitImage-dstImageLayout-00226", &hit_error);
3201             skip |= ValidateImageSubresourceLayers(cb_node, &rgn.srcSubresource, "vkCmdBlitImage()", "srcSubresource", i);
3202             skip |= ValidateImageSubresourceLayers(cb_node, &rgn.dstSubresource, "vkCmdBlitImage()", "dstSubresource", i);
3203             skip |= ValidateImageMipLevel(cb_node, src_image_state, rgn.srcSubresource.mipLevel, i, "vkCmdBlitImage()",
3204                                           "srcSubresource", "VUID-vkCmdBlitImage-srcSubresource-01705");
3205             skip |= ValidateImageMipLevel(cb_node, dst_image_state, rgn.dstSubresource.mipLevel, i, "vkCmdBlitImage()",
3206                                           "dstSubresource", "VUID-vkCmdBlitImage-dstSubresource-01706");
3207             skip |= ValidateImageArrayLayerRange(cb_node, src_image_state, rgn.srcSubresource.baseArrayLayer,
3208                                                  rgn.srcSubresource.layerCount, i, "vkCmdBlitImage()", "srcSubresource",
3209                                                  "VUID-vkCmdBlitImage-srcSubresource-01707");
3210             skip |= ValidateImageArrayLayerRange(cb_node, dst_image_state, rgn.dstSubresource.baseArrayLayer,
3211                                                  rgn.dstSubresource.layerCount, i, "vkCmdBlitImage()", "dstSubresource",
3212                                                  "VUID-vkCmdBlitImage-dstSubresource-01708");
3213             // Warn for zero-sized regions
3214             if ((rgn.srcOffsets[0].x == rgn.srcOffsets[1].x) || (rgn.srcOffsets[0].y == rgn.srcOffsets[1].y) ||
3215                 (rgn.srcOffsets[0].z == rgn.srcOffsets[1].z)) {
3216                 std::stringstream ss;
3217                 ss << "vkCmdBlitImage(): pRegions[" << i << "].srcOffsets specify a zero-volume area.";
3218                 skip |=
3219                     log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3220                             HandleToUint64(cb_node->commandBuffer), kVUID_Core_DrawState_InvalidExtents, "%s", ss.str().c_str());
3221             }
3222             if ((rgn.dstOffsets[0].x == rgn.dstOffsets[1].x) || (rgn.dstOffsets[0].y == rgn.dstOffsets[1].y) ||
3223                 (rgn.dstOffsets[0].z == rgn.dstOffsets[1].z)) {
3224                 std::stringstream ss;
3225                 ss << "vkCmdBlitImage(): pRegions[" << i << "].dstOffsets specify a zero-volume area.";
3226                 skip |=
3227                     log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3228                             HandleToUint64(cb_node->commandBuffer), kVUID_Core_DrawState_InvalidExtents, "%s", ss.str().c_str());
3229             }
3230 
3231             // Check that src/dst layercounts match
3232             if (rgn.srcSubresource.layerCount != rgn.dstSubresource.layerCount) {
3233                 skip |= log_msg(
3234                     report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3235                     HandleToUint64(cb_node->commandBuffer), "VUID-VkImageBlit-layerCount-00239",
3236                     "vkCmdBlitImage(): layerCount in source and destination subresource of pRegions[%d] does not match.", i);
3237             }
3238 
3239             if (rgn.srcSubresource.aspectMask != rgn.dstSubresource.aspectMask) {
3240                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3241                                 HandleToUint64(cb_node->commandBuffer), "VUID-VkImageBlit-aspectMask-00238",
3242                                 "vkCmdBlitImage(): aspectMask members for pRegion[%d] do not match.", i);
3243             }
3244 
3245             if (!VerifyAspectsPresent(rgn.srcSubresource.aspectMask, src_format)) {
3246                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3247                                 HandleToUint64(cb_node->commandBuffer), "VUID-VkImageBlit-aspectMask-00241",
3248                                 "vkCmdBlitImage(): region [%d] source aspectMask (0x%x) specifies aspects not present in source "
3249                                 "image format %s.",
3250                                 i, rgn.srcSubresource.aspectMask, string_VkFormat(src_format));
3251             }
3252 
3253             if (!VerifyAspectsPresent(rgn.dstSubresource.aspectMask, dst_format)) {
3254                 skip |= log_msg(
3255                     report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3256                     HandleToUint64(cb_node->commandBuffer), "VUID-VkImageBlit-aspectMask-00242",
3257                     "vkCmdBlitImage(): region [%d] dest aspectMask (0x%x) specifies aspects not present in dest image format %s.",
3258                     i, rgn.dstSubresource.aspectMask, string_VkFormat(dst_format));
3259             }
3260 
3261             // Validate source image offsets
3262             VkExtent3D src_extent = GetImageSubresourceExtent(src_image_state, &(rgn.srcSubresource));
3263             if (VK_IMAGE_TYPE_1D == src_type) {
3264                 if ((0 != rgn.srcOffsets[0].y) || (1 != rgn.srcOffsets[1].y)) {
3265                     skip |=
3266                         log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3267                                 HandleToUint64(cb_node->commandBuffer), "VUID-VkImageBlit-srcImage-00245",
3268                                 "vkCmdBlitImage(): region [%d], source image of type VK_IMAGE_TYPE_1D with srcOffset[].y values "
3269                                 "of (%1d, %1d). These must be (0, 1).",
3270                                 i, rgn.srcOffsets[0].y, rgn.srcOffsets[1].y);
3271                 }
3272             }
3273 
3274             if ((VK_IMAGE_TYPE_1D == src_type) || (VK_IMAGE_TYPE_2D == src_type)) {
3275                 if ((0 != rgn.srcOffsets[0].z) || (1 != rgn.srcOffsets[1].z)) {
3276                     skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3277                                     HandleToUint64(cb_node->commandBuffer), "VUID-VkImageBlit-srcImage-00247",
3278                                     "vkCmdBlitImage(): region [%d], source image of type VK_IMAGE_TYPE_1D or VK_IMAGE_TYPE_2D with "
3279                                     "srcOffset[].z values of (%1d, %1d). These must be (0, 1).",
3280                                     i, rgn.srcOffsets[0].z, rgn.srcOffsets[1].z);
3281                 }
3282             }
3283 
3284             bool oob = false;
3285             if ((rgn.srcOffsets[0].x < 0) || (rgn.srcOffsets[0].x > static_cast<int32_t>(src_extent.width)) ||
3286                 (rgn.srcOffsets[1].x < 0) || (rgn.srcOffsets[1].x > static_cast<int32_t>(src_extent.width))) {
3287                 oob = true;
3288                 skip |= log_msg(
3289                     report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3290                     HandleToUint64(cb_node->commandBuffer), "VUID-VkImageBlit-srcOffset-00243",
3291                     "vkCmdBlitImage(): region [%d] srcOffset[].x values (%1d, %1d) exceed srcSubresource width extent (%1d).", i,
3292                     rgn.srcOffsets[0].x, rgn.srcOffsets[1].x, src_extent.width);
3293             }
3294             if ((rgn.srcOffsets[0].y < 0) || (rgn.srcOffsets[0].y > static_cast<int32_t>(src_extent.height)) ||
3295                 (rgn.srcOffsets[1].y < 0) || (rgn.srcOffsets[1].y > static_cast<int32_t>(src_extent.height))) {
3296                 oob = true;
3297                 skip |= log_msg(
3298                     report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3299                     HandleToUint64(cb_node->commandBuffer), "VUID-VkImageBlit-srcOffset-00244",
3300                     "vkCmdBlitImage(): region [%d] srcOffset[].y values (%1d, %1d) exceed srcSubresource height extent (%1d).", i,
3301                     rgn.srcOffsets[0].y, rgn.srcOffsets[1].y, src_extent.height);
3302             }
3303             if ((rgn.srcOffsets[0].z < 0) || (rgn.srcOffsets[0].z > static_cast<int32_t>(src_extent.depth)) ||
3304                 (rgn.srcOffsets[1].z < 0) || (rgn.srcOffsets[1].z > static_cast<int32_t>(src_extent.depth))) {
3305                 oob = true;
3306                 skip |= log_msg(
3307                     report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3308                     HandleToUint64(cb_node->commandBuffer), "VUID-VkImageBlit-srcOffset-00246",
3309                     "vkCmdBlitImage(): region [%d] srcOffset[].z values (%1d, %1d) exceed srcSubresource depth extent (%1d).", i,
3310                     rgn.srcOffsets[0].z, rgn.srcOffsets[1].z, src_extent.depth);
3311             }
3312             if (oob) {
3313                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3314                                 HandleToUint64(cb_node->commandBuffer), "VUID-vkCmdBlitImage-pRegions-00215",
3315                                 "vkCmdBlitImage(): region [%d] source image blit region exceeds image dimensions.", i);
3316             }
3317 
3318             // Validate dest image offsets
3319             VkExtent3D dst_extent = GetImageSubresourceExtent(dst_image_state, &(rgn.dstSubresource));
3320             if (VK_IMAGE_TYPE_1D == dst_type) {
3321                 if ((0 != rgn.dstOffsets[0].y) || (1 != rgn.dstOffsets[1].y)) {
3322                     skip |=
3323                         log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3324                                 HandleToUint64(cb_node->commandBuffer), "VUID-VkImageBlit-dstImage-00250",
3325                                 "vkCmdBlitImage(): region [%d], dest image of type VK_IMAGE_TYPE_1D with dstOffset[].y values of "
3326                                 "(%1d, %1d). These must be (0, 1).",
3327                                 i, rgn.dstOffsets[0].y, rgn.dstOffsets[1].y);
3328                 }
3329             }
3330 
3331             if ((VK_IMAGE_TYPE_1D == dst_type) || (VK_IMAGE_TYPE_2D == dst_type)) {
3332                 if ((0 != rgn.dstOffsets[0].z) || (1 != rgn.dstOffsets[1].z)) {
3333                     skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3334                                     HandleToUint64(cb_node->commandBuffer), "VUID-VkImageBlit-dstImage-00252",
3335                                     "vkCmdBlitImage(): region [%d], dest image of type VK_IMAGE_TYPE_1D or VK_IMAGE_TYPE_2D with "
3336                                     "dstOffset[].z values of (%1d, %1d). These must be (0, 1).",
3337                                     i, rgn.dstOffsets[0].z, rgn.dstOffsets[1].z);
3338                 }
3339             }
3340 
3341             oob = false;
3342             if ((rgn.dstOffsets[0].x < 0) || (rgn.dstOffsets[0].x > static_cast<int32_t>(dst_extent.width)) ||
3343                 (rgn.dstOffsets[1].x < 0) || (rgn.dstOffsets[1].x > static_cast<int32_t>(dst_extent.width))) {
3344                 oob = true;
3345                 skip |= log_msg(
3346                     report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3347                     HandleToUint64(cb_node->commandBuffer), "VUID-VkImageBlit-dstOffset-00248",
3348                     "vkCmdBlitImage(): region [%d] dstOffset[].x values (%1d, %1d) exceed dstSubresource width extent (%1d).", i,
3349                     rgn.dstOffsets[0].x, rgn.dstOffsets[1].x, dst_extent.width);
3350             }
3351             if ((rgn.dstOffsets[0].y < 0) || (rgn.dstOffsets[0].y > static_cast<int32_t>(dst_extent.height)) ||
3352                 (rgn.dstOffsets[1].y < 0) || (rgn.dstOffsets[1].y > static_cast<int32_t>(dst_extent.height))) {
3353                 oob = true;
3354                 skip |= log_msg(
3355                     report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3356                     HandleToUint64(cb_node->commandBuffer), "VUID-VkImageBlit-dstOffset-00249",
3357                     "vkCmdBlitImage(): region [%d] dstOffset[].y values (%1d, %1d) exceed dstSubresource height extent (%1d).", i,
3358                     rgn.dstOffsets[0].y, rgn.dstOffsets[1].y, dst_extent.height);
3359             }
3360             if ((rgn.dstOffsets[0].z < 0) || (rgn.dstOffsets[0].z > static_cast<int32_t>(dst_extent.depth)) ||
3361                 (rgn.dstOffsets[1].z < 0) || (rgn.dstOffsets[1].z > static_cast<int32_t>(dst_extent.depth))) {
3362                 oob = true;
3363                 skip |= log_msg(
3364                     report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3365                     HandleToUint64(cb_node->commandBuffer), "VUID-VkImageBlit-dstOffset-00251",
3366                     "vkCmdBlitImage(): region [%d] dstOffset[].z values (%1d, %1d) exceed dstSubresource depth extent (%1d).", i,
3367                     rgn.dstOffsets[0].z, rgn.dstOffsets[1].z, dst_extent.depth);
3368             }
3369             if (oob) {
3370                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3371                                 HandleToUint64(cb_node->commandBuffer), "VUID-vkCmdBlitImage-pRegions-00216",
3372                                 "vkCmdBlitImage(): region [%d] destination image blit region exceeds image dimensions.", i);
3373             }
3374 
3375             if ((VK_IMAGE_TYPE_3D == src_type) || (VK_IMAGE_TYPE_3D == dst_type)) {
3376                 if ((0 != rgn.srcSubresource.baseArrayLayer) || (1 != rgn.srcSubresource.layerCount) ||
3377                     (0 != rgn.dstSubresource.baseArrayLayer) || (1 != rgn.dstSubresource.layerCount)) {
3378                     skip |=
3379                         log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3380                                 HandleToUint64(cb_node->commandBuffer), "VUID-VkImageBlit-srcImage-00240",
3381                                 "vkCmdBlitImage(): region [%d] blit to/from a 3D image type with a non-zero baseArrayLayer, or a "
3382                                 "layerCount other than 1.",
3383                                 i);
3384                 }
3385             }
3386         }  // per-region checks
3387     } else {
3388         assert(0);
3389     }
3390     return skip;
3391 }
3392 
PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer,VkImage srcImage,VkImageLayout srcImageLayout,VkImage dstImage,VkImageLayout dstImageLayout,uint32_t regionCount,const VkImageBlit * pRegions,VkFilter filter)3393 void ValidationStateTracker::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage,
3394                                                        VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout,
3395                                                        uint32_t regionCount, const VkImageBlit *pRegions, VkFilter filter) {
3396     auto cb_node = GetCBState(commandBuffer);
3397     auto src_image_state = GetImageState(srcImage);
3398     auto dst_image_state = GetImageState(dstImage);
3399 
3400     // Update bindings between images and cmd buffer
3401     AddCommandBufferBindingImage(cb_node, src_image_state);
3402     AddCommandBufferBindingImage(cb_node, dst_image_state);
3403 }
3404 
PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer,VkImage srcImage,VkImageLayout srcImageLayout,VkImage dstImage,VkImageLayout dstImageLayout,uint32_t regionCount,const VkImageBlit * pRegions,VkFilter filter)3405 void CoreChecks::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3406                                            VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3407                                            const VkImageBlit *pRegions, VkFilter filter) {
3408     StateTracker::PreCallRecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
3409                                             pRegions, filter);
3410     auto cb_node = GetCBState(commandBuffer);
3411     auto src_image_state = GetImageState(srcImage);
3412     auto dst_image_state = GetImageState(dstImage);
3413 
3414     // Make sure that all image slices are updated to correct layout
3415     for (uint32_t i = 0; i < regionCount; ++i) {
3416         SetImageInitialLayout(cb_node, *src_image_state, pRegions[i].srcSubresource, srcImageLayout);
3417         SetImageInitialLayout(cb_node, *dst_image_state, pRegions[i].dstSubresource, dstImageLayout);
3418     }
3419 }
3420 
3421 // This validates that the initial layout specified in the command buffer for the IMAGE is the same as the global IMAGE layout
ValidateCmdBufImageLayouts(const CMD_BUFFER_STATE * pCB,const ImageSubresPairLayoutMap & globalImageLayoutMap,ImageSubresPairLayoutMap * overlayLayoutMap_arg) const3422 bool CoreChecks::ValidateCmdBufImageLayouts(const CMD_BUFFER_STATE *pCB, const ImageSubresPairLayoutMap &globalImageLayoutMap,
3423                                             ImageSubresPairLayoutMap *overlayLayoutMap_arg) const {
3424     if (disabled.image_layout_validation) return false;
3425     bool skip = false;
3426     ImageSubresPairLayoutMap &overlayLayoutMap = *overlayLayoutMap_arg;
3427     // Iterate over the layout maps for each referenced image
3428     for (const auto &layout_map_entry : pCB->image_layout_map) {
3429         const auto image = layout_map_entry.first;
3430         const auto *image_state = GetImageState(image);
3431         if (!image_state) continue;  // Can't check layouts of a dead image
3432         auto subres_map = layout_map_entry.second.get();
3433         ImageSubresourcePair isr_pair;
3434         isr_pair.image = image;
3435         isr_pair.hasSubresource = true;
3436 
3437         std::string bind_swapchain_msg = "";
3438         if (image_state->bind_swapchain) {
3439             auto swapchain_node = GetSwapchainState(image_state->bind_swapchain);
3440             const auto swapchain_image = swapchain_node->images[image_state->bind_swapchain_imageIndex];
3441             isr_pair.image = swapchain_image;
3442 
3443             string_sprintf(&bind_swapchain_msg, "bind %s imageIndex %d (%s)",
3444                            report_data->FormatHandle(image_state->bind_swapchain).c_str(), image_state->bind_swapchain_imageIndex,
3445                            report_data->FormatHandle(swapchain_image).c_str());
3446         }
3447 
3448         // Validate the initial_uses for each subresource referenced
3449         for (auto it_init = subres_map->BeginInitialUse(); !it_init.AtEnd(); ++it_init) {
3450             isr_pair.subresource = (*it_init).subresource;
3451             VkImageLayout initial_layout = (*it_init).layout;
3452             VkImageLayout image_layout;
3453             if (FindLayout(overlayLayoutMap, isr_pair, image_layout) || FindLayout(globalImageLayoutMap, isr_pair, image_layout)) {
3454                 if (initial_layout == VK_IMAGE_LAYOUT_UNDEFINED) {
3455                     // TODO: Set memory invalid which is in mem_tracker currently
3456                 } else if (image_layout != initial_layout) {
3457                     // Need to look up the inital layout *state* to get a bit more information
3458                     const auto *initial_layout_state = subres_map->GetSubresourceInitialLayoutState(isr_pair.subresource);
3459                     assert(initial_layout_state);  // There's no way we should have an initial layout without matching state...
3460                     bool matches = ImageLayoutMatches(initial_layout_state->aspect_mask, image_layout, initial_layout);
3461                     if (!matches) {
3462                         std::string formatted_label = FormatDebugLabel(" ", pCB->debug_label);
3463                         skip |= log_msg(
3464                             report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3465                             HandleToUint64(pCB->commandBuffer), kVUID_Core_DrawState_InvalidImageLayout,
3466                             "Submitted command buffer expects %s %s (subresource: aspectMask 0x%X array layer %u, mip level %u) "
3467                             "to be in layout %s--instead, current layout is %s.%s",
3468                             report_data->FormatHandle(image).c_str(), bind_swapchain_msg.c_str(), isr_pair.subresource.aspectMask,
3469                             isr_pair.subresource.arrayLayer, isr_pair.subresource.mipLevel, string_VkImageLayout(initial_layout),
3470                             string_VkImageLayout(image_layout), formatted_label.c_str());
3471                     }
3472                 }
3473             }
3474         }
3475 
3476         // Update all layout set operations (which will be a subset of the initial_layouts
3477         for (auto it_set = subres_map->BeginSetLayout(); !it_set.AtEnd(); ++it_set) {
3478             VkImageLayout layout = (*it_set).layout;
3479             isr_pair.subresource = (*it_set).subresource;
3480             SetLayout(overlayLayoutMap, isr_pair, layout);
3481         }
3482     }
3483 
3484     return skip;
3485 }
3486 
UpdateCmdBufImageLayouts(CMD_BUFFER_STATE * pCB)3487 void CoreChecks::UpdateCmdBufImageLayouts(CMD_BUFFER_STATE *pCB) {
3488     for (const auto &layout_map_entry : pCB->image_layout_map) {
3489         const auto image = layout_map_entry.first;
3490         const auto *image_state = GetImageState(image);
3491         if (!image_state) continue;  // Can't set layouts of a dead image
3492         const auto &subres_map = layout_map_entry.second;
3493         ImageSubresourcePair isr_pair;
3494         isr_pair.image = image;
3495         isr_pair.hasSubresource = true;
3496 
3497         // Update all layout set operations (which will be a subset of the initial_layouts
3498         for (auto it_set = subres_map->BeginSetLayout(); !it_set.AtEnd(); ++it_set) {
3499             VkImageLayout layout = (*it_set).layout;
3500             isr_pair.subresource = (*it_set).subresource;
3501             SetGlobalLayout(isr_pair, layout);
3502         }
3503     }
3504 }
3505 
3506 // ValidateLayoutVsAttachmentDescription is a general function where we can validate various state associated with the
3507 // VkAttachmentDescription structs that are used by the sub-passes of a renderpass. Initial check is to make sure that READ_ONLY
3508 // layout attachments don't have CLEAR as their loadOp.
ValidateLayoutVsAttachmentDescription(const debug_report_data * report_data,RenderPassCreateVersion rp_version,const VkImageLayout first_layout,const uint32_t attachment,const VkAttachmentDescription2KHR & attachment_description) const3509 bool CoreChecks::ValidateLayoutVsAttachmentDescription(const debug_report_data *report_data, RenderPassCreateVersion rp_version,
3510                                                        const VkImageLayout first_layout, const uint32_t attachment,
3511                                                        const VkAttachmentDescription2KHR &attachment_description) const {
3512     bool skip = false;
3513     const char *vuid;
3514     const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2);
3515 
3516     // Verify that initial loadOp on READ_ONLY attachments is not CLEAR
3517     if (attachment_description.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
3518         if (use_rp2 && ((first_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL) ||
3519                         (first_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) ||
3520                         (first_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL))) {
3521             skip |=
3522                 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
3523                         "VUID-VkRenderPassCreateInfo2KHR-pAttachments-02522",
3524                         "Cannot clear attachment %d with invalid first layout %s.", attachment, string_VkImageLayout(first_layout));
3525         } else if (!use_rp2 && ((first_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL) ||
3526                                 (first_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL))) {
3527             skip |=
3528                 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
3529                         "VUID-VkRenderPassCreateInfo-pAttachments-00836",
3530                         "Cannot clear attachment %d with invalid first layout %s.", attachment, string_VkImageLayout(first_layout));
3531         }
3532     }
3533     if (attachment_description.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
3534         if (first_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL) {
3535             vuid = use_rp2 ? kVUID_Core_DrawState_InvalidRenderpass : "VUID-VkRenderPassCreateInfo-pAttachments-01566";
3536             skip |=
3537                 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
3538                         "Cannot clear attachment %d with invalid first layout %s.", attachment, string_VkImageLayout(first_layout));
3539         }
3540     }
3541 
3542     if (attachment_description.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
3543         if (first_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL) {
3544             vuid = use_rp2 ? kVUID_Core_DrawState_InvalidRenderpass : "VUID-VkRenderPassCreateInfo-pAttachments-01567";
3545             skip |=
3546                 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
3547                         "Cannot clear attachment %d with invalid first layout %s.", attachment, string_VkImageLayout(first_layout));
3548         }
3549     }
3550     return skip;
3551 }
3552 
ValidateLayouts(RenderPassCreateVersion rp_version,VkDevice device,const VkRenderPassCreateInfo2KHR * pCreateInfo) const3553 bool CoreChecks::ValidateLayouts(RenderPassCreateVersion rp_version, VkDevice device,
3554                                  const VkRenderPassCreateInfo2KHR *pCreateInfo) const {
3555     bool skip = false;
3556     const char *vuid;
3557     const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2);
3558     const char *const function_name = use_rp2 ? "vkCreateRenderPass2KHR()" : "vkCreateRenderPass()";
3559 
3560     for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
3561         VkFormat format = pCreateInfo->pAttachments[i].format;
3562         if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
3563             if ((FormatIsColor(format) || FormatHasDepth(format)) &&
3564                 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3565                 skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
3566                                 kVUID_Core_DrawState_InvalidRenderpass,
3567                                 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and initialLayout == "
3568                                 "VK_IMAGE_LAYOUT_UNDEFINED.  This is probably not what you intended.  Consider using "
3569                                 "VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the image truely is undefined at the start of the "
3570                                 "render pass.");
3571             }
3572             if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3573                 skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
3574                                 kVUID_Core_DrawState_InvalidRenderpass,
3575                                 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD and initialLayout "
3576                                 "== VK_IMAGE_LAYOUT_UNDEFINED.  This is probably not what you intended.  Consider using "
3577                                 "VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the image truely is undefined at the start of the "
3578                                 "render pass.");
3579             }
3580         }
3581     }
3582 
3583     // Track when we're observing the first use of an attachment
3584     std::vector<bool> attach_first_use(pCreateInfo->attachmentCount, true);
3585     for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) {
3586         const VkSubpassDescription2KHR &subpass = pCreateInfo->pSubpasses[i];
3587 
3588         // Check input attachments first, so we can detect first-use-as-input for VU #00349
3589         for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) {
3590             auto attach_index = subpass.pInputAttachments[j].attachment;
3591             if (attach_index == VK_ATTACHMENT_UNUSED) continue;
3592             switch (subpass.pInputAttachments[j].layout) {
3593                 case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL:
3594                 case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
3595                     // These are ideal.
3596                     break;
3597 
3598                 case VK_IMAGE_LAYOUT_GENERAL:
3599                     // May not be optimal. TODO: reconsider this warning based on other constraints.
3600                     skip |= log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
3601                                     VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_DrawState_InvalidImageLayout,
3602                                     "Layout for input attachment is GENERAL but should be READ_ONLY_OPTIMAL.");
3603                     break;
3604 
3605                 case VK_IMAGE_LAYOUT_UNDEFINED:
3606                 case VK_IMAGE_LAYOUT_PREINITIALIZED:
3607                     vuid = use_rp2 ? "VUID-VkAttachmentReference2KHR-layout-03077" : "VUID-VkAttachmentReference-layout-00857";
3608                     skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
3609                                     "Layout for input attachment reference %u in subpass %u is %s but must be "
3610                                     "DEPTH_STENCIL_READ_ONLY, SHADER_READ_ONLY_OPTIMAL, or GENERAL.",
3611                                     j, i, string_VkImageLayout(subpass.pInputAttachments[j].layout));
3612                     break;
3613 
3614                 case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL_KHR:
3615                 case VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL_KHR:
3616                     if (device_extensions.vk_khr_maintenance2) {
3617                         break;
3618                     } else {
3619                         // Intentionally fall through to generic error message
3620                     }
3621                     // fall through
3622 
3623                 default:
3624                     // No other layouts are acceptable
3625                     skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
3626                                     kVUID_Core_DrawState_InvalidImageLayout,
3627                                     "Layout for input attachment is %s but can only be READ_ONLY_OPTIMAL or GENERAL.",
3628                                     string_VkImageLayout(subpass.pInputAttachments[j].layout));
3629             }
3630 
3631             if (attach_first_use[attach_index]) {
3632                 skip |= ValidateLayoutVsAttachmentDescription(report_data, rp_version, subpass.pInputAttachments[j].layout,
3633                                                               attach_index, pCreateInfo->pAttachments[attach_index]);
3634 
3635                 bool used_as_depth =
3636                     (subpass.pDepthStencilAttachment != NULL && subpass.pDepthStencilAttachment->attachment == attach_index);
3637                 bool used_as_color = false;
3638                 for (uint32_t k = 0; !used_as_depth && !used_as_color && k < subpass.colorAttachmentCount; ++k) {
3639                     used_as_color = (subpass.pColorAttachments[k].attachment == attach_index);
3640                 }
3641                 if (!used_as_depth && !used_as_color &&
3642                     pCreateInfo->pAttachments[attach_index].loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
3643                     vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-loadOp-03064" : "VUID-VkSubpassDescription-loadOp-00846";
3644                     skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
3645                                     "%s: attachment %u is first used as an input attachment in subpass %u with loadOp=CLEAR.",
3646                                     function_name, attach_index, attach_index);
3647                 }
3648             }
3649             attach_first_use[attach_index] = false;
3650         }
3651 
3652         for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) {
3653             auto attach_index = subpass.pColorAttachments[j].attachment;
3654             if (attach_index == VK_ATTACHMENT_UNUSED) continue;
3655 
3656             // TODO: Need a way to validate shared presentable images here, currently just allowing
3657             // VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR
3658             //  as an acceptable layout, but need to make sure shared presentable images ONLY use that layout
3659             switch (subpass.pColorAttachments[j].layout) {
3660                 case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
3661                 // This is ideal.
3662                 case VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR:
3663                     // TODO: See note above, just assuming that attachment is shared presentable and allowing this for now.
3664                     break;
3665 
3666                 case VK_IMAGE_LAYOUT_GENERAL:
3667                     // May not be optimal; TODO: reconsider this warning based on other constraints?
3668                     skip |= log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
3669                                     VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_DrawState_InvalidImageLayout,
3670                                     "Layout for color attachment is GENERAL but should be COLOR_ATTACHMENT_OPTIMAL.");
3671                     break;
3672 
3673                 case VK_IMAGE_LAYOUT_UNDEFINED:
3674                 case VK_IMAGE_LAYOUT_PREINITIALIZED:
3675                     vuid = use_rp2 ? "VUID-VkAttachmentReference2KHR-layout-03077" : "VUID-VkAttachmentReference-layout-00857";
3676                     skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
3677                                     "Layout for color attachment reference %u in subpass %u is %s but should be "
3678                                     "COLOR_ATTACHMENT_OPTIMAL or GENERAL.",
3679                                     j, i, string_VkImageLayout(subpass.pColorAttachments[j].layout));
3680                     break;
3681 
3682                 default:
3683                     skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
3684                                     kVUID_Core_DrawState_InvalidImageLayout,
3685                                     "Layout for color attachment is %s but can only be COLOR_ATTACHMENT_OPTIMAL or GENERAL.",
3686                                     string_VkImageLayout(subpass.pColorAttachments[j].layout));
3687             }
3688 
3689             if (subpass.pResolveAttachments && (subpass.pResolveAttachments[j].attachment != VK_ATTACHMENT_UNUSED) &&
3690                 (subpass.pResolveAttachments[j].layout == VK_IMAGE_LAYOUT_UNDEFINED ||
3691                  subpass.pResolveAttachments[j].layout == VK_IMAGE_LAYOUT_PREINITIALIZED)) {
3692                 vuid = use_rp2 ? "VUID-VkAttachmentReference2KHR-layout-03077" : "VUID-VkAttachmentReference-layout-00857";
3693                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
3694                                 "Layout for resolve attachment reference %u in subpass %u is %s but should be "
3695                                 "COLOR_ATTACHMENT_OPTIMAL or GENERAL.",
3696                                 j, i, string_VkImageLayout(subpass.pResolveAttachments[j].layout));
3697             }
3698 
3699             if (attach_first_use[attach_index]) {
3700                 skip |= ValidateLayoutVsAttachmentDescription(report_data, rp_version, subpass.pColorAttachments[j].layout,
3701                                                               attach_index, pCreateInfo->pAttachments[attach_index]);
3702             }
3703             attach_first_use[attach_index] = false;
3704         }
3705 
3706         if (subpass.pDepthStencilAttachment && subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
3707             switch (subpass.pDepthStencilAttachment->layout) {
3708                 case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
3709                 case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL:
3710                     // These are ideal.
3711                     break;
3712 
3713                 case VK_IMAGE_LAYOUT_GENERAL:
3714                     // May not be optimal; TODO: reconsider this warning based on other constraints? GENERAL can be better than
3715                     // doing a bunch of transitions.
3716                     skip |= log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
3717                                     VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_DrawState_InvalidImageLayout,
3718                                     "GENERAL layout for depth attachment may not give optimal performance.");
3719                     break;
3720 
3721                 case VK_IMAGE_LAYOUT_UNDEFINED:
3722                 case VK_IMAGE_LAYOUT_PREINITIALIZED:
3723                     vuid = use_rp2 ? "VUID-VkAttachmentReference2KHR-layout-03077" : "VUID-VkAttachmentReference-layout-00857";
3724                     skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
3725                                     "Layout for depth attachment reference in subpass %u is %s but must be a valid depth/stencil "
3726                                     "layout or GENERAL.",
3727                                     i, string_VkImageLayout(subpass.pDepthStencilAttachment->layout));
3728                     break;
3729 
3730                 case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL_KHR:
3731                 case VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL_KHR:
3732                     if (device_extensions.vk_khr_maintenance2) {
3733                         break;
3734                     } else {
3735                         // Intentionally fall through to generic error message
3736                     }
3737                     // fall through
3738 
3739                 default:
3740                     // No other layouts are acceptable
3741                     skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
3742                                     kVUID_Core_DrawState_InvalidImageLayout,
3743                                     "Layout for depth attachment is %s but can only be DEPTH_STENCIL_ATTACHMENT_OPTIMAL, "
3744                                     "DEPTH_STENCIL_READ_ONLY_OPTIMAL or GENERAL.",
3745                                     string_VkImageLayout(subpass.pDepthStencilAttachment->layout));
3746             }
3747 
3748             auto attach_index = subpass.pDepthStencilAttachment->attachment;
3749             if (attach_first_use[attach_index]) {
3750                 skip |= ValidateLayoutVsAttachmentDescription(report_data, rp_version, subpass.pDepthStencilAttachment->layout,
3751                                                               attach_index, pCreateInfo->pAttachments[attach_index]);
3752             }
3753             attach_first_use[attach_index] = false;
3754         }
3755     }
3756     return skip;
3757 }
3758 
3759 // Helper function to validate correct usage bits set for buffers or images. Verify that (actual & desired) flags != 0 or, if strict
3760 // is true, verify that (actual & desired) flags == desired
ValidateUsageFlags(VkFlags actual,VkFlags desired,VkBool32 strict,const VulkanTypedHandle & typed_handle,const char * msgCode,char const * func_name,char const * usage_str) const3761 bool CoreChecks::ValidateUsageFlags(VkFlags actual, VkFlags desired, VkBool32 strict, const VulkanTypedHandle &typed_handle,
3762                                     const char *msgCode, char const *func_name, char const *usage_str) const {
3763     bool correct_usage = false;
3764     bool skip = false;
3765     const char *type_str = object_string[typed_handle.type];
3766     if (strict) {
3767         correct_usage = ((actual & desired) == desired);
3768     } else {
3769         correct_usage = ((actual & desired) != 0);
3770     }
3771     if (!correct_usage) {
3772         if (msgCode == kVUIDUndefined) {
3773             // TODO: Fix callers with kVUIDUndefined to use correct validation checks.
3774             skip = log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, get_debug_report_enum[typed_handle.type],
3775                            typed_handle.handle, kVUID_Core_MemTrack_InvalidUsageFlag,
3776                            "Invalid usage flag for %s used by %s. In this case, %s should have %s set during creation.",
3777                            report_data->FormatHandle(typed_handle).c_str(), func_name, type_str, usage_str);
3778         } else {
3779             skip =
3780                 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, get_debug_report_enum[typed_handle.type], typed_handle.handle,
3781                         msgCode, "Invalid usage flag for %s used by %s. In this case, %s should have %s set during creation.",
3782                         report_data->FormatHandle(typed_handle).c_str(), func_name, type_str, usage_str);
3783         }
3784     }
3785     return skip;
3786 }
3787 
3788 // Helper function to validate usage flags for buffers. For given buffer_state send actual vs. desired usage off to helper above
3789 // where an error will be flagged if usage is not correct
ValidateImageUsageFlags(IMAGE_STATE const * image_state,VkFlags desired,bool strict,const char * msgCode,char const * func_name,char const * usage_string) const3790 bool CoreChecks::ValidateImageUsageFlags(IMAGE_STATE const *image_state, VkFlags desired, bool strict, const char *msgCode,
3791                                          char const *func_name, char const *usage_string) const {
3792     return ValidateUsageFlags(image_state->createInfo.usage, desired, strict,
3793                               VulkanTypedHandle(image_state->image, kVulkanObjectTypeImage), msgCode, func_name, usage_string);
3794 }
3795 
ValidateImageFormatFeatureFlags(IMAGE_STATE const * image_state,VkFormatFeatureFlags desired,char const * func_name,const char * linear_vuid,const char * optimal_vuid) const3796 bool CoreChecks::ValidateImageFormatFeatureFlags(IMAGE_STATE const *image_state, VkFormatFeatureFlags desired,
3797                                                  char const *func_name, const char *linear_vuid, const char *optimal_vuid) const {
3798     VkFormatProperties format_properties = GetPDFormatProperties(image_state->createInfo.format);
3799     bool skip = false;
3800     if (image_state->createInfo.tiling == VK_IMAGE_TILING_LINEAR) {
3801         if ((format_properties.linearTilingFeatures & desired) != desired) {
3802             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
3803                             HandleToUint64(image_state->image), linear_vuid,
3804                             "In %s, invalid linearTilingFeatures (0x%08X) for format %u used by %s.", func_name,
3805                             format_properties.linearTilingFeatures, image_state->createInfo.format,
3806                             report_data->FormatHandle(image_state->image).c_str());
3807         }
3808     } else if (image_state->createInfo.tiling == VK_IMAGE_TILING_OPTIMAL) {
3809         if ((format_properties.optimalTilingFeatures & desired) != desired) {
3810             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
3811                             HandleToUint64(image_state->image), optimal_vuid,
3812                             "In %s, invalid optimalTilingFeatures (0x%08X) for format %u used by %s.", func_name,
3813                             format_properties.optimalTilingFeatures, image_state->createInfo.format,
3814                             report_data->FormatHandle(image_state->image).c_str());
3815         }
3816     }
3817     return skip;
3818 }
3819 
ValidateImageSubresourceLayers(const CMD_BUFFER_STATE * cb_node,const VkImageSubresourceLayers * subresource_layers,char const * func_name,char const * member,uint32_t i) const3820 bool CoreChecks::ValidateImageSubresourceLayers(const CMD_BUFFER_STATE *cb_node, const VkImageSubresourceLayers *subresource_layers,
3821                                                 char const *func_name, char const *member, uint32_t i) const {
3822     bool skip = false;
3823     // layerCount must not be zero
3824     if (subresource_layers->layerCount == 0) {
3825         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3826                         HandleToUint64(cb_node->commandBuffer), "VUID-VkImageSubresourceLayers-layerCount-01700",
3827                         "In %s, pRegions[%u].%s.layerCount must not be zero.", func_name, i, member);
3828     }
3829     // aspectMask must not contain VK_IMAGE_ASPECT_METADATA_BIT
3830     if (subresource_layers->aspectMask & VK_IMAGE_ASPECT_METADATA_BIT) {
3831         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3832                         HandleToUint64(cb_node->commandBuffer), "VUID-VkImageSubresourceLayers-aspectMask-00168",
3833                         "In %s, pRegions[%u].%s.aspectMask has VK_IMAGE_ASPECT_METADATA_BIT set.", func_name, i, member);
3834     }
3835     // if aspectMask contains COLOR, it must not contain either DEPTH or STENCIL
3836     if ((subresource_layers->aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) &&
3837         (subresource_layers->aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
3838         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
3839                         HandleToUint64(cb_node->commandBuffer), "VUID-VkImageSubresourceLayers-aspectMask-00167",
3840                         "In %s, pRegions[%u].%s.aspectMask has VK_IMAGE_ASPECT_COLOR_BIT and either VK_IMAGE_ASPECT_DEPTH_BIT or "
3841                         "VK_IMAGE_ASPECT_STENCIL_BIT set.",
3842                         func_name, i, member);
3843     }
3844     return skip;
3845 }
3846 
3847 // Helper function to validate usage flags for buffers. For given buffer_state send actual vs. desired usage off to helper above
3848 // where an error will be flagged if usage is not correct
ValidateBufferUsageFlags(BUFFER_STATE const * buffer_state,VkFlags desired,bool strict,const char * msgCode,char const * func_name,char const * usage_string) const3849 bool CoreChecks::ValidateBufferUsageFlags(BUFFER_STATE const *buffer_state, VkFlags desired, bool strict, const char *msgCode,
3850                                           char const *func_name, char const *usage_string) const {
3851     return ValidateUsageFlags(buffer_state->createInfo.usage, desired, strict,
3852                               VulkanTypedHandle(buffer_state->buffer, kVulkanObjectTypeBuffer), msgCode, func_name, usage_string);
3853 }
3854 
ValidateBufferViewRange(const BUFFER_STATE * buffer_state,const VkBufferViewCreateInfo * pCreateInfo,const VkPhysicalDeviceLimits * device_limits)3855 bool CoreChecks::ValidateBufferViewRange(const BUFFER_STATE *buffer_state, const VkBufferViewCreateInfo *pCreateInfo,
3856                                          const VkPhysicalDeviceLimits *device_limits) {
3857     bool skip = false;
3858 
3859     const VkDeviceSize &range = pCreateInfo->range;
3860     if (range != VK_WHOLE_SIZE) {
3861         // Range must be greater than 0
3862         if (range <= 0) {
3863             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
3864                             HandleToUint64(buffer_state->buffer), "VUID-VkBufferViewCreateInfo-range-00928",
3865                             "If VkBufferViewCreateInfo range (%" PRIuLEAST64
3866                             ") does not equal VK_WHOLE_SIZE, range must be greater than 0.",
3867                             range);
3868         }
3869         // Range must be a multiple of the element size of format
3870         const uint32_t format_size = FormatElementSize(pCreateInfo->format);
3871         if (SafeModulo(range, format_size) != 0) {
3872             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
3873                             HandleToUint64(buffer_state->buffer), "VUID-VkBufferViewCreateInfo-range-00929",
3874                             "If VkBufferViewCreateInfo range (%" PRIuLEAST64
3875                             ") does not equal VK_WHOLE_SIZE, range must be a multiple of the element size of the format "
3876                             "(%" PRIu32 ").",
3877                             range, format_size);
3878         }
3879         // Range divided by the element size of format must be less than or equal to VkPhysicalDeviceLimits::maxTexelBufferElements
3880         if (SafeDivision(range, format_size) > device_limits->maxTexelBufferElements) {
3881             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
3882                             HandleToUint64(buffer_state->buffer), "VUID-VkBufferViewCreateInfo-range-00930",
3883                             "If VkBufferViewCreateInfo range (%" PRIuLEAST64
3884                             ") does not equal VK_WHOLE_SIZE, range divided by the element size of the format (%" PRIu32
3885                             ") must be less than or equal to VkPhysicalDeviceLimits::maxTexelBufferElements (%" PRIuLEAST32 ").",
3886                             range, format_size, device_limits->maxTexelBufferElements);
3887         }
3888         // The sum of range and offset must be less than or equal to the size of buffer
3889         if (range + pCreateInfo->offset > buffer_state->createInfo.size) {
3890             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
3891                             HandleToUint64(buffer_state->buffer), "VUID-VkBufferViewCreateInfo-offset-00931",
3892                             "If VkBufferViewCreateInfo range (%" PRIuLEAST64
3893                             ") does not equal VK_WHOLE_SIZE, the sum of offset (%" PRIuLEAST64
3894                             ") and range must be less than or equal to the size of the buffer (%" PRIuLEAST64 ").",
3895                             range, pCreateInfo->offset, buffer_state->createInfo.size);
3896         }
3897     }
3898     return skip;
3899 }
3900 
ValidateBufferViewBuffer(const BUFFER_STATE * buffer_state,const VkBufferViewCreateInfo * pCreateInfo)3901 bool CoreChecks::ValidateBufferViewBuffer(const BUFFER_STATE *buffer_state, const VkBufferViewCreateInfo *pCreateInfo) {
3902     bool skip = false;
3903     const VkFormatProperties format_properties = GetPDFormatProperties(pCreateInfo->format);
3904     if ((buffer_state->createInfo.usage & VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT) &&
3905         !(format_properties.bufferFeatures & VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT)) {
3906         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
3907                         HandleToUint64(buffer_state->buffer), "VUID-VkBufferViewCreateInfo-buffer-00933",
3908                         "If buffer was created with `usage` containing VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT, format must "
3909                         "be supported for uniform texel buffers");
3910     }
3911     if ((buffer_state->createInfo.usage & VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT) &&
3912         !(format_properties.bufferFeatures & VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT)) {
3913         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
3914                         HandleToUint64(buffer_state->buffer), "VUID-VkBufferViewCreateInfo-buffer-00934",
3915                         "If buffer was created with `usage` containing VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT, format must "
3916                         "be supported for storage texel buffers");
3917     }
3918     return skip;
3919 }
3920 
PreCallValidateCreateBuffer(VkDevice device,const VkBufferCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkBuffer * pBuffer)3921 bool CoreChecks::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo *pCreateInfo,
3922                                              const VkAllocationCallbacks *pAllocator, VkBuffer *pBuffer) {
3923     bool skip = false;
3924 
3925     // TODO: Add check for "VUID-vkCreateBuffer-flags-00911"        (sparse address space accounting)
3926 
3927     if ((pCreateInfo->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT) && (!enabled_features.core.sparseBinding)) {
3928         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
3929                         "VUID-VkBufferCreateInfo-flags-00915",
3930                         "vkCreateBuffer(): the sparseBinding device feature is disabled: Buffers cannot be created with the "
3931                         "VK_BUFFER_CREATE_SPARSE_BINDING_BIT set.");
3932     }
3933 
3934     if ((pCreateInfo->flags & VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT) && (!enabled_features.core.sparseResidencyBuffer)) {
3935         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
3936                         "VUID-VkBufferCreateInfo-flags-00916",
3937                         "vkCreateBuffer(): the sparseResidencyBuffer device feature is disabled: Buffers cannot be created with "
3938                         "the VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT set.");
3939     }
3940 
3941     if ((pCreateInfo->flags & VK_BUFFER_CREATE_SPARSE_ALIASED_BIT) && (!enabled_features.core.sparseResidencyAliased)) {
3942         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
3943                         "VUID-VkBufferCreateInfo-flags-00917",
3944                         "vkCreateBuffer(): the sparseResidencyAliased device feature is disabled: Buffers cannot be created with "
3945                         "the VK_BUFFER_CREATE_SPARSE_ALIASED_BIT set.");
3946     }
3947 
3948     auto chained_devaddr_struct = lvl_find_in_chain<VkBufferDeviceAddressCreateInfoEXT>(pCreateInfo->pNext);
3949     if (chained_devaddr_struct) {
3950         if (!(pCreateInfo->flags & VK_BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT_EXT) &&
3951             chained_devaddr_struct->deviceAddress != 0) {
3952             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
3953                             "VUID-VkBufferCreateInfo-deviceAddress-02604",
3954                             "vkCreateBuffer(): Non-zero VkBufferDeviceAddressCreateInfoEXT::deviceAddress "
3955                             "requires VK_BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT_EXT.");
3956         }
3957     }
3958 
3959     if ((pCreateInfo->flags & VK_BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT_EXT) &&
3960         !enabled_features.buffer_address.bufferDeviceAddressCaptureReplay) {
3961         skip |= log_msg(
3962             report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
3963             "VUID-VkBufferCreateInfo-flags-02605",
3964             "vkCreateBuffer(): the bufferDeviceAddressCaptureReplay device feature is disabled: Buffers cannot be created with "
3965             "the VK_BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT_EXT set.");
3966     }
3967 
3968     if ((pCreateInfo->usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_EXT) &&
3969         !enabled_features.buffer_address.bufferDeviceAddress) {
3970         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
3971                         "VUID-VkBufferCreateInfo-usage-02606",
3972                         "vkCreateBuffer(): the bufferDeviceAddress device feature is disabled: Buffers cannot be created with "
3973                         "the VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_EXT set.");
3974     }
3975 
3976     if (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT && pCreateInfo->pQueueFamilyIndices) {
3977         skip |= ValidateQueueFamilies(pCreateInfo->queueFamilyIndexCount, pCreateInfo->pQueueFamilyIndices, "vkCreateBuffer",
3978                                       "pCreateInfo->pQueueFamilyIndices", "VUID-VkBufferCreateInfo-sharingMode-01419",
3979                                       "VUID-VkBufferCreateInfo-sharingMode-01419", false);
3980     }
3981 
3982     return skip;
3983 }
3984 
PostCallRecordCreateBuffer(VkDevice device,const VkBufferCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkBuffer * pBuffer,VkResult result)3985 void ValidationStateTracker::PostCallRecordCreateBuffer(VkDevice device, const VkBufferCreateInfo *pCreateInfo,
3986                                                         const VkAllocationCallbacks *pAllocator, VkBuffer *pBuffer,
3987                                                         VkResult result) {
3988     if (result != VK_SUCCESS) return;
3989     // TODO : This doesn't create deep copy of pQueueFamilyIndices so need to fix that if/when we want that data to be valid
3990     std::unique_ptr<BUFFER_STATE> buffer_state(new BUFFER_STATE(*pBuffer, pCreateInfo));
3991 
3992     // Get a set of requirements in the case the app does not
3993     DispatchGetBufferMemoryRequirements(device, *pBuffer, &buffer_state->requirements);
3994 
3995     bufferMap.insert(std::make_pair(*pBuffer, std::move(buffer_state)));
3996 }
3997 
PreCallValidateCreateBufferView(VkDevice device,const VkBufferViewCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkBufferView * pView)3998 bool CoreChecks::PreCallValidateCreateBufferView(VkDevice device, const VkBufferViewCreateInfo *pCreateInfo,
3999                                                  const VkAllocationCallbacks *pAllocator, VkBufferView *pView) {
4000     bool skip = false;
4001     BUFFER_STATE *buffer_state = GetBufferState(pCreateInfo->buffer);
4002     // If this isn't a sparse buffer, it needs to have memory backing it at CreateBufferView time
4003     if (buffer_state) {
4004         skip |= ValidateMemoryIsBoundToBuffer(buffer_state, "vkCreateBufferView()", "VUID-VkBufferViewCreateInfo-buffer-00935");
4005         // In order to create a valid buffer view, the buffer must have been created with at least one of the following flags:
4006         // UNIFORM_TEXEL_BUFFER_BIT or STORAGE_TEXEL_BUFFER_BIT
4007         skip |= ValidateBufferUsageFlags(buffer_state,
4008                                          VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT, false,
4009                                          "VUID-VkBufferViewCreateInfo-buffer-00932", "vkCreateBufferView()",
4010                                          "VK_BUFFER_USAGE_[STORAGE|UNIFORM]_TEXEL_BUFFER_BIT");
4011 
4012         // Buffer view offset must be less than the size of buffer
4013         if (pCreateInfo->offset >= buffer_state->createInfo.size) {
4014             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
4015                             HandleToUint64(buffer_state->buffer), "VUID-VkBufferViewCreateInfo-offset-00925",
4016                             "VkBufferViewCreateInfo offset (%" PRIuLEAST64
4017                             ") must be less than the size of the buffer (%" PRIuLEAST64 ").",
4018                             pCreateInfo->offset, buffer_state->createInfo.size);
4019         }
4020 
4021         const VkPhysicalDeviceLimits *device_limits = &phys_dev_props.limits;
4022         // Buffer view offset must be a multiple of VkPhysicalDeviceLimits::minTexelBufferOffsetAlignment
4023         if ((pCreateInfo->offset % device_limits->minTexelBufferOffsetAlignment) != 0 &&
4024             !enabled_features.texel_buffer_alignment_features.texelBufferAlignment) {
4025             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
4026                             HandleToUint64(buffer_state->buffer), "VUID-VkBufferViewCreateInfo-offset-02749",
4027                             "VkBufferViewCreateInfo offset (%" PRIuLEAST64
4028                             ") must be a multiple of VkPhysicalDeviceLimits::minTexelBufferOffsetAlignment (%" PRIuLEAST64 ").",
4029                             pCreateInfo->offset, device_limits->minTexelBufferOffsetAlignment);
4030         }
4031 
4032         if (enabled_features.texel_buffer_alignment_features.texelBufferAlignment) {
4033             VkDeviceSize elementSize = FormatElementSize(pCreateInfo->format);
4034             if ((elementSize % 3) == 0) {
4035                 elementSize /= 3;
4036             }
4037             if (buffer_state->createInfo.usage & VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT) {
4038                 VkDeviceSize alignmentRequirement =
4039                     phys_dev_ext_props.texel_buffer_alignment_props.storageTexelBufferOffsetAlignmentBytes;
4040                 if (phys_dev_ext_props.texel_buffer_alignment_props.storageTexelBufferOffsetSingleTexelAlignment) {
4041                     alignmentRequirement = std::min(alignmentRequirement, elementSize);
4042                 }
4043                 if (SafeModulo(pCreateInfo->offset, alignmentRequirement) != 0) {
4044                     skip |= log_msg(
4045                         report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
4046                         HandleToUint64(buffer_state->buffer), "VUID-VkBufferViewCreateInfo-buffer-02750",
4047                         "If buffer was created with usage containing VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT, "
4048                         "VkBufferViewCreateInfo offset (%" PRIuLEAST64
4049                         ") must be a multiple of the lesser of "
4050                         "VkPhysicalDeviceTexelBufferAlignmentPropertiesEXT::storageTexelBufferOffsetAlignmentBytes (%" PRIuLEAST64
4051                         ") or, if VkPhysicalDeviceTexelBufferAlignmentPropertiesEXT::storageTexelBufferOffsetSingleTexelAlignment "
4052                         "(%" PRId32
4053                         ") is VK_TRUE, the size of a texel of the requested format. "
4054                         "If the size of a texel is a multiple of three bytes, then the size of a "
4055                         "single component of format is used instead",
4056                         pCreateInfo->offset, phys_dev_ext_props.texel_buffer_alignment_props.storageTexelBufferOffsetAlignmentBytes,
4057                         phys_dev_ext_props.texel_buffer_alignment_props.storageTexelBufferOffsetSingleTexelAlignment);
4058                 }
4059             }
4060             if (buffer_state->createInfo.usage & VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT) {
4061                 VkDeviceSize alignmentRequirement =
4062                     phys_dev_ext_props.texel_buffer_alignment_props.uniformTexelBufferOffsetAlignmentBytes;
4063                 if (phys_dev_ext_props.texel_buffer_alignment_props.uniformTexelBufferOffsetSingleTexelAlignment) {
4064                     alignmentRequirement = std::min(alignmentRequirement, elementSize);
4065                 }
4066                 if (SafeModulo(pCreateInfo->offset, alignmentRequirement) != 0) {
4067                     skip |= log_msg(
4068                         report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
4069                         HandleToUint64(buffer_state->buffer), "VUID-VkBufferViewCreateInfo-buffer-02751",
4070                         "If buffer was created with usage containing VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT, "
4071                         "VkBufferViewCreateInfo offset (%" PRIuLEAST64
4072                         ") must be a multiple of the lesser of "
4073                         "VkPhysicalDeviceTexelBufferAlignmentPropertiesEXT::uniformTexelBufferOffsetAlignmentBytes (%" PRIuLEAST64
4074                         ") or, if VkPhysicalDeviceTexelBufferAlignmentPropertiesEXT::uniformTexelBufferOffsetSingleTexelAlignment "
4075                         "(%" PRId32
4076                         ") is VK_TRUE, the size of a texel of the requested format. "
4077                         "If the size of a texel is a multiple of three bytes, then the size of a "
4078                         "single component of format is used instead",
4079                         pCreateInfo->offset, phys_dev_ext_props.texel_buffer_alignment_props.uniformTexelBufferOffsetAlignmentBytes,
4080                         phys_dev_ext_props.texel_buffer_alignment_props.uniformTexelBufferOffsetSingleTexelAlignment);
4081                 }
4082             }
4083         }
4084 
4085         skip |= ValidateBufferViewRange(buffer_state, pCreateInfo, device_limits);
4086 
4087         skip |= ValidateBufferViewBuffer(buffer_state, pCreateInfo);
4088     }
4089     return skip;
4090 }
4091 
PostCallRecordCreateBufferView(VkDevice device,const VkBufferViewCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkBufferView * pView,VkResult result)4092 void ValidationStateTracker::PostCallRecordCreateBufferView(VkDevice device, const VkBufferViewCreateInfo *pCreateInfo,
4093                                                             const VkAllocationCallbacks *pAllocator, VkBufferView *pView,
4094                                                             VkResult result) {
4095     if (result != VK_SUCCESS) return;
4096     bufferViewMap[*pView] = std::unique_ptr<BUFFER_VIEW_STATE>(new BUFFER_VIEW_STATE(*pView, pCreateInfo));
4097 }
4098 
4099 // For the given format verify that the aspect masks make sense
ValidateImageAspectMask(VkImage image,VkFormat format,VkImageAspectFlags aspect_mask,const char * func_name,const char * vuid) const4100 bool CoreChecks::ValidateImageAspectMask(VkImage image, VkFormat format, VkImageAspectFlags aspect_mask, const char *func_name,
4101                                          const char *vuid) const {
4102     bool skip = false;
4103     VkDebugReportObjectTypeEXT objectType = VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;
4104     if (image != VK_NULL_HANDLE) {
4105         objectType = VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT;
4106     }
4107 
4108     if (FormatIsColor(format)) {
4109         if ((aspect_mask & VK_IMAGE_ASPECT_COLOR_BIT) != VK_IMAGE_ASPECT_COLOR_BIT) {
4110             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, objectType, HandleToUint64(image), vuid,
4111                             "%s: Color image formats must have the VK_IMAGE_ASPECT_COLOR_BIT set.", func_name);
4112         } else if ((aspect_mask & VK_IMAGE_ASPECT_COLOR_BIT) != aspect_mask) {
4113             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, objectType, HandleToUint64(image), vuid,
4114                             "%s: Color image formats must have ONLY the VK_IMAGE_ASPECT_COLOR_BIT set.", func_name);
4115         }
4116     } else if (FormatIsDepthAndStencil(format)) {
4117         if ((aspect_mask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) == 0) {
4118             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, objectType, HandleToUint64(image), vuid,
4119                             "%s: Depth/stencil image formats must have at least one of VK_IMAGE_ASPECT_DEPTH_BIT and "
4120                             "VK_IMAGE_ASPECT_STENCIL_BIT set.",
4121                             func_name);
4122         } else if ((aspect_mask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != aspect_mask) {
4123             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, objectType, HandleToUint64(image), vuid,
4124                             "%s: Combination depth/stencil image formats can have only the VK_IMAGE_ASPECT_DEPTH_BIT and "
4125                             "VK_IMAGE_ASPECT_STENCIL_BIT set.",
4126                             func_name);
4127         }
4128     } else if (FormatIsDepthOnly(format)) {
4129         if ((aspect_mask & VK_IMAGE_ASPECT_DEPTH_BIT) != VK_IMAGE_ASPECT_DEPTH_BIT) {
4130             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, objectType, HandleToUint64(image), vuid,
4131                             "%s: Depth-only image formats must have the VK_IMAGE_ASPECT_DEPTH_BIT set.", func_name);
4132         } else if ((aspect_mask & VK_IMAGE_ASPECT_DEPTH_BIT) != aspect_mask) {
4133             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, objectType, HandleToUint64(image), vuid,
4134                             "%s: Depth-only image formats can have only the VK_IMAGE_ASPECT_DEPTH_BIT set.", func_name);
4135         }
4136     } else if (FormatIsStencilOnly(format)) {
4137         if ((aspect_mask & VK_IMAGE_ASPECT_STENCIL_BIT) != VK_IMAGE_ASPECT_STENCIL_BIT) {
4138             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, objectType, HandleToUint64(image), vuid,
4139                             "%s: Stencil-only image formats must have the VK_IMAGE_ASPECT_STENCIL_BIT set.", func_name);
4140         } else if ((aspect_mask & VK_IMAGE_ASPECT_STENCIL_BIT) != aspect_mask) {
4141             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, objectType, HandleToUint64(image), vuid,
4142                             "%s: Stencil-only image formats can have only the VK_IMAGE_ASPECT_STENCIL_BIT set.", func_name);
4143         }
4144     } else if (FormatIsMultiplane(format)) {
4145         VkImageAspectFlags valid_flags = VK_IMAGE_ASPECT_COLOR_BIT | VK_IMAGE_ASPECT_PLANE_0_BIT | VK_IMAGE_ASPECT_PLANE_1_BIT;
4146         if (3 == FormatPlaneCount(format)) {
4147             valid_flags = valid_flags | VK_IMAGE_ASPECT_PLANE_2_BIT;
4148         }
4149         if ((aspect_mask & valid_flags) != aspect_mask) {
4150             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, objectType, HandleToUint64(image), vuid,
4151                             "%s: Multi-plane image formats may have only VK_IMAGE_ASPECT_COLOR_BIT or VK_IMAGE_ASPECT_PLANE_n_BITs "
4152                             "set, where n = [0, 1, 2].",
4153                             func_name);
4154         }
4155     }
4156     return skip;
4157 }
4158 
ValidateImageSubresourceRange(const uint32_t image_mip_count,const uint32_t image_layer_count,const VkImageSubresourceRange & subresourceRange,const char * cmd_name,const char * param_name,const char * image_layer_count_var_name,const uint64_t image_handle,SubresourceRangeErrorCodes errorCodes) const4159 bool CoreChecks::ValidateImageSubresourceRange(const uint32_t image_mip_count, const uint32_t image_layer_count,
4160                                                const VkImageSubresourceRange &subresourceRange, const char *cmd_name,
4161                                                const char *param_name, const char *image_layer_count_var_name,
4162                                                const uint64_t image_handle, SubresourceRangeErrorCodes errorCodes) const {
4163     bool skip = false;
4164 
4165     // Validate mip levels
4166     if (subresourceRange.baseMipLevel >= image_mip_count) {
4167         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, image_handle,
4168                         errorCodes.base_mip_err,
4169                         "%s: %s.baseMipLevel (= %" PRIu32
4170                         ") is greater or equal to the mip level count of the image (i.e. greater or equal to %" PRIu32 ").",
4171                         cmd_name, param_name, subresourceRange.baseMipLevel, image_mip_count);
4172     }
4173 
4174     if (subresourceRange.levelCount != VK_REMAINING_MIP_LEVELS) {
4175         if (subresourceRange.levelCount == 0) {
4176             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, image_handle,
4177                             errorCodes.mip_count_err, "%s: %s.levelCount is 0.", cmd_name, param_name);
4178         } else {
4179             const uint64_t necessary_mip_count = uint64_t{subresourceRange.baseMipLevel} + uint64_t{subresourceRange.levelCount};
4180 
4181             if (necessary_mip_count > image_mip_count) {
4182                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, image_handle,
4183                                 errorCodes.mip_count_err,
4184                                 "%s: %s.baseMipLevel + .levelCount (= %" PRIu32 " + %" PRIu32 " = %" PRIu64
4185                                 ") is greater than the mip level count of the image (i.e. greater than %" PRIu32 ").",
4186                                 cmd_name, param_name, subresourceRange.baseMipLevel, subresourceRange.levelCount,
4187                                 necessary_mip_count, image_mip_count);
4188             }
4189         }
4190     }
4191 
4192     // Validate array layers
4193     if (subresourceRange.baseArrayLayer >= image_layer_count) {
4194         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, image_handle,
4195                         errorCodes.base_layer_err,
4196                         "%s: %s.baseArrayLayer (= %" PRIu32
4197                         ") is greater or equal to the %s of the image when it was created (i.e. greater or equal to %" PRIu32 ").",
4198                         cmd_name, param_name, subresourceRange.baseArrayLayer, image_layer_count_var_name, image_layer_count);
4199     }
4200 
4201     if (subresourceRange.layerCount != VK_REMAINING_ARRAY_LAYERS) {
4202         if (subresourceRange.layerCount == 0) {
4203             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, image_handle,
4204                             errorCodes.layer_count_err, "%s: %s.layerCount is 0.", cmd_name, param_name);
4205         } else {
4206             const uint64_t necessary_layer_count =
4207                 uint64_t{subresourceRange.baseArrayLayer} + uint64_t{subresourceRange.layerCount};
4208 
4209             if (necessary_layer_count > image_layer_count) {
4210                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, image_handle,
4211                                 errorCodes.layer_count_err,
4212                                 "%s: %s.baseArrayLayer + .layerCount (= %" PRIu32 " + %" PRIu32 " = %" PRIu64
4213                                 ") is greater than the %s of the image when it was created (i.e. greater than %" PRIu32 ").",
4214                                 cmd_name, param_name, subresourceRange.baseArrayLayer, subresourceRange.layerCount,
4215                                 necessary_layer_count, image_layer_count_var_name, image_layer_count);
4216             }
4217         }
4218     }
4219 
4220     return skip;
4221 }
4222 
ValidateCreateImageViewSubresourceRange(const IMAGE_STATE * image_state,bool is_imageview_2d_type,const VkImageSubresourceRange & subresourceRange)4223 bool CoreChecks::ValidateCreateImageViewSubresourceRange(const IMAGE_STATE *image_state, bool is_imageview_2d_type,
4224                                                          const VkImageSubresourceRange &subresourceRange) {
4225     bool is_khr_maintenance1 = device_extensions.vk_khr_maintenance1;
4226     bool is_image_slicable = image_state->createInfo.imageType == VK_IMAGE_TYPE_3D &&
4227                              (image_state->createInfo.flags & VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR);
4228     bool is_3D_to_2D_map = is_khr_maintenance1 && is_image_slicable && is_imageview_2d_type;
4229 
4230     const auto image_layer_count = is_3D_to_2D_map ? image_state->createInfo.extent.depth : image_state->createInfo.arrayLayers;
4231     const auto image_layer_count_var_name = is_3D_to_2D_map ? "extent.depth" : "arrayLayers";
4232 
4233     SubresourceRangeErrorCodes subresourceRangeErrorCodes = {};
4234     subresourceRangeErrorCodes.base_mip_err = "VUID-VkImageViewCreateInfo-subresourceRange-01478";
4235     subresourceRangeErrorCodes.mip_count_err = "VUID-VkImageViewCreateInfo-subresourceRange-01718";
4236     subresourceRangeErrorCodes.base_layer_err = is_khr_maintenance1 ? (is_3D_to_2D_map ? "VUID-VkImageViewCreateInfo-image-02724"
4237                                                                                        : "VUID-VkImageViewCreateInfo-image-01482")
4238                                                                     : "VUID-VkImageViewCreateInfo-subresourceRange-01480";
4239     subresourceRangeErrorCodes.layer_count_err = is_khr_maintenance1
4240                                                      ? (is_3D_to_2D_map ? "VUID-VkImageViewCreateInfo-subresourceRange-02725"
4241                                                                         : "VUID-VkImageViewCreateInfo-subresourceRange-01483")
4242                                                      : "VUID-VkImageViewCreateInfo-subresourceRange-01719";
4243 
4244     return ValidateImageSubresourceRange(image_state->createInfo.mipLevels, image_layer_count, subresourceRange,
4245                                          "vkCreateImageView", "pCreateInfo->subresourceRange", image_layer_count_var_name,
4246                                          HandleToUint64(image_state->image), subresourceRangeErrorCodes);
4247 }
4248 
ValidateCmdClearColorSubresourceRange(const IMAGE_STATE * image_state,const VkImageSubresourceRange & subresourceRange,const char * param_name) const4249 bool CoreChecks::ValidateCmdClearColorSubresourceRange(const IMAGE_STATE *image_state,
4250                                                        const VkImageSubresourceRange &subresourceRange,
4251                                                        const char *param_name) const {
4252     SubresourceRangeErrorCodes subresourceRangeErrorCodes = {};
4253     subresourceRangeErrorCodes.base_mip_err = "VUID-vkCmdClearColorImage-baseMipLevel-01470";
4254     subresourceRangeErrorCodes.mip_count_err = "VUID-vkCmdClearColorImage-pRanges-01692";
4255     subresourceRangeErrorCodes.base_layer_err = "VUID-vkCmdClearColorImage-baseArrayLayer-01472";
4256     subresourceRangeErrorCodes.layer_count_err = "VUID-vkCmdClearColorImage-pRanges-01693";
4257 
4258     return ValidateImageSubresourceRange(image_state->createInfo.mipLevels, image_state->createInfo.arrayLayers, subresourceRange,
4259                                          "vkCmdClearColorImage", param_name, "arrayLayers", HandleToUint64(image_state->image),
4260                                          subresourceRangeErrorCodes);
4261 }
4262 
ValidateCmdClearDepthSubresourceRange(const IMAGE_STATE * image_state,const VkImageSubresourceRange & subresourceRange,const char * param_name) const4263 bool CoreChecks::ValidateCmdClearDepthSubresourceRange(const IMAGE_STATE *image_state,
4264                                                        const VkImageSubresourceRange &subresourceRange,
4265                                                        const char *param_name) const {
4266     SubresourceRangeErrorCodes subresourceRangeErrorCodes = {};
4267     subresourceRangeErrorCodes.base_mip_err = "VUID-vkCmdClearDepthStencilImage-baseMipLevel-01474";
4268     subresourceRangeErrorCodes.mip_count_err = "VUID-vkCmdClearDepthStencilImage-pRanges-01694";
4269     subresourceRangeErrorCodes.base_layer_err = "VUID-vkCmdClearDepthStencilImage-baseArrayLayer-01476";
4270     subresourceRangeErrorCodes.layer_count_err = "VUID-vkCmdClearDepthStencilImage-pRanges-01695";
4271 
4272     return ValidateImageSubresourceRange(image_state->createInfo.mipLevels, image_state->createInfo.arrayLayers, subresourceRange,
4273                                          "vkCmdClearDepthStencilImage", param_name, "arrayLayers",
4274                                          HandleToUint64(image_state->image), subresourceRangeErrorCodes);
4275 }
4276 
ValidateImageBarrierSubresourceRange(const IMAGE_STATE * image_state,const VkImageSubresourceRange & subresourceRange,const char * cmd_name,const char * param_name)4277 bool CoreChecks::ValidateImageBarrierSubresourceRange(const IMAGE_STATE *image_state,
4278                                                       const VkImageSubresourceRange &subresourceRange, const char *cmd_name,
4279                                                       const char *param_name) {
4280     SubresourceRangeErrorCodes subresourceRangeErrorCodes = {};
4281     subresourceRangeErrorCodes.base_mip_err = "VUID-VkImageMemoryBarrier-subresourceRange-01486";
4282     subresourceRangeErrorCodes.mip_count_err = "VUID-VkImageMemoryBarrier-subresourceRange-01724";
4283     subresourceRangeErrorCodes.base_layer_err = "VUID-VkImageMemoryBarrier-subresourceRange-01488";
4284     subresourceRangeErrorCodes.layer_count_err = "VUID-VkImageMemoryBarrier-subresourceRange-01725";
4285 
4286     return ValidateImageSubresourceRange(image_state->createInfo.mipLevels, image_state->createInfo.arrayLayers, subresourceRange,
4287                                          cmd_name, param_name, "arrayLayers", HandleToUint64(image_state->image),
4288                                          subresourceRangeErrorCodes);
4289 }
4290 
PreCallValidateCreateImageView(VkDevice device,const VkImageViewCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkImageView * pView)4291 bool CoreChecks::PreCallValidateCreateImageView(VkDevice device, const VkImageViewCreateInfo *pCreateInfo,
4292                                                 const VkAllocationCallbacks *pAllocator, VkImageView *pView) {
4293     bool skip = false;
4294     IMAGE_STATE *image_state = GetImageState(pCreateInfo->image);
4295     if (image_state) {
4296         skip |=
4297             ValidateImageUsageFlags(image_state,
4298                                     VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT |
4299                                         VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
4300                                         VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV | VK_IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT,
4301                                     false, kVUIDUndefined, "vkCreateImageView()",
4302                                     "VK_IMAGE_USAGE_[SAMPLED|STORAGE|COLOR_ATTACHMENT|DEPTH_STENCIL_ATTACHMENT|INPUT_ATTACHMENT|"
4303                                     "SHADING_RATE_IMAGE|FRAGMENT_DENSITY_MAP]_BIT");
4304         // If this isn't a sparse image, it needs to have memory backing it at CreateImageView time
4305         skip |= ValidateMemoryIsBoundToImage(image_state, "vkCreateImageView()", "VUID-VkImageViewCreateInfo-image-01020");
4306         // Checks imported from image layer
4307         skip |= ValidateCreateImageViewSubresourceRange(
4308             image_state, pCreateInfo->viewType == VK_IMAGE_VIEW_TYPE_2D || pCreateInfo->viewType == VK_IMAGE_VIEW_TYPE_2D_ARRAY,
4309             pCreateInfo->subresourceRange);
4310 
4311         VkImageCreateFlags image_flags = image_state->createInfo.flags;
4312         VkFormat image_format = image_state->createInfo.format;
4313         VkImageUsageFlags image_usage = image_state->createInfo.usage;
4314         VkImageTiling image_tiling = image_state->createInfo.tiling;
4315         VkFormat view_format = pCreateInfo->format;
4316         VkImageAspectFlags aspect_mask = pCreateInfo->subresourceRange.aspectMask;
4317         VkImageType image_type = image_state->createInfo.imageType;
4318         VkImageViewType view_type = pCreateInfo->viewType;
4319 
4320         // If there's a chained VkImageViewUsageCreateInfo struct, modify image_usage to match
4321         auto chained_ivuci_struct = lvl_find_in_chain<VkImageViewUsageCreateInfoKHR>(pCreateInfo->pNext);
4322         if (chained_ivuci_struct) {
4323             image_usage = chained_ivuci_struct->usage;
4324         }
4325 
4326         // Validate VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT state, if view/image formats differ
4327         if ((image_flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT) && (image_format != view_format)) {
4328             if (FormatIsMultiplane(image_format)) {
4329                 VkFormat compat_format = FindMultiplaneCompatibleFormat(image_format, aspect_mask);
4330                 if (view_format != compat_format) {
4331                     // View format must match the multiplane compatible format
4332                     std::stringstream ss;
4333                     ss << "vkCreateImageView(): ImageView format " << string_VkFormat(view_format)
4334                        << " is not compatible with plane " << GetPlaneIndex(aspect_mask) << " of underlying image format "
4335                        << string_VkFormat(image_format) << ", must be " << string_VkFormat(compat_format) << ".";
4336                     skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4337                                     HandleToUint64(pCreateInfo->image), "VUID-VkImageViewCreateInfo-image-01586", "%s",
4338                                     ss.str().c_str());
4339                 }
4340             } else {
4341                 if ((!device_extensions.vk_khr_maintenance2 ||
4342                      !(image_flags & VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT_KHR))) {
4343                     // Format MUST be compatible (in the same format compatibility class) as the format the image was created with
4344                     if (FormatCompatibilityClass(image_format) != FormatCompatibilityClass(view_format)) {
4345                         std::stringstream ss;
4346                         ss << "vkCreateImageView(): ImageView format " << string_VkFormat(view_format)
4347                            << " is not in the same format compatibility class as "
4348                            << report_data->FormatHandle(pCreateInfo->image).c_str() << "  format " << string_VkFormat(image_format)
4349                            << ".  Images created with the VK_IMAGE_CREATE_MUTABLE_FORMAT BIT "
4350                            << "can support ImageViews with differing formats but they must be in the same compatibility class.";
4351                         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4352                                         HandleToUint64(pCreateInfo->image), "VUID-VkImageViewCreateInfo-image-01018", "%s",
4353                                         ss.str().c_str());
4354                     }
4355                 }
4356             }
4357         } else {
4358             // Format MUST be IDENTICAL to the format the image was created with
4359             if (image_format != view_format) {
4360                 std::stringstream ss;
4361                 ss << "vkCreateImageView() format " << string_VkFormat(view_format) << " differs from "
4362                    << report_data->FormatHandle(pCreateInfo->image).c_str() << " format " << string_VkFormat(image_format)
4363                    << ".  Formats MUST be IDENTICAL unless VK_IMAGE_CREATE_MUTABLE_FORMAT BIT was set on image creation.";
4364                 skip |=
4365                     log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4366                             HandleToUint64(pCreateInfo->image), "VUID-VkImageViewCreateInfo-image-01019", "%s", ss.str().c_str());
4367             }
4368         }
4369 
4370         // Validate correct image aspect bits for desired formats and format consistency
4371         skip |= ValidateImageAspectMask(image_state->image, image_format, aspect_mask, "vkCreateImageView()");
4372 
4373         switch (image_type) {
4374             case VK_IMAGE_TYPE_1D:
4375                 if (view_type != VK_IMAGE_VIEW_TYPE_1D && view_type != VK_IMAGE_VIEW_TYPE_1D_ARRAY) {
4376                     skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4377                                     HandleToUint64(pCreateInfo->image), "VUID-VkImageViewCreateInfo-subResourceRange-01021",
4378                                     "vkCreateImageView(): pCreateInfo->viewType %s is not compatible with image type %s.",
4379                                     string_VkImageViewType(view_type), string_VkImageType(image_type));
4380                 }
4381                 break;
4382             case VK_IMAGE_TYPE_2D:
4383                 if (view_type != VK_IMAGE_VIEW_TYPE_2D && view_type != VK_IMAGE_VIEW_TYPE_2D_ARRAY) {
4384                     if ((view_type == VK_IMAGE_VIEW_TYPE_CUBE || view_type == VK_IMAGE_VIEW_TYPE_CUBE_ARRAY) &&
4385                         !(image_flags & VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT)) {
4386                         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4387                                         HandleToUint64(pCreateInfo->image), "VUID-VkImageViewCreateInfo-image-01003",
4388                                         "vkCreateImageView(): pCreateInfo->viewType %s is not compatible with image type %s.",
4389                                         string_VkImageViewType(view_type), string_VkImageType(image_type));
4390                     } else if (view_type != VK_IMAGE_VIEW_TYPE_CUBE && view_type != VK_IMAGE_VIEW_TYPE_CUBE_ARRAY) {
4391                         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4392                                         HandleToUint64(pCreateInfo->image), "VUID-VkImageViewCreateInfo-subResourceRange-01021",
4393                                         "vkCreateImageView(): pCreateInfo->viewType %s is not compatible with image type %s.",
4394                                         string_VkImageViewType(view_type), string_VkImageType(image_type));
4395                     }
4396                 }
4397                 break;
4398             case VK_IMAGE_TYPE_3D:
4399                 if (device_extensions.vk_khr_maintenance1) {
4400                     if (view_type != VK_IMAGE_VIEW_TYPE_3D) {
4401                         if ((view_type == VK_IMAGE_VIEW_TYPE_2D || view_type == VK_IMAGE_VIEW_TYPE_2D_ARRAY)) {
4402                             if (!(image_flags & VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR)) {
4403                                 skip |=
4404                                     log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4405                                             HandleToUint64(pCreateInfo->image), "VUID-VkImageViewCreateInfo-image-01005",
4406                                             "vkCreateImageView(): pCreateInfo->viewType %s is not compatible with image type %s.",
4407                                             string_VkImageViewType(view_type), string_VkImageType(image_type));
4408                             } else if ((image_flags & (VK_IMAGE_CREATE_SPARSE_BINDING_BIT | VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT |
4409                                                        VK_IMAGE_CREATE_SPARSE_ALIASED_BIT))) {
4410                                 skip |=
4411                                     log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4412                                             HandleToUint64(pCreateInfo->image), "VUID-VkImageViewCreateInfo-subResourceRange-01021",
4413                                             "vkCreateImageView(): pCreateInfo->viewType %s is not compatible with image type %s "
4414                                             "when the VK_IMAGE_CREATE_SPARSE_BINDING_BIT, VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT, or "
4415                                             "VK_IMAGE_CREATE_SPARSE_ALIASED_BIT flags are enabled.",
4416                                             string_VkImageViewType(view_type), string_VkImageType(image_type));
4417                             }
4418                         } else {
4419                             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4420                                             HandleToUint64(pCreateInfo->image), "VUID-VkImageViewCreateInfo-subResourceRange-01021",
4421                                             "vkCreateImageView(): pCreateInfo->viewType %s is not compatible with image type %s.",
4422                                             string_VkImageViewType(view_type), string_VkImageType(image_type));
4423                         }
4424                     }
4425                 } else {
4426                     if (view_type != VK_IMAGE_VIEW_TYPE_3D) {
4427                         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4428                                         HandleToUint64(pCreateInfo->image), "VUID-VkImageViewCreateInfo-subResourceRange-01021",
4429                                         "vkCreateImageView(): pCreateInfo->viewType %s is not compatible with image type %s.",
4430                                         string_VkImageViewType(view_type), string_VkImageType(image_type));
4431                     }
4432                 }
4433                 break;
4434             default:
4435                 break;
4436         }
4437 
4438         // External format checks needed when VK_ANDROID_external_memory_android_hardware_buffer enabled
4439         if (device_extensions.vk_android_external_memory_android_hardware_buffer) {
4440             skip |= ValidateCreateImageViewANDROID(pCreateInfo);
4441         }
4442 
4443         VkFormatProperties format_properties = GetPDFormatProperties(view_format);
4444         VkFormatFeatureFlags tiling_features = (image_tiling & VK_IMAGE_TILING_LINEAR) ? format_properties.linearTilingFeatures
4445                                                                                        : format_properties.optimalTilingFeatures;
4446 
4447         if (tiling_features == 0) {
4448             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4449                             HandleToUint64(pCreateInfo->image), "VUID-VkImageViewCreateInfo-None-02273",
4450                             "vkCreateImageView(): pCreateInfo->format %s with tiling %s has no supported format features on this "
4451                             "physical device.",
4452                             string_VkFormat(view_format), string_VkImageTiling(image_tiling));
4453         } else if ((image_usage & VK_IMAGE_USAGE_SAMPLED_BIT) && !(tiling_features & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) {
4454             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4455                             HandleToUint64(pCreateInfo->image), "VUID-VkImageViewCreateInfo-usage-02274",
4456                             "vkCreateImageView(): pCreateInfo->format %s with tiling %s does not support usage that includes "
4457                             "VK_IMAGE_USAGE_SAMPLED_BIT.",
4458                             string_VkFormat(view_format), string_VkImageTiling(image_tiling));
4459         } else if ((image_usage & VK_IMAGE_USAGE_STORAGE_BIT) && !(tiling_features & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT)) {
4460             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4461                             HandleToUint64(pCreateInfo->image), "VUID-VkImageViewCreateInfo-usage-02275",
4462                             "vkCreateImageView(): pCreateInfo->format %s with tiling %s does not support usage that includes "
4463                             "VK_IMAGE_USAGE_STORAGE_BIT.",
4464                             string_VkFormat(view_format), string_VkImageTiling(image_tiling));
4465         } else if ((image_usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) &&
4466                    !(tiling_features & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) {
4467             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4468                             HandleToUint64(pCreateInfo->image), "VUID-VkImageViewCreateInfo-usage-02276",
4469                             "vkCreateImageView(): pCreateInfo->format %s with tiling %s does not support usage that includes "
4470                             "VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT.",
4471                             string_VkFormat(view_format), string_VkImageTiling(image_tiling));
4472         } else if ((image_usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) &&
4473                    !(tiling_features & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
4474             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4475                             HandleToUint64(pCreateInfo->image), "VUID-VkImageViewCreateInfo-usage-02277",
4476                             "vkCreateImageView(): pCreateInfo->format %s with tiling %s does not support usage that includes "
4477                             "VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT.",
4478                             string_VkFormat(view_format), string_VkImageTiling(image_tiling));
4479         }
4480 
4481         if (image_usage & VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV) {
4482             if (view_type != VK_IMAGE_VIEW_TYPE_2D && view_type != VK_IMAGE_VIEW_TYPE_2D_ARRAY) {
4483                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4484                                 HandleToUint64(pCreateInfo->image), "VUID-VkImageViewCreateInfo-image-02086",
4485                                 "vkCreateImageView() If image was created with usage containing "
4486                                 "VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV, viewType must be "
4487                                 "VK_IMAGE_VIEW_TYPE_2D or VK_IMAGE_VIEW_TYPE_2D_ARRAY.");
4488             }
4489             if (view_format != VK_FORMAT_R8_UINT) {
4490                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4491                                 HandleToUint64(pCreateInfo->image), "VUID-VkImageViewCreateInfo-image-02087",
4492                                 "vkCreateImageView() If image was created with usage containing "
4493                                 "VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV, format must be VK_FORMAT_R8_UINT.");
4494             }
4495         }
4496     }
4497     return skip;
4498 }
4499 
PostCallRecordCreateImageView(VkDevice device,const VkImageViewCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkImageView * pView,VkResult result)4500 void ValidationStateTracker::PostCallRecordCreateImageView(VkDevice device, const VkImageViewCreateInfo *pCreateInfo,
4501                                                            const VkAllocationCallbacks *pAllocator, VkImageView *pView,
4502                                                            VkResult result) {
4503     if (result != VK_SUCCESS) return;
4504     auto image_state = GetImageState(pCreateInfo->image);
4505     imageViewMap[*pView] = std::unique_ptr<IMAGE_VIEW_STATE>(new IMAGE_VIEW_STATE(image_state, *pView, pCreateInfo));
4506 }
4507 
PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer,VkBuffer srcBuffer,VkBuffer dstBuffer,uint32_t regionCount,const VkBufferCopy * pRegions)4508 bool CoreChecks::PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
4509                                               uint32_t regionCount, const VkBufferCopy *pRegions) {
4510     const auto cb_node = GetCBState(commandBuffer);
4511     const auto src_buffer_state = GetBufferState(srcBuffer);
4512     const auto dst_buffer_state = GetBufferState(dstBuffer);
4513 
4514     bool skip = false;
4515     skip |= ValidateMemoryIsBoundToBuffer(src_buffer_state, "vkCmdCopyBuffer()", "VUID-vkCmdCopyBuffer-srcBuffer-00119");
4516     skip |= ValidateMemoryIsBoundToBuffer(dst_buffer_state, "vkCmdCopyBuffer()", "VUID-vkCmdCopyBuffer-dstBuffer-00121");
4517     // Validate that SRC & DST buffers have correct usage flags set
4518     skip |=
4519         ValidateBufferUsageFlags(src_buffer_state, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, true, "VUID-vkCmdCopyBuffer-srcBuffer-00118",
4520                                  "vkCmdCopyBuffer()", "VK_BUFFER_USAGE_TRANSFER_SRC_BIT");
4521     skip |=
4522         ValidateBufferUsageFlags(dst_buffer_state, VK_BUFFER_USAGE_TRANSFER_DST_BIT, true, "VUID-vkCmdCopyBuffer-dstBuffer-00120",
4523                                  "vkCmdCopyBuffer()", "VK_BUFFER_USAGE_TRANSFER_DST_BIT");
4524     skip |=
4525         ValidateCmdQueueFlags(cb_node, "vkCmdCopyBuffer()", VK_QUEUE_TRANSFER_BIT | VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT,
4526                               "VUID-vkCmdCopyBuffer-commandBuffer-cmdpool");
4527     skip |= ValidateCmd(cb_node, CMD_COPYBUFFER, "vkCmdCopyBuffer()");
4528     skip |= InsideRenderPass(cb_node, "vkCmdCopyBuffer()", "VUID-vkCmdCopyBuffer-renderpass");
4529     return skip;
4530 }
4531 
PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer,VkBuffer srcBuffer,VkBuffer dstBuffer,uint32_t regionCount,const VkBufferCopy * pRegions)4532 void ValidationStateTracker::PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
4533                                                         uint32_t regionCount, const VkBufferCopy *pRegions) {
4534     auto cb_node = GetCBState(commandBuffer);
4535     auto src_buffer_state = GetBufferState(srcBuffer);
4536     auto dst_buffer_state = GetBufferState(dstBuffer);
4537 
4538     // Update bindings between buffers and cmd buffer
4539     AddCommandBufferBindingBuffer(cb_node, src_buffer_state);
4540     AddCommandBufferBindingBuffer(cb_node, dst_buffer_state);
4541 }
4542 
ValidateIdleBuffer(VkBuffer buffer)4543 bool CoreChecks::ValidateIdleBuffer(VkBuffer buffer) {
4544     bool skip = false;
4545     auto buffer_state = GetBufferState(buffer);
4546     if (!buffer_state) {
4547         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, HandleToUint64(buffer),
4548                         kVUID_Core_DrawState_DoubleDestroy, "Cannot free %s that has not been allocated.",
4549                         report_data->FormatHandle(buffer).c_str());
4550     } else {
4551         if (buffer_state->in_use.load()) {
4552             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
4553                             HandleToUint64(buffer), "VUID-vkDestroyBuffer-buffer-00922",
4554                             "Cannot free %s that is in use by a command buffer.", report_data->FormatHandle(buffer).c_str());
4555         }
4556     }
4557     return skip;
4558 }
4559 
PreCallValidateDestroyImageView(VkDevice device,VkImageView imageView,const VkAllocationCallbacks * pAllocator)4560 bool CoreChecks::PreCallValidateDestroyImageView(VkDevice device, VkImageView imageView, const VkAllocationCallbacks *pAllocator) {
4561     IMAGE_VIEW_STATE *image_view_state = GetImageViewState(imageView);
4562     const VulkanTypedHandle obj_struct(imageView, kVulkanObjectTypeImageView);
4563 
4564     bool skip = false;
4565     if (image_view_state) {
4566         skip |=
4567             ValidateObjectNotInUse(image_view_state, obj_struct, "vkDestroyImageView", "VUID-vkDestroyImageView-imageView-01026");
4568     }
4569     return skip;
4570 }
4571 
PreCallRecordDestroyImageView(VkDevice device,VkImageView imageView,const VkAllocationCallbacks * pAllocator)4572 void ValidationStateTracker::PreCallRecordDestroyImageView(VkDevice device, VkImageView imageView,
4573                                                            const VkAllocationCallbacks *pAllocator) {
4574     IMAGE_VIEW_STATE *image_view_state = GetImageViewState(imageView);
4575     if (!image_view_state) return;
4576     const VulkanTypedHandle obj_struct(imageView, kVulkanObjectTypeImageView);
4577 
4578     // Any bound cmd buffers are now invalid
4579     InvalidateCommandBuffers(image_view_state->cb_bindings, obj_struct);
4580     imageViewMap.erase(imageView);
4581 }
4582 
PreCallValidateDestroyBuffer(VkDevice device,VkBuffer buffer,const VkAllocationCallbacks * pAllocator)4583 bool CoreChecks::PreCallValidateDestroyBuffer(VkDevice device, VkBuffer buffer, const VkAllocationCallbacks *pAllocator) {
4584     auto buffer_state = GetBufferState(buffer);
4585 
4586     bool skip = false;
4587     if (buffer_state) {
4588         skip |= ValidateIdleBuffer(buffer);
4589     }
4590     return skip;
4591 }
4592 
PreCallRecordDestroyBuffer(VkDevice device,VkBuffer buffer,const VkAllocationCallbacks * pAllocator)4593 void ValidationStateTracker::PreCallRecordDestroyBuffer(VkDevice device, VkBuffer buffer, const VkAllocationCallbacks *pAllocator) {
4594     if (!buffer) return;
4595     auto buffer_state = GetBufferState(buffer);
4596     const VulkanTypedHandle obj_struct(buffer, kVulkanObjectTypeBuffer);
4597 
4598     InvalidateCommandBuffers(buffer_state->cb_bindings, obj_struct);
4599     for (auto mem_binding : buffer_state->GetBoundMemory()) {
4600         auto mem_info = GetDevMemState(mem_binding);
4601         if (mem_info) {
4602             RemoveBufferMemoryRange(HandleToUint64(buffer), mem_info);
4603         }
4604     }
4605     ClearMemoryObjectBindings(obj_struct);
4606     bufferMap.erase(buffer_state->buffer);
4607 }
4608 
PreCallRecordDestroyBuffer(VkDevice device,VkBuffer buffer,const VkAllocationCallbacks * pAllocator)4609 void CoreChecks::PreCallRecordDestroyBuffer(VkDevice device, VkBuffer buffer, const VkAllocationCallbacks *pAllocator) {
4610     if (!buffer) return;
4611 
4612     // Clean up validation specific data
4613     EraseQFOReleaseBarriers<VkBufferMemoryBarrier>(buffer);
4614 
4615     // Clean up generic buffer state
4616     StateTracker::PreCallRecordDestroyBuffer(device, buffer, pAllocator);
4617 }
PreCallValidateDestroyBufferView(VkDevice device,VkBufferView bufferView,const VkAllocationCallbacks * pAllocator)4618 bool CoreChecks::PreCallValidateDestroyBufferView(VkDevice device, VkBufferView bufferView,
4619                                                   const VkAllocationCallbacks *pAllocator) {
4620     auto buffer_view_state = GetBufferViewState(bufferView);
4621     const VulkanTypedHandle obj_struct(bufferView, kVulkanObjectTypeBufferView);
4622     bool skip = false;
4623     if (buffer_view_state) {
4624         skip |= ValidateObjectNotInUse(buffer_view_state, obj_struct, "vkDestroyBufferView",
4625                                        "VUID-vkDestroyBufferView-bufferView-00936");
4626     }
4627     return skip;
4628 }
4629 
PreCallRecordDestroyBufferView(VkDevice device,VkBufferView bufferView,const VkAllocationCallbacks * pAllocator)4630 void ValidationStateTracker::PreCallRecordDestroyBufferView(VkDevice device, VkBufferView bufferView,
4631                                                             const VkAllocationCallbacks *pAllocator) {
4632     if (!bufferView) return;
4633     auto buffer_view_state = GetBufferViewState(bufferView);
4634     const VulkanTypedHandle obj_struct(bufferView, kVulkanObjectTypeBufferView);
4635 
4636     // Any bound cmd buffers are now invalid
4637     InvalidateCommandBuffers(buffer_view_state->cb_bindings, obj_struct);
4638     bufferViewMap.erase(bufferView);
4639 }
4640 
PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer,VkBuffer dstBuffer,VkDeviceSize dstOffset,VkDeviceSize size,uint32_t data)4641 bool CoreChecks::PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4642                                               VkDeviceSize size, uint32_t data) {
4643     auto cb_node = GetCBState(commandBuffer);
4644     auto buffer_state = GetBufferState(dstBuffer);
4645     bool skip = false;
4646     skip |= ValidateMemoryIsBoundToBuffer(buffer_state, "vkCmdFillBuffer()", "VUID-vkCmdFillBuffer-dstBuffer-00031");
4647     skip |=
4648         ValidateCmdQueueFlags(cb_node, "vkCmdFillBuffer()", VK_QUEUE_TRANSFER_BIT | VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT,
4649                               "VUID-vkCmdFillBuffer-commandBuffer-cmdpool");
4650     skip |= ValidateCmd(cb_node, CMD_FILLBUFFER, "vkCmdFillBuffer()");
4651     // Validate that DST buffer has correct usage flags set
4652     skip |= ValidateBufferUsageFlags(buffer_state, VK_BUFFER_USAGE_TRANSFER_DST_BIT, true, "VUID-vkCmdFillBuffer-dstBuffer-00029",
4653                                      "vkCmdFillBuffer()", "VK_BUFFER_USAGE_TRANSFER_DST_BIT");
4654     skip |= InsideRenderPass(cb_node, "vkCmdFillBuffer()", "VUID-vkCmdFillBuffer-renderpass");
4655     return skip;
4656 }
4657 
PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer,VkBuffer dstBuffer,VkDeviceSize dstOffset,VkDeviceSize size,uint32_t data)4658 void ValidationStateTracker::PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4659                                                         VkDeviceSize size, uint32_t data) {
4660     auto cb_node = GetCBState(commandBuffer);
4661     auto buffer_state = GetBufferState(dstBuffer);
4662     // Update bindings between buffer and cmd buffer
4663     AddCommandBufferBindingBuffer(cb_node, buffer_state);
4664 }
4665 
ValidateBufferImageCopyData(uint32_t regionCount,const VkBufferImageCopy * pRegions,IMAGE_STATE * image_state,const char * function)4666 bool CoreChecks::ValidateBufferImageCopyData(uint32_t regionCount, const VkBufferImageCopy *pRegions, IMAGE_STATE *image_state,
4667                                              const char *function) {
4668     bool skip = false;
4669 
4670     for (uint32_t i = 0; i < regionCount; i++) {
4671         if (image_state->createInfo.imageType == VK_IMAGE_TYPE_1D) {
4672             if ((pRegions[i].imageOffset.y != 0) || (pRegions[i].imageExtent.height != 1)) {
4673                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4674                                 HandleToUint64(image_state->image), "VUID-VkBufferImageCopy-srcImage-00199",
4675                                 "%s(): pRegion[%d] imageOffset.y is %d and imageExtent.height is %d. For 1D images these must be 0 "
4676                                 "and 1, respectively.",
4677                                 function, i, pRegions[i].imageOffset.y, pRegions[i].imageExtent.height);
4678             }
4679         }
4680 
4681         if ((image_state->createInfo.imageType == VK_IMAGE_TYPE_1D) || (image_state->createInfo.imageType == VK_IMAGE_TYPE_2D)) {
4682             if ((pRegions[i].imageOffset.z != 0) || (pRegions[i].imageExtent.depth != 1)) {
4683                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4684                                 HandleToUint64(image_state->image), "VUID-VkBufferImageCopy-srcImage-00201",
4685                                 "%s(): pRegion[%d] imageOffset.z is %d and imageExtent.depth is %d. For 1D and 2D images these "
4686                                 "must be 0 and 1, respectively.",
4687                                 function, i, pRegions[i].imageOffset.z, pRegions[i].imageExtent.depth);
4688             }
4689         }
4690 
4691         if (image_state->createInfo.imageType == VK_IMAGE_TYPE_3D) {
4692             if ((0 != pRegions[i].imageSubresource.baseArrayLayer) || (1 != pRegions[i].imageSubresource.layerCount)) {
4693                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4694                                 HandleToUint64(image_state->image), "VUID-VkBufferImageCopy-baseArrayLayer-00213",
4695                                 "%s(): pRegion[%d] imageSubresource.baseArrayLayer is %d and imageSubresource.layerCount is %d. "
4696                                 "For 3D images these must be 0 and 1, respectively.",
4697                                 function, i, pRegions[i].imageSubresource.baseArrayLayer, pRegions[i].imageSubresource.layerCount);
4698             }
4699         }
4700 
4701         // If the the calling command's VkImage parameter's format is not a depth/stencil format,
4702         // then bufferOffset must be a multiple of the calling command's VkImage parameter's element size
4703         uint32_t element_size = FormatElementSize(image_state->createInfo.format, pRegions[i].imageSubresource.aspectMask);
4704 
4705         if (!FormatIsDepthAndStencil(image_state->createInfo.format) && SafeModulo(pRegions[i].bufferOffset, element_size) != 0) {
4706             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4707                             HandleToUint64(image_state->image), "VUID-VkBufferImageCopy-bufferOffset-00193",
4708                             "%s(): pRegion[%d] bufferOffset 0x%" PRIxLEAST64
4709                             " must be a multiple of this format's texel size (%" PRIu32 ").",
4710                             function, i, pRegions[i].bufferOffset, element_size);
4711         }
4712 
4713         //  BufferOffset must be a multiple of 4
4714         if (SafeModulo(pRegions[i].bufferOffset, 4) != 0) {
4715             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4716                             HandleToUint64(image_state->image), "VUID-VkBufferImageCopy-bufferOffset-00194",
4717                             "%s(): pRegion[%d] bufferOffset 0x%" PRIxLEAST64 " must be a multiple of 4.", function, i,
4718                             pRegions[i].bufferOffset);
4719         }
4720 
4721         //  BufferRowLength must be 0, or greater than or equal to the width member of imageExtent
4722         if ((pRegions[i].bufferRowLength != 0) && (pRegions[i].bufferRowLength < pRegions[i].imageExtent.width)) {
4723             skip |=
4724                 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4725                         HandleToUint64(image_state->image), "VUID-VkBufferImageCopy-bufferRowLength-00195",
4726                         "%s(): pRegion[%d] bufferRowLength (%d) must be zero or greater-than-or-equal-to imageExtent.width (%d).",
4727                         function, i, pRegions[i].bufferRowLength, pRegions[i].imageExtent.width);
4728         }
4729 
4730         //  BufferImageHeight must be 0, or greater than or equal to the height member of imageExtent
4731         if ((pRegions[i].bufferImageHeight != 0) && (pRegions[i].bufferImageHeight < pRegions[i].imageExtent.height)) {
4732             skip |= log_msg(
4733                 report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4734                 HandleToUint64(image_state->image), "VUID-VkBufferImageCopy-bufferImageHeight-00196",
4735                 "%s(): pRegion[%d] bufferImageHeight (%d) must be zero or greater-than-or-equal-to imageExtent.height (%d).",
4736                 function, i, pRegions[i].bufferImageHeight, pRegions[i].imageExtent.height);
4737         }
4738 
4739         // Calculate adjusted image extent, accounting for multiplane image factors
4740         VkExtent3D adusted_image_extent = GetImageSubresourceExtent(image_state, &pRegions[i].imageSubresource);
4741         // imageOffset.x and (imageExtent.width + imageOffset.x) must both be >= 0 and <= image subresource width
4742         if ((pRegions[i].imageOffset.x < 0) || (pRegions[i].imageOffset.x > static_cast<int32_t>(adusted_image_extent.width)) ||
4743             ((pRegions[i].imageOffset.x + pRegions[i].imageExtent.width) > static_cast<int32_t>(adusted_image_extent.width))) {
4744             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4745                             HandleToUint64(image_state->image), "VUID-VkBufferImageCopy-imageOffset-00197",
4746                             "%s(): Both pRegion[%d] imageoffset.x (%d) and (imageExtent.width + imageOffset.x) (%d) must be >= "
4747                             "zero or <= image subresource width (%d).",
4748                             function, i, pRegions[i].imageOffset.x, (pRegions[i].imageOffset.x + pRegions[i].imageExtent.width),
4749                             adusted_image_extent.width);
4750         }
4751 
4752         // imageOffset.y and (imageExtent.height + imageOffset.y) must both be >= 0 and <= image subresource height
4753         if ((pRegions[i].imageOffset.y < 0) || (pRegions[i].imageOffset.y > static_cast<int32_t>(adusted_image_extent.height)) ||
4754             ((pRegions[i].imageOffset.y + pRegions[i].imageExtent.height) > static_cast<int32_t>(adusted_image_extent.height))) {
4755             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4756                             HandleToUint64(image_state->image), "VUID-VkBufferImageCopy-imageOffset-00198",
4757                             "%s(): Both pRegion[%d] imageoffset.y (%d) and (imageExtent.height + imageOffset.y) (%d) must be >= "
4758                             "zero or <= image subresource height (%d).",
4759                             function, i, pRegions[i].imageOffset.y, (pRegions[i].imageOffset.y + pRegions[i].imageExtent.height),
4760                             adusted_image_extent.height);
4761         }
4762 
4763         // imageOffset.z and (imageExtent.depth + imageOffset.z) must both be >= 0 and <= image subresource depth
4764         if ((pRegions[i].imageOffset.z < 0) || (pRegions[i].imageOffset.z > static_cast<int32_t>(adusted_image_extent.depth)) ||
4765             ((pRegions[i].imageOffset.z + pRegions[i].imageExtent.depth) > static_cast<int32_t>(adusted_image_extent.depth))) {
4766             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4767                             HandleToUint64(image_state->image), "VUID-VkBufferImageCopy-imageOffset-00200",
4768                             "%s(): Both pRegion[%d] imageoffset.z (%d) and (imageExtent.depth + imageOffset.z) (%d) must be >= "
4769                             "zero or <= image subresource depth (%d).",
4770                             function, i, pRegions[i].imageOffset.z, (pRegions[i].imageOffset.z + pRegions[i].imageExtent.depth),
4771                             adusted_image_extent.depth);
4772         }
4773 
4774         // subresource aspectMask must have exactly 1 bit set
4775         const int num_bits = sizeof(VkFlags) * CHAR_BIT;
4776         std::bitset<num_bits> aspect_mask_bits(pRegions[i].imageSubresource.aspectMask);
4777         if (aspect_mask_bits.count() != 1) {
4778             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4779                             HandleToUint64(image_state->image), "VUID-VkBufferImageCopy-aspectMask-00212",
4780                             "%s: aspectMasks for imageSubresource in each region must have only a single bit set.", function);
4781         }
4782 
4783         // image subresource aspect bit must match format
4784         if (!VerifyAspectsPresent(pRegions[i].imageSubresource.aspectMask, image_state->createInfo.format)) {
4785             skip |= log_msg(
4786                 report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4787                 HandleToUint64(image_state->image), "VUID-VkBufferImageCopy-aspectMask-00211",
4788                 "%s(): pRegion[%d] subresource aspectMask 0x%x specifies aspects that are not present in image format 0x%x.",
4789                 function, i, pRegions[i].imageSubresource.aspectMask, image_state->createInfo.format);
4790         }
4791 
4792         // Checks that apply only to compressed images
4793         if (FormatIsCompressed(image_state->createInfo.format) || FormatIsSinglePlane_422(image_state->createInfo.format)) {
4794             auto block_size = FormatTexelBlockExtent(image_state->createInfo.format);
4795 
4796             //  BufferRowLength must be a multiple of block width
4797             if (SafeModulo(pRegions[i].bufferRowLength, block_size.width) != 0) {
4798                 skip |= log_msg(
4799                     report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4800                     HandleToUint64(image_state->image), "VUID-VkBufferImageCopy-bufferRowLength-00203",
4801                     "%s(): pRegion[%d] bufferRowLength (%d) must be a multiple of the compressed image's texel width (%d)..",
4802                     function, i, pRegions[i].bufferRowLength, block_size.width);
4803             }
4804 
4805             //  BufferRowHeight must be a multiple of block height
4806             if (SafeModulo(pRegions[i].bufferImageHeight, block_size.height) != 0) {
4807                 skip |= log_msg(
4808                     report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4809                     HandleToUint64(image_state->image), "VUID-VkBufferImageCopy-bufferImageHeight-00204",
4810                     "%s(): pRegion[%d] bufferImageHeight (%d) must be a multiple of the compressed image's texel height (%d)..",
4811                     function, i, pRegions[i].bufferImageHeight, block_size.height);
4812             }
4813 
4814             //  image offsets must be multiples of block dimensions
4815             if ((SafeModulo(pRegions[i].imageOffset.x, block_size.width) != 0) ||
4816                 (SafeModulo(pRegions[i].imageOffset.y, block_size.height) != 0) ||
4817                 (SafeModulo(pRegions[i].imageOffset.z, block_size.depth) != 0)) {
4818                 skip |=
4819                     log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4820                             HandleToUint64(image_state->image), "VUID-VkBufferImageCopy-imageOffset-00205",
4821                             "%s(): pRegion[%d] imageOffset(x,y) (%d, %d) must be multiples of the compressed image's texel "
4822                             "width & height (%d, %d)..",
4823                             function, i, pRegions[i].imageOffset.x, pRegions[i].imageOffset.y, block_size.width, block_size.height);
4824             }
4825 
4826             // bufferOffset must be a multiple of block size (linear bytes)
4827             uint32_t block_size_in_bytes = FormatElementSize(image_state->createInfo.format);
4828             if (SafeModulo(pRegions[i].bufferOffset, block_size_in_bytes) != 0) {
4829                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4830                                 HandleToUint64(image_state->image), "VUID-VkBufferImageCopy-bufferOffset-00206",
4831                                 "%s(): pRegion[%d] bufferOffset (0x%" PRIxLEAST64
4832                                 ") must be a multiple of the compressed image's texel block size (%" PRIu32 ")..",
4833                                 function, i, pRegions[i].bufferOffset, block_size_in_bytes);
4834             }
4835 
4836             // imageExtent width must be a multiple of block width, or extent+offset width must equal subresource width
4837             VkExtent3D mip_extent = GetImageSubresourceExtent(image_state, &(pRegions[i].imageSubresource));
4838             if ((SafeModulo(pRegions[i].imageExtent.width, block_size.width) != 0) &&
4839                 (pRegions[i].imageExtent.width + pRegions[i].imageOffset.x != mip_extent.width)) {
4840                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4841                                 HandleToUint64(image_state->image), "VUID-VkBufferImageCopy-imageExtent-00207",
4842                                 "%s(): pRegion[%d] extent width (%d) must be a multiple of the compressed texture block width "
4843                                 "(%d), or when added to offset.x (%d) must equal the image subresource width (%d)..",
4844                                 function, i, pRegions[i].imageExtent.width, block_size.width, pRegions[i].imageOffset.x,
4845                                 mip_extent.width);
4846             }
4847 
4848             // imageExtent height must be a multiple of block height, or extent+offset height must equal subresource height
4849             if ((SafeModulo(pRegions[i].imageExtent.height, block_size.height) != 0) &&
4850                 (pRegions[i].imageExtent.height + pRegions[i].imageOffset.y != mip_extent.height)) {
4851                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4852                                 HandleToUint64(image_state->image), "VUID-VkBufferImageCopy-imageExtent-00208",
4853                                 "%s(): pRegion[%d] extent height (%d) must be a multiple of the compressed texture block height "
4854                                 "(%d), or when added to offset.y (%d) must equal the image subresource height (%d)..",
4855                                 function, i, pRegions[i].imageExtent.height, block_size.height, pRegions[i].imageOffset.y,
4856                                 mip_extent.height);
4857             }
4858 
4859             // imageExtent depth must be a multiple of block depth, or extent+offset depth must equal subresource depth
4860             if ((SafeModulo(pRegions[i].imageExtent.depth, block_size.depth) != 0) &&
4861                 (pRegions[i].imageExtent.depth + pRegions[i].imageOffset.z != mip_extent.depth)) {
4862                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
4863                                 HandleToUint64(image_state->image), "VUID-VkBufferImageCopy-imageExtent-00209",
4864                                 "%s(): pRegion[%d] extent width (%d) must be a multiple of the compressed texture block depth "
4865                                 "(%d), or when added to offset.z (%d) must equal the image subresource depth (%d)..",
4866                                 function, i, pRegions[i].imageExtent.depth, block_size.depth, pRegions[i].imageOffset.z,
4867                                 mip_extent.depth);
4868             }
4869         }
4870     }
4871 
4872     return skip;
4873 }
4874 
ValidateImageBounds(const debug_report_data * report_data,const IMAGE_STATE * image_state,const uint32_t regionCount,const VkBufferImageCopy * pRegions,const char * func_name,const char * msg_code)4875 static bool ValidateImageBounds(const debug_report_data *report_data, const IMAGE_STATE *image_state, const uint32_t regionCount,
4876                                 const VkBufferImageCopy *pRegions, const char *func_name, const char *msg_code) {
4877     bool skip = false;
4878     const VkImageCreateInfo *image_info = &(image_state->createInfo);
4879 
4880     for (uint32_t i = 0; i < regionCount; i++) {
4881         VkExtent3D extent = pRegions[i].imageExtent;
4882         VkOffset3D offset = pRegions[i].imageOffset;
4883 
4884         if (IsExtentSizeZero(&extent))  // Warn on zero area subresource
4885         {
4886             skip |=
4887                 log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, (uint64_t)0,
4888                         kVUID_Core_Image_ZeroAreaSubregion, "%s: pRegion[%d] imageExtent of {%1d, %1d, %1d} has zero area",
4889                         func_name, i, extent.width, extent.height, extent.depth);
4890         }
4891 
4892         VkExtent3D image_extent = GetImageSubresourceExtent(image_state, &(pRegions[i].imageSubresource));
4893 
4894         // If we're using a compressed format, valid extent is rounded up to multiple of block size (per 18.1)
4895         if (FormatIsCompressed(image_info->format)) {
4896             auto block_extent = FormatTexelBlockExtent(image_info->format);
4897             if (image_extent.width % block_extent.width) {
4898                 image_extent.width += (block_extent.width - (image_extent.width % block_extent.width));
4899             }
4900             if (image_extent.height % block_extent.height) {
4901                 image_extent.height += (block_extent.height - (image_extent.height % block_extent.height));
4902             }
4903             if (image_extent.depth % block_extent.depth) {
4904                 image_extent.depth += (block_extent.depth - (image_extent.depth % block_extent.depth));
4905             }
4906         }
4907 
4908         if (0 != ExceedsBounds(&offset, &extent, &image_extent)) {
4909             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, (uint64_t)0,
4910                             msg_code, "%s: pRegion[%d] exceeds image bounds..", func_name, i);
4911         }
4912     }
4913 
4914     return skip;
4915 }
4916 
ValidateBufferBounds(const debug_report_data * report_data,IMAGE_STATE * image_state,BUFFER_STATE * buff_state,uint32_t regionCount,const VkBufferImageCopy * pRegions,const char * func_name,const char * msg_code)4917 static inline bool ValidateBufferBounds(const debug_report_data *report_data, IMAGE_STATE *image_state, BUFFER_STATE *buff_state,
4918                                         uint32_t regionCount, const VkBufferImageCopy *pRegions, const char *func_name,
4919                                         const char *msg_code) {
4920     bool skip = false;
4921 
4922     VkDeviceSize buffer_size = buff_state->createInfo.size;
4923 
4924     for (uint32_t i = 0; i < regionCount; i++) {
4925         VkExtent3D copy_extent = pRegions[i].imageExtent;
4926 
4927         VkDeviceSize buffer_width = (0 == pRegions[i].bufferRowLength ? copy_extent.width : pRegions[i].bufferRowLength);
4928         VkDeviceSize buffer_height = (0 == pRegions[i].bufferImageHeight ? copy_extent.height : pRegions[i].bufferImageHeight);
4929         VkDeviceSize unit_size = FormatElementSize(image_state->createInfo.format,
4930                                                    pRegions[i].imageSubresource.aspectMask);  // size (bytes) of texel or block
4931 
4932         if (FormatIsCompressed(image_state->createInfo.format) || FormatIsSinglePlane_422(image_state->createInfo.format)) {
4933             // Switch to texel block units, rounding up for any partially-used blocks
4934             auto block_dim = FormatTexelBlockExtent(image_state->createInfo.format);
4935             buffer_width = (buffer_width + block_dim.width - 1) / block_dim.width;
4936             buffer_height = (buffer_height + block_dim.height - 1) / block_dim.height;
4937 
4938             copy_extent.width = (copy_extent.width + block_dim.width - 1) / block_dim.width;
4939             copy_extent.height = (copy_extent.height + block_dim.height - 1) / block_dim.height;
4940             copy_extent.depth = (copy_extent.depth + block_dim.depth - 1) / block_dim.depth;
4941         }
4942 
4943         // Either depth or layerCount may be greater than 1 (not both). This is the number of 'slices' to copy
4944         uint32_t z_copies = std::max(copy_extent.depth, pRegions[i].imageSubresource.layerCount);
4945         if (IsExtentSizeZero(&copy_extent) || (0 == z_copies)) {
4946             // TODO: Issue warning here? Already warned in ValidateImageBounds()...
4947         } else {
4948             // Calculate buffer offset of final copied byte, + 1.
4949             VkDeviceSize max_buffer_offset = (z_copies - 1) * buffer_height * buffer_width;      // offset to slice
4950             max_buffer_offset += ((copy_extent.height - 1) * buffer_width) + copy_extent.width;  // add row,col
4951             max_buffer_offset *= unit_size;                                                      // convert to bytes
4952             max_buffer_offset += pRegions[i].bufferOffset;                                       // add initial offset (bytes)
4953 
4954             if (buffer_size < max_buffer_offset) {
4955                 skip |=
4956                     log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, (uint64_t)0,
4957                             msg_code, "%s: pRegion[%d] exceeds buffer size of %" PRIu64 " bytes..", func_name, i, buffer_size);
4958             }
4959         }
4960     }
4961 
4962     return skip;
4963 }
4964 
PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer,VkImage srcImage,VkImageLayout srcImageLayout,VkBuffer dstBuffer,uint32_t regionCount,const VkBufferImageCopy * pRegions)4965 bool CoreChecks::PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4966                                                      VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) {
4967     const auto cb_node = GetCBState(commandBuffer);
4968     const auto src_image_state = GetImageState(srcImage);
4969     const auto dst_buffer_state = GetBufferState(dstBuffer);
4970 
4971     bool skip = ValidateBufferImageCopyData(regionCount, pRegions, src_image_state, "vkCmdCopyImageToBuffer");
4972 
4973     // Validate command buffer state
4974     skip |= ValidateCmd(cb_node, CMD_COPYIMAGETOBUFFER, "vkCmdCopyImageToBuffer()");
4975 
4976     // Command pool must support graphics, compute, or transfer operations
4977     const auto pPool = GetCommandPoolState(cb_node->createInfo.commandPool);
4978 
4979     VkQueueFlags queue_flags = GetPhysicalDeviceState()->queue_family_properties[pPool->queueFamilyIndex].queueFlags;
4980 
4981     if (0 == (queue_flags & (VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT))) {
4982         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
4983                         HandleToUint64(cb_node->createInfo.commandPool), "VUID-vkCmdCopyImageToBuffer-commandBuffer-cmdpool",
4984                         "Cannot call vkCmdCopyImageToBuffer() on a command buffer allocated from a pool without graphics, compute, "
4985                         "or transfer capabilities..");
4986     }
4987     skip |= ValidateImageBounds(report_data, src_image_state, regionCount, pRegions, "vkCmdCopyImageToBuffer()",
4988                                 "VUID-vkCmdCopyImageToBuffer-pRegions-00182");
4989     skip |= ValidateBufferBounds(report_data, src_image_state, dst_buffer_state, regionCount, pRegions, "vkCmdCopyImageToBuffer()",
4990                                  "VUID-vkCmdCopyImageToBuffer-pRegions-00183");
4991 
4992     skip |= ValidateImageSampleCount(src_image_state, VK_SAMPLE_COUNT_1_BIT, "vkCmdCopyImageToBuffer(): srcImage",
4993                                      "VUID-vkCmdCopyImageToBuffer-srcImage-00188");
4994     skip |= ValidateMemoryIsBoundToImage(src_image_state, "vkCmdCopyImageToBuffer()", "VUID-vkCmdCopyImageToBuffer-srcImage-00187");
4995     skip |=
4996         ValidateMemoryIsBoundToBuffer(dst_buffer_state, "vkCmdCopyImageToBuffer()", "VUID-vkCmdCopyImageToBuffer-dstBuffer-00192");
4997 
4998     // Validate that SRC image & DST buffer have correct usage flags set
4999     skip |= ValidateImageUsageFlags(src_image_state, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, true,
5000                                     "VUID-vkCmdCopyImageToBuffer-srcImage-00186", "vkCmdCopyImageToBuffer()",
5001                                     "VK_IMAGE_USAGE_TRANSFER_SRC_BIT");
5002     skip |= ValidateBufferUsageFlags(dst_buffer_state, VK_BUFFER_USAGE_TRANSFER_DST_BIT, true,
5003                                      "VUID-vkCmdCopyImageToBuffer-dstBuffer-00191", "vkCmdCopyImageToBuffer()",
5004                                      "VK_BUFFER_USAGE_TRANSFER_DST_BIT");
5005     if (api_version >= VK_API_VERSION_1_1 || device_extensions.vk_khr_maintenance1) {
5006         skip |= ValidateImageFormatFeatureFlags(src_image_state, VK_FORMAT_FEATURE_TRANSFER_SRC_BIT, "vkCmdCopyImageToBuffer()",
5007                                                 "VUID-vkCmdCopyImageToBuffer-srcImage-01998",
5008                                                 "VUID-vkCmdCopyImageToBuffer-srcImage-01998");
5009     }
5010     skip |= InsideRenderPass(cb_node, "vkCmdCopyImageToBuffer()", "VUID-vkCmdCopyImageToBuffer-renderpass");
5011     bool hit_error = false;
5012     const char *src_invalid_layout_vuid = (src_image_state->shared_presentable && device_extensions.vk_khr_shared_presentable_image)
5013                                               ? "VUID-vkCmdCopyImageToBuffer-srcImageLayout-01397"
5014                                               : "VUID-vkCmdCopyImageToBuffer-srcImageLayout-00190";
5015     for (uint32_t i = 0; i < regionCount; ++i) {
5016         skip |= ValidateImageSubresourceLayers(cb_node, &pRegions[i].imageSubresource, "vkCmdCopyImageToBuffer()",
5017                                                "imageSubresource", i);
5018         skip |= VerifyImageLayout(cb_node, src_image_state, pRegions[i].imageSubresource, srcImageLayout,
5019                                   VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, "vkCmdCopyImageToBuffer()", src_invalid_layout_vuid,
5020                                   "VUID-vkCmdCopyImageToBuffer-srcImageLayout-00189", &hit_error);
5021         skip |= ValidateCopyBufferImageTransferGranularityRequirements(
5022             cb_node, src_image_state, &pRegions[i], i, "vkCmdCopyImageToBuffer()", "VUID-vkCmdCopyImageToBuffer-imageOffset-01794");
5023         skip |=
5024             ValidateImageMipLevel(cb_node, src_image_state, pRegions[i].imageSubresource.mipLevel, i, "vkCmdCopyImageToBuffer()",
5025                                   "imageSubresource", "VUID-vkCmdCopyImageToBuffer-imageSubresource-01703");
5026         skip |= ValidateImageArrayLayerRange(cb_node, src_image_state, pRegions[i].imageSubresource.baseArrayLayer,
5027                                              pRegions[i].imageSubresource.layerCount, i, "vkCmdCopyImageToBuffer()",
5028                                              "imageSubresource", "VUID-vkCmdCopyImageToBuffer-imageSubresource-01704");
5029     }
5030     return skip;
5031 }
5032 
PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer,VkImage srcImage,VkImageLayout srcImageLayout,VkBuffer dstBuffer,uint32_t regionCount,const VkBufferImageCopy * pRegions)5033 void ValidationStateTracker::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
5034                                                                VkImageLayout srcImageLayout, VkBuffer dstBuffer,
5035                                                                uint32_t regionCount, const VkBufferImageCopy *pRegions) {
5036     auto cb_node = GetCBState(commandBuffer);
5037     auto src_image_state = GetImageState(srcImage);
5038     auto dst_buffer_state = GetBufferState(dstBuffer);
5039 
5040     // Update bindings between buffer/image and cmd buffer
5041     AddCommandBufferBindingImage(cb_node, src_image_state);
5042     AddCommandBufferBindingBuffer(cb_node, dst_buffer_state);
5043 }
PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer,VkImage srcImage,VkImageLayout srcImageLayout,VkBuffer dstBuffer,uint32_t regionCount,const VkBufferImageCopy * pRegions)5044 void CoreChecks::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5045                                                    VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) {
5046     StateTracker::PreCallRecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions);
5047 
5048     auto cb_node = GetCBState(commandBuffer);
5049     auto src_image_state = GetImageState(srcImage);
5050     // Make sure that all image slices record referenced layout
5051     for (uint32_t i = 0; i < regionCount; ++i) {
5052         SetImageInitialLayout(cb_node, *src_image_state, pRegions[i].imageSubresource, srcImageLayout);
5053     }
5054 }
5055 
PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer,VkBuffer srcBuffer,VkImage dstImage,VkImageLayout dstImageLayout,uint32_t regionCount,const VkBufferImageCopy * pRegions)5056 bool CoreChecks::PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
5057                                                      VkImageLayout dstImageLayout, uint32_t regionCount,
5058                                                      const VkBufferImageCopy *pRegions) {
5059     const auto cb_node = GetCBState(commandBuffer);
5060     const auto src_buffer_state = GetBufferState(srcBuffer);
5061     const auto dst_image_state = GetImageState(dstImage);
5062 
5063     bool skip = ValidateBufferImageCopyData(regionCount, pRegions, dst_image_state, "vkCmdCopyBufferToImage");
5064 
5065     // Validate command buffer state
5066     skip |= ValidateCmd(cb_node, CMD_COPYBUFFERTOIMAGE, "vkCmdCopyBufferToImage()");
5067 
5068     // Command pool must support graphics, compute, or transfer operations
5069     const auto pPool = GetCommandPoolState(cb_node->createInfo.commandPool);
5070     VkQueueFlags queue_flags = GetPhysicalDeviceState()->queue_family_properties[pPool->queueFamilyIndex].queueFlags;
5071     if (0 == (queue_flags & (VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT))) {
5072         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
5073                         HandleToUint64(cb_node->createInfo.commandPool), "VUID-vkCmdCopyBufferToImage-commandBuffer-cmdpool",
5074                         "Cannot call vkCmdCopyBufferToImage() on a command buffer allocated from a pool without graphics, compute, "
5075                         "or transfer capabilities..");
5076     }
5077     skip |= ValidateImageBounds(report_data, dst_image_state, regionCount, pRegions, "vkCmdCopyBufferToImage()",
5078                                 "VUID-vkCmdCopyBufferToImage-pRegions-00172");
5079     skip |= ValidateBufferBounds(report_data, dst_image_state, src_buffer_state, regionCount, pRegions, "vkCmdCopyBufferToImage()",
5080                                  "VUID-vkCmdCopyBufferToImage-pRegions-00171");
5081     skip |= ValidateImageSampleCount(dst_image_state, VK_SAMPLE_COUNT_1_BIT, "vkCmdCopyBufferToImage(): dstImage",
5082                                      "VUID-vkCmdCopyBufferToImage-dstImage-00179");
5083     skip |=
5084         ValidateMemoryIsBoundToBuffer(src_buffer_state, "vkCmdCopyBufferToImage()", "VUID-vkCmdCopyBufferToImage-srcBuffer-00176");
5085     skip |= ValidateMemoryIsBoundToImage(dst_image_state, "vkCmdCopyBufferToImage()", "VUID-vkCmdCopyBufferToImage-dstImage-00178");
5086     skip |= ValidateBufferUsageFlags(src_buffer_state, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, true,
5087                                      "VUID-vkCmdCopyBufferToImage-srcBuffer-00174", "vkCmdCopyBufferToImage()",
5088                                      "VK_BUFFER_USAGE_TRANSFER_SRC_BIT");
5089     skip |= ValidateImageUsageFlags(dst_image_state, VK_IMAGE_USAGE_TRANSFER_DST_BIT, true,
5090                                     "VUID-vkCmdCopyBufferToImage-dstImage-00177", "vkCmdCopyBufferToImage()",
5091                                     "VK_IMAGE_USAGE_TRANSFER_DST_BIT");
5092     if (api_version >= VK_API_VERSION_1_1 || device_extensions.vk_khr_maintenance1) {
5093         skip |= ValidateImageFormatFeatureFlags(dst_image_state, VK_FORMAT_FEATURE_TRANSFER_DST_BIT, "vkCmdCopyBufferToImage()",
5094                                                 "VUID-vkCmdCopyBufferToImage-dstImage-01997",
5095                                                 "VUID-vkCmdCopyBufferToImage-dstImage-01997");
5096     }
5097     skip |= InsideRenderPass(cb_node, "vkCmdCopyBufferToImage()", "VUID-vkCmdCopyBufferToImage-renderpass");
5098     bool hit_error = false;
5099     const char *dst_invalid_layout_vuid = (dst_image_state->shared_presentable && device_extensions.vk_khr_shared_presentable_image)
5100                                               ? "VUID-vkCmdCopyBufferToImage-dstImageLayout-01396"
5101                                               : "VUID-vkCmdCopyBufferToImage-dstImageLayout-00181";
5102     for (uint32_t i = 0; i < regionCount; ++i) {
5103         skip |= ValidateImageSubresourceLayers(cb_node, &pRegions[i].imageSubresource, "vkCmdCopyBufferToImage()",
5104                                                "imageSubresource", i);
5105         skip |= VerifyImageLayout(cb_node, dst_image_state, pRegions[i].imageSubresource, dstImageLayout,
5106                                   VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, "vkCmdCopyBufferToImage()", dst_invalid_layout_vuid,
5107                                   "VUID-vkCmdCopyBufferToImage-dstImageLayout-00180", &hit_error);
5108         skip |= ValidateCopyBufferImageTransferGranularityRequirements(
5109             cb_node, dst_image_state, &pRegions[i], i, "vkCmdCopyBufferToImage()", "VUID-vkCmdCopyBufferToImage-imageOffset-01793");
5110         skip |=
5111             ValidateImageMipLevel(cb_node, dst_image_state, pRegions[i].imageSubresource.mipLevel, i, "vkCmdCopyBufferToImage()",
5112                                   "imageSubresource", "VUID-vkCmdCopyBufferToImage-imageSubresource-01701");
5113         skip |= ValidateImageArrayLayerRange(cb_node, dst_image_state, pRegions[i].imageSubresource.baseArrayLayer,
5114                                              pRegions[i].imageSubresource.layerCount, i, "vkCmdCopyBufferToImage()",
5115                                              "imageSubresource", "VUID-vkCmdCopyBufferToImage-imageSubresource-01702");
5116     }
5117     return skip;
5118 }
5119 
PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer,VkBuffer srcBuffer,VkImage dstImage,VkImageLayout dstImageLayout,uint32_t regionCount,const VkBufferImageCopy * pRegions)5120 void ValidationStateTracker::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
5121                                                                VkImageLayout dstImageLayout, uint32_t regionCount,
5122                                                                const VkBufferImageCopy *pRegions) {
5123     auto cb_node = GetCBState(commandBuffer);
5124     auto src_buffer_state = GetBufferState(srcBuffer);
5125     auto dst_image_state = GetImageState(dstImage);
5126 
5127     AddCommandBufferBindingBuffer(cb_node, src_buffer_state);
5128     AddCommandBufferBindingImage(cb_node, dst_image_state);
5129 }
5130 
PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer,VkBuffer srcBuffer,VkImage dstImage,VkImageLayout dstImageLayout,uint32_t regionCount,const VkBufferImageCopy * pRegions)5131 void CoreChecks::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
5132                                                    VkImageLayout dstImageLayout, uint32_t regionCount,
5133                                                    const VkBufferImageCopy *pRegions) {
5134     StateTracker::PreCallRecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
5135 
5136     auto cb_node = GetCBState(commandBuffer);
5137     auto dst_image_state = GetImageState(dstImage);
5138     // Make sure that all image slices are record referenced layout
5139     for (uint32_t i = 0; i < regionCount; ++i) {
5140         SetImageInitialLayout(cb_node, *dst_image_state, pRegions[i].imageSubresource, dstImageLayout);
5141     }
5142 }
5143 
PreCallValidateGetImageSubresourceLayout(VkDevice device,VkImage image,const VkImageSubresource * pSubresource,VkSubresourceLayout * pLayout)5144 bool CoreChecks::PreCallValidateGetImageSubresourceLayout(VkDevice device, VkImage image, const VkImageSubresource *pSubresource,
5145                                                           VkSubresourceLayout *pLayout) {
5146     bool skip = false;
5147     const VkImageAspectFlags sub_aspect = pSubresource->aspectMask;
5148 
5149     // The aspectMask member of pSubresource must only have a single bit set
5150     const int num_bits = sizeof(sub_aspect) * CHAR_BIT;
5151     std::bitset<num_bits> aspect_mask_bits(sub_aspect);
5152     if (aspect_mask_bits.count() != 1) {
5153         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(image),
5154                         "VUID-vkGetImageSubresourceLayout-aspectMask-00997",
5155                         "vkGetImageSubresourceLayout(): VkImageSubresource.aspectMask must have exactly 1 bit set.");
5156     }
5157 
5158     const IMAGE_STATE *image_entry = GetImageState(image);
5159     if (!image_entry) {
5160         return skip;
5161     }
5162 
5163     // image must have been created with tiling equal to VK_IMAGE_TILING_LINEAR
5164     if (image_entry->createInfo.tiling != VK_IMAGE_TILING_LINEAR) {
5165         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(image),
5166                         "VUID-vkGetImageSubresourceLayout-image-00996",
5167                         "vkGetImageSubresourceLayout(): Image must have tiling of VK_IMAGE_TILING_LINEAR.");
5168     }
5169 
5170     // mipLevel must be less than the mipLevels specified in VkImageCreateInfo when the image was created
5171     if (pSubresource->mipLevel >= image_entry->createInfo.mipLevels) {
5172         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(image),
5173                         "VUID-vkGetImageSubresourceLayout-mipLevel-01716",
5174                         "vkGetImageSubresourceLayout(): pSubresource.mipLevel (%d) must be less than %d.", pSubresource->mipLevel,
5175                         image_entry->createInfo.mipLevels);
5176     }
5177 
5178     // arrayLayer must be less than the arrayLayers specified in VkImageCreateInfo when the image was created
5179     if (pSubresource->arrayLayer >= image_entry->createInfo.arrayLayers) {
5180         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(image),
5181                         "VUID-vkGetImageSubresourceLayout-arrayLayer-01717",
5182                         "vkGetImageSubresourceLayout(): pSubresource.arrayLayer (%d) must be less than %d.",
5183                         pSubresource->arrayLayer, image_entry->createInfo.arrayLayers);
5184     }
5185 
5186     // subresource's aspect must be compatible with image's format.
5187     const VkFormat img_format = image_entry->createInfo.format;
5188     if (FormatIsMultiplane(img_format)) {
5189         VkImageAspectFlags allowed_flags = (VK_IMAGE_ASPECT_PLANE_0_BIT_KHR | VK_IMAGE_ASPECT_PLANE_1_BIT_KHR);
5190         const char *vuid = "VUID-vkGetImageSubresourceLayout-format-01581";  // 2-plane version
5191         if (FormatPlaneCount(img_format) > 2u) {
5192             allowed_flags |= VK_IMAGE_ASPECT_PLANE_2_BIT_KHR;
5193             vuid = "VUID-vkGetImageSubresourceLayout-format-01582";  // 3-plane version
5194         }
5195         if (sub_aspect != (sub_aspect & allowed_flags)) {
5196             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
5197                             HandleToUint64(image), vuid,
5198                             "vkGetImageSubresourceLayout(): For multi-planar images, VkImageSubresource.aspectMask (0x%" PRIx32
5199                             ") must be a single-plane specifier flag.",
5200                             sub_aspect);
5201         }
5202     } else if (FormatIsColor(img_format)) {
5203         if (sub_aspect != VK_IMAGE_ASPECT_COLOR_BIT) {
5204             skip |= log_msg(
5205                 report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(image),
5206                 "VUID-VkImageSubresource-aspectMask-parameter",
5207                 "vkGetImageSubresourceLayout(): For color formats, VkImageSubresource.aspectMask must be VK_IMAGE_ASPECT_COLOR.");
5208         }
5209     } else if (FormatIsDepthOrStencil(img_format)) {
5210         if ((sub_aspect != VK_IMAGE_ASPECT_DEPTH_BIT) && (sub_aspect != VK_IMAGE_ASPECT_STENCIL_BIT)) {
5211             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
5212                             HandleToUint64(image), "VUID-VkImageSubresource-aspectMask-parameter",
5213                             "vkGetImageSubresourceLayout(): For depth/stencil formats, VkImageSubresource.aspectMask must be "
5214                             "either VK_IMAGE_ASPECT_DEPTH_BIT or VK_IMAGE_ASPECT_STENCIL_BIT.");
5215         }
5216     }
5217 
5218     if (device_extensions.vk_android_external_memory_android_hardware_buffer) {
5219         skip |= ValidateGetImageSubresourceLayoutANDROID(image);
5220     }
5221 
5222     return skip;
5223 }
5224