1# Vulkan Loader Specification and Architecture Overview
2
3<br/>
4
5## Goals of this document ##
6
7Specify necessary functions and expected behavior of interface between the
8loader library and ICDs and layers for Windows, Linux and Android based
9systems. Also describe the application visible behaviors of the loader.
10
11<br/>
12
13## Audience ##
14
15This document is primarily targeted at Vulkan application, driver and layer developers.
16However, it can also be used by any developer interested in understanding more about
17how the Vulkan loader and layers interact.
18
19<br/>
20
21
22## Loader goals ##
23
24-   Support multiple ICDs (Installable Client Drivers) to co-exist on a system
25without interfering with each other.
26
27-   Support optional modules (layers) that can be enabled by an application,
28developer or the system and have no impact when not enabled.
29
30-   Negligible performance cost for an application calling through the loader
31to an ICD entry point.
32
33<br/>
34
35## Architectural overview of layers and loader ##
36
37Vulkan is a layered architecture placing the Application on one end, the
38ICDs on the other, and the loader and some number of layers in between.
39
40Layers are implemented as libraries that can be enabled in different ways
41(including by application request) and loaded during CreateInstance.  Each
42layer can chooses to hook (intercept) any Vulkan commands which in turn
43can be ignored, augmented, or simply passed along.  A layer may also
44expose functionality not available in the loader or any ICD.  Some examples
45of this include: the ability to perform Vulkan API tracing and debugging,
46validate API usage, or overlay additional content on the applications surfaces.
47
48The loader is responsible for working with the various layers as well as
49supporting multiple GPUs and their drivers.  Any Vulkan command may
50wind up calling into a diverse set of modules: loader, layers, and ICDs.
51The loader is critical to managing the proper dispatching of Vulkan
52commands to the appropriate set of layers and ICDs. The Vulkan object
53model allows the loader to insert layers into a call chain so that the layers
54can process Vulkan commands prior to the ICD being called.
55
56Vulkan uses an object model to control the scope of a particular action /
57operation.  The object to be acted on is always the first parameter of a Vulkan
58call and is a dispatchable object (see Vulkan specification section 2.3 Object
59Model).  Under the covers, the dispatchable object handle is a pointer to a
60structure, which in turn, contains a pointer to a dispatch table maintained by
61the loader.  This dispatch table contains pointers to the Vulkan functions appropriate to
62that object.
63
64There are two types of dispatch tables the loader maintains:
65-  **Instance Dispatch Table**
66  - Contains any function that takes a VkInstance or VkPhysicalDevice as their first parameter
67    - vkEnumeratePhysicalDevices
68    - vkDestroyInstance
69    - vkCreateInstance
70    - ...
71-  **Device Dispatch Table**
72  - Contains any function that takes a VkDevice, VkQueue or VkCommandBuffer as their first parameter
73
74These instance and device dispatch tables are constructed when the application
75calls vkCreateInstance and vkCreateDevice. At that time the application and/or
76system can specify optional layers to be included. The loader will initialize
77the specified layers to create a call chain for each Vulkan function and each
78entry of the dispatch table will point to the first element of that chain.
79Thus, the loader builds an instance call chain for each VkInstance that is
80created and a device call chain for each VkDevice that is created.
81
82For example, the diagram below represents what happens in the call chain for
83vkCreateInstance. After initializing the chain, the loader will call into the
84first layer's vkCreateInstance which will call the next finally terminating in
85the loader again where this function calls every ICD's vkCreateInstance and
86saves the results. This allows every enabled layer for this chain to set up
87what it needs based on the VkInstanceCreateInfo structure from the application.
88![Instance call chain](instance_call_chain.png)
89
90This also highlights some of the complexity the loader must manage when using
91instance chains. As shown here, the loader must aggregate information from
92multiple devices when they are present. This means that the loader has to know
93about instance level extensions to aggregate them correctly.
94
95Device chains are created at vkCreateDevice and are generally simpler because
96they deal with only a single device and the ICD can always be the terminator of
97the chain. The below diagram also illustrates how layers (either device or
98instance) can skip intercepting any given Vulkan entry point.
99![Chain skipping layers](chain_skipping_layers.png)
100
101<br/>
102
103## Application interface to loader ##
104
105In this section we'll discuss how an application interacts with the loader.
106
107-   Linking to loader library for core and WSI extension symbols.
108
109-   Dynamic Vulkan command lookup & application dispatch table.
110
111-   Loader library filenames for linking to different Vulkan ABI versions.
112
113-   Layers
114
115-   Extensions
116
117-   vkGetInstanceProcAddr, vkGetDeviceProcAddr
118
119The loader library on Windows, Linux and Android will export all core Vulkan
120and all appropriate Window System Interface (WSI) extensions. This is done to
121make it simpler to get started with Vulkan development. When an application
122links directly to the loader library in this way, the Vulkan calls are simple
123trampoline functions that jump to the appropriate dispatch table entry for the
124object they are given.
125
126Applications are not required to link directly to the loader library, instead
127they can use the appropriate platform specific dynamic symbol lookup on the
128loader library to initialize the application's own dispatch table. This allows
129an application to fail gracefully if the loader cannot be found, and it
130provides the fastest mechanism for the application to call Vulkan functions. An
131application will only need to query (via system calls such as dlsym()) the
132address of vkGetInstanceProcAddr from the loader library. Using
133vkGetInstanceProcAddr the application can then discover the address of all
134instance and global functions and extensions, such as vkCreateInstance,
135vkEnumerateInstanceExtensionProperties and vkEnumerateInstanceLayerProperties
136in a platform independent way.
137
138The Vulkan loader library will be distributed in various ways including Vulkan
139SDKs, OS package distributions and IHV driver packages. These details are
140beyond the scope of this document. However, the name and versioning of the
141Vulkan loader library is specified so an app can link to the correct Vulkan ABI
142library version. Vulkan versioning is such that ABI backwards compatibility is
143guaranteed for all versions with the same major number (e.g. 1.0 and 1.1). On
144Windows, the loader library encodes the ABI version in its name such that
145multiple ABI incompatible versions of the loader can peacefully coexist on a
146given system. The Vulkan loader library file name is "vulkan-<ABI
147version>.dll". For example, for Vulkan version 1.X on Windows the library
148filename is vulkan-1.dll. And this library file can typically be found in the
149windows/system32 directory (on 64-bit Windows installs, the 32-bit version of
150the loader with the same name can be found in the windows/sysWOW64 directory).
151
152For Linux, shared libraries are versioned based on a suffix. Thus, the ABI
153number is not encoded in the base of the library filename as on Windows. On
154Linux an application wanting to link to the latest Vulkan ABI version would
155just link to the name vulkan (libvulkan.so).  A specific Vulkan ABI version can
156also be linked to by applications (e.g. libvulkan.so.1).
157
158#### Layer Usage
159
160Applications desiring Vulkan functionality beyond what the core API offers may
161use various layers or extensions. A layer cannot introduce new Vulkan API
162entry-points not exposed in Vulkan.h, but may offer extensions that do. A
163common use of layers is for API validation which can be enabled by loading the
164layer during application development, but not loading the layer for application
165release. This eliminates the overhead of validating the application's
166usage of the API, something that wasn't available on some previous graphics
167APIs.
168
169Layers discovered by the loader are reported to the application via
170vkEnumerateInstanceLayerProperties.  Layers are enabled at vkCreateInstance
171and are active for all Vulkan commands using the given VkInstance and any
172of it's child objects.  For example, the ppEnabledLayerNames array in the
173VkInstanceCreateInfo structure is used by the application to list the layer
174names to be enabled at vkCreateInstance. At vkCreateInstance and
175vkCreateDevice, the loader will construct call chains that include the application
176specified (enabled) layers.  Order is important in the
177ppEnabledLayerNames array; array element 0 is the topmost (closest to the
178application) layer inserted in the chain and the last array element is closest
179to the driver.
180
181**NOTE**: vkCreateDevice originally was able to select layers in a
182similar manner to vkCreateInstance.  This lead to the concept of "instance
183layers" and "device layers".  It was decided by Khronos to deprecate the
184"device layer" functionality and only consider "instance layers".
185Therefore, vkCreateDevice will use the layers specified at vkCreateInstance.
186Additionally, vkEnumerateDeviceLayerProperties has been deprecated.  
187
188Developers may want to enable layers that are not enabled by the given
189application they are using. On Linux and Windows, the environment variable
190"VK\_INSTANCE\_LAYERS" can be used to enable
191additional layers which are not specified (enabled) by the application at
192vkCreateInstance. VK\_INSTANCE\_LAYERS is a colon
193(Linux)/semi-colon (Windows) separated list of layer names to enable. Order is
194relevant with the first layer in the list being the topmost layer (closest to
195the application) and the last layer in the list being the bottommost layer
196(closest to the driver).
197
198Application specified layers and user specified layers (via environment
199variables) are aggregated and duplicates removed by the loader when enabling
200layers. Layers specified via environment variable are topmost (closest to the
201application) while layers specified by the application are bottommost.
202
203An example of using these environment variables to activate the validation
204layer VK\_LAYER\_LUNARG\_parameter\_validation on Windows or Linux is as follows:
205
206```
207> $ export VK_INSTANCE_LAYERS=VK_LAYER_LUNARG_parameter_validation
208
209```
210
211#### Implicit vs Explicit Layers
212
213Some platforms, including Linux and Windows, support layers which are enabled
214automatically by the loader rather than explicitly by the application (or via
215environment variable). Explicit layers are those layers enabled by the
216application (or environment variable) by providing the layer name. Implicit
217layers are those layers enabled by the loader automatically. Any implicit
218layers the loader discovers on the system in the appropriate location will be
219enabled (subject to environment variable overrides described later). Discovery
220of properly installed implicit and explicit layers is described later.
221Explicitly enabling a layer that is implicitly enabled has no additional
222effect: the layer will still be enabled implicitly by the loader.
223
224Implicit layers have an additional requirement over explicit layers in that they
225require being able to be disabled by an environmental variable.  This is due
226to the fact that they are not visible to the application and could cause issues.
227A good principle to keep in mind would be to define both an enable and disable
228environment variable so the users can deterministicly enable the functionality.
229On Desktop platforms (Windows and Linux), these enable/disable settings are
230defined in the layer's JSON file.
231
232Extensions are optional functionality provided by a layer, the loader or an
233ICD. Extensions can modify the behavior of the Vulkan API and need to be
234specified and registered with Khronos.
235
236#### Instance/Device Extensions
237
238Instance extensions can be discovered via
239vkEnumerateInstanceExtensionProperties. Device extensions can be discovered via
240vkEnumerateDeviceExtensionProperties. The loader discovers and aggregates all
241extensions from layers (both explicit and implicit), ICDs and the loader before
242reporting them to the application in vkEnumerate\*ExtensionProperties. The
243pLayerName parameter in these functions is used to select either a single layer
244or the Vulkan platform implementation. If pLayerName is NULL, extensions from
245Vulkan implementation components (including loader, implicit layers, and ICDs)
246are enumerated. If pLayerName is equal to a discovered layer module name then
247any extensions from that layer (which may be implicit or explicit) are
248enumerated. Duplicate extensions (e.g. an implicit layer and ICD might report
249support for the same extension) are eliminated by the loader. For duplicates, the
250ICD version is reported and the layer version is culled. Extensions must
251be enabled (in vkCreateInstance or vkCreateDevice) before they can be used.
252
253Extension command entry points should be queried via vkGetInstanceProcAddr or
254vkGetDeviceProcAddr. vkGetDeviceProcAddr can only be used to query for device
255extension or core device entry points. Device entry points include any command
256that uses a VkDevice as the first parameter or a dispatchable object that is a
257child of a VkDevice (currently this includes VkQueue and VkCommandBuffer).
258vkGetInstanceProcAddr can be used to query either device or instance extension
259entry points in addition to all core entry points.
260
261VkGetDeviceProcAddr is particularly interesting because it will provide the
262most efficient way to call into the ICD. For example, the diagram below shows
263what could happen if the application were to use vkGetDeviceProcAddr for the
264function "vkGetDeviceQueue" and "vkDestroyDevice" but not "vkAllocateMemory".
265The resulting function pointer (fpGetDeviceQueue) would be the ICD's entry
266point if the loader and any enabled layers do not need to see that call. Even
267if an enabled layer intercepts the call (e.g. vkDestroyDevice) the loader
268trampoline code is skipped for function pointers obtained via
269vkGetDeviceProcAddr. This also means that function pointers obtained via
270vkGetDeviceProcAddr will only work with the specific VkDevice it was created
271for, using it with another device has undefined results. For extensions,
272Get\*ProcAddr will often be the only way to access extension API features.
273
274![Get*ProcAddr efficiency](get_proc_addr.png)
275
276##### WSI Extensions
277
278Khronos approved WSI extensions are available and provide Windows System Integration
279support for various execution environments. It is important to understand that some WSI
280extensions are valid for all targets, but others are particular to a given execution
281environment (and loader). This desktop loader (currently targeting Windows and Linux)
282only enables those WSI extensions that are appropriate to the current environment.
283For the most part, the selection is done in the loader using  compile-time preprocessor
284flags. All versions of the desktop loader currently expose at least the following WSI
285extension support:
286- VK_KHR_surface
287- VK_KHR_swapchain
288- VK_KHR_display
289
290In addition, each of the following OS targets for the loader support target-specific extensions:
291- **Windows** : VK_KHR_win32_surface
292- **Linux (default)** : VK_KHR_xcb_surface and VK_KHR_xlib_surface
293- **Linux (Wayland build)** : VK_KHR_wayland_surface
294- **Linux (Mir build)** : VK_KHR_mir_surface
295
296**NOTE:** Wayland and Mir targets are not fully supported at this time and should be considered
297alpha quality.
298
299It is important to understand that while the loader may support the various entry-points
300for these extensions, there is a hand-shake required to actually use them:
301* At least one physical device must support the extension(s)
302* The application must select such a physical device
303* The application must request the extension(s) be enabled while creating the instance or logical device (This depends on whether or not the given extension works with an instance or a device).
304* The instance and/or logical device creation must succeed.
305
306Only then can you expect to properly use a WSI extension in your Vulkan program.
307
308##### New Extensions
309
310With the ability to expand Vulkan so easily, extensions will be created that the loader knows
311nothing about.  If the extension is a device extension, the loader will pass the unknown
312entry-point down the device call chain ending with the appropriate ICD entry-points.
313However, if the extension is an instance extension, the loader will fail to load it.
314
315*But why doesn't the loader support unknown instance extensions?*
316<br/>
317Let's look again at the Instance call chain:
318![Instance call chain](instance_call_chain.png)
319
320Notice that for a normal instance function call, the loader has to handle passing along the
321function call to the available ICDs.  If the loader has no idea of the parameters or return
322value of the instance call, it can't properly pass information along to the ICDs.
323There may be ways to do this, which will be explored in the future.  However, for now, this
324loader does not support any unknown instance extensions.
325
326Because the device call-chain does not pass through the loader terminator, this is not
327a problem for device extensions.  Instead, device extensions terminate directly in the
328ICD they are associated with.
329
330*Is this a big problem?*
331<br/>
332No!  Most extension functionality only affects a device and not an instance or a physical
333device.  Thus, the overwhelming majority of extensions will be device extensions rather than
334instance extensions.
335
336
337## Vulkan Installable Client Driver interface with the loader ##
338
339### ICD discovery
340
341Vulkan allows multiple drivers each with one or more devices (represented by a
342Vulkan VkPhysicalDevice object) to be used collectively. The loader is
343responsible for discovering available Vulkan ICDs on the system. Given a list
344of available ICDs, the loader can enumerate all the physical devices available
345for an application and return this information to the application. The process
346in which the loader discovers the available Installable Client Drivers (ICDs)
347on a system is platform dependent. Windows, Linux and Android ICD discovery
348details are listed below.
349
350#### Windows
351
352##### Properly-Installed ICDs
353
354In order to find properly-installed ICDs, the Vulkan loader will scan the
355values in the following Windows registry key:
356
357HKEY\_LOCAL\_MACHINE\\SOFTWARE\\Khronos\\Vulkan\\Drivers
358
359On 64-bit Windows, when a 32-bit application is triggered, the loader
360will scan for 32-bit drivers in a separate area of the registry:
361
362HKEY\_LOCAL\_MACHINE\\SOFTWARE\\WOW6432Node\\Khronos\\Vulkan\\Drivers
363
364For each value in this key which has DWORD data set to 0, the loader opens the
365JSON format text information file (a.k.a. "manifest file") specified by the
366name of the value. Each name must be a full pathname to the text manifest file.
367The Vulkan loader will open each manifest file to obtain the name or pathname
368of an ICD shared library (".dll") file. For example:
369
370 ```
371 {
372    "file_format_version": "1.0.0",
373    "ICD": {
374        "library_path": "path to ICD library",
375        "api_version": "1.0.5"
376    }
377  }
378  ```
379
380
381The "library\_path" specifies either a filename, a relative pathname, or a full
382pathname to an ICD shared library file, which the loader will attempt to load
383using LoadLibrary(). If the ICD is specified via a filename, the shared library
384lives in the system's DLL search path (e.g. in the "C:\Windows\System32"
385folder). If the ICD is specified via a relative pathname, it is relative to the
386path of the manifest file. Relative pathnames are those that do not start with
387a drive specifier (e.g. "C:"), nor with a directory separator (i.e. the '\\'
388character), but do contain at least one directory separator.
389
390The "file\_format\_version" specifies a major.minor.patch version number in
391case the format of the text information file changes in the future. If the same
392ICD shared library supports multiple, incompatible versions of text manifest
393file format versions, it must have separate JSON files for each (all of which may
394point to the same shared library).
395
396The "api\_version" specifies the major.minor.patch version number of the Vulkan
397API that the shared library (referenced by "library\_path") was built with.
398
399There are no rules about the name of the text information files (except the
400.json suffix).
401
402There are no rules about the name of the ICD shared library files. For example,
403if the registry contains the following values,
404
405```
406[HKEY_LOCAL_MACHINE\SOFTWARE\Khronos\Vulkan\Drivers\]
407
408"C:\vendor a\vk_vendora.json"=dword:00000000
409
410"C:\windows\system32\vendorb_vk.json"=dword:00000000
411
412"C:\windows\system32\vendorc_icd.json"=dword:00000000
413```
414then the loader will open the following text information files, with the
415specified contents:
416
417| Text File Name | Text File Contents |
418|----------------|--------------------|
419|vk\_vendora.json  | "ICD": { "library\_path": "C:\VENDOR A\vk_vendora.dll", "api_version": "1.0.5" } |
420| vendorb\_vk.json |  "ICD": { "library\_path": "vendorb\_vk.dll", "api_version": "1.0.5" } |
421|vendorc\_icd.json  | "ICD": { "library\_path": "vedorc\_icd.dll", "api_version": "1.0.5" }|
422
423Then the loader will open the three files mentioned in the "Text File Contents"
424column, and then try to load and use the three shared libraries indicated by
425the ICD.library\_path value.
426
427##### Using Pre-Production ICDs
428
429IHV developers (and sometimes other developers) need to use special,
430pre-production ICDs. In some cases, a pre-production ICD may be in an
431installable package. In other cases, a pre-production ICD may simply be a
432shared library in the developer's build tree. In this latter case, we want to
433allow developers to point to such an ICD without modifying the
434properly-installed ICD(s) on their system.
435
436This need is met with the use of the "VK\_ICD\_FILENAMES" environment variable,
437which will override the mechanism used for finding properly-installed ICDs. In
438other words, only the ICDs listed in "VK\_ICD\_FILENAMES" will be used. The
439"VK\_ICD\_FILENAMES" environment variable is a semi-colon-separated list of ICD
440text information files (aka manifest files), containing the following:
441
442- A full pathname (e.g. "C:\\my\_build\\my\_icd.json")
443
444Typically, "VK\_ICD\_FILENAMES" will only contain a full pathname to one info
445file for a developer-built ICD. A semi-colon is only used if more than one ICD
446is listed.
447
448For example, if a developer wants to refer to one ICD that they built, they
449could set the "VK\_ICD\_FILENAMES" environment variable to:
450
451C:\\my\_build\\my\_icd.json
452
453If a developer wants to refer to two ICDs, one of which is a properly-installed
454ICD, they can use the full pathname of the text file:
455
456C:\\Windows\\System32\\vendorc\_icd.json;C:\\my\_build\\my\_icd.json
457
458Notice the semi-colon between "C:\\Windows\\System32\\vendorc\_icd.json" and
459"C:\\my\_build\\my\_icd.json".
460
461#### Linux
462
463##### Properly-Installed ICDs
464
465In order to find properly-installed ICDs, the Vulkan loader will scan the files
466in the following Linux directories:
467
468/usr/share/vulkan/icd.d
469/etc/vulkan/icd.d
470$HOME/.local/share/vulkan/icd.d
471
472Where $HOME is the current home directory of the application's user id; this
473path will be ignored for suid programs.
474
475These directories will contain text information files (a.k.a. "manifest
476files"), that use a JSON format.
477
478The Vulkan loader will open each manifest file found to obtain the name or
479pathname of an ICD shared library (".so") file. For example:
480
481```
482{
483    "file_format_version": "1.0.0",
484    "ICD": {
485        "library_path": "path to ICD library",
486        "api_version": "1.0.5"
487    }
488}
489```
490The "library\_path" specifies either a filename, a relative pathname, or a full
491pathname to an ICD shared library file. If the ICD is specified via a filename,
492the loader will attempt to open that file as a shared object using dlopen(),
493and the file must be in a directory that dlopen is configured to look in (Note:
494various distributions are configured differently). A distribution is free to
495create Vulkan-specific system directories (e.g. ".../vulkan/icd"), but is not
496required to do so. If the ICD is specified via a relative pathname, it is
497relative to the path of the info file. Relative pathnames are those that do not
498start with, but do contain at least one directory separator (i.e. the '/'
499character). For example, "lib/vendora.so" and "./vendora.so" are examples of
500relative pathnames.
501
502The "file\_format\_version" provides a major.minor.patch version number in case
503the format of the manifest file changes in the future. If the same ICD shared
504library supports multiple, incompatible versions of manifest file format
505versions, it must have multiple manifest files (all of which may point to the
506same shared library).
507
508The "api\_version" specifies the major.minor.patch version number of the Vulkan
509API that the shared library (referenced by "library\_path") was built with.
510
511The "/usr/share/vulkan/icd.d" directory is for ICDs that are installed from
512Linux-distribution-provided packages. The "/etc/vulkan/icd.d" directory is for
513ICDs that are installed from non-Linux-distribution-provided packages.
514
515There are no rules about the name of the text files (except the .json suffix).
516
517There are no rules about the name of the ICD shared library files. For example,
518if the "/usr/share/vulkan/icd.d" directory contain the following files, with
519the specified contents:
520
521| Text File Name    | Text File Contents     |
522|-------------------|------------------------|
523| vk\_vendora.json | "ICD": { "library\_path": "vendora.so", "api_version": "1.0.5" } |
524| vendorb\_vk.json | "ICD": { "library\_path": "vendorb\_vulkan\_icd.so", "api_version": "1.0.5" } |
525| vendorc\_icd.json | "ICD": { "library\_path": "/usr/lib/VENDORC/icd.so", "api_version": "1.0.5" } |
526
527then the loader will open the three files mentioned in the "Text File Contents"
528column, and then try to load and use the three shared libraries indicated by
529the ICD.library\_path value.
530
531##### Using Pre-Production ICDs
532
533IHV developers (and sometimes other developers) need to use special,
534pre-production ICDs. In some cases, a pre-production ICD may be in an
535installable package. In other cases, a pre-production ICD may simply be a
536shared library in the developer's build tree. In this latter case, we want to
537allow developers to point to such an ICD without modifying the
538properly-installed ICD(s) on their system.
539
540This need is met with the use of the "VK\_ICD\_FILENAMES" environment variable,
541which will override the mechanism used for finding properly-installed ICDs. In
542other words, only the ICDs listed in "VK\_ICD\_FILENAMES" will be used.
543
544The "VK\_ICD\_FILENAMES" environment variable is a colon-separated list of ICD
545manifest files, containing the following:
546
547- A filename (e.g. "libvkicd.json") in the "/usr/share/vulkan/icd.d", "/etc/vulkan/icd.d" "$HOME/.local/share/vulkan/icd.d" directories
548
549- A full pathname (e.g. "/my\_build/my\_icd.json")
550
551Typically, "VK\_ICD\_FILENAMES" will only contain a full pathname to one info
552file for a developer-built ICD. A colon is only used if more than one ICD is
553listed.
554
555For example, if a developer wants to refer to one ICD that they built, they
556could set the "VK\_ICD\_FILENAMES" environment variable to:
557
558/my\_build/my\_icd.json
559
560If a developer wants to refer to two ICDs, one of which is a properly-installed
561ICD, they can use the name of the text file in the system directory:
562
563vendorc\_vulkan.json:/my\_build/my\_icd.json
564
565Notice the colon between "vendorc\_vulkan.json" and "/my\_build/my\_icd.json".
566
567NOTE: this environment variable will be ignored for suid programs.
568
569#### Android
570
571The Android loader lives in the system library folder. The location cannot be
572changed. The loader will load the driver/ICD via hw_get_module with the ID
573of "vulkan". Due to security policies in Android none of this can be modified
574under normal use.
575
576<br/>
577
578## ICD interface requirements ##
579
580Generally, for all Vulkan commands issued by an application, the loader can be
581viewed as a pass through. That is, the loader generally doesn't modify the
582commands or their parameters, but simply calls the ICDs entry point for that
583command. There are specific additional interface requirements an ICD needs to comply with that
584are over and above any requirements from the Vulkan specification including WSI extension specification.
585These addtional requirements are versioned to allow flexibility in the future.
586These interface requirements will be set forth in the following sections: 1) describing
587which "loader-ICD" interface version is available, 2) detailing the most recent interface version;
5883) the supported, older interface requirements will be described as differences
589from the most recent interface version.
590
591#### Windows and Linux
592
593##### Version Negotiation Between Loader and ICDs
594
595All ICDs (supporting interface version 2 or higher) must export the following
596function that is used for determination of the interface version that will be used.
597This entry point is not a part of the Vulkan API itself, only a private interface
598between the loader and ICDs.
599
600VKAPI_ATTR VkResult VKAPI_CALL vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion);
601
602This entry point reports the "loader-ICD" interface version supported by both the loader and the ICD.
603The loader informs the ICD of it's desired interface version (typically the latest) via the
604pSupportedVersion parameter.
605This call is the first call made by the loader into the ICD  (prior to any calls to
606vk\_icdGetInstanceProcAddr).
607
608If a loader sees that an ICD does not export this symbol it knows that it's dealing
609with a legacy ICD supporting either interface version 0 or 1.
610Similarly, if an ICD sees a call to vk\_icdGetInstanceProcAddr before a call to
611vk_icdGetLoaderICDInterfaceVersion then it knows that it's dealing with a legacy loader
612supporting version 0 or 1.
613**Note** if the loader calls vk\_icdGetInstanceProcAddr first it supports at least version 1,
614otherwise the loader only supports version 0.
615
616The pSupportedVersion parameter is both an input and output parameter.
617It is filled in by the loader before the call with the desired latest interface version supported by the loader.
618
619If the ICD receiving the call no longer supports the interface version provided
620by the loader (due to deprecation) then it can report VK_ERROR_INCOMPATIBLE_DRIVER error,
621otherwise it sets the value pointed by pSupportedVersion to the latest interface
622version supported by both the ICD and the loader and returns VK_SUCCESS.
623The ICD should report VK_SUCCESS in case the loader provided interface version
624is newer than that supported by the ICD, as it's the loader's responsibility to
625determine whether it can support the older interface version supported by the ICD.
626The ICD should also report VK_SUCCESS in the case it's interface version is greater
627than the loader's, but return the loader's version. Thus, upon return of VK_SUCCESS
628the pSupportedVersion will contain the desired interface version to be used by the ICD.
629
630If the loader receives back an interface version from the ICD that the loader no longer
631supports (due to deprecation) or it receives a VK_ERROR_INCOMPATIBLE_DRIVER error
632instead of VK_SUCCESS then the loader will treat the ICD as incompatible
633and will not load it for use.  In this case the application will not see the ICDs vkPhysicalDevice
634during enumeration.
635
636##### Loader Version 3 Interface Changes
637
638The primary change occuring in version 3 of the loader/ICD interface is to allow an ICD to
639handle Creation/Destruction of their own KHR_surfaces.  Up until this point, the loader created
640a surface object that was used by all ICDs.  However, some ICDs may want to provide their
641own surface handles.  If an ICD chooses to enable this support, they must export support for
642version 3 of the Loader/ICD interface as well as any Vulkan command that uses a KHR_surface handle,
643such as:
644- vkCreateXXXSurfaceKHR (where XXX is the platform specific identifier [i.e.CreateWin32SurfaceKHR for Windows])
645- vkDestroySurfaceKHR
646- vkCreateSwapchainKHR
647- vkGetPhysicalDeviceSurfaceSupportKHR
648- vkGetPhysicalDeviceSurfaceCapabilitiesKHR
649- vkGetPhysicalDeviceSurfaceFormatsKHR
650- vkGetPhysicalDeviceSurfacePresentModesKHR
651
652An ICD can still choose to not take advantage of this functionality by simply not exposing the
653above the vkCreateXXXSurfaceKHR and vkDestroySurfaceKHR commands.
654
655##### Loader Version 2 Interface Requirements
656
657Version 2 interface has requirements in three areas:
658 1. ICD Vulkan entry point discovery,
659 2. KHR_surface related requirements in the WSI extensions,
660 3. Vulkan dispatchable object creation requirements.
661
662######  ICD Vulkan entry point discovery
663All ICDs must export the following function that is used for discovery of ICD Vulkan entry points.
664This entry point is not a part of the Vulkan API itself, only a private interface between the loader and ICDs for version 1 and higher interfaces.
665
666VKAPI\_ATTR PFN\_vkVoidFunction VKAPI\_CALL vk\_icdGetInstanceProcAddr(VkInstance instance, const char* pName);
667
668This function has very similar semantics to the Vulkan command vkGetInstanceProcAddr.
669vk\_icdGetInstanceProcAddr returns valid function pointers for all the global level
670and instance level Vulkan commands, and also for vkGetDeviceProcAddr.
671Global level commands are those
672which contain no dispatchable object as the first parameter, such as
673vkCreateInstance and vkEnumerateInstanceExtensionProperties. The ICD must
674support querying global level entry points by calling
675vk\_icdGetInstanceProcAddr with a NULL VkInstance parameter. Instance level
676commands are those that have either VkInstance, or VkPhysicalDevice as the
677first parameter dispatchable object. Both core entry points and any instance
678extension entry points the ICD supports should be available via
679vk\_icdGetInstanceProcAddr. Future Vulkan instance extensions may define and
680use new instance level dispatchable objects other than VkInstance and
681VkPhysicalDevice, in which case extension entry points using these newly
682defined dispatchable objects must be queryable via vk\_icdGetInstanceProcAddr.
683
684All other Vulkan entry points must either NOT be exported from the ICD
685library or else NOT use the official Vulkan function names if they are
686exported. This requirement is for ICD libraries that include other
687functionality (such as OpenGL library) and thus could be loaded by the
688application prior to when the Vulkan loader library is loaded by the
689application. In other words, the ICD library exported Vulkan symbols must not
690clash with the loader's exported Vulkan symbols.
691
692Beware of interposing by dynamic OS library loaders if the official Vulkan
693names are used. On Linux, if official names are used, the ICD library must be
694linked with -Bsymbolic.
695
696###### Handling KHR_surface objects in the WSI extensions
697Normally, ICDs handle object creation and destruction for various Vulkan
698objects. The WSI surface extensions for Linux and Windows
699(VK\_KHR\_win32\_surface, VK\_KHR\_xcb\_surface, VK\_KHR\_xlib\_surface,
700VK\_KHR\_mir\_surface, VK\_KHR\_wayland\_surface, and VK\_KHR\_surface) are
701handled differently. For these extensions, the VkSurfaceKHR object creation and
702destruction is handled by the loader as follows:
703
7041. Loader handles the vkCreate\*SurfaceKHR() and vkDestroySurfaceKHR()
705   functions including creating/destroying the VkSurfaceKHR object.
706
7072. VkSurfaceKHR objects have the underlying structure (VkIcdSurface\*) as
708   defined in include/vulkan/vk\_icd.h.
709
7103. ICDs can cast any VkSurfaceKHR object to a pointer to the appropriate
711   VkIcdSurface\* structure.
712
7134. VkIcdSurface\* structures include VkIcdSurfaceWin32, VkIcdSurfaceXcb,
714   VkIcdSurfaceXlib, VkIcdSurfaceMir, and VkIcdSurfaceWayland. The first field
715   in the structure is a VkIcdSurfaceBase enumerant that indicates whether the
716   surface object is Win32, Xcb, Xlib, Mir, or Wayland.
717
718###### ICD dispatchable object creation
719As previously covered, the loader requires dispatch tables to be accessible
720within Vulkan dispatchable objects, which include VkInstance, VkPhysicalDevice,
721VkDevice, VkQueue, and VkCommandBuffer. The specific requirements on all
722dispatchable objects created by ICDs are as follows:
723
724- All dispatchable objects created by an ICD can be cast to void \*\*
725
726- The loader will replace the first entry with a pointer to the dispatch table
727  which is owned by the loader. This implies three things for ICD drivers:
728
7291. The ICD must return a pointer for the opaque dispatchable object handle.
730
7312. This pointer points to a regular C structure with the first entry being a
732   pointer. Note: for any C\++ ICD's that implement VK objects directly as C\++
733   classes. The C\++ compiler may put a vtable at offset zero if your class is
734   non-POD due to the use of a virtual function. In this case use a regular C
735   structure (see below).
736
7373. The loader checks for a magic value (ICD\_LOADER\_MAGIC) in all the created
738   dispatchable objects, as follows (see include/vulkan/vk\_icd.h):
739
740```
741
742#include "vk_icd.h"
743
744union _VK_LOADER_DATA {
745    uintptr loadermagic;
746    void *loaderData;
747} VK_LOADER_DATA;
748
749vkObj alloc_icd_obj()
750{
751    vkObj *newObj = alloc_obj();
752    ...
753    // Initialize pointer to loader's dispatch table with ICD_LOADER_MAGIC
754
755    set_loader_magic_value(newObj);
756    ...
757    return newObj;
758}
759```
760
761##### Loader Version 0 and 1 Interface Differences
762
763Version 0 and 1 interfaces do not support version negotiation via vk\_icdNegotiateLoaderICDInterfaceVersion.
764ICDs can distinguish version 0 and version 1 interfaces as follows:
765if the loader calls vk\_icdGetInstanceProcAddr first it supports version 1,
766otherwise the loader only supports version 0.
767
768Version 0 interface does not support vk\_icdGetInstanceProcAddr.  Version 0 interface requirements for
769obtaining ICD Vulkan entry points are as follows:
770
771- vkGetInstanceProcAddr exported in the ICD library and returns valid function
772  pointers for all the Vulkan API entry points;
773
774- vkCreateInstance exported in the ICD library;
775
776- vkEnumerateInstanceExtensionProperties exported in the ICD library;
777
778
779Additional Notes:
780
781- The loader will filter out extensions requested in vkCreateInstance and
782vkCreateDevice before calling into the ICD; Filtering will be of extensions
783advertised by entities (e.g. layers) different from the ICD in question.
784- The loader will not call the ICD for vkEnumerate\*LayerProperties() as layer
785properties are obtained from the layer libraries and layer JSON files.
786- If an ICD library wants to implement a layer it can do so by having the
787appropriate layer JSON manifest file refer to the ICD library file.
788- The loader will not call the ICD for
789  vkEnumerate\*ExtensionProperties(pLayerName != NULL).
790- ICDs creating new dispatchable objects via device extensions need to initialize
791the created dispatchable object.  The loader has generic trampoline code for unknown
792device extensions.  This generic trampoline code doesn't initialize the dispatch table within
793the newly created object.  See the section for more information on how to initialize created
794dispatchable objects for extensions non known by the loader. [layer link](#creating-new-dispatchable-objects)
795
796#### Android
797
798The Android loader uses the same protocol for initializing the dispatch
799table as described above. The only difference is that the Android
800loader queries layer and extension information directly from the
801respective libraries and does not use the json manifest files used
802by the Windows and Linux loaders.
803
804<br/>
805
806## Vulkan layer interface with the loader ##
807
808### Layer discovery
809
810#### Windows
811
812<a name="ManifestFileExample"></a>
813##### Properly-Installed Layers
814
815In order to find properly-installed layers, the Vulkan loader will use a
816similar mechanism as used for ICDs. Text information files (aka manifest
817files), that use a JSON format, are read in order to identify the names and
818attributes of layers and their extensions. The use of manifest files allows the
819loader to avoid loading any shared library files when the application does not
820query nor request any extensions. Layers and extensions have additional
821complexity, and so their manifest files contain more information than ICD info
822files. For example, a layer shared library file may contain multiple
823layers/extensions (perhaps even an ICD).
824
825In order to find properly-installed layers, the Vulkan loader will scan the
826values in the following Windows registry keys:
827
828HKEY\_LOCAL\_MACHINE\\SOFTWARE\\Khronos\\Vulkan\\ExplicitLayers
829
830HKEY\_LOCAL\_MACHINE\\SOFTWARE\\Khronos\\Vulkan\\ImplicitLayers
831
832Explicit layers are those which are enabled by an application (e.g. with the
833vkCreateInstance function), or by an environment variable (as mentioned
834previously).
835
836Implicit layers are those which are enabled by their existence. For example,
837certain application environments (e.g. Steam or an automotive infotainment
838system) may have layers which they always want enabled for all applications
839that they start. Other implicit layers may be for all applications started on a
840given system (e.g. layers that overlay frames-per-second). Implicit layers are
841enabled automatically, whereas explicit layers must be enabled explicitly. What
842distinguishes a layer as implicit or explicit is by which registry key its
843layer information file is referenced by.
844
845For each value in these keys which has DWORD data set to 0, the loader opens
846the JSON manifest file specified by the name of the value. Each name must be a
847full pathname to the manifest file.
848
849The Vulkan loader will open each info file to obtain information about the
850layer, including the name or pathname of a shared library (".dll") file.
851
852This manifest file is in the JSON format as shown in the following example.
853See the section [Layer Library Manifest File](#LayerLibraryManifestFile) for more information about each of the nodes in the JSON file.
854
855```
856{
857   "file_format_version" : "1.0.0",
858   "layer": {
859       "name": "VK_LAYER_LUNARG_overlay",
860       "type": "INSTANCE",
861       "library_path": "vkOverlayLayer.dll"
862       "api_version" : "1.0.5",
863       "implementation_version" : "2",
864       "description" : "LunarG HUD layer",
865       "functions": {
866           "vkGetInstanceProcAddr": "OverlayLayer_GetInstanceProcAddr",
867           "vkGetDeviceProcAddr": "OverlayLayer_GetDeviceProcAddr"
868       },
869       "instance_extensions": [
870           {
871               "name": "VK_EXT_debug_report",
872               "spec_version": "1"
873           },
874           {
875               "name": "VK_VENDOR_ext_x",
876               "spec_version": "3"
877            }
878       ],
879       "device_extensions": [
880           {
881               "name": "VK_EXT_debug_marker",
882               "spec_version": "1",
883               "entrypoints": ["vkCmdDbgMarkerBegin", "vkCmdDbgMarkerEnd"]
884           }
885       ],
886       "enable_environment": {
887           "ENABLE_LAYER_OVERLAY_1": "1"
888       }
889       "disable_environment": {
890           "DISABLE_LAYER_OVERLAY_1": ""
891       }
892   }
893}
894```
895
896The "library\_path" specifies either a filename, a relative pathname, or a full
897pathname to a layer shared library (".dll") file, which the loader will attempt
898to load using LoadLibrary(). If the layer is specified via a relative pathname,
899it is relative to the path of the info file (e.g. for cases when an application
900provides a layer that is in the same folder hierarchy as the rest of the
901application files). If the layer is specified via a filename, the shared
902library lives in the system's DLL search path (e.g. in the
903"C:\\Windows\\System32" folder).
904
905If defining multiple layers in a single JSON file prior to "file\_format\_version"
9061.0.1, you would simply define multiple "layer" objects.  However, this is not
907valid JSON syntax.  Instead, you should now define "file\_format\_version"
9081.0.1 (or newer) and use the new "layers" array object as seen in the
909following example:
910
911```
912{
913   "file_format_version" : "1.0.1",
914   "layers": [
915      {
916           "name": "VK_LAYER_layer_name1",
917           "type": "INSTANCE",
918           ...
919      },
920      {
921           "name": "VK_LAYER_layer_name2",
922           "type": "INSTANCE",
923           ...
924      }
925   ]
926}
927```
928
929You could use the "layers" array object to define a single layer, as long as
930your "file\_format\_version" is defined to at least 1.0.1.  It is functionally the
931same as using a single "layer" object.
932
933There are no rules about the name of the text files (except the .json suffix).
934
935There are no rules about the name of the layer shared library files.
936
937##### Using Pre-Production Layers
938
939As with ICDs, developers may need to use special, pre-production layers,
940without modifying the properly-installed layers. This need is met with the use
941of the "VK\_LAYER\_PATH" environment variable, which will override the
942mechanism using for finding properly-installed layers. Because many layers may
943exist on a system, this environment variable is a semi-colon-separated list of
944folders that contain layer info files. Only the folder listed in
945"VK\_LAYER\_PATH" will be scanned for info files. Each semi-colon-separated
946entry is:
947
948- The full pathname of a folder containing layer info files
949
950#### Linux
951
952##### Properly-Installed Layers
953
954In order to find properly-installed layers, the Vulkan loader will use a
955similar mechanism as used for ICDs. Text information files, that use a JSON
956format, are read in order to identify the names and attributes of layers and
957their extensions. The use of text info files allows the loader to avoid loading
958any shared library files when the application does not query nor request any
959extensions. Layers and extensions have additional complexity, and so their info
960files contain more information than ICD info files. For example, a layer shared
961library file may contain multiple layers/extensions (perhaps even an ICD).
962
963The Vulkan loader will scan the files in the following Linux directories:
964
965/usr/share/vulkan/explicit\_layer.d
966/usr/share/vulkan/implicit\_layer.d
967/etc/vulkan/explicit\_layer.d
968/etc/vulkan/implicit\_layer.d
969\$HOME/.local/share/vulkan/explicit\_layer.d
970\$HOME/.local/share/vulkan/implicit\_layer.d
971
972Where $HOME is the current home directory of the application's user id; this
973path will be ignored for suid programs.
974
975Explicit layers are those which are enabled by an application (e.g. with the
976vkCreateInstance function), or by an environment variable (as mentioned
977previously). Implicit layers are those which are enabled by their existence.
978For example, certain application environments (e.g. Steam or an automotive
979infotainment system) may have layers which they always want enabled for all
980applications that they start. Other implicit layers may be for all applications
981started on a given system (e.g. layers that overlay frames-per-second).
982Implicit layers are enabled automatically, whereas explicit layers must be
983enabled explicitly. What distinguishes a layer as implicit or explicit is by
984which directory its layer information file exists in.
985
986The "/usr/share/vulkan/\*\_layer.d" directories are for layers that are
987installed from Linux-distribution-provided packages. The
988"/etc/vulkan/\*\_layer.d" directories are for layers that are installed from
989non-Linux-distribution-provided packages.
990
991This manifest file is in the JSON format as shown in the following example.
992See the section [Layer Library Manifest File](#LayerLibraryManifestFile) for more information about each of the nodes in the JSON file.
993
994```
995{
996   "file_format_version" : "1.0.0",
997   "layer": {
998       "name": "VK_LAYER_LUNARG_overlay",
999       "type": "INSTANCE",
1000       "library_path": "libvkOverlayLayer.so"
1001       "api_version" : "1.0.5",
1002       "implementation_version" : "2",
1003       "description" : "LunarG HUD layer",
1004       "functions": {
1005           "vkGetInstanceProcAddr": "OverlayLayer_GetInstanceProcAddr",
1006           "vkGetDeviceProcAddr": "OverlayLayer_GetDeviceProcAddr"
1007       },
1008       "instance_extensions": [
1009           {
1010               "name": "VK_EXT_debug_report",
1011               "spec_version": "1"
1012           },
1013           {
1014               "name": "VK_VENDOR_ext_x",
1015               "spec_version": "3"
1016            }
1017       ],
1018       "device_extensions": [
1019           {
1020               "name": "VK_EXT_debug_marker",
1021               "spec_version": "1",
1022               "entrypoints": ["vkCmdDbgMarkerBegin", "vkCmdDbgMarkerEnd"]
1023           }
1024       ],
1025       "enable_environment": {
1026           "ENABLE_LAYER_OVERLAY_1": "1"
1027       },
1028       "disable_environment": {
1029           "DISABLE_LAYER_OVERLAY_1": ""
1030       }
1031   }
1032}
1033```
1034The "library\_path" specifies either a filename, a relative pathname, or a full
1035pathname to a layer shared library (".so") file, which the loader will attempt
1036to load using dlopen(). If the layer is specified via a filename, the loader
1037will attempt to open that file as a shared object using dlopen(), and the file
1038must be in a directory that dlopen is configured to look in (Note: various
1039distributions are configured differently). A distribution is free to create
1040Vulkan-specific system directories (e.g. ".../vulkan/layers"), but is not
1041required to do so. If the layer is specified via a relative pathname, it is
1042relative to the path of the info file (e.g. for cases when an application
1043provides a layer that is in the same directory hierarchy as the rest of the
1044application files).
1045
1046There are no rules about the name of the text files (except the .json suffix).
1047
1048There are no rules about the name of the layer shared library files.
1049
1050##### Using Pre-Production Layers
1051
1052As with ICDs, developers may need to use special, pre-production layers,
1053without modifying the properly-installed layers.  This need is met with the use
1054of the "VK\_LAYER\_PATH" environment variable, which will override the
1055mechanism using for finding properly-installed layers. Because many layers may
1056exist on a system, this environment variable is a colon-separated list of
1057directories that contain layer info files. Only the directories listed in
1058"VK\_LAYER\_PATH" will be scanned for info files. Each colon-separated entry
1059is:
1060
1061- The full pathname of a directory containing layer info files
1062
1063NOTE: these environment variables will be ignored for suid programs.
1064
1065#### Android
1066
1067The recommended way to enable layers is for applications
1068to programatically enable them. The layers are provided by the application
1069and must live in the application's library folder. The application
1070enables the layers at vkCreateInstance as any Vulkan
1071application would.
1072An application enabled for debug has more options. It can enumerate and enable
1073layers located in /data/local/vulkan/debug.
1074
1075<br/>
1076
1077## Layer interface requirements ##
1078
1079#### Architectural interface overview
1080
1081There are two key architectural features that drive the loader to layer library
1082interface: 1) separate and distinct instance and device call chains, and 2)
1083distributed dispatch. First these architectural features will be described and
1084then the detailed interface will be specified.
1085
1086Call chains are the links of calls for a given Vulkan command from layer module
1087to layer module with the loader and or the ICD being the bottom most command.
1088Call chains are constructed at both the instance level and the device level by
1089the loader with cooperation from the layer libraries. Instance call chains are
1090constructed by the loader when layers are enabled at vkCreateInstance. Device
1091call chains are constructed by the loader when layers are enabled, by the loader, at
1092vkCreateDevice. A layer can intercept Vulkan instance commands, device commands
1093or both. For a layer to intercept instance commands, it must participate in the
1094instance call chain. For a layer to intercept device commands, it must
1095participate in the device chain.
1096
1097Normally, when a layer intercepts a given Vulkan command, it will call down the
1098instance or device chain as needed. The loader and all layer libraries that
1099participate in a call chain cooperate to ensure the correct sequencing of calls
1100from one entity to the next. This group effort for call chain sequencing is
1101hereinafter referred to as distributed dispatch. In distributed dispatch, since
1102each layer is responsible for properly calling the next entity in the device or
1103instance chain, a dispatch mechanism is required for all Vulkan commands a
1104layer intercepts. For Vulkan commands that are not intercepted by a layer, or
1105if the layer chooses to terminate a given Vulkan command by not calling down
1106the chain, then no dispatch mechanism is needed for that particular Vulkan
1107command.  Only for those Vulkan commands, which may be a subset of all Vulkan
1108commands, that a layer intercepts is a dispatching mechanism by the layer
1109needed. The loader is responsible for dispatching all core and instance
1110extension Vulkan commands to the first entity in the chain.
1111
1112Instance level Vulkan commands are those that have the dispatchable objects
1113VkInstance, or VkPhysicalDevice as the first parameter and also includes
1114vkCreateInstance.
1115
1116Device level Vulkan commands are those that use VkDevice, VkQueue or
1117VkCommandBuffer as the first parameter and also include vkCreateDevice. Future
1118extensions may introduce new instance or device level dispatchable objects, so
1119the above lists may be extended in the future.
1120
1121#### Layer Library Interface
1122
1123A layer library is a container of layers.  This section defines an extensible
1124interface to discover layers contained in layer libraries.
1125The extensible programming interface is used on Android only. For Windows and Linux,
1126the layer manifest JSON files are used.
1127
1128It also specifies the minimal conventions
1129and rules a layer must follow. Other sections might have other guidelines that layers should follow.
1130
1131##### Layer Conventions and Rules
1132
1133A layer, when inserted into an otherwise compliant Vulkan implementation, must
1134still result in a compliant Vulkan implementation[\*].  It must additionally
1135follow some conventions and rules.
1136
1137A layer is always chained with other layers.  It must not make invalid calls
1138to or rely on undefined behaviors of its lower layers.  When it changes the
1139behavior of a command, it must make sure its upper layers do not make invalid
1140calls to or rely on undefined behaviors of its lower layers because of the
1141changed behavior.  For example, when a layer intercepts an object creation
1142command to wrap the objects created by its lower layers, it must make sure its
1143lower layers never see the wrapping objects, directly from itself or
1144indirectly from its upper layers.
1145
1146When a layer requires host memory, it may ignore the provided allocators.  It
1147should use memory allocators if the layer is intended to run in a production
1148environment, such as an implicit layer that is always enabled.  That will
1149allow applications to include the layer's memory usage.
1150
1151`vkEnumerateInstanceLayerProperties` must enumerate and only enumerate the
1152layer itself.
1153
1154`vkEnumerateInstanceExtensionProperties` must handle the case where
1155`pLayerName` is itself.  It must return `VK_ERROR_LAYER_NOT_PRESENT`
1156otherwise, including when `pLayerName` is `NULL`.
1157
1158`vkEnumerateDeviceLayerProperties` is deprecated and may be omitted.  The
1159behavior is undefined.
1160
1161`vkEnumerateDeviceExtensionProperties` must handle the case where `pLayerName`
1162is itself.  In other cases, it should normally chain to other layers.
1163
1164`vkCreateInstance` must not generate an error for unrecognized layer names and
1165extension names.  It may assume the layer names and extension names have been
1166validated.
1167
1168`vkGetInstanceProcAddr` intercepts a Vulkan command by returning a local entry point,
1169otherwise it returns the value obtained by calling down the instance chain.
1170    These commands must be intercepted
1171   - vkGetInstanceProcAddr
1172   - vkCreateInstance
1173   - vkCreateDevice (only required for any device-level chaining)
1174
1175   For compatibility with older layer libraries,
1176   - when `pName` is `vkCreateDevice`, it ignores `instance`.
1177
1178`vkGetDeviceProcAddr` intercepts a Vulkan command by returning a local entry point,
1179otherwise it returns the value obtained by calling down the device chain.
1180
1181The specification requires `NULL` to be returned from `vkGetInstanceProcAddr` and
1182`vkGetDeviceProcAddr` for disabled commands.  A layer may return `NULL` itself or
1183rely on the following layers to do so.
1184
1185[\*]: The intention is for layers to have a well-defined baseline behavior.
1186Some of the conventions or rules, for example, may be considered abuses of the
1187specification.
1188
1189##### Layer Library API Version 0
1190
1191A layer library supporting interface version 0 must define and export these
1192introspection functions, unrelated to any Vulkan command despite the names,
1193signatures, and other similarities:
1194
1195 - `vkEnumerateInstanceLayerProperties` enumerates all layers in a layer
1196   library.  This function never fails.
1197
1198   When a layer library contains only one layer, this function may be an alias
1199   to the layer's `vkEnumerateInstanceLayerProperties`.
1200
1201 - `vkEnumerateInstanceExtensionProperties` enumerates instance extensions of
1202   layers in a layer library.  `pLayerName` is always a valid layer name.
1203   This function never fails.
1204
1205   When a layer library contains only one layer, this function may be an alias
1206   to the layer's `vkEnumerateInstanceExtensionProperties`.
1207
1208 - `vkEnumerateDeviceLayerProperties` enumerates a subset (can be full,
1209   proper, or empty subset) of layers in a layer library.  `physicalDevice` is
1210   always `VK_NULL_HANDLE`.  This function never fails.
1211
1212   If a layer is not enumerated by this function, it will not participate in
1213   device command interception.
1214
1215 - `vkEnumerateDeviceExtensionProperties` enumerates device extensions of
1216   layers in a layer library.  `physicalDevice` is always `VK_NULL_HANDLE`.
1217   `pLayerName` is always a valid layer name.  This function never fails.
1218
1219The introspection functions are not used by the desktop loader.
1220
1221It must also define and export these functions one for each layer in the library:
1222
1223 - `<layerName>GetInstanceProcAddr(instance, pName)` behaves identically to a layer's vkGetInstanceProcAddr except it is exported.
1224
1225   When a layer library contains only one layer, this function may
1226   alternatively be named `vkGetInstanceProcAddr`.
1227
1228 - `<layerName>GetDeviceProcAddr`  behaves identically to a layer's vkGetDeviceProcAddr except it is exported.
1229
1230   When a layer library contains only one layer, this function may
1231   alternatively be named `vkGetDeviceProcAddr`.
1232
1233All layers contained within a library must support [`vk_layer.h`][].  They do not need to
1234implement commands that they do not intercept.  They are recommended not to export
1235any commands.
1236
1237<a name="LayerLibraryManifestFile"></a>
1238##### Layer Library Manifest File Version 0
1239On Windows and Linux (desktop), the loader uses manifest files to discover
1240layer libraries and layers.  The desktop loader doesn't directly query the
1241layer library except during chaining.
1242On Android, the loader queries the layer libraries via the introspection functions as outlined above.
1243
1244The layer libraries and the manifest files must be kept in sync.
1245
1246The following table associates the desktop JSON nodes with the layer library introspection queries. It also indicates requirements.
1247
1248| Property | JSON node | Introspection query | Notes |
1249|----------|-----------|-----------------------|-------|
1250| file version | file_format_version | N/A | one node required per JSON file |
1251| layers in library | layer | vkEnumerateInstanceLayerProperties | one node required per layer |
1252| layer name | name | vkEnumerateInstanceLayerProperties | one node is required |
1253| layer type | type | vkEnumerate*LayerProperties | see Note 1 |
1254| library location | library_path | N/A | one node is required |
1255| vulkan spec version | api_version | vkEnumerateInstanceLayerProperties | one node is required |
1256| layer implementation version | api_version | vkEnumerateInstanceLayerProperties | see Note 2 |
1257| layer description | description | vkEnumerateInstanceLayerProperties | one node is required |
1258| chaining functions | functions | vkGet*ProcAddr | see Note 3 |
1259| instance extensions | instance_extensions | vkEnumerateInstanceExtensionProperties | see Note 4 |
1260| device extensions | device_extensions | vkEnumerateDeviceExtensionProperties | see Note 5 |
1261| enable implicit | enable_environment | N/A | See Note 6 |
1262| disable implicit | enable_environment | N/A | See Note 7 |
1263
1264"file\_format\_version" is used to indicate the valid JSON syntax of the file.
1265As nodes are added or deleted which would change the parsing of this file,
1266the file_format_version should change. This version
1267is NOT the same as the layer library interface version. The interface version is a superset
1268of the "file_format_version" and includes the semantics of the nodes in the JSON file.
1269For interface version 0 the file format version must be "1.0.0"
1270
1271Note 1: Prior to deprecation, the "type" node was used to indicate which layer chain(s)
1272to activate the layer upon: instance, device, or both.
1273Distinct instance and device layers are deprecated; there are now just layers.
1274Allowable values for type (both before and after deprecation) are "INSTANCE", "GLOBAL" and, "DEVICE."
1275"DEVICE" layers are skipped over by the loader as if they were not found.
1276Thus, layers must have a type of "GLOBAL" or "INSTANCE" for the loader to include the layer in the enumerated instance layer list.
1277
1278"library\_path" is the filename, full path, or relative path to the library file.
1279See [Manifest File Example](#ManifestFileExample) section for more details.
1280
1281Note 2: One "implementation\_version" node is required per layer. This node gives the layer version, a single number
1282increasing with backward uncompatible changes.
1283
1284Note 3: The "functions" node is required if the layer is using alternative
1285names for vkGetInstanceProcAddr or vkGetDeviceProcAddr. vkGetInstanceProcAddr and vkGetDeviceProcAddr
1286are required for all layers. See further requirements in the Layer Library API section above.
1287
1288Note 4: One "instance_extensions" node with an array of one or more elements
1289required if any instance
1290extensions are supported by a layer, otherwise the node is optional.  Each
1291element of the array must have the nodes "name" and "spec_version" which
1292correspond to  VkExtensionProperties "extensionName" and "specVersion"
1293respectively.
1294
1295Note 5: One "device_extensions" node with an array of one or more elements
1296required if any device
1297extensions are supported by a layer, otherwise the node is optional.  Each
1298element of the array must have the nodes "name" and "spec_version" which
1299correspond to  VkExtensionProperties "extensionName" and "specVersion"
1300respectively. Additionally, each element of the array of device extensions
1301must have the node "entrypoints" if the device extension adds Vulkan API commands,
1302otherwise this node is not required.
1303The "entrypoint" node is an array of the names of all entrypoints added by the
1304supported extension.
1305```
1306    "device_extensions": [
1307        {
1308            "name": "VK_EXT_debug_marker",
1309            "spec_version": "1",
1310            "entrypoints": ["vkCmdDbgMarkerBegin", "vkCmdDbgMarkerEnd"]
1311        }
1312 ```
1313
1314Note 6: The "enable\_environment" node is only for implicit layers only. It is optional for implicit layers.
1315This node gives an environment variable and value required to enable an implicit layer. This
1316environment variable (which should vary with each "version" of the layer) must be set to the
1317given value or else the implicit layer is not loaded. This is for application environments (e.g. Steam) which
1318want to enable a layer(s) only for applications that they launch, and allows
1319for applications run outside of an application environment to not get that
1320implicit layer(s).
1321
1322Note 7: The "disable\_environment" node is only for implicit layers only. It is required for implicit layers.
1323This node gives an environment variable and value required to disable an implicit layer. In
1324rare cases of an application not working with an implicit layer, the
1325application can set this environment variable (before calling Vulkan commands)
1326in order to "blacklist" the layer. This environment variable (which should vary
1327with each "version" of the layer) must be set (not particularly to any value).
1328If both the "enable\_environment" and
1329"disable\_environment" variables are set, the implicit layer is disabled.
1330
1331#### Layer Dispatch Interface Version 0
1332##### Layer intercept requirements
1333
1334- Layers intercept a Vulkan command by defining a C/C++ function with signature
1335identical to the Vulkan API for that command.
1336- A layer must intercept at least vkGetInstanceProcAddr and
1337vkCreateInstance.  Additionally, a layer would also intercept vkGetDeviceProcAddr and vkCreateDevice to participate in the device chain.
1338- For any Vulkan command a layer intercepts which has a non-void return value,
1339an appropriate value must be returned by the layer intercept function.
1340- The layer intercept function must call down the chain to the corresponding
1341Vulkan command in the next entity. Undefined results will occur if a layer
1342doesn't propagate calls down the chain. The two exceptions to this requirement
1343are vkGetInstanceProcAddr and vkGetDeviceProcAddr which only call down the
1344chain for Vulkan commands that they do not intercept.
1345- Layer intercept functions may insert extra calls to Vulkan commands in
1346addition to the intercept. For example, a layer intercepting vkQueueSubmit may
1347want to add a call to vkQueueWaitIdle after calling down the chain for
1348vkQueueSubmit.  Any additional calls inserted by a layer must be on the same
1349chain. They should call down the chain.
1350
1351##### Distributed dispatching requirements
1352
1353- For each entry point a layer intercepts, it must keep track of the entry
1354point residing in the next entity in the chain it will call down into. In other
1355words, the layer must have a list of pointers to functions of the appropriate
1356type to call into the next entity. This can be implemented in various ways but
1357for clarity will be referred to as a dispatch table.
1358- A layer can use the VkLayerDispatchTable structure as a device dispatch table
1359(see include/vulkan/vk_layer.h).
1360- A layer can use the VkLayerInstanceDispatchTable structure as a instance
1361dispatch table (see include/vulkan/vk_layer.h).
1362- Layers vkGetInstanceProcAddr function uses the next entity's
1363vkGetInstanceProcAddr to call down the chain for unknown (i.e. non-intercepted)
1364functions.
1365- Layers vkGetDeviceProcAddr function uses the next entity's
1366vkGetDeviceProcAddr to call down the chain for unknown (i.e. non-intercepted)
1367functions.
1368
1369##### Layer dispatch initialization
1370
1371- A layer initializes its instance dispatch table within its vkCreateInstance
1372function.
1373- A layer initializes its device dispatch table within its vkCreateDevice
1374function.
1375- The loader passes a linked list of initialization structures to layers via
1376the "pNext" field in the VkInstanceCreateInfo and VkDeviceCreateInfo structures
1377for vkCreateInstance  and VkCreateDevice respectively.
1378- The head node in this linked list is of type VkLayerInstanceCreateInfo for
1379instance and VkLayerDeviceCreateInfo for device. See file
1380include/vulkan/vk_layer.h for details.
1381- A VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO is used by the loader for the
1382"sType" field in VkLayerInstanceCreateInfo.
1383- A VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO is used by the loader for the
1384"sType" field in VkLayerDeviceCreateInfo.
1385- The "function" field indicates how the union field "u" should be interpreted
1386within VkLayer*CreateInfo. The loader will set the "function" field to
1387VK_LAYER_LINK_INFO. This indicates "u" field should be VkLayerInstanceLink or
1388VkLayerDeviceLink.
1389- The VkLayerInstanceLink and VkLayerDeviceLink structures are the list nodes.
1390- The VkLayerInstanceLink contains the next entity's vkGetInstanceProcAddr used
1391by a layer.
1392- The VkLayerDeviceLink contains the next entity's vkGetInstanceProcAddr and
1393vkGetDeviceProcAddr used by a layer.
1394- Given the above structures set up by the loader, layer must initialize their
1395dispatch table as follows:
1396  - Find the  VkLayerInstanceCreateInfo/VkLayerDeviceCreateInfo structure in
1397the VkInstanceCreateInfo/VkDeviceCreateInfo structure.
1398  - Get the next entity's vkGet*ProcAddr from the "pLayerInfo" field.
1399  - For CreateInstance get the next entity's vkCreateInstance by calling the
1400"pfnNextGetInstanceProcAddr":
1401     pfnNextGetInstanceProcAddr(NULL, "vkCreateInstance").
1402  - For CreateDevice get the next entity's vkCreateDevice by calling the
1403"pfnNextGetInstanceProcAddr":
1404     pfnNextGetInstanceProcAddr(NULL, "vkCreateDevice").
1405  - Advanced the linked list to the next node: pLayerInfo = pLayerInfo->pNext.
1406  - Call down the chain either CreateDevice or CreateInstance
1407  - Initialize your layer dispatch table by calling the next entity's
1408Get*ProcAddr function once for each Vulkan command needed in your dispatch
1409table
1410
1411##### Example code for CreateInstance
1412
1413```cpp
1414VkResult vkCreateInstance(
1415        const VkInstanceCreateInfo *pCreateInfo,
1416        const VkAllocationCallbacks *pAllocator,
1417        VkInstance *pInstance)
1418{
1419   VkLayerInstanceCreateInfo *chain_info =
1420        get_chain_info(pCreateInfo, VK_LAYER_LINK_INFO);
1421
1422    assert(chain_info->u.pLayerInfo);
1423    PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr =
1424        chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr;
1425    PFN_vkCreateInstance fpCreateInstance =
1426        (PFN_vkCreateInstance)fpGetInstanceProcAddr(NULL, "vkCreateInstance");
1427    if (fpCreateInstance == NULL) {
1428        return VK_ERROR_INITIALIZATION_FAILED;
1429    }
1430
1431    // Advance the link info for the next element of the chain
1432    chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext;
1433
1434    // Continue call down the chain
1435    VkResult result = fpCreateInstance(pCreateInfo, pAllocator, pInstance);
1436    if (result != VK_SUCCESS)
1437        return result;
1438
1439    // Init layer's dispatch table using GetInstanceProcAddr of
1440    // next layer in the chain.
1441    instance_dispatch_table = new VkLayerInstanceDispatchTable;
1442    layer_init_instance_dispatch_table(
1443        *pInstance, my_data->instance_dispatch_table, fpGetInstanceProcAddr);
1444
1445    // Other layer initialization
1446    ...
1447
1448    return VK_SUCCESS;
1449}
1450```
1451
1452##### Example code for CreateDevice
1453
1454```cpp
1455VkResult 
1456vkCreateDevice(
1457        VkPhysicalDevice gpu,
1458        const VkDeviceCreateInfo *pCreateInfo,
1459        const VkAllocationCallbacks *pAllocator,
1460        VkDevice *pDevice)
1461{
1462    VkLayerDeviceCreateInfo *chain_info =
1463        get_chain_info(pCreateInfo, VK_LAYER_LINK_INFO);
1464
1465    PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr =
1466        chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr;
1467    PFN_vkGetDeviceProcAddr fpGetDeviceProcAddr =
1468        chain_info->u.pLayerInfo->pfnNextGetDeviceProcAddr;
1469    PFN_vkCreateDevice fpCreateDevice =
1470        (PFN_vkCreateDevice)fpGetInstanceProcAddr(NULL, "vkCreateDevice");
1471    if (fpCreateDevice == NULL) {
1472        return VK_ERROR_INITIALIZATION_FAILED;
1473    }
1474
1475    // Advance the link info for the next element on the chain
1476    chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext;
1477
1478    VkResult result = fpCreateDevice(gpu, pCreateInfo, pAllocator, pDevice);
1479    if (result != VK_SUCCESS) {
1480        return result;
1481    }
1482
1483    // initialize layer's dispatch table
1484    device_dispatch_table = new VkLayerDispatchTable;
1485    layer_init_device_dispatch_table(
1486        *pDevice, device_dispatch_table, fpGetDeviceProcAddr);
1487
1488    // Other layer initialization
1489    ...
1490
1491    return VK_SUCCESS;
1492}
1493```
1494
1495#### Special Considerations
1496##### Associating private data with Vulkan objects within a layer
1497A layer may want to associate it's own private data with one or more Vulkan
1498objects.  Two common methods to do this are hash maps and object wrapping. 
1499
1500###### Wrapping:
1501
1502The loader supports layers wrapping any Vulkan object including dispatchable
1503objects.
1504For commands that return object handles, the layer saves the handle that is
1505returned from a lower-level layer (possibly the ICD), and returns its own
1506handle to the layer above it (possibly the application).  For commands that are
1507given previously-returned handles, the layer unwraps the handle; that is it
1508looks up the saved handle and gives that to the layer below it.
1509
1510Layers which wrap objects must ensure they always unwrap objects before passing
1511them down the chain.  This means that the layer must intercept every Vulkan
1512command which uses the object in question, and wrap or unwrap the object, as
1513appropriate.  This includes adding support for all extensions with commands
1514using any object the layer wraps.
1515
1516Layers above the object wrapping layer will see the wrapped object. Layers
1517which wrap dispatchable objects must ensure that the first field in the wrapping
1518structure is a pointer to a dispatch table as defined in vk_layer.h. Specifically, an
1519instance wrapped dispatchable object could be as follows:
1520```
1521struct my_wrapped_instance_obj_ {
1522    VkLayerInstanceDispatchTable *disp;
1523    // whatever data layer wants to add to this object
1524};
1525```
1526A device wrapped dispatchable object could be as follows:
1527```
1528struct my_wrapped_instance_obj_ {
1529    VkLayerDispatchTable *disp;
1530    // whatever data layer wants to add to this object
1531};
1532```
1533
1534Layers that wrap dispatchable objects must follow the guidelines for creating
1535new dispatchable objects (below).
1536
1537<u><b>Cautions</b></u>
1538
1539Layers are generally discouraged from wrapping objects, because of the
1540potential for incompatibilities with new extensions.  For example, let's say
1541that a layer wraps VkImage objects, and properly wraps and unwraps VkImage
1542object handles for all core commands.  If a new extension is created which has
1543commands that take VkImage objects as parameters, and if the layer does not
1544support those new commands, an application that uses both the layer and the new
1545extension will have undefined behavior when those new commands are called (e.g.
1546the application may crash).  This is becaues the lower-level layers and ICD
1547won't receive the handle that they generated.  Instead, they will receive a
1548handle that is only known by the layer that is wrapping the object.
1549
1550Because of the potential for incompatibilities with unsupported extensions,
1551layers that wrap objects must check which extensions are being used by the
1552application, and take appropriate action if the layer is used with unsupported
1553extensions (e.g. disable layer functionality, stop wrapping objects, issue a
1554message to the user).
1555
1556The reason that the validation layers wrap objects, is to track the proper use
1557and destruction of each object.  They issue a validation error if used with
1558unsupported extensions, alerting the user to the potential for undefined
1559behavior.
1560
1561###### Hash Maps:
1562Alternatively, a layer may want to use a hash map to associate data with a
1563given object. The key to the map could be the object. Alternatively, for
1564dispatchable objects at a given level (eg device or instance) the layer may
1565want data associated with the VkDevice or VkInstance objects. Since
1566there are multiple dispatchable objects for a given VkInstance or VkDevice, the
1567VkDevice or VkInstance object is not a great map key. Instead the layer should
1568use the dispatch table pointer within the VkDevice or VkInstance since that
1569will be unique for a given VkInstance or VkDevice.
1570
1571##### Creating new dispatchable objects
1572Layers which create dispatchable objects take special care. Remember that loader
1573trampoline code normally fills in the dispatch table pointer in the newly
1574created object. Thus, the layer must fill in the dispatch table pointer if the
1575loader trampoline will not do so.  Common cases where a layer (or ICD) may create a
1576dispatchable object without loader trampoline code is as follows:
1577- object wrapping layers that wrap dispatchable objects
1578- layers which add extensions that create dispatchable objects
1579- layers which insert extra Vulkan commands in the stream of commands they
1580intercept from the application
1581- ICDs which add extensions that create dispatchable objects
1582
1583The Windows/Linux loader provides a callback that can be used for initializing
1584a dispatchable object.  The callback is passed as an extension structure via the
1585pNext field in VkInstanceCreateInfo and VkDeviceCreateInfo.  The callback prototype
1586is defined as follows for instance and device callbacks respectively (see vk_layer.h):
1587```
1588VKAPI_ATTR VkResult VKAPI_CALL vkSetInstanceLoaderData(VkInstance instance, void *object);
1589VKAPI_ATTR VkResult VKAPI_CALL vkSetDeviceLoaderData)(VkDevice device, void *object);
1590```
1591To obtain these callbacks the layer must search through the list of structures
1592pointed to by the "pNext" field in the VkInstanceCreateInfo  and VkDeviceCreateInfo parameters to find any callback structures inserted by the loader. The salient details are as follows:
1593- For CreateInstance the callback structure pointed to by "pNext" is VkLayerInstanceCreateInfo as defined in vk_layer.h.
1594- A "sType" field in of VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO within VkInstanceCreateInfo parameter indicates a loader structure.
1595- Within VkLayerInstanceCreateInfo, the "function" field indicates how the union field "u" should be interpreted.
1596- A "function" equal to VK_LOADER_DATA_CALLBACK indicates the "u" field will contain the callback in "pfnSetInstanceLoaderData".
1597- For CreateDevice the callback structure pointed to by "pNext" is VkLayerDeviceCreateInfo as defined in include/vulkan/vk_layer.h.
1598- A "sType" field in of VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO within VkDeviceCreateInfo parameter indicates a loader structure.
1599- Within VkLayerDeviceCreateInfo, the "function" field indicates how the union field "u" should be interpreted.
1600- A "function" equal to VK_LOADER_DATA_CALLBACK indicates the "u" field will contain the callback in "pfnSetDeviceLoaderData".
1601
1602Alternatively, if an older loader is being used that doesn't provide these callbacks, the layer may manually initialize the newly created dispatchable object.
1603To fill in the dispatch table pointer in newly created dispatchable object,
1604the layer should copy the dispatch pointer, which is always the first entry in the structure, from an existing parent object of the same level (instance versus
1605device). For example, if there is a newly created VkCommandBuffer object, then the dispatch pointer from the VkDevice object, which is the parent of the VkCommandBuffer object, should be copied into the newly created object.
1606
1607