# Vulkan Validation and Debugging Layers

Vulkan supports intercepting or hooking API entry points via the Layer framework. A Layer can intercept all or any subset of Vulkan API entry points. Multiple layers can be chained together to cascade their functionality in the appearance of a single, larger layer.

Vulkan application developers will enable layers to validate and debug their applications.

## Layers Included in the SDK

The LunarG Vulkan SDK includes the following layers:

Layer Name | Layer Type | Description
--- | --- | ---
VK_LAYER_LUNARG_api_dump | utility | print API calls and their parameters and values
VK_LAYER_LUNARG_monitor | utility | outputs the frames-per-second of the target application in the applications title bar
VK_LAYER_GOOGLE_unique_objects | utility | wrap all Vulkan objects in a unique pointer at create time and unwrap them at use time
VK_LAYER_LUNARG_core_validation | validation | validate the descriptor set, pipeline state, and dynamic state; validate the interfaces between SPIR-V modules and the graphics pipeline; track and validate GPU memory and its binding to objects and command buffers; validate texture formats and render target formats
VK_LAYER_LUNARG_object_tracker | validation | track all Vulkan objects and flag invalid objects and object memory leaks
VK_LAYER_LUNARG_parameter_validation | validation | validate API parameter values
VK_LAYER_LUNARG_screenshot | utility | outputs specified frames to an image file as they are presented
VK_LAYER_GOOGLE_threading | validation | check validity of multi-threaded API usage

Later sections of this document detail the specific functions of the layers described above.

In addition to the above individually specified layers, a built-in meta-layer definition has been provided which simplifies validation for applications. Specifying this short-hand layer definition will load a standard set of validation layers in the optimal order:

         VK_LAYER_LUNARG_standard_validation

Specifying this layer definition will load the following layers in the order show below:

         VK_LAYER_GOOGLE_threading
         VK_LAYER_LUNARG_parameter_validation
         VK_LAYER_LUNARG_object_tracker
         VK_LAYER_LUNARG_core_validation
         VK_LAYER_GOOGLE_unique_objects

This is done by the Vulkan loader. The loader will remove redundant layer specifications and enforce the order of the standard_validation layer. Layers not included in the meta-layer will be added to the layer chain as expected.

Use of the LUNARG_standard_validation layer is recommended as the order and names of the Vulkan Validations layers may change. Using standard_validation on the desktop will help to insulate applications from these changes.

## A Note on Layer Message Types

Validation layers will output messages of several types. It is important to note the meaning of the ERROR type as compared to the WARN type:

Type | Debug Report Flag | Definitions
--- | --- | ---
Error | VK_DEBUG_REPORT_ERROR_BIT_EXT | Errors are output when a validation layer detects that some application behavior has violated the Vulkan Specification. When an error is encountered it is recommended that the user callback function return 'true' for optimal validation results. Any validation error may result in undefined behavior and errors should be corrected as they are encountered for best results
Warn | VK_DEBUG_REPORT_WARNING_BIT_EXT | Warnings are output in cases where mistakes are commonly made and do NOT necessarily indicate that an app has violated the Vulkan Specification. Warnings basically translate to 'Did you really mean to do this?'
Perf Warn | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT | Performance Warnings are output in cases where a possible inefficiency has been detected. These also do NOT imply that the specification was violated
Info | VK_DEBUG_REPORT_INFORMATION_BIT_EXT | These log messages are for informational purposes only. For instance, the core_validation layer can print out lists of memory objects and their bindings which may help with debugging or improving application efficiency

## Configuring Layers on Linux

The Vulkan Loader searches the `/usr/share/vulkan/implicit_layer.d`, `/usr/share/vulkan/explicit_layer.d`, `/etc/vulkan/implicit_layer.d`, `/etc/vulkan/explicit_layer.d` `$HOME/.local/share/vulkan/explicit_layer.d`, and `$HOME/.local/share/vulkan/implicit_layer.d` directories for layer JSON manifest files.

Sample Layer manifest file (core_validation.json):

    {
        "file_format_version" : "1.0.0",
        "layer" : {
            "name": "VK_LAYER_LUNARG_core_validation",
            "type": "GLOBAL",
            "library_path": "libVKLayer_core_validation.so",
            "api_version": "1.0.21",
            "implementation_version": "1",
            "description": "LunarG Validation Layer"
            "instance_extensions": [
                 {
                     "name": "VK_EXT_debug_report",
                     "spec_version": "3"
                 }
             ]
        }
    }

