1 /*
2  *
3  * Copyright (c) 2015-2018 The Khronos Group Inc.
4  * Copyright (c) 2015-2018 Valve Corporation
5  * Copyright (c) 2015-2018 LunarG, Inc.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * Author: Ian Elliot <ian@lunarg.com>
20  * Author: Jon Ashburn <jon@lunarg.com>
21  * Author: Lenny Komow <lenny@lunarg.com>
22  *
23  */
24 #pragma once
25 
26 #if defined(_WIN32)
27 // WinSock2.h must be included *BEFORE* windows.h
28 #include <winsock2.h>
29 #endif  // _WIN32
30 
31 #if defined(__Fuchsia__)
32 #include "dlopen_fuchsia.h"
33 #endif  // defined(__Fuchsia__)
34 
35 #include "vulkan/vk_platform.h"
36 #include "vulkan/vk_sdk_platform.h"
37 
38 #if defined(__linux__) || defined(__APPLE__) || defined(__Fuchsia__) || defined(__FreeBSD__) || \
39   defined(__DragonFly__)
40 /* Linux-specific common code: */
41 
42 // Headers:
43 //#ifndef _GNU_SOURCE
44 //#define _GNU_SOURCE 1
45 //#endif
46 #include <unistd.h>
47 // Note: The following file is for dynamic loading:
48 #include <dlfcn.h>
49 #include <pthread.h>
50 #include <assert.h>
51 #include <string.h>
52 #include <stdbool.h>
53 #include <stdlib.h>
54 #include <libgen.h>
55 
56 // VK Library Filenames, Paths, etc.:
57 #define PATH_SEPARATOR ':'
58 #define DIRECTORY_SYMBOL '/'
59 
60 #define VULKAN_DIR "vulkan/"
61 #define VULKAN_ICDCONF_DIR "icd.d"
62 #define VULKAN_ICD_DIR "icd"
63 #define VULKAN_SETTINGSCONF_DIR "settings.d"
64 #define VULKAN_ELAYERCONF_DIR "explicit_layer.d"
65 #define VULKAN_ILAYERCONF_DIR "implicit_layer.d"
66 #define VULKAN_LAYER_DIR "layer"
67 
68 #define VK_DRIVERS_INFO_RELATIVE_DIR VULKAN_DIR VULKAN_ICDCONF_DIR
69 #define VK_SETTINGS_INFO_RELATIVE_DIR VULKAN_DIR VULKAN_SETTINGSCONF_DIR
70 #define VK_ELAYERS_INFO_RELATIVE_DIR VULKAN_DIR VULKAN_ELAYERCONF_DIR
71 #define VK_ILAYERS_INFO_RELATIVE_DIR VULKAN_DIR VULKAN_ILAYERCONF_DIR
72 
73 #define VK_DRIVERS_INFO_REGISTRY_LOC ""
74 #define VK_SETTINGS_INFO_REGISTRY_LOC ""
75 #define VK_ELAYERS_INFO_REGISTRY_LOC ""
76 #define VK_ILAYERS_INFO_REGISTRY_LOC ""
77 
78 #if !defined(DEFAULT_VK_LAYERS_PATH)
79 #define DEFAULT_VK_LAYERS_PATH ""
80 #endif
81 #if !defined(LAYERS_SOURCE_PATH)
82 #define LAYERS_SOURCE_PATH NULL
83 #endif
84 #define LAYERS_PATH_ENV "VK_LAYER_PATH"
85 #define ENABLED_LAYERS_ENV "VK_INSTANCE_LAYERS"
86 
87 // C99:
88 #define PRINTF_SIZE_T_SPECIFIER "%zu"
89 
90 // File IO
loader_platform_file_exists(const char * path)91 static inline bool loader_platform_file_exists(const char *path) {
92     if (access(path, F_OK))
93         return false;
94     else
95         return true;
96 }
97 
loader_platform_is_path_absolute(const char * path)98 static inline bool loader_platform_is_path_absolute(const char *path) {
99     if (path[0] == '/')
100         return true;
101     else
102         return false;
103 }
104 
loader_platform_dirname(char * path)105 static inline char *loader_platform_dirname(char *path) { return dirname(path); }
106 
107 #if defined(__linux__)
108 
109 // find application path + name. Path cannot be longer than 1024, returns NULL if it is greater than that.
loader_platform_executable_path(char * buffer,size_t size)110 static inline char *loader_platform_executable_path(char *buffer, size_t size) {
111     ssize_t count = readlink("/proc/self/exe", buffer, size);
112     if (count == -1) return NULL;
113     if (count == 0) return NULL;
114     buffer[count] = '\0';
115     return buffer;
116 }
117 #elif defined(__APPLE__)  // defined(__linux__)
118 #include <libproc.h>
loader_platform_executable_path(char * buffer,size_t size)119 static inline char *loader_platform_executable_path(char *buffer, size_t size) {
120     pid_t pid = getpid();
121     int ret = proc_pidpath(pid, buffer, size);
122     if (ret <= 0) return NULL;
123     buffer[ret] = '\0';
124     return buffer;
125 }
126 #elif defined(__Fuchsia__)
loader_platform_executable_path(char * buffer,size_t size)127 static inline char *loader_platform_executable_path(char *buffer, size_t size) { return NULL; }
128 #endif  // defined (__APPLE__)
129 
130 // Compatability with compilers that don't support __has_feature
131 #ifndef __has_feature
132 #define __has_feature(x) 0
133 #endif
134 
135 #if __has_feature(address_sanitizer) || defined(__SANITIZE_ADDRESS__)
136 #define LOADER_ADDRESS_SANITIZER
137 #endif
138 
139 // Dynamic Loading of libraries:
140 typedef void *loader_platform_dl_handle;
141 // When loading the library, we use RTLD_LAZY so that not all symbols have to be
142 // resolved at this time (which improves performance). Note that if not all symbols
143 // can be resolved, this could cause crashes later. Use the LD_BIND_NOW environment
144 // variable to force all symbols to be resolved here.
145 #define LOADER_DLOPEN_MODE (RTLD_LAZY | RTLD_LOCAL)
146 
147 #if defined(__Fuchsia__)
loader_platform_open_driver(const char * libPath)148 static inline loader_platform_dl_handle loader_platform_open_driver(const char *libPath) {
149     return dlopen_fuchsia(libPath, LOADER_DLOPEN_MODE, true);
150 }
loader_platform_open_library(const char * libPath)151 static inline loader_platform_dl_handle loader_platform_open_library(const char *libPath) {
152     return dlopen_fuchsia(libPath, LOADER_DLOPEN_MODE, false);
153 }
154 #else
loader_platform_open_library(const char * libPath)155 static inline loader_platform_dl_handle loader_platform_open_library(const char *libPath) {
156     return dlopen(libPath, LOADER_DLOPEN_MODE);
157 }
158 #endif
159 
loader_platform_open_library_error(const char * libPath)160 static inline const char *loader_platform_open_library_error(const char *libPath) {
161 #ifdef __Fuchsia__
162     return dlerror_fuchsia();
163 #else
164     return dlerror();
165 #endif
166 }
loader_platform_close_library(loader_platform_dl_handle library)167 static inline void loader_platform_close_library(loader_platform_dl_handle library) { dlclose(library); }
loader_platform_get_proc_address(loader_platform_dl_handle library,const char * name)168 static inline void *loader_platform_get_proc_address(loader_platform_dl_handle library, const char *name) {
169     assert(library);
170     assert(name);
171     return dlsym(library, name);
172 }
loader_platform_get_proc_address_error(const char * name)173 static inline const char *loader_platform_get_proc_address_error(const char *name) { return dlerror(); }
174 
175 // Threads:
176 typedef pthread_t loader_platform_thread;
177 #define THREAD_LOCAL_DECL __thread
178 
179 // The once init functionality is not used on Linux
180 #define LOADER_PLATFORM_THREAD_ONCE_DECLARATION(var)
181 #define LOADER_PLATFORM_THREAD_ONCE_DEFINITION(var)
182 #define LOADER_PLATFORM_THREAD_ONCE(ctl, func)
183 
184 // Thread IDs:
185 typedef pthread_t loader_platform_thread_id;
loader_platform_get_thread_id()186 static inline loader_platform_thread_id loader_platform_get_thread_id() { return pthread_self(); }
187 
188 // Thread mutex:
189 typedef pthread_mutex_t loader_platform_thread_mutex;
loader_platform_thread_create_mutex(loader_platform_thread_mutex * pMutex)190 static inline void loader_platform_thread_create_mutex(loader_platform_thread_mutex *pMutex) { pthread_mutex_init(pMutex, NULL); }
loader_platform_thread_lock_mutex(loader_platform_thread_mutex * pMutex)191 static inline void loader_platform_thread_lock_mutex(loader_platform_thread_mutex *pMutex) { pthread_mutex_lock(pMutex); }
loader_platform_thread_unlock_mutex(loader_platform_thread_mutex * pMutex)192 static inline void loader_platform_thread_unlock_mutex(loader_platform_thread_mutex *pMutex) { pthread_mutex_unlock(pMutex); }
loader_platform_thread_delete_mutex(loader_platform_thread_mutex * pMutex)193 static inline void loader_platform_thread_delete_mutex(loader_platform_thread_mutex *pMutex) { pthread_mutex_destroy(pMutex); }
194 typedef pthread_cond_t loader_platform_thread_cond;
loader_platform_thread_init_cond(loader_platform_thread_cond * pCond)195 static inline void loader_platform_thread_init_cond(loader_platform_thread_cond *pCond) { pthread_cond_init(pCond, NULL); }
loader_platform_thread_cond_wait(loader_platform_thread_cond * pCond,loader_platform_thread_mutex * pMutex)196 static inline void loader_platform_thread_cond_wait(loader_platform_thread_cond *pCond, loader_platform_thread_mutex *pMutex) {
197     pthread_cond_wait(pCond, pMutex);
198 }
loader_platform_thread_cond_broadcast(loader_platform_thread_cond * pCond)199 static inline void loader_platform_thread_cond_broadcast(loader_platform_thread_cond *pCond) { pthread_cond_broadcast(pCond); }
200 
201 #define loader_stack_alloc(size) alloca(size)
202 
203 #elif defined(_WIN32)  // defined(__linux__)
204 /* Windows-specific common code: */
205 // WinBase.h defines CreateSemaphore and synchapi.h defines CreateEvent
206 //  undefine them to avoid conflicts with VkLayerDispatchTable struct members.
207 #ifdef CreateSemaphore
208 #undef CreateSemaphore
209 #endif
210 #ifdef CreateEvent
211 #undef CreateEvent
212 #endif
213 #include <assert.h>
214 #include <stdio.h>
215 #include <string.h>
216 #include <io.h>
217 #include <stdbool.h>
218 #include <shlwapi.h>
219 #include <direct.h>
220 #ifdef __cplusplus
221 #include <iostream>
222 #include <string>
223 #endif  // __cplusplus
224 
225 // VK Library Filenames, Paths, etc.:
226 #define PATH_SEPARATOR ';'
227 #define DIRECTORY_SYMBOL '\\'
228 #define DEFAULT_VK_REGISTRY_HIVE HKEY_LOCAL_MACHINE
229 #define DEFAULT_VK_REGISTRY_HIVE_STR "HKEY_LOCAL_MACHINE"
230 #define SECONDARY_VK_REGISTRY_HIVE HKEY_CURRENT_USER
231 #define SECONDARY_VK_REGISTRY_HIVE_STR "HKEY_CURRENT_USER"
232 
233 #define VK_DRIVERS_INFO_RELATIVE_DIR ""
234 #define VK_SETTINGS_INFO_RELATIVE_DIR ""
235 #define VK_ELAYERS_INFO_RELATIVE_DIR ""
236 #define VK_ILAYERS_INFO_RELATIVE_DIR ""
237 
238 #ifdef _WIN64
239 #define HKR_VK_DRIVER_NAME API_NAME "DriverName"
240 #else
241 #define HKR_VK_DRIVER_NAME API_NAME "DriverNameWow"
242 #endif
243 #define VK_DRIVERS_INFO_REGISTRY_LOC "SOFTWARE\\Khronos\\" API_NAME "\\Drivers"
244 #define VK_SETTINGS_INFO_REGISTRY_LOC "SOFTWARE\\Khronos\\" API_NAME "\\Settings"
245 #define VK_ELAYERS_INFO_REGISTRY_LOC "SOFTWARE\\Khronos\\" API_NAME "\\ExplicitLayers"
246 #define VK_ILAYERS_INFO_REGISTRY_LOC "SOFTWARE\\Khronos\\" API_NAME "\\ImplicitLayers"
247 
248 #if !defined(DEFAULT_VK_LAYERS_PATH)
249 #define DEFAULT_VK_LAYERS_PATH ""
250 #endif
251 #if !defined(LAYERS_SOURCE_PATH)
252 #define LAYERS_SOURCE_PATH NULL
253 #endif
254 #define LAYERS_PATH_ENV "VK_LAYER_PATH"
255 #define ENABLED_LAYERS_ENV "VK_INSTANCE_LAYERS"
256 
257 #define PRINTF_SIZE_T_SPECIFIER "%Iu"
258 
259 #if defined(_WIN32)
260 // Get the key for the plug n play driver registry
261 // The string returned by this function should NOT be freed
LoaderPnpDriverRegistry()262 static inline const char *LoaderPnpDriverRegistry() {
263     BOOL is_wow;
264     IsWow64Process(GetCurrentProcess(), &is_wow);
265     return is_wow ? "VulkanDriverNameWow" : "VulkanDriverName";
266 }
LoaderPnpDriverRegistryWide()267 static inline const wchar_t *LoaderPnpDriverRegistryWide() {
268     BOOL is_wow;
269     IsWow64Process(GetCurrentProcess(), &is_wow);
270     return is_wow ? L"VulkanDriverNameWow" : L"VulkanDriverName";
271 }
272 
273 // Get the key for the plug 'n play explicit layer registry
274 // The string returned by this function should NOT be freed
LoaderPnpELayerRegistry()275 static inline const char *LoaderPnpELayerRegistry() {
276     BOOL is_wow;
277     IsWow64Process(GetCurrentProcess(), &is_wow);
278     return is_wow ? "VulkanExplicitLayersWow" : "VulkanExplicitLayers";
279 }
LoaderPnpELayerRegistryWide()280 static inline const wchar_t *LoaderPnpELayerRegistryWide() {
281     BOOL is_wow;
282     IsWow64Process(GetCurrentProcess(), &is_wow);
283     return is_wow ? L"VulkanExplicitLayersWow" : L"VulkanExplicitLayers";
284 }
285 
286 // Get the key for the plug 'n play implicit layer registry
287 // The string returned by this function should NOT be freed
LoaderPnpILayerRegistry()288 static inline const char *LoaderPnpILayerRegistry() {
289     BOOL is_wow;
290     IsWow64Process(GetCurrentProcess(), &is_wow);
291     return is_wow ? "VulkanImplicitLayersWow" : "VulkanImplicitLayers";
292 }
LoaderPnpILayerRegistryWide()293 static inline const wchar_t *LoaderPnpILayerRegistryWide() {
294     BOOL is_wow;
295     IsWow64Process(GetCurrentProcess(), &is_wow);
296     return is_wow ? L"VulkanImplicitLayersWow" : L"VulkanImplicitLayers";
297 }
298 #endif
299 
300 // File IO
loader_platform_file_exists(const char * path)301 static bool loader_platform_file_exists(const char *path) {
302     if ((_access(path, 0)) == -1)
303         return false;
304     else
305         return true;
306 }
307 
loader_platform_is_path_absolute(const char * path)308 static bool loader_platform_is_path_absolute(const char *path) {
309     if (!path || !*path) {
310         return false;
311     }
312     if (*path == DIRECTORY_SYMBOL || path[1] == ':') {
313         return true;
314     }
315     return false;
316 }
317 
318 // WIN32 runtime doesn't have dirname().
loader_platform_dirname(char * path)319 static inline char *loader_platform_dirname(char *path) {
320     char *current, *next;
321 
322     // TODO/TBD: Do we need to deal with the Windows's ":" character?
323 
324     for (current = path; *current != '\0'; current = next) {
325         next = strchr(current, DIRECTORY_SYMBOL);
326         if (next == NULL) {
327             if (current != path) *(current - 1) = '\0';
328             return path;
329         } else {
330             // Point one character past the DIRECTORY_SYMBOL:
331             next++;
332         }
333     }
334     return path;
335 }
336 
loader_platform_executable_path(char * buffer,size_t size)337 static inline char *loader_platform_executable_path(char *buffer, size_t size) {
338     DWORD ret = GetModuleFileName(NULL, buffer, (DWORD)size);
339     if (ret == 0) return NULL;
340     if (ret > size) return NULL;
341     buffer[ret] = '\0';
342     return buffer;
343 }
344 
345 // Dynamic Loading:
346 typedef HMODULE loader_platform_dl_handle;
loader_platform_open_library(const char * lib_path)347 static loader_platform_dl_handle loader_platform_open_library(const char *lib_path) {
348     // Try loading the library the original way first.
349     loader_platform_dl_handle lib_handle = LoadLibrary(lib_path);
350     if (lib_handle == NULL && GetLastError() == ERROR_MOD_NOT_FOUND) {
351         // If that failed, then try loading it with broader search folders.
352         lib_handle = LoadLibraryEx(lib_path, NULL, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR);
353     }
354     return lib_handle;
355 }
loader_platform_open_library_error(const char * libPath)356 static char *loader_platform_open_library_error(const char *libPath) {
357     static char errorMsg[164];
358     (void)snprintf(errorMsg, 163, "Failed to open dynamic library \"%s\" with error %lu", libPath, GetLastError());
359     return errorMsg;
360 }
loader_platform_close_library(loader_platform_dl_handle library)361 static void loader_platform_close_library(loader_platform_dl_handle library) { FreeLibrary(library); }
loader_platform_get_proc_address(loader_platform_dl_handle library,const char * name)362 static void *loader_platform_get_proc_address(loader_platform_dl_handle library, const char *name) {
363     assert(library);
364     assert(name);
365     return (void *)GetProcAddress(library, name);
366 }
loader_platform_get_proc_address_error(const char * name)367 static char *loader_platform_get_proc_address_error(const char *name) {
368     static char errorMsg[120];
369     (void)snprintf(errorMsg, 119, "Failed to find function \"%s\" in dynamic library", name);
370     return errorMsg;
371 }
372 
373 // Threads:
374 typedef HANDLE loader_platform_thread;
375 
376 // __declspec(thread) is not supported by MinGW compiler (ignored with warning or
377 //                    cause error depending on compiler switches)
378 //
379 // __thread should be used instead
380 //
381 // __MINGW32__ defined for both 32 and 64 bit MinGW compilers, so it is enough to
382 // detect any (32 or 64) flavor of MinGW compiler.
383 //
384 // @note __GNUC__ could be used as a more generic way to detect _any_
385 //       GCC[-compatible] compiler on Windows, but this fix was tested
386 //       only with MinGW, so keep it explicit at the moment.
387 #if defined(__MINGW32__)
388 #define THREAD_LOCAL_DECL __thread
389 #else
390 #define THREAD_LOCAL_DECL __declspec(thread)
391 #endif
392 
393 // The once init functionality is not used when building a DLL on Windows. This is because there is no way to clean up the
394 // resources allocated by anything allocated by once init. This isn't a problem for static libraries, but it is for dynamic
395 // ones. When building a DLL, we use DllMain() instead to allow properly cleaning up resources.
396 #define LOADER_PLATFORM_THREAD_ONCE_DECLARATION(var)
397 #define LOADER_PLATFORM_THREAD_ONCE_DEFINITION(var)
398 #define LOADER_PLATFORM_THREAD_ONCE(ctl, func)
399 
400 // Thread IDs:
401 typedef DWORD loader_platform_thread_id;
loader_platform_get_thread_id()402 static loader_platform_thread_id loader_platform_get_thread_id() { return GetCurrentThreadId(); }
403 
404 // Thread mutex:
405 typedef CRITICAL_SECTION loader_platform_thread_mutex;
loader_platform_thread_create_mutex(loader_platform_thread_mutex * pMutex)406 static void loader_platform_thread_create_mutex(loader_platform_thread_mutex *pMutex) { InitializeCriticalSection(pMutex); }
loader_platform_thread_lock_mutex(loader_platform_thread_mutex * pMutex)407 static void loader_platform_thread_lock_mutex(loader_platform_thread_mutex *pMutex) { EnterCriticalSection(pMutex); }
loader_platform_thread_unlock_mutex(loader_platform_thread_mutex * pMutex)408 static void loader_platform_thread_unlock_mutex(loader_platform_thread_mutex *pMutex) { LeaveCriticalSection(pMutex); }
loader_platform_thread_delete_mutex(loader_platform_thread_mutex * pMutex)409 static void loader_platform_thread_delete_mutex(loader_platform_thread_mutex *pMutex) { DeleteCriticalSection(pMutex); }
410 typedef CONDITION_VARIABLE loader_platform_thread_cond;
loader_platform_thread_init_cond(loader_platform_thread_cond * pCond)411 static void loader_platform_thread_init_cond(loader_platform_thread_cond *pCond) { InitializeConditionVariable(pCond); }
loader_platform_thread_cond_wait(loader_platform_thread_cond * pCond,loader_platform_thread_mutex * pMutex)412 static void loader_platform_thread_cond_wait(loader_platform_thread_cond *pCond, loader_platform_thread_mutex *pMutex) {
413     SleepConditionVariableCS(pCond, pMutex, INFINITE);
414 }
loader_platform_thread_cond_broadcast(loader_platform_thread_cond * pCond)415 static void loader_platform_thread_cond_broadcast(loader_platform_thread_cond *pCond) { WakeAllConditionVariable(pCond); }
416 
417 #define loader_stack_alloc(size) _alloca(size)
418 #else  // defined(_WIN32)
419 
420 #error The "loader_platform.h" file must be modified for this OS.
421 
422 // NOTE: In order to support another OS, an #elif needs to be added (above the
423 // "#else // defined(_WIN32)") for that OS, and OS-specific versions of the
424 // contents of this file must be created.
425 
426 // NOTE: Other OS-specific changes are also needed for this OS.  Search for
427 // files with "WIN32" in it, as a quick way to find files that must be changed.
428 
429 #endif  // defined(_WIN32)
430 
431 // returns true if the given string appears to be a relative or absolute
432 // path, as opposed to a bare filename.
loader_platform_is_path(const char * path)433 static inline bool loader_platform_is_path(const char *path) { return strchr(path, DIRECTORY_SYMBOL) != NULL; }
434