1 /* Copyright (c) 2015-2017, 2019-2021 The Khronos Group Inc.
2  * Copyright (c) 2015-2017, 2019-2021 Valve Corporation
3  * Copyright (c) 2015-2017, 2019-2021 LunarG, Inc.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * Author: Mark Lobodzinski <mark@lunarg.com>
18  * Author: Courtney Goeltzenleuchter <courtney@LunarG.com>
19  * Author: Dave Houlton <daveh@lunarg.com>
20  */
21 
22 #pragma once
23 
24 #include <cassert>
25 #include <cstddef>
26 #include <functional>
27 #include <stdbool.h>
28 #include <string>
29 #include <vector>
30 #include <iomanip>
31 #include "cast_utils.h"
32 #include "vk_format_utils.h"
33 #include "vk_layer_logging.h"
34 
35 #ifndef WIN32
36 #include <strings.h>  // For ffs()
37 #else
38 #include <intrin.h>  // For __lzcnt()
39 #endif
40 
41 #define STRINGIFY(s) STRINGIFY_HELPER(s)
42 #define STRINGIFY_HELPER(s) #s
43 
44 #ifdef __cplusplus
CastTo3D(const VkExtent2D & d2)45 static inline VkExtent3D CastTo3D(const VkExtent2D &d2) {
46     VkExtent3D d3 = {d2.width, d2.height, 1};
47     return d3;
48 }
49 
CastTo3D(const VkOffset2D & d2)50 static inline VkOffset3D CastTo3D(const VkOffset2D &d2) {
51     VkOffset3D d3 = {d2.x, d2.y, 0};
52     return d3;
53 }
54 
55 // Convert integer API version to a string
StringAPIVersion(uint32_t version)56 static inline std::string StringAPIVersion(uint32_t version) {
57     std::stringstream version_name;
58     uint32_t major = VK_VERSION_MAJOR(version);
59     uint32_t minor = VK_VERSION_MINOR(version);
60     uint32_t patch = VK_VERSION_PATCH(version);
61     version_name << major << "." << minor << "." << patch << " (0x" << std::setfill('0') << std::setw(8) << std::hex << version
62                  << ")";
63     return version_name.str();
64 }
65 
66 // Traits objects to allow string_join to operate on collections of const char *
67 template <typename String>
68 struct StringJoinSizeTrait {
sizeStringJoinSizeTrait69     static size_t size(const String &str) { return str.size(); }
70 };
71 
72 template <>
73 struct StringJoinSizeTrait<const char *> {
74     static size_t size(const char *str) {
75         if (!str) return 0;
76         return strlen(str);
77     }
78 };
79 // Similar to perl/python join
80 //    * String must support size, reserve, append, and be default constructable
81 //    * StringCollection must support size, const forward iteration, and store
82 //      strings compatible with String::append
83 //    * Accessor trait can be set if default accessors (compatible with string
84 //      and const char *) don't support size(StringCollection::value_type &)
85 //
86 // Return type based on sep type
87 template <typename String = std::string, typename StringCollection = std::vector<String>,
88           typename Accessor = StringJoinSizeTrait<typename StringCollection::value_type>>
89 static inline String string_join(const String &sep, const StringCollection &strings) {
90     String joined;
91     const size_t count = strings.size();
92     if (!count) return joined;
93 
94     // Prereserved storage, s.t. we will execute in linear time (avoids reallocation copies)
95     size_t reserve = (count - 1) * sep.size();
96     for (const auto &str : strings) {
97         reserve += Accessor::size(str);  // abstracted to allow const char * type in StringCollection
98     }
99     joined.reserve(reserve + 1);
100 
101     // Seps only occur *between* strings entries, so first is special
102     auto current = strings.cbegin();
103     joined.append(*current);
104     ++current;
105     for (; current != strings.cend(); ++current) {
106         joined.append(sep);
107         joined.append(*current);
108     }
109     return joined;
110 }
111 
112 // Requires StringCollection::value_type has a const char * constructor and is compatible the string_join::String above
113 template <typename StringCollection = std::vector<std::string>, typename SepString = std::string>
114 static inline SepString string_join(const char *sep, const StringCollection &strings) {
115     return string_join<SepString, StringCollection>(SepString(sep), strings);
116 }
117 
118 static inline std::string string_trim(const std::string &s) {
119     const char *whitespace = " \t\f\v\n\r";
120 
121     const auto trimmed_beg = s.find_first_not_of(whitespace);
122     if (trimmed_beg == std::string::npos) return "";
123 
124     const auto trimmed_end = s.find_last_not_of(whitespace);
125     assert(trimmed_end != std::string::npos && trimmed_beg <= trimmed_end);
126 
127     return s.substr(trimmed_beg, trimmed_end - trimmed_beg + 1);
128 }
129 
130 // Perl/Python style join operation for general types using stream semantics
131 // Note: won't be as fast as string_join above, but simpler to use (and code)
132 // Note: Modifiable reference doesn't match the google style but does match std style for stream handling and algorithms
133 template <typename Stream, typename String, typename ForwardIt>
134 Stream &stream_join(Stream &stream, const String &sep, ForwardIt first, ForwardIt last) {
135     if (first != last) {
136         stream << *first;
137         ++first;
138         while (first != last) {
139             stream << sep << *first;
140             ++first;
141         }
142     }
143     return stream;
144 }
145 
146 // stream_join For whole collections with forward iterators
147 template <typename Stream, typename String, typename Collection>
148 Stream &stream_join(Stream &stream, const String &sep, const Collection &values) {
149     return stream_join(stream, sep, values.cbegin(), values.cend());
150 }
151 
152 typedef void *dispatch_key;
153 static inline dispatch_key get_dispatch_key(const void *object) { return (dispatch_key) * (VkLayerDispatchTable **)object; }
154 
155 VK_LAYER_EXPORT VkLayerInstanceCreateInfo *get_chain_info(const VkInstanceCreateInfo *pCreateInfo, VkLayerFunction func);
156 VK_LAYER_EXPORT VkLayerDeviceCreateInfo *get_chain_info(const VkDeviceCreateInfo *pCreateInfo, VkLayerFunction func);
157 
158 static inline bool IsPowerOfTwo(unsigned x) { return x && !(x & (x - 1)); }
159 
160 static inline uint32_t MostSignificantBit(uint32_t mask) {
161     uint32_t highest_view_bit = 0;
162     for (uint32_t k = 0; k < 32; ++k) {
163         if (((mask >> k) & 1) != 0) {
164             highest_view_bit = k;
165         }
166     }
167     return highest_view_bit;
168 }
169 
170 static inline uint32_t SampleCountSize(VkSampleCountFlagBits sample_count) {
171     uint32_t size = 0;
172     switch (sample_count) {
173         case VK_SAMPLE_COUNT_1_BIT:
174             size = 1;
175             break;
176         case VK_SAMPLE_COUNT_2_BIT:
177             size = 2;
178             break;
179         case VK_SAMPLE_COUNT_4_BIT:
180             size = 4;
181             break;
182         case VK_SAMPLE_COUNT_8_BIT:
183             size = 8;
184             break;
185         case VK_SAMPLE_COUNT_16_BIT:
186             size = 16;
187             break;
188         case VK_SAMPLE_COUNT_32_BIT:
189             size = 32;
190             break;
191         case VK_SAMPLE_COUNT_64_BIT:
192             size = 64;
193             break;
194         default:
195             size = 0;
196     }
197     return size;
198 }
199 
200 static inline bool IsIdentitySwizzle(VkComponentMapping components) {
201     // clang-format off
202     return (
203         ((components.r == VK_COMPONENT_SWIZZLE_IDENTITY) || (components.r == VK_COMPONENT_SWIZZLE_R)) &&
204         ((components.g == VK_COMPONENT_SWIZZLE_IDENTITY) || (components.g == VK_COMPONENT_SWIZZLE_G)) &&
205         ((components.b == VK_COMPONENT_SWIZZLE_IDENTITY) || (components.b == VK_COMPONENT_SWIZZLE_B)) &&
206         ((components.a == VK_COMPONENT_SWIZZLE_IDENTITY) || (components.a == VK_COMPONENT_SWIZZLE_A))
207     );
208     // clang-format on
209 }
210 
211 static inline VkDeviceSize GetIndexAlignment(VkIndexType indexType) {
212     switch (indexType) {
213         case VK_INDEX_TYPE_UINT16:
214             return 2;
215         case VK_INDEX_TYPE_UINT32:
216             return 4;
217         case VK_INDEX_TYPE_UINT8_EXT:
218             return 1;
219         default:
220             // Not a real index type. Express no alignment requirement here; we expect upper layer
221             // to have already picked up on the enum being nonsense.
222             return 1;
223     }
224 }
225 
226 static inline uint32_t GetPlaneIndex(VkImageAspectFlags aspect) {
227     // Returns an out of bounds index on error
228     switch (aspect) {
229         case VK_IMAGE_ASPECT_PLANE_0_BIT:
230             return 0;
231             break;
232         case VK_IMAGE_ASPECT_PLANE_1_BIT:
233             return 1;
234             break;
235         case VK_IMAGE_ASPECT_PLANE_2_BIT:
236             return 2;
237             break;
238         default:
239             // If more than one plane bit is set, return error condition
240             return FORMAT_MAX_PLANES;
241             break;
242     }
243 }
244 
245 // Perform a zero-tolerant modulo operation
246 static inline VkDeviceSize SafeModulo(VkDeviceSize dividend, VkDeviceSize divisor) {
247     VkDeviceSize result = 0;
248     if (divisor != 0) {
249         result = dividend % divisor;
250     }
251     return result;
252 }
253 
254 static inline VkDeviceSize SafeDivision(VkDeviceSize dividend, VkDeviceSize divisor) {
255     VkDeviceSize result = 0;
256     if (divisor != 0) {
257         result = dividend / divisor;
258     }
259     return result;
260 }
261 
262 extern "C" {
263 #endif
264 
265 #define VK_LAYER_API_VERSION VK_MAKE_VERSION(1, 0, VK_HEADER_VERSION)
266 
267 typedef enum VkStringErrorFlagBits {
268     VK_STRING_ERROR_NONE = 0x00000000,
269     VK_STRING_ERROR_LENGTH = 0x00000001,
270     VK_STRING_ERROR_BAD_DATA = 0x00000002,
271 } VkStringErrorFlagBits;
272 typedef VkFlags VkStringErrorFlags;
273 
274 VK_LAYER_EXPORT void layer_debug_report_actions(debug_report_data *report_data, const VkAllocationCallbacks *pAllocator,
275                                                 const char *layer_identifier);
276 
277 VK_LAYER_EXPORT void layer_debug_messenger_actions(debug_report_data *report_data, const VkAllocationCallbacks *pAllocator,
278                                                    const char *layer_identifier);
279 
280 VK_LAYER_EXPORT VkStringErrorFlags vk_string_validate(const int max_length, const char *char_array);
281 VK_LAYER_EXPORT bool white_list(const char *item, const std::set<std::string> &whitelist);
282 
283 static inline int u_ffs(int val) {
284 #ifdef WIN32
285     unsigned long bit_pos = 0;
286     if (_BitScanForward(&bit_pos, val) != 0) {
287         bit_pos += 1;
288     }
289     return bit_pos;
290 #else
291     return ffs(val);
292 #endif
293 }
294 
295 #ifdef __cplusplus
296 }
297 #endif
298 
299 #ifdef __cplusplus
300 // clang sets _MSC_VER to 1800 and _MSC_FULL_VER to 180000000, but we only want to clean up after MSVC.
301 #if defined(_MSC_FULL_VER) && !defined(__clang__)
302 // Minimum Visual Studio 2015 Update 2, or libc++ with C++17
303 // But, before Visual Studio 2017 version 15.7, __cplusplus is not set
304 // correctly. See:
305 //   https://docs.microsoft.com/en-us/cpp/build/reference/zc-cplusplus?view=msvc-160
306 // Also, according to commit e2a6c442cb1e4, SDKs older than NTDDI_WIN10_RS2 do not
307 // support shared_mutex.
308 #if _MSC_FULL_VER >= 190023918 && NTDDI_VERSION > NTDDI_WIN10_RS2 && (!defined(_LIBCPP_VERSION) || __cplusplus >= 201703)
309 #define VVL_USE_SHARED_MUTEX 1
310 #endif
311 #elif __cplusplus >= 201703
312 #define VVL_USE_SHARED_MUTEX 1
313 #elif __cplusplus >= 201402
314 #define VVL_USE_SHARED_TIMED_MUTEX 1
315 #endif
316 
317 #if defined(VVL_USE_SHARED_MUTEX) || defined(VVL_USE_SHARED_TIMED_MUTEX)
318 #include <shared_mutex>
319 #endif
320 
321 class ReadWriteLock {
322   private:
323 #if defined(VVL_USE_SHARED_MUTEX)
324     typedef std::shared_mutex Lock;
325 #elif defined(VVL_USE_SHARED_TIMED_MUTEX)
326     typedef std::shared_timed_mutex Lock;
327 #else
328     typedef std::mutex Lock;
329 #endif
330 
331   public:
332     void lock() { m_lock.lock(); }
333     bool try_lock() { return m_lock.try_lock(); }
334     void unlock() { m_lock.unlock(); }
335 #if defined(VVL_USE_SHARED_MUTEX) || defined(VVL_USE_SHARED_TIMED_MUTEX)
336     void lock_shared() { m_lock.lock_shared(); }
337     bool try_lock_shared() { return m_lock.try_lock_shared(); }
338     void unlock_shared() { m_lock.unlock_shared(); }
339 #else
340     void lock_shared() { lock(); }
341     bool try_lock_shared() { return try_lock(); }
342     void unlock_shared() { unlock(); }
343 #endif
344   private:
345     Lock m_lock;
346 };
347 
348 #if defined(VVL_USE_SHARED_MUTEX) || defined(VVL_USE_SHARED_TIMED_MUTEX)
349 typedef std::shared_lock<ReadWriteLock> ReadLockGuard;
350 #else
351 typedef std::unique_lock<ReadWriteLock> ReadLockGuard;
352 #endif
353 typedef std::unique_lock<ReadWriteLock> WriteLockGuard;
354 
355 // Limited concurrent_unordered_map that supports internally-synchronized
356 // insert/erase/access. Splits locking across N buckets and uses shared_mutex
357 // for read/write locking. Iterators are not supported. The following
358 // operations are supported:
359 //
360 // insert_or_assign: Insert a new element or update an existing element.
361 // insert: Insert a new element and return whether it was inserted.
362 // erase: Remove an element.
363 // contains: Returns true if the key is in the map.
364 // find: Returns != end() if found, value is in ret->second.
365 // pop: Erases and returns the erased value if found.
366 //
367 // find/end: find returns a vaguely iterator-like type that can be compared to
368 // end and can use iter->second to retrieve the reference. This is to ease porting
369 // for existing code that combines the existence check and lookup in a single
370 // operation (and thus a single lock). i.e.:
371 //
372 //      auto iter = map.find(key);
373 //      if (iter != map.end()) {
374 //          T t = iter->second;
375 //          ...
376 //
377 // snapshot: Return an array of elements (key, value pairs) that satisfy an optional
378 // predicate. This can be used as a substitute for iterators in exceptional cases.
379 template <typename Key, typename T, int BUCKETSLOG2 = 2, typename Hash = layer_data::hash<Key>>
380 class vl_concurrent_unordered_map {
381   public:
382     void insert_or_assign(const Key &key, const T &value) {
383         uint32_t h = ConcurrentMapHashObject(key);
384         WriteLockGuard lock(locks[h].lock);
385         maps[h][key] = value;
386     }
387 
388     bool insert(const Key &key, const T &value) {
389         uint32_t h = ConcurrentMapHashObject(key);
390         WriteLockGuard lock(locks[h].lock);
391         auto ret = maps[h].emplace(key, value);
392         return ret.second;
393     }
394 
395     // returns size_type
396     size_t erase(const Key &key) {
397         uint32_t h = ConcurrentMapHashObject(key);
398         WriteLockGuard lock(locks[h].lock);
399         return maps[h].erase(key);
400     }
401 
402     bool contains(const Key &key) const {
403         uint32_t h = ConcurrentMapHashObject(key);
404         ReadLockGuard lock(locks[h].lock);
405         return maps[h].count(key) != 0;
406     }
407 
408     // type returned by find() and end().
409     class FindResult {
410       public:
411         FindResult(bool a, T b) : result(a, std::move(b)) {}
412 
413         // == and != only support comparing against end()
414         bool operator==(const FindResult &other) const {
415             if (result.first == false && other.result.first == false) {
416                 return true;
417             }
418             return false;
419         }
420         bool operator!=(const FindResult &other) const { return !(*this == other); }
421 
422         // Make -> act kind of like an iterator.
423         std::pair<bool, T> *operator->() { return &result; }
424         const std::pair<bool, T> *operator->() const { return &result; }
425 
426       private:
427         // (found, reference to element)
428         std::pair<bool, T> result;
429     };
430 
431     // find()/end() return a FindResult containing a copy of the value. For end(),
432     // return a default value.
433     FindResult end() const { return FindResult(false, T()); }
434 
435     FindResult find(const Key &key) const {
436         uint32_t h = ConcurrentMapHashObject(key);
437         ReadLockGuard lock(locks[h].lock);
438 
439         auto itr = maps[h].find(key);
440         bool found = itr != maps[h].end();
441 
442         if (found) {
443             return FindResult(true, itr->second);
444         } else {
445             return end();
446         }
447     }
448 
449     FindResult pop(const Key &key) {
450         uint32_t h = ConcurrentMapHashObject(key);
451         WriteLockGuard lock(locks[h].lock);
452 
453         auto itr = maps[h].find(key);
454         bool found = itr != maps[h].end();
455 
456         if (found) {
457             auto ret = std::move(FindResult(true, itr->second));
458             maps[h].erase(itr);
459             return ret;
460         } else {
461             return end();
462         }
463     }
464 
465     std::vector<std::pair<const Key, T>> snapshot(std::function<bool(T)> f = nullptr) const {
466         std::vector<std::pair<const Key, T>> ret;
467         for (int h = 0; h < BUCKETS; ++h) {
468             ReadLockGuard lock(locks[h].lock);
469             for (const auto &j : maps[h]) {
470                 if (!f || f(j.second)) {
471                     ret.emplace_back(j.first, j.second);
472                 }
473             }
474         }
475         return ret;
476     }
477 
478   private:
479     static const int BUCKETS = (1 << BUCKETSLOG2);
480 
481     layer_data::unordered_map<Key, T, Hash> maps[BUCKETS];
482     struct {
483         mutable ReadWriteLock lock;
484         // Put each lock on its own cache line to avoid false cache line sharing.
485         char padding[(-int(sizeof(ReadWriteLock))) & 63];
486     } locks[BUCKETS];
487 
488     uint32_t ConcurrentMapHashObject(const Key &object) const {
489         uint64_t u64 = (uint64_t)(uintptr_t)object;
490         uint32_t hash = (uint32_t)(u64 >> 32) + (uint32_t)u64;
491         hash ^= (hash >> BUCKETSLOG2) ^ (hash >> (2 * BUCKETSLOG2));
492         hash &= (BUCKETS - 1);
493         return hash;
494     }
495 };
496 #endif
497