Full and relative (to JSON manifest file) `library_path` names are supported, as are unqualified file names. If just a filename is specified, the loader will search the default library directory (eg `/usr/lib/x86_64-linux-gnu/` on Ubuntu x64) for the layer shared library.

Setting the `VK_LAYER_PATH` environment variable overrides the default Loader layer search mechanism. When set, the Loader will search only the directory(s) identified by `$VK_LAYER_PATH` for layer manifest files.

Applications can query available layers via the `vkEnumerateInstanceLayerProperties()` command.

## Configuring Layers on Windows

The Vulkan Loader searches the following registry keys to find layers:

    HKEY_LOCAL_MACHINE\SOFTWARE\Khronos\Vulkan\ExplicitLayers
    HKEY_LOCAL_MACHINE\SOFTWARE\Khronos\Vulkan\ImplicitLayers

For each value in each of the above two keys for which DWORD data set to 0, the Vulkan Loader opens the json text file specified by the value name. For example, if the HKEY_LOCAL_MACHINE\SOFTWARE\Khronos\Vulkan\ExplicitLayers key contains the following value:

    Name                                          Type         Data
    C:\VulkanSDK\1.0.21\Bin\core_validation.json   REG_DWORD    0x00000000

The Loader will open the file C:\VulkanSDK\1.0.21\Bin\core_validation.json to find the pathname to the layer library file. The core_validation.json file might contain:

    {
        "file_format_version" : "1.0.0",
        "layer" : {
            "name": "VK_LAYER_LUNARG_core_validation",
            "type": "GLOBAL",
            "library_path": ".\\libVKLayer_core_validation.dll"
            "api_version": "1.0.21",
            "implementation_version": "1",
            "description": "LunarG Validation Layer"
            "instance_extensions": [
                 {
                     "name": "VK_EXT_debug_report",
                     "spec_version": "3"
                 }
             ]
        }
    }

Full and relative (to JSON manifest file) `library_path` names are supported, as are unqualified file names. If just a filename is specified, the loader will search the default library directory (typically `C:\Windows\System32`) for the layer shared library. For the above example, the layer library file for the VK_LAYER_LUNARG_core_validation layer is libVKLayer_core_validation.dll, and that file will be loaded from `C:\VulkanSDK\1.0.21\Bin` and used by the loader if the VK_LAYER_LUNARG_core_validation layer is activated.

## Activating Layers on Linux

Before or during execution of a Vulkan application, the Loader must be informed of the layers to activate. Applications can activate layers at runtime via the `vkCreateInstance()` entry point.

Layers configured in `/usr/share/vulkan/implicit_layer.d`, `$HOME/.local/share/vulkan/implicit_layer.d`, and `/etc/vulkan/implicit_layer.d` are activated automatically by the Loader.

Layers configured in `/usr/share/vulkan/explicit_layer.d`, `$HOME/.local/share/vulkan/explicit_layer.d`, and `/etc/vulkan/explicit_layer.d` can be activated by applications at runtime. These explicit layers can also be activated by the user by setting the `VK_INSTANCE_LAYERS` environment variable. Set this variable to identify a colon separated list of layer names to activate. Order is relevant with the first layer in the list being the topmost layer (closest to the application) and the last layer in the list being the bottom-most layer (closest to the driver).

For example, the list of explicit layers to activate can be specified with:

    $ export VK_INSTANCE_LAYERS=VK_LAYER_LUNARG_api_dump:VK_LAYER_LUNARG_core_validation

To activate layers in a local SDK install, identify certain library paths and the layer JSON manifest file directory in addition to the layers to activate. If the Vulkan SDK was locally installed to `/sdks`, `VULKAN_SDK=/sdks/VulkanSDK/1.0.21/x86_64`:

    $ export VK_LAYER_PATH=$VULKAN_SDK/lib/vulkan/layers
    $ export LD_LIBRARY_PATH=$VULKAN_SDK/lib:$VULKAN_SDK/lib/vulkan/layers
    $ export VK_INSTANCE_LAYERS=VK_LAYER_LUNARG_api_dump:VK_LAYER_LUNARG_core_validation
    $ ./cube

Developers may choose to activate all Vulkan Validation layers simply by using LUNARG_standard_validation. To do so via the environment:

    $ export VK_INSTANCE_LAYERS=VK_LAYER_LUNARG_standard_validation

