blob: f2e77bef653d2606a2495424a7882ceb2cc8d652 [file] [log] [blame]
Karl Schultz7b024b42018-08-30 16:18:18 -06001/* Copyright (c) 2018-2019 The Khronos Group Inc.
2 * Copyright (c) 2018-2019 Valve Corporation
3 * Copyright (c) 2018-2019 LunarG, Inc.
4 * Copyright (C) 2018-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 */
19
20// Allow use of STL min and max functions in Windows
21#define NOMINMAX
22
23#include "core_validation.h"
24#include "shader_validation.h"
25#include "gpu_validation.h"
26#include "spirv-tools/libspirv.h"
27#include "spirv-tools/optimizer.hpp"
28#include "spirv-tools/instrument.hpp"
29#include <SPIRV/spirv.hpp>
30#include <algorithm>
31#include <regex>
32
33// This is the number of bindings in the debug descriptor set.
34static const uint32_t kNumBindingsInSet = 1;
35
36// Implementation for Device Memory Manager class
37VkResult GpuDeviceMemoryManager::GetBlock(GpuDeviceMemoryBlock *block) {
38 assert(block->buffer == VK_NULL_HANDLE); // avoid possible overwrite/leak of an allocated block
39 VkResult result = VK_SUCCESS;
40 MemoryChunk *pChunk = nullptr;
41 // Look for a chunk with available offsets.
42 for (auto &chunk : chunk_list_) {
43 if (!chunk.available_offsets.empty()) {
44 pChunk = &chunk;
45 break;
46 }
47 }
48 // If no chunks with available offsets, allocate device memory and set up offsets.
49 if (pChunk == nullptr) {
50 MemoryChunk new_chunk;
51 result = AllocMemoryChunk(new_chunk);
52 if (result == VK_SUCCESS) {
53 new_chunk.available_offsets.resize(blocks_per_chunk_);
54 for (uint32_t offset = 0, i = 0; i < blocks_per_chunk_; offset += block_size_, ++i) {
55 new_chunk.available_offsets[i] = offset;
56 }
57 chunk_list_.push_front(std::move(new_chunk));
58 pChunk = &chunk_list_.front();
59 } else {
60 // Indicate failure
61 block->buffer = VK_NULL_HANDLE;
62 block->memory = VK_NULL_HANDLE;
63 return result;
64 }
65 }
66 // Give the requester an available offset
67 block->buffer = pChunk->buffer;
68 block->memory = pChunk->memory;
69 block->offset = pChunk->available_offsets.back();
70 pChunk->available_offsets.pop_back();
71 return result;
72}
73
74void GpuDeviceMemoryManager::PutBackBlock(VkBuffer buffer, VkDeviceMemory memory, uint32_t offset) {
75 GpuDeviceMemoryBlock block = {buffer, memory, offset};
76 PutBackBlock(block);
77}
78
79void GpuDeviceMemoryManager::PutBackBlock(GpuDeviceMemoryBlock &block) {
80 // Find the chunk belonging to the allocated offset and make the offset available again
81 auto chunk = std::find_if(std::begin(chunk_list_), std::end(chunk_list_),
82 [&block](const MemoryChunk &c) { return c.buffer == block.buffer; });
83 if (chunk_list_.end() == chunk) {
84 assert(false);
85 } else {
86 chunk->available_offsets.push_back(block.offset);
87 if (chunk->available_offsets.size() == blocks_per_chunk_) {
88 // All offsets have been returned
89 FreeMemoryChunk(*chunk);
90 chunk_list_.erase(chunk);
91 }
92 }
93}
94
95void ResetBlock(GpuDeviceMemoryBlock &block) {
96 block.buffer = VK_NULL_HANDLE;
97 block.memory = VK_NULL_HANDLE;
98 block.offset = 0;
99}
100
101bool BlockUsed(GpuDeviceMemoryBlock &block) { return (block.buffer != VK_NULL_HANDLE) && (block.memory != VK_NULL_HANDLE); }
102
103bool GpuDeviceMemoryManager::MemoryTypeFromProperties(uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex) {
104 // Search memtypes to find first index with those properties
105 const VkPhysicalDeviceMemoryProperties *props = GetPhysicalDeviceMemoryProperties(dev_data_);
106 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
107 if ((typeBits & 1) == 1) {
108 // Type is available, does it match user properties?
109 if ((props->memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
110 *typeIndex = i;
111 return true;
112 }
113 }
114 typeBits >>= 1;
115 }
116 // No memory types matched, return failure
117 return false;
118}
119
120VkResult GpuDeviceMemoryManager::AllocMemoryChunk(MemoryChunk &chunk) {
121 VkBuffer buffer;
122 VkDeviceMemory memory;
123 VkBufferCreateInfo buffer_create_info = {};
124 VkMemoryRequirements mem_reqs = {};
125 VkMemoryAllocateInfo mem_alloc = {};
126 VkResult result = VK_SUCCESS;
127 bool pass;
128 void *pData;
129 const auto *dispatch_table = GetDispatchTable(dev_data_);
130
131 buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
132 buffer_create_info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
133 buffer_create_info.size = chunk_size_;
134 result = dispatch_table->CreateBuffer(GetDevice(dev_data_), &buffer_create_info, NULL, &buffer);
135 if (result != VK_SUCCESS) {
136 return result;
137 }
138
139 dispatch_table->GetBufferMemoryRequirements(GetDevice(dev_data_), buffer, &mem_reqs);
140
141 mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
142 mem_alloc.pNext = NULL;
143 mem_alloc.allocationSize = mem_reqs.size;
144 pass = MemoryTypeFromProperties(mem_reqs.memoryTypeBits,
145 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
146 &mem_alloc.memoryTypeIndex);
147 if (!pass) {
148 dispatch_table->DestroyBuffer(GetDevice(dev_data_), buffer, NULL);
149 return result;
150 }
151 result = dispatch_table->AllocateMemory(GetDevice(dev_data_), &mem_alloc, NULL, &memory);
152 if (result != VK_SUCCESS) {
153 dispatch_table->DestroyBuffer(GetDevice(dev_data_), buffer, NULL);
154 return result;
155 }
156
157 result = dispatch_table->BindBufferMemory(GetDevice(dev_data_), buffer, memory, 0);
158 if (result != VK_SUCCESS) {
159 dispatch_table->DestroyBuffer(GetDevice(dev_data_), buffer, NULL);
160 dispatch_table->FreeMemory(GetDevice(dev_data_), memory, NULL);
161 return result;
162 }
163
164 result = dispatch_table->MapMemory(GetDevice(dev_data_), memory, 0, mem_alloc.allocationSize, 0, &pData);
165 if (result == VK_SUCCESS) {
166 memset(pData, 0, chunk_size_);
167 dispatch_table->UnmapMemory(GetDevice(dev_data_), memory);
168 } else {
169 dispatch_table->DestroyBuffer(GetDevice(dev_data_), buffer, NULL);
170 dispatch_table->FreeMemory(GetDevice(dev_data_), memory, NULL);
171 return result;
172 }
173 chunk.buffer = buffer;
174 chunk.memory = memory;
175 return result;
176}
177
178void GpuDeviceMemoryManager::FreeMemoryChunk(MemoryChunk &chunk) {
179 GetDispatchTable(dev_data_)->DestroyBuffer(GetDevice(dev_data_), chunk.buffer, NULL);
180 GetDispatchTable(dev_data_)->FreeMemory(GetDevice(dev_data_), chunk.memory, NULL);
181}
182
183// Implementation for Descriptor Set Manager class
184VkResult GpuDescriptorSetManager::GetDescriptorSets(uint32_t count, VkDescriptorPool *pool,
185 std::vector<VkDescriptorSet> *desc_sets) {
186 auto gpu_state = GetGpuValidationState(dev_data_);
187 const uint32_t default_pool_size = kItemsPerChunk;
188 VkResult result = VK_SUCCESS;
189 VkDescriptorPool pool_to_use = VK_NULL_HANDLE;
190
191 if (0 == count) {
192 return result;
193 }
194 desc_sets->clear();
195 desc_sets->resize(count);
196
197 for (auto &pool : desc_pool_map_) {
198 if (pool.second.used + count < pool.second.size) {
199 pool_to_use = pool.first;
200 break;
201 }
202 }
203 if (VK_NULL_HANDLE == pool_to_use) {
204 uint32_t pool_count = default_pool_size;
205 if (count > default_pool_size) {
206 pool_count = count;
207 }
208 const VkDescriptorPoolSize size_counts = {
209 VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
210 pool_count * kNumBindingsInSet,
211 };
212 VkDescriptorPoolCreateInfo desc_pool_info = {};
213 desc_pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
214 desc_pool_info.pNext = NULL;
215 desc_pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
216 desc_pool_info.maxSets = pool_count;
217 desc_pool_info.poolSizeCount = 1;
218 desc_pool_info.pPoolSizes = &size_counts;
219 result = GetDispatchTable(dev_data_)->CreateDescriptorPool(GetDevice(dev_data_), &desc_pool_info, NULL, &pool_to_use);
220 assert(result == VK_SUCCESS);
221 if (result != VK_SUCCESS) {
222 return result;
223 }
224 desc_pool_map_[pool_to_use].size = desc_pool_info.maxSets;
225 desc_pool_map_[pool_to_use].used = 0;
226 }
227 std::vector<VkDescriptorSetLayout> desc_layouts(count, gpu_state->debug_desc_layout);
228
229 VkDescriptorSetAllocateInfo alloc_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, NULL, pool_to_use, count,
230 desc_layouts.data()};
231
232 result = GetDispatchTable(dev_data_)->AllocateDescriptorSets(GetDevice(dev_data_), &alloc_info, desc_sets->data());
233 assert(result == VK_SUCCESS);
234 if (result != VK_SUCCESS) {
235 return result;
236 }
237 *pool = pool_to_use;
238 desc_pool_map_[pool_to_use].used += count;
239 return result;
240}
241
242void GpuDescriptorSetManager::PutBackDescriptorSet(VkDescriptorPool desc_pool, VkDescriptorSet desc_set) {
243 auto iter = desc_pool_map_.find(desc_pool);
244 if (iter != desc_pool_map_.end()) {
245 VkResult result = GetDispatchTable(dev_data_)->FreeDescriptorSets(GetDevice(dev_data_), desc_pool, 1, &desc_set);
246 assert(result == VK_SUCCESS);
247 if (result != VK_SUCCESS) {
248 return;
249 }
250 desc_pool_map_[desc_pool].used--;
251 if (0 == desc_pool_map_[desc_pool].used) {
252 GetDispatchTable(dev_data_)->DestroyDescriptorPool(GetDevice(dev_data_), desc_pool, NULL);
253 desc_pool_map_.erase(desc_pool);
254 }
255 }
256 return;
257}
258
259// Convenience function for reporting problems with setting up GPU Validation.
260static void ReportSetupProblem(const layer_data *dev_data, VkDebugReportObjectTypeEXT object_type, uint64_t object_handle,
261 const char *const specific_message) {
262 log_msg(GetReportData(dev_data), VK_DEBUG_REPORT_ERROR_BIT_EXT, object_type, object_handle,
263 "UNASSIGNED-GPU-Assisted Validation Error. ", "Detail: (%s)", specific_message);
264}
265
266// Turn on necessary device features.
267std::unique_ptr<safe_VkDeviceCreateInfo> GpuPreCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo *create_info,
268 VkPhysicalDeviceFeatures *supported_features) {
269 std::unique_ptr<safe_VkDeviceCreateInfo> new_info(new safe_VkDeviceCreateInfo(create_info));
270 if (supported_features->fragmentStoresAndAtomics || supported_features->vertexPipelineStoresAndAtomics) {
Tony-LunarG48b478a2019-01-15 16:35:22 -0700271 VkPhysicalDeviceFeatures new_features = {};
272 if (new_info->pEnabledFeatures) {
273 new_features = *new_info->pEnabledFeatures;
274 }
Karl Schultz7b024b42018-08-30 16:18:18 -0600275 new_features.fragmentStoresAndAtomics = supported_features->fragmentStoresAndAtomics;
276 new_features.vertexPipelineStoresAndAtomics = supported_features->vertexPipelineStoresAndAtomics;
277 delete new_info->pEnabledFeatures;
278 new_info->pEnabledFeatures = new VkPhysicalDeviceFeatures(new_features);
279 }
280 return new_info;
281}
282
283// Perform initializations that can be done at Create Device time.
284void GpuPostCallRecordCreateDevice(layer_data *dev_data) {
285 auto gpu_state = GetGpuValidationState(dev_data);
286 const auto *dispatch_table = GetDispatchTable(dev_data);
287
288 if (GetPhysicalDeviceProperties(dev_data)->apiVersion < VK_API_VERSION_1_1) {
289 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
290 "GPU-Assisted validation requires Vulkan 1.1 or later. GPU-Assisted Validation disabled.");
291 gpu_state->aborted = true;
292 return;
293 }
294 // Some devices have extremely high limits here, so set a reasonable max because we have to pad
295 // the pipeline layout with dummy descriptor set layouts.
296 gpu_state->adjusted_max_desc_sets = GetPhysicalDeviceProperties(dev_data)->limits.maxBoundDescriptorSets;
297 gpu_state->adjusted_max_desc_sets = std::min(33U, gpu_state->adjusted_max_desc_sets);
298
299 // We can't do anything if there is only one.
300 // Device probably not a legit Vulkan device, since there should be at least 4. Protect ourselves.
301 if (gpu_state->adjusted_max_desc_sets == 1) {
302 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
303 "Device can bind only a single descriptor set. GPU-Assisted Validation disabled.");
304 gpu_state->aborted = true;
305 return;
306 }
307 gpu_state->desc_set_bind_index = gpu_state->adjusted_max_desc_sets - 1;
308 log_msg(GetReportData(dev_data), VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
309 HandleToUint64(GetDevice(dev_data)), "UNASSIGNED-GPU-Assisted Validation. ",
310 "Shaders using descriptor set at index %d. ", gpu_state->desc_set_bind_index);
311
312 std::unique_ptr<GpuDeviceMemoryManager> memory_manager(
313 new GpuDeviceMemoryManager(dev_data, sizeof(uint32_t) * (spvtools::kInstMaxOutCnt + 1)));
314 std::unique_ptr<GpuDescriptorSetManager> desc_set_manager(new GpuDescriptorSetManager(dev_data));
315
316 // The descriptor indexing checks require only the first "output" binding.
317 const VkDescriptorSetLayoutBinding debug_desc_layout_bindings[kNumBindingsInSet] = {
318 {
319 0, // output
320 VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
321 1,
322 VK_SHADER_STAGE_ALL_GRAPHICS,
323 NULL,
324 },
325 };
326
327 const VkDescriptorSetLayoutCreateInfo debug_desc_layout_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, NULL, 0,
328 kNumBindingsInSet, debug_desc_layout_bindings};
329
330 const VkDescriptorSetLayoutCreateInfo dummy_desc_layout_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, NULL, 0, 0,
331 NULL};
332
333 VkResult result = dispatch_table->CreateDescriptorSetLayout(GetDevice(dev_data), &debug_desc_layout_info, NULL,
334 &gpu_state->debug_desc_layout);
335
336 // This is a layout used to "pad" a pipeline layout to fill in any gaps to the selected bind index.
337 VkResult result2 = dispatch_table->CreateDescriptorSetLayout(GetDevice(dev_data), &dummy_desc_layout_info, NULL,
338 &gpu_state->dummy_desc_layout);
339 assert((result == VK_SUCCESS) && (result2 == VK_SUCCESS));
340 if ((result != VK_SUCCESS) || (result2 != VK_SUCCESS)) {
341 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
342 "Unable to create descriptor set layout. GPU-Assisted Validation disabled.");
343 if (result == VK_SUCCESS) {
344 dispatch_table->DestroyDescriptorSetLayout(GetDevice(dev_data), gpu_state->debug_desc_layout, NULL);
345 }
346 if (result2 == VK_SUCCESS) {
347 dispatch_table->DestroyDescriptorSetLayout(GetDevice(dev_data), gpu_state->dummy_desc_layout, NULL);
348 }
349 gpu_state->debug_desc_layout = VK_NULL_HANDLE;
350 gpu_state->dummy_desc_layout = VK_NULL_HANDLE;
351 gpu_state->aborted = true;
352 return;
353 }
354 gpu_state->memory_manager = std::move(memory_manager);
355 gpu_state->desc_set_manager = std::move(desc_set_manager);
356}
357
358// Clean up device-related resources
359void GpuPreCallRecordDestroyDevice(layer_data *dev_data) {
360 auto gpu_state = GetGpuValidationState(dev_data);
361
362 if (gpu_state->debug_desc_layout) {
363 GetDispatchTable(dev_data)->DestroyDescriptorSetLayout(GetDevice(dev_data), gpu_state->debug_desc_layout, NULL);
364 gpu_state->debug_desc_layout = VK_NULL_HANDLE;
365 }
366 if (gpu_state->dummy_desc_layout) {
367 GetDispatchTable(dev_data)->DestroyDescriptorSetLayout(GetDevice(dev_data), gpu_state->dummy_desc_layout, NULL);
368 gpu_state->dummy_desc_layout = VK_NULL_HANDLE;
369 }
370}
371
372// Bind our debug descriptor set immediately after binding a pipeline if the pipeline layout is not using our slot.
373void GpuPostCallDispatchCmdBindPipeline(layer_data *dev_data, VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
374 VkPipeline pipeline) {
375 auto gpu_state = GetGpuValidationState(dev_data);
376 if (gpu_state->aborted) {
377 return;
378 }
379 const GLOBAL_CB_NODE *cb_state = GetCBNode(dev_data, commandBuffer);
380 auto iter = cb_state->lastBound.find(pipelineBindPoint); // find() allows read-only access to cb_state
381 if (iter != cb_state->lastBound.end()) {
382 auto pipeline_state = iter->second.pipeline_state;
383 if (pipeline_state && (pipeline_state->pipeline_layout.set_layouts.size() <= gpu_state->desc_set_bind_index)) {
384 GetDispatchTable(dev_data)->CmdBindDescriptorSets(
385 commandBuffer, pipelineBindPoint, pipeline_state->pipeline_layout.layout, gpu_state->desc_set_bind_index, 1,
386 &cb_state->gpu_buffer_desc_set, 0, nullptr);
387 }
388 }
389}
390
391// Modify the pipeline layout to include our debug descriptor set and any needed padding with the dummy descriptor set.
392VkResult GpuOverrideDispatchCreatePipelineLayout(layer_data *dev_data, const VkPipelineLayoutCreateInfo *pCreateInfo,
393 const VkAllocationCallbacks *pAllocator, VkPipelineLayout *pPipelineLayout) {
394 auto gpu_state = GetGpuValidationState(dev_data);
395 if (gpu_state->aborted) {
396 return GetDispatchTable(dev_data)->CreatePipelineLayout(GetDevice(dev_data), pCreateInfo, pAllocator, pPipelineLayout);
397 }
398 VkPipelineLayoutCreateInfo new_create_info = *pCreateInfo;
399 std::vector<VkDescriptorSetLayout> new_layouts;
400 if (new_create_info.setLayoutCount >= gpu_state->adjusted_max_desc_sets) {
401 std::ostringstream strm;
402 strm << "Pipeline Layout conflict with validation's descriptor set at slot " << gpu_state->desc_set_bind_index << ". "
403 << "Application has too many descriptor sets in the pipeline layout to continue with gpu validation. "
404 << "Validation is not modifying the pipeline layout. "
405 << "Instrumented shaders are replaced with non-instrumented shaders.";
406 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
407 strm.str().c_str());
408 } else {
409 // Modify the pipeline layout by:
410 // 1. Copying the caller's descriptor set desc_layouts
411 // 2. Fill in dummy descriptor layouts up to the max binding
412 // 3. Fill in with the debug descriptor layout at the max binding slot
413 new_layouts.reserve(gpu_state->adjusted_max_desc_sets);
414 new_layouts.insert(new_layouts.end(), &pCreateInfo->pSetLayouts[0], &pCreateInfo->pSetLayouts[pCreateInfo->setLayoutCount]);
415 for (uint32_t i = pCreateInfo->setLayoutCount; i < gpu_state->adjusted_max_desc_sets - 1; ++i) {
416 new_layouts.push_back(gpu_state->dummy_desc_layout);
417 }
418 new_layouts.push_back(gpu_state->debug_desc_layout);
419 new_create_info.pSetLayouts = new_layouts.data();
420 new_create_info.setLayoutCount = gpu_state->adjusted_max_desc_sets;
421 }
422 VkResult result;
423 result = GetDispatchTable(dev_data)->CreatePipelineLayout(GetDevice(dev_data), &new_create_info, pAllocator, pPipelineLayout);
424 assert(result == VK_SUCCESS);
425 if (result != VK_SUCCESS) {
426 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
427 "Unable to create pipeline layout. Device could become unstable.");
428 gpu_state->aborted = true;
429 }
430 return result;
431}
432
433// Each command buffer gets a piece of device memory and a descriptor set for the debug buffer.
434void GpuPostCallRecordAllocateCommandBuffers(layer_data *dev_data, const VkCommandBufferAllocateInfo *pCreateInfo,
435 VkCommandBuffer *pCommandBuffer) {
436 VkResult result;
437
438 auto gpu_state = GetGpuValidationState(dev_data);
439 if (gpu_state->aborted) return;
440
441 std::vector<VkDescriptorSet> desc_sets;
442 VkDescriptorPool desc_pool = VK_NULL_HANDLE;
443 result = gpu_state->desc_set_manager->GetDescriptorSets(pCreateInfo->commandBufferCount, &desc_pool, &desc_sets);
444 assert(result == VK_SUCCESS);
445 if (result != VK_SUCCESS) {
446 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
447 "Unable to allocate descriptor sets. Device could become unstable.");
448 gpu_state->aborted = true;
449 return;
450 }
451
452 VkDescriptorBufferInfo desc_buffer_info = {};
453 desc_buffer_info.range = gpu_state->memory_manager->GetBlockSize();
454
455 VkWriteDescriptorSet desc_write = {};
456 desc_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
457 desc_write.descriptorCount = 1;
458 desc_write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
459 desc_write.pBufferInfo = &desc_buffer_info;
460
461 for (uint32_t i = 0; i < pCreateInfo->commandBufferCount; i++) {
462 auto cb_node = GetCBNode(dev_data, pCommandBuffer[i]);
463
464 GpuDeviceMemoryBlock block = {};
465 result = gpu_state->memory_manager->GetBlock(&block);
466 if (result != VK_SUCCESS) {
467 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
468 "Unable to allocate device memory. Device could become unstable.");
469 gpu_state->aborted = true;
470 return;
471 }
472
473 // Record buffer and memory info in CB state tracking
474 cb_node->gpu_output_memory_block = block;
475 cb_node->gpu_buffer_desc_set = desc_sets[i];
476 cb_node->gpu_buffer_desc_pool = desc_pool;
477
478 // Write the descriptor
479 desc_buffer_info.buffer = block.buffer;
480 desc_buffer_info.offset = block.offset;
481 desc_write.dstSet = cb_node->gpu_buffer_desc_set;
482 GetDispatchTable(dev_data)->UpdateDescriptorSets(GetDevice(dev_data), 1, &desc_write, 0, NULL);
483 }
484}
485
486// Free the device memory and descriptor set associated with a command buffer.
487void GpuPreCallRecordFreeCommandBuffers(layer_data *dev_data, uint32_t commandBufferCount, const VkCommandBuffer *pCommandBuffers) {
488 auto gpu_state = GetGpuValidationState(dev_data);
489 if (gpu_state->aborted) {
490 return;
491 }
492 for (uint32_t i = 0; i < commandBufferCount; ++i) {
493 auto cb_node = GetCBNode(dev_data, pCommandBuffers[i]);
494 if (BlockUsed(cb_node->gpu_output_memory_block)) {
495 gpu_state->memory_manager->PutBackBlock(cb_node->gpu_output_memory_block);
496 ResetBlock(cb_node->gpu_output_memory_block);
497 }
498 if (cb_node->gpu_buffer_desc_set != VK_NULL_HANDLE) {
499 gpu_state->desc_set_manager->PutBackDescriptorSet(cb_node->gpu_buffer_desc_pool, cb_node->gpu_buffer_desc_set);
500 cb_node->gpu_buffer_desc_set = VK_NULL_HANDLE;
501 }
502 }
503}
504
505// Just gives a warning about a possible deadlock.
506void GpuPreCallValidateCmdWaitEvents(layer_data *dev_data, VkPipelineStageFlags sourceStageMask) {
507 if (sourceStageMask & VK_PIPELINE_STAGE_HOST_BIT) {
508 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
509 "CmdWaitEvents recorded with VK_PIPELINE_STAGE_HOST_BIT set. "
510 "GPU_Assisted validation waits on queue completion. "
511 "This wait could block the host's signaling of this event, resulting in deadlock.");
512 }
513}
514
515// Examine the pipelines to see if they use the debug descriptor set binding index.
516// If any do, create new non-instrumented shader modules and use them to replace the instrumented
517// shaders in the pipeline. Return the (possibly) modified create infos to the caller.
518std::vector<safe_VkGraphicsPipelineCreateInfo> GpuPreCallRecordCreateGraphicsPipelines(
519 layer_data *dev_data, VkPipelineCache pipelineCache, uint32_t count, const VkGraphicsPipelineCreateInfo *pCreateInfos,
520 const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines, std::vector<std::unique_ptr<PIPELINE_STATE>> &pipe_state) {
521 auto gpu_state = GetGpuValidationState(dev_data);
522
523 std::vector<safe_VkGraphicsPipelineCreateInfo> new_pipeline_create_infos;
524 std::vector<unsigned int> pipeline_uses_debug_index(count);
525
526 // Walk through all the pipelines, make a copy of each and flag each pipeline that contains a shader that uses the debug
527 // descriptor set index.
528 for (uint32_t pipeline = 0; pipeline < count; ++pipeline) {
529 new_pipeline_create_infos.push_back(pipe_state[pipeline]->graphicsPipelineCI);
530 if (pipe_state[pipeline]->active_slots.find(gpu_state->desc_set_bind_index) != pipe_state[pipeline]->active_slots.end()) {
531 pipeline_uses_debug_index[pipeline] = 1;
532 }
533 }
534
535 // See if any pipeline has shaders using the debug descriptor set index
536 if (std::all_of(pipeline_uses_debug_index.begin(), pipeline_uses_debug_index.end(), [](unsigned int i) { return i == 0; })) {
537 // None of the shaders in all the pipelines use the debug descriptor set index, so use the pipelines
538 // as they stand with the instrumented shaders.
539 return new_pipeline_create_infos;
540 }
541
542 // At least one pipeline has a shader that uses the debug descriptor set index.
543 for (uint32_t pipeline = 0; pipeline < count; ++pipeline) {
544 if (pipeline_uses_debug_index[pipeline]) {
545 for (uint32_t stage = 0; stage < pCreateInfos[pipeline].stageCount; ++stage) {
546 const shader_module *shader = GetShaderModuleState(dev_data, pCreateInfos[pipeline].pStages[stage].module);
547 VkShaderModuleCreateInfo create_info = {};
548 VkShaderModule shader_module;
549 create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
550 create_info.pCode = shader->words.data();
551 create_info.codeSize = shader->words.size() * sizeof(uint32_t);
552 VkResult result =
553 GetDispatchTable(dev_data)->CreateShaderModule(GetDevice(dev_data), &create_info, pAllocator, &shader_module);
554 if (result == VK_SUCCESS) {
555 new_pipeline_create_infos[pipeline].pStages[stage].module = shader_module;
556 } else {
557 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
558 HandleToUint64(pCreateInfos[pipeline].pStages[stage].module),
559 "Unable to replace instrumented shader with non-instrumented one. "
560 "Device could become unstable.");
561 }
562 }
563 }
564 }
565 return new_pipeline_create_infos;
566}
567
568// For every pipeline:
569// - For every shader in a pipeline:
570// - If the shader had to be replaced in PreCallRecord (because the pipeline is using the debug desc set index):
571// - Destroy it since it has been bound into the pipeline by now. This is our only chance to delete it.
572// - Track the shader in the shader_map
573// - Save the shader binary if it contains debug code
574void GpuPostCallRecordCreateGraphicsPipelines(layer_data *dev_data, const uint32_t count,
575 const VkGraphicsPipelineCreateInfo *pCreateInfos,
576 const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines) {
577 auto gpu_state = GetGpuValidationState(dev_data);
578 for (uint32_t pipeline = 0; pipeline < count; ++pipeline) {
579 auto pipeline_state = GetPipelineState(dev_data, pPipelines[pipeline]);
580 if (nullptr == pipeline_state) continue;
581 for (uint32_t stage = 0; stage < pipeline_state->graphicsPipelineCI.stageCount; ++stage) {
582 if (pipeline_state->active_slots.find(gpu_state->desc_set_bind_index) != pipeline_state->active_slots.end()) {
583 GetDispatchTable(dev_data)->DestroyShaderModule(GetDevice(dev_data), pCreateInfos->pStages[stage].module,
584 pAllocator);
585 }
586 auto shader_state = GetShaderModuleState(dev_data, pipeline_state->graphicsPipelineCI.pStages[stage].module);
587 std::vector<unsigned int> code;
588 // Save the shader binary if debug info is present.
589 // The core_validation ShaderModule tracker saves the binary too, but discards it when the ShaderModule
590 // is destroyed. Applications may destroy ShaderModules after they are placed in a pipeline and before
591 // the pipeline is used, so we have to keep another copy.
592 if (shader_state && shader_state->has_valid_spirv) { // really checking for presense of SPIR-V code.
593 for (auto insn : *shader_state) {
594 if (insn.opcode() == spv::OpLine) {
595 code = shader_state->words;
596 break;
597 }
598 }
599 }
600 gpu_state->shader_map[shader_state->gpu_validation_shader_id].pipeline = pipeline_state->pipeline;
601 // Be careful to use the originally bound (instrumented) shader here, even if PreCallRecord had to back it
602 // out with a non-instrumented shader. The non-instrumented shader (found in pCreateInfo) was destroyed above.
603 gpu_state->shader_map[shader_state->gpu_validation_shader_id].shader_module =
604 pipeline_state->graphicsPipelineCI.pStages[stage].module;
605 gpu_state->shader_map[shader_state->gpu_validation_shader_id].pgm = std::move(code);
606 }
607 }
608}
609
610// Remove all the shader trackers associated with this destroyed pipeline.
611void GpuPreCallRecordDestroyPipeline(layer_data *dev_data, const VkPipeline pipeline) {
612 auto gpu_state = GetGpuValidationState(dev_data);
613 for (auto it = gpu_state->shader_map.begin(); it != gpu_state->shader_map.end();) {
614 if (it->second.pipeline == pipeline) {
615 it = gpu_state->shader_map.erase(it);
616 } else {
617 ++it;
618 }
619 }
620}
621
Karl Schultz24137052019-01-12 08:16:32 -0700622// This is a temporary workaround to fix a missing operation in the spirv-tools
623// instrumentation pass.
624// The instrumentation pass creates an array (of uint) variable to store the debug
625// data. But it doesn't set the ArrayStride decoration (to 4). Some drivers
626// move along and come up with a value of 4, but some don't and use a stride value of 0.
627// Add our own decoration to the SPIR-V type definition for the array.
628static void FixMissingStride(layer_data *dev_data, std::vector<unsigned int> &new_pgm) {
629 auto gpu_state = GetGpuValidationState(dev_data);
630 unsigned int insert_offset = 0;
631 shader_module shader;
632 shader.words = new_pgm;
633 if (shader.words.size() > 0) {
634 // Find the ID of the variable referenced by our debug descriptor set.
635 // If found, also save an offset for a good place to insert our additional decoration later.
636 unsigned int variable_id = 0;
637 for (auto insn : shader) {
638 if (insn.opcode() == spv::OpDecorate) {
639 if (insn.word(2) == spv::Decoration::DecorationDescriptorSet && insn.word(3) == gpu_state->desc_set_bind_index) {
640 variable_id = insn.word(1);
641 insn++;
642 insert_offset = insn.offset();
643 break;
644 }
645 }
646 }
647 if (variable_id == 0) return;
648
649 // Look up the variable and find its type ptr.
650 unsigned int variable_type_ptr_id = 0;
651 for (auto insn : shader) {
652 if (insn.opcode() == spv::OpVariable) {
653 if (insn.word(2) == variable_id) {
654 variable_type_ptr_id = insn.word(1);
655 break;
656 }
657 }
658 }
659 if (variable_type_ptr_id == 0) return;
660
661 // Look up the type ptr of the variable to find its type
662 unsigned int type_id = 0;
663 for (auto insn : shader) {
664 if (insn.opcode() == spv::OpTypePointer) {
665 if (insn.word(1) == variable_type_ptr_id) {
666 type_id = insn.word(3);
667 break;
668 }
669 }
670 }
671 if (type_id == 0) return;
672
673 // Look up the type that we want to annotate with the stride.
674 // We don't really know what the actual type is that is pointed to by the type ptr we just found.
675 // I suppose we could scan on the OpType* opcodes to look for an ID match.
676 // But we happen to know that there is a struct here, so look for just OpTypeStruct.
677 // We also know that the second struct member is the array of debug output words.
678 unsigned int array_type_id = 0;
679 for (auto insn : shader) {
680 if (insn.opcode() == spv::OpTypeStruct) {
681 if (insn.word(1) == type_id && insn.len() >= 4) { // has at least 2 members
682 array_type_id = insn.word(3); // second member type
683 break;
684 }
685 }
686 }
687 if (array_type_id == 0) return;
688
689 // See if the array stride decoration for the type of the debug data array is already there.
690 // Don't insert a new one if there is one already there.
691 bool stride_already_there = false;
692 for (auto insn : shader) {
693 if (insn.opcode() == spv::OpDecorate) {
694 if (insn.len() == 4 && insn.word(1) == array_type_id && insn.word(2) == spv::Decoration::DecorationArrayStride) {
695 stride_already_there = true;
696 break;
697 }
698 }
699 }
700 if (stride_already_there) return;
701
702 // Build an OpDecorate instruction to add the stride information and insert it in the program.
703 if (insert_offset != 0) {
704 std::vector<unsigned int> inst(4);
705 inst[0] = (4 << 16) | spv::OpDecorate;
706 inst[1] = array_type_id;
707 inst[2] = spv::Decoration::DecorationArrayStride;
708 inst[3] = 4;
709 auto it = new_pgm.begin();
710 new_pgm.insert(it + insert_offset, inst.begin(), inst.end());
711 }
712 }
713}
714
Karl Schultz7b024b42018-08-30 16:18:18 -0600715// Call the SPIR-V Optimizer to run the instrumentation pass on the shader.
716static bool GpuInstrumentShader(layer_data *dev_data, const VkShaderModuleCreateInfo *pCreateInfo,
717 std::vector<unsigned int> &new_pgm, uint32_t *unique_shader_id) {
718 auto gpu_state = GetGpuValidationState(dev_data);
719 if (gpu_state->aborted) return false;
720 if (pCreateInfo->pCode[0] != spv::MagicNumber) return false;
721
722 // Load original shader SPIR-V
723 uint32_t num_words = static_cast<uint32_t>(pCreateInfo->codeSize / 4);
724 new_pgm.clear();
725 new_pgm.reserve(num_words);
726 new_pgm.insert(new_pgm.end(), &pCreateInfo->pCode[0], &pCreateInfo->pCode[num_words]);
727
728 // Call the optimizer to instrument the shader.
729 // Use the unique_shader_module_id as a shader ID so we can look up its handle later in the shader_map.
730 using namespace spvtools;
731 spv_target_env target_env = SPV_ENV_VULKAN_1_1;
732 Optimizer optimizer(target_env);
733 optimizer.RegisterPass(CreateInstBindlessCheckPass(gpu_state->desc_set_bind_index, gpu_state->unique_shader_module_id));
734 optimizer.RegisterPass(CreateAggressiveDCEPass());
735 bool pass = optimizer.Run(new_pgm.data(), new_pgm.size(), &new_pgm);
736 if (!pass) {
737 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT, VK_NULL_HANDLE,
738 "Failure to instrument shader. Proceeding with non-instrumented shader.");
739 }
Karl Schultz24137052019-01-12 08:16:32 -0700740 FixMissingStride(dev_data, new_pgm);
Karl Schultz7b024b42018-08-30 16:18:18 -0600741 *unique_shader_id = gpu_state->unique_shader_module_id++;
742 return pass;
743}
744
745// Override the CreateShaderModule command to provide the instrumented shader to the driver.
746VkResult GpuOverrideDispatchCreateShaderModule(layer_data *dev_data, const VkShaderModuleCreateInfo *pCreateInfo,
747 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule,
748 uint32_t *unique_shader_id) {
749 VkShaderModuleCreateInfo instrumented_create_info = *pCreateInfo;
750 std::vector<unsigned int> instrumented_pgm;
751 bool pass = GpuInstrumentShader(dev_data, pCreateInfo, instrumented_pgm, unique_shader_id);
752 if (pass) {
753 instrumented_create_info.pCode = instrumented_pgm.data();
754 instrumented_create_info.codeSize = instrumented_pgm.size() * sizeof(unsigned int);
755 }
756 // We trust the optimizer's instrumentation pass to not change the validity of the SPIR-V as determined by
757 // the prior call to PreCallValidate.
758 // But we do pass the instrumented shader to the driver.
759 VkResult result =
760 GetDispatchTable(dev_data)->CreateShaderModule(GetDevice(dev_data), &instrumented_create_info, pAllocator, pShaderModule);
761 return result;
762}
763
764// Generate the stage-specific part of the message.
765static void GenerateStageMessage(const uint32_t *debug_record, std::string &msg) {
766 using namespace spvtools;
767 std::ostringstream strm;
768 switch (debug_record[kInstCommonOutStageIdx]) {
769 case 0: {
770 strm << "Stage = Vertex. Vertex ID = " << debug_record[kInstVertOutVertexId]
771 << " Instance ID = " << debug_record[kInstVertOutInstanceId] << ". ";
772 } break;
773 case 1: {
774 strm << "Stage = Tessellation Control. Invocation ID = " << debug_record[kInstTessOutInvocationId] << ". ";
775 } break;
776 case 2: {
777 strm << "Stage = Tessellation Eval. Invocation ID = " << debug_record[kInstTessOutInvocationId] << ". ";
778 } break;
779 case 3: {
780 strm << "Stage = Geometry. Primitive ID = " << debug_record[kInstGeomOutPrimitiveId]
781 << " Invocation ID = " << debug_record[kInstGeomOutInvocationId] << ". ";
782 } break;
783 case 4: {
784 strm << "Stage = Fragment. Fragment coord (x,y) = ("
785 << *reinterpret_cast<const float *>(&debug_record[kInstFragOutFragCoordX]) << ", "
786 << *reinterpret_cast<const float *>(&debug_record[kInstFragOutFragCoordY]) << "). ";
787 } break;
788 case 5: {
789 strm << "Stage = Compute. Global invocation ID = " << debug_record[kInstCompOutGlobalInvocationId] << ". ";
790 } break;
791 default: {
792 strm << "Internal Error (unexpected stage = " << debug_record[kInstCommonOutStageIdx] << "). ";
793 assert(false);
794 } break;
795 }
796 msg = strm.str();
797}
798
799// Generate the part of the message describing the violation.
800static void GenerateValidationMessage(const uint32_t *debug_record, std::string &msg, std::string &vuid_msg) {
801 using namespace spvtools;
802 std::ostringstream strm;
803 switch (debug_record[kInstValidationOutError]) {
804 case 0: {
805 strm << "Index of " << debug_record[kInstBindlessOutDescIndex] << " used to index descriptor array of length "
806 << debug_record[kInstBindlessOutDescBound] << ". ";
807 vuid_msg = "UNASSIGNED-Image descriptor index out of bounds";
808 } break;
809 case 1: {
810 strm << "Index of " << debug_record[kInstBindlessOutDescIndex] << " used to index descriptor array of length "
811 << debug_record[kInstBindlessOutDescBound] << ". ";
812 vuid_msg = "UNASSIGNED-Sampler index out of bounds";
813 } break;
814 case 2: {
815 strm << "Descriptor index " << debug_record[kInstBindlessOutDescIndex] << " is uninitialized. ";
816 vuid_msg = "UNASSIGNED-Image descriptor uninitialized";
817 } break;
818 case 3: {
819 strm << "Descriptor index " << debug_record[kInstBindlessOutDescIndex] << " is uninitialized. ";
820 vuid_msg = "UNASSIGNED-Sampler descriptor uninitialized";
821 } break;
822 default: {
823 strm << "Internal Error (unexpected error type = " << debug_record[kInstValidationOutError] << "). ";
824 vuid_msg = "UNASSIGNED-Internal Error";
825 assert(false);
826 } break;
827 }
828 msg = strm.str();
829}
830
831static std::string LookupDebugUtilsName(const layer_data *dev_data, const uint64_t object) {
832 const debug_report_data *debug_data = GetReportData(dev_data);
833 auto utils_name_iter = debug_data->debugUtilsObjectNameMap->find(object);
834 if (utils_name_iter != debug_data->debugUtilsObjectNameMap->end()) {
835 return "(" + utils_name_iter->second + ")";
836 } else {
837 return "";
838 }
839}
840
841// Generate message from the common portion of the debug report record.
842static void GenerateCommonMessage(const layer_data *dev_data, const GLOBAL_CB_NODE *cb_node, const uint32_t *debug_record,
843 const VkShaderModule shader_module_handle, const VkPipeline pipeline_handle, std::string &msg) {
844 using namespace spvtools;
845 std::ostringstream strm;
846 if (shader_module_handle == VK_NULL_HANDLE) {
847 strm << std::hex << std::showbase << "Internal Error: Unable to locate information for shader used in command buffer "
848 << LookupDebugUtilsName(dev_data, HandleToUint64(cb_node->commandBuffer)) << "("
849 << HandleToUint64(cb_node->commandBuffer) << "). ";
850 assert(true);
851 } else {
852 strm << std::hex << std::showbase << "Command buffer "
853 << LookupDebugUtilsName(dev_data, HandleToUint64(cb_node->commandBuffer)) << "("
854 << HandleToUint64(cb_node->commandBuffer) << "). "
855 << "Pipeline " << LookupDebugUtilsName(dev_data, HandleToUint64(pipeline_handle)) << "("
856 << HandleToUint64(pipeline_handle) << "). "
857 << "Shader Module " << LookupDebugUtilsName(dev_data, HandleToUint64(shader_module_handle)) << "("
858 << HandleToUint64(shader_module_handle) << "). ";
859 }
860 strm << std::dec << std::noshowbase;
861 strm << "Shader Instruction Index = " << debug_record[kInstCommonOutInstructionIdx] << ". ";
862 msg = strm.str();
863}
864
865// Read the contents of the SPIR-V OpSource instruction and any following continuation instructions.
866// Split the single string into a vector of strings, one for each line, for easier processing.
867static void ReadOpSource(const shader_module &shader, const uint32_t reported_file_id, std::vector<std::string> &opsource_lines) {
868 for (auto insn : shader) {
869 if ((insn.opcode() == spv::OpSource) && (insn.len() >= 5) && (insn.word(3) == reported_file_id)) {
870 std::istringstream in_stream;
871 std::string cur_line;
872 in_stream.str((char *)&insn.word(4));
873 while (std::getline(in_stream, cur_line)) {
874 opsource_lines.push_back(cur_line);
875 }
876 while ((++insn).opcode() == spv::OpSourceContinued) {
877 in_stream.str((char *)&insn.word(1));
878 while (std::getline(in_stream, cur_line)) {
879 opsource_lines.push_back(cur_line);
880 }
881 }
882 break;
883 }
884 }
885}
886
887// Extract the filename, line number, and column number from the correct OpLine and build a message string from it.
888// Scan the source (from OpSource) to find the line of source at the reported line number and place it in another message string.
889static void GenerateSourceMessages(const std::vector<unsigned int> &pgm, const uint32_t *debug_record, std::string &filename_msg,
890 std::string &source_msg) {
891 using namespace spvtools;
892 std::ostringstream filename_stream;
893 std::ostringstream source_stream;
894 shader_module shader;
895 shader.words = pgm;
896 // Find the OpLine just before the failing instruction indicated by the debug info.
897 // SPIR-V can only be iterated in the forward direction due to its opcode/length encoding.
898 uint32_t instruction_index = 0;
899 uint32_t reported_file_id = 0;
900 uint32_t reported_line_number = 0;
901 uint32_t reported_column_number = 0;
902 if (shader.words.size() > 0) {
903 for (auto insn : shader) {
904 if (insn.opcode() == spv::OpLine) {
905 reported_file_id = insn.word(1);
906 reported_line_number = insn.word(2);
907 reported_column_number = insn.word(3);
908 }
909 if (instruction_index == debug_record[kInstCommonOutInstructionIdx]) {
910 break;
911 }
912 instruction_index++;
913 }
914 }
915 // Create message with file information obtained from the OpString pointed to by the discovered OpLine.
916 std::string reported_filename;
917 if (reported_file_id == 0) {
918 filename_stream
919 << "Unable to find SPIR-V OpLine for source information. Build shader with debug info to get source information.";
920 } else {
921 bool found_opstring = false;
922 for (auto insn : shader) {
923 if ((insn.opcode() == spv::OpString) && (insn.len() >= 3) && (insn.word(1) == reported_file_id)) {
924 found_opstring = true;
925 reported_filename = (char *)&insn.word(2);
926 if (reported_filename.empty()) {
927 filename_stream << "Shader validation error occurred at line " << reported_line_number;
928 } else {
929 filename_stream << "Shader validation error occurred in file: " << reported_filename << " at line "
930 << reported_line_number;
931 }
932 if (reported_column_number > 0) {
933 filename_stream << ", column " << reported_column_number;
934 }
935 filename_stream << ".";
936 break;
937 }
938 }
939 if (!found_opstring) {
940 filename_stream << "Unable to find SPIR-V OpString for file id " << reported_file_id << " from OpLine instruction.";
941 }
942 }
943 filename_msg = filename_stream.str();
944
945 // Create message to display source code line containing error.
946 if ((reported_file_id != 0)) {
947 // Read the source code and split it up into separate lines.
948 std::vector<std::string> opsource_lines;
949 ReadOpSource(shader, reported_file_id, opsource_lines);
950 // Find the line in the OpSource content that corresponds to the reported error file and line.
951 if (!opsource_lines.empty()) {
952 // The task here is to search the OpSource content to find the #line directive with the
953 // line number that is closest to, but still prior to the reported error line number and
954 // still within the reported filename.
955 // From this known position in the OpSource content we can add the difference between
956 // the #line line number and the reported error line number to determine the location
957 // in the OpSource content of the reported error line.
958 //
959 // Considerations:
960 // - Look only at #line directives that specify the reported_filename since
961 // the reported error line number refers to its location in the reported filename.
962 // - If a #line directive does not have a filename, the file is the reported filename, or
963 // the filename found in a prior #line directive. (This is C-preprocessor behavior)
964 // - It is possible (e.g., inlining) for blocks of code to get shuffled out of their
965 // original order and the #line directives are used to keep the numbering correct. This
966 // is why we need to examine the entire contents of the source, instead of leaving early
967 // when finding a #line line number larger than the reported error line number.
968 //
969 std::regex line_regex( // matches #line directives
970 "^" // beginning of line
971 "\\s*" // optional whitespace
972 "#" // required text
973 "\\s*" // optional whitespace
974 "line" // required text
975 "\\s+" // required whitespace
976 "([0-9]+)" // required first capture - line number
977 "(\\s+)?" // optional second capture - whitespace
978 "(\".+\")?" // optional third capture - quoted filename with at least one char inside
979 ".*"); // rest of line (needed when using std::regex_match since the entire line is tested)
980 uint32_t saved_line_number = 0;
981 std::string current_filename = reported_filename; // current "preprocessor" filename state.
982 std::vector<std::string>::size_type saved_opsource_offset = 0;
983 bool found_best_line = false;
984 for (auto it = opsource_lines.begin(); it != opsource_lines.end(); ++it) {
985 std::smatch captures;
986 bool found_line = std::regex_match(*it, captures, line_regex);
987 if (!found_line) continue;
988 // filename is optional and considered found only if the whitespace and the filename are captured
989 bool found_filename = captures[2].matched && captures[3].matched;
990 if (found_filename) {
991 // Remove enclosing double quotes. The regex guarantees the quotes and at least one char.
992 current_filename = captures[3].str().substr(1, captures[3].str().size() - 2);
993 }
994 if ((!found_filename) || (current_filename == reported_filename)) {
995 // captures[1] is valid whenever the regex matches, which it has at this point.
996 uint32_t parsed_line_number = std::stoul(captures[1]);
997 // Update the candidate best line directive, if the current one is prior and closer to the reported line
998 if (reported_line_number >= parsed_line_number) {
999 if (!found_best_line ||
1000 (reported_line_number - parsed_line_number <= reported_line_number - saved_line_number)) {
1001 saved_line_number = parsed_line_number;
1002 saved_opsource_offset = std::distance(opsource_lines.begin(), it);
1003 found_best_line = true;
1004 }
1005 }
1006 }
1007 }
1008 if (found_best_line) {
1009 assert(reported_line_number >= saved_line_number);
1010 std::vector<std::string>::size_type opsource_index =
1011 (reported_line_number - saved_line_number) + 1 + saved_opsource_offset;
1012 if (opsource_index < opsource_lines.size()) {
1013 source_stream << "\n" << reported_line_number << ": " << opsource_lines[opsource_index].c_str();
1014 } else {
1015 source_stream << "Internal error: calculated source line of " << opsource_index << " for source size of "
1016 << opsource_lines.size() << " lines.";
1017 }
1018 } else {
1019 source_stream << "Unable to find suitable #line directive in SPIR-V OpSource.";
1020 }
1021 } else {
1022 source_stream << "Unable to find SPIR-V OpSource.";
1023 }
1024 }
1025 source_msg = source_stream.str();
1026}
1027
1028// Pull together all the information from the debug record to build the error message strings,
1029// and then assemble them into a single message string.
1030// Retrieve the shader program referenced by the unique shader ID provided in the debug record.
1031// We had to keep a copy of the shader program with the same lifecycle as the pipeline to make
1032// sure it is available when the pipeline is submitted. (The ShaderModule tracking object also
1033// keeps a copy, but it can be destroyed after the pipeline is created and before it is submitted.)
1034//
1035static void AnalyzeAndReportError(const layer_data *dev_data, GLOBAL_CB_NODE *cb_node, VkQueue queue,
1036 uint32_t *const debug_output_buffer) {
1037 using namespace spvtools;
1038 const uint32_t total_words = debug_output_buffer[0];
1039 // A zero here means that the shader instrumentation didn't write anything.
1040 // If you have nothing to say, don't say it here.
1041 if (0 == total_words) {
1042 return;
1043 }
1044 // The first word in the debug output buffer is the number of words that would have
1045 // been written by the shader instrumentation, if there was enough room in the buffer we provided.
1046 // The number of words actually written by the shaders is determined by the size of the buffer
1047 // we provide via the descriptor. So, we process only the number of words that can fit in the
1048 // buffer.
1049 // Each "report" written by the shader instrumentation is considered a "record". This function
1050 // is hard-coded to process only one record because it expects the buffer to be large enough to
1051 // hold only one record. If there is a desire to process more than one record, this function needs
1052 // to be modified to loop over records and the buffer size increased.
1053 auto gpu_state = GetGpuValidationState(dev_data);
1054 std::string validation_message;
1055 std::string stage_message;
1056 std::string common_message;
1057 std::string filename_message;
1058 std::string source_message;
1059 std::string vuid_msg;
1060 VkShaderModule shader_module_handle = VK_NULL_HANDLE;
1061 VkPipeline pipeline_handle = VK_NULL_HANDLE;
1062 std::vector<unsigned int> pgm;
1063 // The first record starts at this offset after the total_words.
1064 const uint32_t *debug_record = &debug_output_buffer[kDebugOutputDataOffset];
1065 // Lookup the VkShaderModule handle and SPIR-V code used to create the shader, using the unique shader ID value returned
1066 // by the instrumented shader.
1067 auto it = gpu_state->shader_map.find(debug_record[kInstCommonOutShaderId]);
1068 if (it != gpu_state->shader_map.end()) {
1069 shader_module_handle = it->second.shader_module;
1070 pipeline_handle = it->second.pipeline;
1071 pgm = it->second.pgm;
1072 }
1073 GenerateValidationMessage(debug_record, validation_message, vuid_msg);
1074 GenerateStageMessage(debug_record, stage_message);
1075 GenerateCommonMessage(dev_data, cb_node, debug_record, shader_module_handle, pipeline_handle, common_message);
1076 GenerateSourceMessages(pgm, debug_record, filename_message, source_message);
1077 log_msg(GetReportData(dev_data), VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT, HandleToUint64(queue),
1078 vuid_msg.c_str(), "%s %s %s %s%s", validation_message.c_str(), common_message.c_str(), stage_message.c_str(),
1079 filename_message.c_str(), source_message.c_str());
1080 // The debug record at word kInstCommonOutSize is the number of words in the record
1081 // written by the shader. Clear the entire record plus the total_words word at the start.
1082 const uint32_t words_to_clear = 1 + std::min(debug_record[kInstCommonOutSize], (uint32_t)kInstMaxOutCnt);
1083 memset(debug_output_buffer, 0, sizeof(uint32_t) * words_to_clear);
1084}
1085
1086// For the given command buffer, map its debug data buffer and read its contents for analysis.
1087static void ProcessInstrumentationBuffer(const layer_data *dev_data, VkQueue queue, GLOBAL_CB_NODE *cb_node) {
1088 auto gpu_state = GetGpuValidationState(dev_data);
1089 if (cb_node && cb_node->hasDrawCmd && cb_node->gpu_output_memory_block.memory) {
1090 VkResult result;
1091 char *pData;
1092 uint32_t block_offset = cb_node->gpu_output_memory_block.offset;
1093 uint32_t block_size = gpu_state->memory_manager->GetBlockSize();
1094 uint32_t offset_to_data = 0;
1095 const uint32_t map_align =
1096 std::max(1U, static_cast<uint32_t>(GetPhysicalDeviceProperties(dev_data)->limits.minMemoryMapAlignment));
1097
1098 // Adjust the offset to the alignment required for mapping.
1099 block_offset = (block_offset / map_align) * map_align;
1100 offset_to_data = cb_node->gpu_output_memory_block.offset - block_offset;
1101 block_size += offset_to_data;
1102 result = GetDispatchTable(dev_data)->MapMemory(cb_node->device, cb_node->gpu_output_memory_block.memory, block_offset,
1103 block_size, 0, (void **)&pData);
1104 // Analyze debug output buffer
1105 if (result == VK_SUCCESS) {
1106 AnalyzeAndReportError(dev_data, cb_node, queue, (uint32_t *)(pData + offset_to_data));
1107 GetDispatchTable(dev_data)->UnmapMemory(cb_node->device, cb_node->gpu_output_memory_block.memory);
1108 }
1109 }
1110}
1111
1112// Wait for the queue to complete execution. Check the debug buffers for all the
1113// command buffers that were submitted.
1114void GpuPostCallQueueSubmit(const layer_data *dev_data, VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits,
1115 VkFence fence, mutex_t &global_lock) {
1116 auto gpu_state = GetGpuValidationState(dev_data);
1117 if (gpu_state->aborted) return;
1118 core_validation::QueueWaitIdle(queue);
1119 unique_lock_t lock(global_lock);
1120 for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) {
1121 const VkSubmitInfo *submit = &pSubmits[submit_idx];
1122 for (uint32_t i = 0; i < submit->commandBufferCount; i++) {
1123 auto cb_node = GetCBNode(dev_data, submit->pCommandBuffers[i]);
1124 ProcessInstrumentationBuffer(dev_data, queue, cb_node);
1125 for (auto secondaryCmdBuffer : cb_node->linkedCommandBuffers) {
1126 ProcessInstrumentationBuffer(dev_data, queue, secondaryCmdBuffer);
1127 }
1128 }
1129 }
1130}