Alternatively, the layers can be loaded manually like so:

    $ export VK_INSTANCE_LAYERS=VK_LAYER_LUNARG_core_validation:VK_LAYER_LUNARG_object_tracker:VK_LAYER_LUNARG_parameter_validation:VK_LAYER_GOOGLE_threading:VK_LAYER_GOOGLE_unique_objects

## Activating Layers on Windows

Before or during execution of a Vulkan application, the Loader must be informed of the layers to activate. Applications can activate layers at runtime via the `vkCreateInstance()` entry point.

Layers configured in registry key `HKEY_LOCAL_MACHINE\SOFTWARE\Khronos\Vulkan\ImplicitLayers` are activated automatically by the Loader.

Layers configured in registry key `HKEY_LOCAL_MACHINE\SOFTWARE\Khronos\Vulkan\ExplicitLayers` can be activated by applications at runtime. These explicit layers can also be activated by the user by setting the `VK_INSTANCE_LAYERS` environment variable. Set this variable to identify a semi-colon separated list of layer names to activate. Order is relevant with the first layer in the list being the topmost layer (closest to the application) and the last layer in the list being the bottom-most layer (closest to the driver).

In a Command Window, the list of explicit layers to activate can be specified with:

    C:\> set VK_INSTANCE_LAYERS=VK_LAYER_LUNARG_api_dump;VK_LAYER_LUNARG_core_validation

`VK_INSTANCE_LAYERS` can also be set in the system environment variables.

To activate layers located in a particular SDK install, identify the layer JSON manifest file directory using the VK_LAYER_PATH environment variable. For example, if a Vulkan SDK is locally installed to `C:\VulkanSDK\1.0.21`:

    C:\> set VK_LAYER_PATH=C:\VulkanSDK\1.0.21\Bin
    C:\> set VK_INSTANCE_LAYERS=VK_LAYER_LUNARG_api_dump;VK_LAYER_LUNARG_core_validation
    C:\> cube

Developers may choose to activate all Vulkan Validation layers simply by using LUNARG_standard_validation. To do so via the environment:

    C:\> set  VK_INSTANCE_LAYERS=VK_LAYER_LUNARG_standard_validation

Alternatively, the layers can be loaded manually like so:

    C:\> set  VK_INSTANCE_LAYERS=VK_LAYER_LUNARG_core_validation;VK_LAYER_LUNARG_object_tracker;VK_LAYER_LUNARG_parameter_validation;VK_LAYER_GOOGLE_threading

## Layer Controls

There are two general methods for controlling layer behavior supported by most of the layers listed herein: layer settings file and the VK_EXT_debug_report extension. The VK_EXT_debug_report extension is for apps to programmatically control layer message logging. The layer settings file provides a general mechanism for a user to control various layer behaviors by providing arbitrary settings. Currently the layer settings file has settings only pertaining to layer message logging.

The validation layers support both methods.

### VK_EXT_debug_report

The prefered method for an app to control layer logging is via VK_EXT_debug_report extension. Using VK_EXT_debug_report extension allows an application to register multiple callbacks with the validation layers. Some callbacks may log the information to a file, others may cause a debug break point or other application defined behavior. An application can register callbacks even when no validation layers are enabled, but they will only be called for loader and, if implemented, driver events. This extension provides a flags parameter indicating the severity level of the message: error, warning, etc. Using these flags, an application can filter the messages recieved by their callback to a desired severity level.

Refer to the Debug Report Extension ** for details on using this extension.**

### Layer Settings File

In addition to activating the layers, specific reporting levels must be set for each layer programmatically or via the `vk_layer_settings.txt` settings file. If no environment variable variable `VK_LAYER_SETTINGS_PATH` is set, then this must be a file called `vk_layer_settings.txt` in the working directory of the application. If `VK_LAYER_SETTINGS_PATH` is set and is a directory, then the settings file must be a file called `vk_layer_settings.txt` in the directory given by `VK_LAYER_SETTINGS_PATH`. If `VK_LAYER_SETTINGS_PATH` is set and is not a directory, then it must point to a file (with any name) which is the layer settings file.

Note: To generate layer reporting output, a layer settings file must be provided that identifies specific reporting levels for the layers enabled via the `VK_INSTANCE_LAYER` environment variable.

The settings file consists of comment lines and settings lines. Comment lines begin with the `#` character. Settings lines have the following format:

`<``LayerName``><``setting_name``> = <``setting_value``>`

Three settings are common to all layers:

Setting | Values | Description
--- | --- | ---
LayerName.report_flags | info | Report information level messages
| warn | Report warning level messages
| perf | Report performance level warning messages
| error | Report error level messages
| debug | No output messages
LayerName.debug_action | VK_DBG_LAYER_ACTION_IGNORE | Ignore message reporting
| VK_DBG_LAYER_ACTION_LOG_MSG | Report messages to log
| VK_DBG_LAYER_ACTION_DEBUG_OUTPUT | (Windows) Report messages to debug console of Microsoft Visual Studio
| VK_DBG_LAYER_ACTION_BREAK | Break on messages (not currently used)
LayerName.log_filename | filename.txt | Name of file to log `report_flags` level messages; default is `stdout`

Layer-specific settings are also supported in the layer settings file.

Sample layer settings file contents:

    lunarg_core_validation.report_flags = info,error
    lunarg_core_validation.debug_action = VK_DBG_LAYER_ACTION_LOG_MSG
    # VK_LAYER_LUNARG_api_dump custom settings
    lunarg_api_dump.no_addr = TRUE
    lunarg_api_dump.file = FALSE

The LunarG Vulkan SDK includes a sample layer settings file identifying the available and supported settings for each layer. On Linux, you can find the sample layer settings file in `config/vk_layer_settings.txt` of your local Vulkan SDK install. On Windows, you can find the sample layer settings file in `Config\vk_layer_settings.txt` of your local Vulkan SDK install.

Note: If layers are activated via `VK_INSTANCE_LAYER` environment variable and if neither an application-defined callback is defined nor a layer settings file is present, the loader/layers will provide default callbacks enabling output of Error-level messages to standard out (and via OutputDebugString on Windows).

### Layer Output Message Format

The output messages of the validation layers included in the SDK follow the same format:

    {LAYER_IDENTIFIER}<INFO|WARN|ERROR> : <Message description>

Examples of output from validation layers:

    SC(ERROR): object: 0x0 type: 0 location: 1619 msgCode: 3: fragment shader consumes input location 5.0 which is not written by vertex shader

    OBJTRACK(INFO): object: 0x23 type: 5 location: 552 msgCode: 0: OBJ_STAT Destroy VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT obj 0x23 (33 total objs remain & 1 VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT objs).

    MEM(ERROR): object: 0x1d33 type: 8 location: 466 msgCode: 12: vkCmdBeginRenderPass(): Cannot read invalid memory 0x1d33, please fill the memory before using.

## Layer Details

### VK_LAYER_LUNARG_api_dump

The VK_LAYER_LUNARG_api_dump utility layer prints API calls, parameters, and values to the identified output stream.

VK_LAYER_LUNARG_api_dump has three custom settings that can be set to `TRUE` or `FALSE` values:

Setting | Description
--- | ---
lunarg_api_dump.detailed | if TRUE (the default), dump all function parameters and values; if FALSE, dump only function signatures
lunarg_api_dump.file | dump to file; otherwise dump to `stdout`
lunarg_api_dump.no_addr | if TRUE, replace all addresses with static string "`address`"
lunarg_api_dump.flush | if TRUE, force I/O flush after every line

### VK_LAYER_LUNARG_core_validation

The VK_LAYER_LUNARG_core_validation layer validates the status of descriptor sets, command buffers, shader modules, pipeline states, renderpass usage, synchronization, dynamic states and is the workhorse layer for many other types of valid usage.

VK_LAYER_LUNARG_core_validation validates that:

- the descriptor set state and pipeline state at each draw call are consistent
- pipelines are created correctly, known when used and bound at draw time
- descriptor sets are known and of valid types, formats, and layout
- descriptor set regions are valid, bound, and updated appropriately
- command buffers referenced are known and valid
- command sequencing for specific state dependencies and renderpass use is correct
- memory is available
- dynamic state is correctly set

The VK_LAYER_LUNARG_core_validation layer will print errors if validation checks are not correctly met. VK_LAYER_LUNARG_core_validation will also display the values of the objects tracked.

####VK_LAYER_LUNARG_core_validation Shader validation functionality Checks performed by this layer apply to the VS->FS and FS->CB interfaces with the pipeline. These checks include:

- validating that all variables which are part of a shader interface are decorated with either `spv::DecLocation` or `spv::DecBuiltin` (that is, only the SSO rendezvous-by-location model is supported)
- emitting a warning if a location is declared only in the producing stage (useless work is being done)
- emitting an error if a location is declared only in the consuming stage (garbage will be read)

A special error checking case invoked when the FS stage writes a built-in corresponding to the legacy `gl_FragColor`. In this case, an error is emitted if

- the FS also writes any user-defined output
- the CB has any attachment with a `UINT` or `SINT` type

These extra checks are to ensure that the legacy broadcast of `gl_FragColor` to all bound color attachments is well-defined.

####VK_LAYER_LUNARG_core_validation Swapchain validation functionality This are of functionality validates the use of the WSI (Window System Integration) "swapchain" extensions (i.e. `VK_EXT_KHR_swapchain` and `VK_EXT_KHR_device_swapchain`).

### VK_LAYER_LUNARG_core_validation Memory/Resource related functionality

This layer additionally attempts to ensure that memory objects are managed correctly by the application. These memory objects may be bound to pipelines, objects, and command buffers, and then submitted to the GPU for work. Specifically the layer validates that:

- the correct memory objects have been bound
- memory objects are specified correctly upon command buffer submittal
- only existing memory objects are referenced
- destroyed memory objects are not referenced
- the application has confirmed any memory objects to be reused or destroyed have been properly unbound
- checks texture formats and render target formats

Errors will be printed if validation checks are not correctly met and warnings if improper (but not illegal) use of memory is detected. This validation layer also dumps all memory references and bindings for each operation.

### VK_LAYER_LUNARG_monitor

The VK_LAYER_LUNARG_monitor utility layer prints the real-time frames-per-second value to the application's title bar

### VK_LAYER_LUNARG_object_tracker

The VK_LAYER_LUNARG_object_tracker layer tracks all Vulkan objects. Object lifetimes are validated along with issues related to unknown objects and object destruction and cleanup.

All Vulkan dispatchable and non-dispatchable objects are tracked by the VK_LAYER_LUNARG_object_tracker layer.

This layer validates that:

- only known objects are referenced and destroyed
- lookups are performed only on objects being tracked
- objects are correctly freed/destroyed

The VK_LAYER_LUNARG_object_tracker layer will print errors if validation checks are not correctly met and warnings if improper reference of objects is detected.

### VK_LAYER_LUNARG_parameter_validation

The VK_LAYER_LUNARG_parameter_validation validation layer checks the input parameters to API calls for validity. This layer performs the following tasks:

- validation of structures; structures are recursed if necessary
- validation of enumerated type values
- null pointer conditions
- stateless valid usage checks
- validation of `VkResult`

### VK_LAYER_LUNARG_screenshot

The VK_LAYER_LUNARG_screenshot layer records frames to image files. The environment variable VK_SCREENSHOT_FRAMES can be set to a comma-separated list of frame numbers. When the frames corrosponding to these numbers are presented, the screenshot layer will record the image buffer to PPM files in the working directory. For example, if VK_SCREENSHOT_FRAMES is set to "4,8,15,16,23,42", the files created will be: 4.ppm, 8.ppm, 15.ppm, etc.

Checks include:

- validating that handles used are valid
- if an extension's function is used, it must have been enabled (including for the appropriate `VkInstance` or `VkDevice`)
- the query functions must be called before creating a swapchain
- the results of the query functions are compared with the values used to create a swapchain
- all `VkSwapchainKHR`s associated with a `VkDevice` must be destroyed before the `VkDevice` is destroyed
- applications should not call `vkAcquireNextImageKHR()` so many times that the call cannot succeed
- applications must own an image (i.e. by calling `vkAcquireNextImageKHR()`) in order to present
- image indices must be within range

### VK_LAYER_GOOGLE_threading

The VK_LAYER_GOOGLE_threading layer checks multi-threading of API calls for validity. Checks performed by this layer include ensuring that only one thread at a time uses an object in free-threaded API calls

### VK_LAYER_GOOGLE_unique_objects

The VK_LAYER_LUNARG_unique_objects is a validation-supporting utility layer which enables consistent and coherent validation in addition to proper operation on systems which return non-unique object handles. This layer aliases all non-dispatchable Vulkan objects with a unique identifier at object-creation time. The aliased handles are used during validation to ensure that duplicate object handles are correctly managed and tracked by the validation layers. Note that for optimal efficiency, this layer MUST be last in the chain (closest to the display driver).

NOTE: If you are developing Vulkan extensions which include new APIs taking one or more Vulkan dispatchable objects as parameters, you may find it necessary to disable the unique_objects layer to be able in order use the validation layers. The best way to do this is to explicitly load the layers in the optimal order specified earlier but without this layer. This should result in a minimal decrease in functionality but still allow you to benefit from using the validation layers.