Creating custom views of native objects in the debugger

Visual Studio 2012 introduces a new type visualization framework for the native debugger. The Natvis framework lets you customize the way Visual Studio displays native types in debugger variable windows such as the Watch, Locals, and Data Tips windows. It supersedes the autoexp.dat file that has been used in earlier versions of Visual Studio and offers Xml syntax, better diagnostics, versioning, and multiple file support.

Note

The Natvis framework is not used for visualizations when:

  • Mixed mode debugging a desktop application (i.e. an app that is not a Windows Store app) and the Managed C++ Compatibility Mode option is checked in the Debugging/General page of the Visual Studio Options dialog box.

  • C/C++ edit and continue is enabled in the Debugging/Edit and Continue page of the Visual Studio Options dialog box.

To view or edit the Visual Studio debugging option, choose Debug, Options and Settings and then select a specific page.

In this topic

Why create Natvis visualizations?

Using Natvis files

Diagnosing Natvis errors

Syntax reference

  • Expressions and formatting

  • Condition attribute

  • AutoVisualizer

  • Type

    • Visualizer type matching

    • Versioning

  • DisplayString

  • StringView

  • Expand

    • Item expansion

    • ArrayItems expansion

    • IndexListItems expansion

    • LinkedListItems expansion

    • TreeItems expansion

    • ExpandedItem expansion

    • Synthetic Item expansion

  • HResult

  • UIVisualizer

Why create Natvis visualizations?

Note

Component authors can use the natvis framework to create visualization rules for their types that make it easy for developers to inspect them during debugging.

For example, the image below shows a variable of type Windows::UI::Xaml::Controls::TextBox that is displayed in the debugger without any custom visualizations applied.

TextBox default visualization

The highlighted row points to the data member supplying the Text property of the TextBox class. The complex class hierarchy makes it difficult to find the value of this important member because we have to drill down deep in the variable window. Moreover, the debugger doesn’t know how to interpret the custom string type used by the object so we cannot see the string held inside the textbox.

The same TextBoxobject type has a much simpler view in the variable window when custom visualization rules are applied. The important members of the class can be viewed together and the debugger is able to show the underlying string value of the custom string type.

TextBox data using visualizer

Using Natvis files

Visualizations for native types are specified in .natvis files. A .natvis file is simply an .xml file with a .natvis extension. The schema is defined in %VSINSTALLDIR%\Xml\Schemas\natvis.xsd. Visual Studio ships with some .natvis files in %VSINSTALLDIR%\Common7\Packages\Debugger\Visualizers folder. These files contain visualization rules for many common types and can serve as examples when writing visualizations for new types

The basic structure of a .natvis file is one or more Type elements, where each Type element represents a visualization entry for a type whose fully qualified name is specified in the Name attribute.

<?xml version="1.0" encoding="utf-8"?>
<AutoVisualizer xmlns="https://schemas.microsoft.com/vstudio/debugger/natvis/2010">
  <Type Name="MyNamespace::CFoo">
    .
    .
  </Type>

  <Type Name="...">
    .
    .
  </Type>
</AutoVisualizer>

You can start writing a visualization for your types by creating a .natvis file with this structure and dropping it into one of these locations:

  • %VSINSTALLDIR%\Common7\Packages\Debugger\Visualizers (requires admin access)

  • %USERPROFILE%\My Documents\Visual Studio 2012\Visualizers\

  • Visual Studio extension folders (the extension manifest must contain a NativeVisualizer asset entry)

At the start of each debugging session, Visual Studio loads and processes every .natvis file it can find in these locations (it is NOT necessary to restart Visual Studio). This makes writing new visualizations easy: you can stop debugging, make changes to your visualization entries, save the .natvis file and then start debugging again to see the effects of your changes.

Diagnosing Natvis errors

Natvis diagnostics helps you to troubleshoot issues when writing new visualizations. When the Visual Studio debugger encounters errors in a visualization entry, such as xml schema errors, or expressions that fail to parse, it simply ignores the errors and either displays the type in its raw form or picks another suitable visualization. To understand why a certain visualization entry is ignored and to see what the underlying errors are, you can turn on visualization diagnostics by setting the following registry value:

[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0_Config\Debugger]

"EnableNatvisDiagnostics"=dword:00000001

Enable Natvis diagnositics in the registry

When natvis diagnostics is on, the Output window in Visual Studio displays status messages, such as when a .natvis file is parsed, or an expression is successfully evaluated, or error messages such as file and expression parse errors.

Syntax reference

Expressions and formatting

Natvis visualizations use C++ expressions to specify the data items to display. In addition to the enhancements and limitations of C++ expressions in the debugger that are described in Expressions in Native C++, you should be aware of the following differences:

  • Natvis expressions are evaluated in the context of the object being visualized, not the current stack frame. For example, if you use x in a natvis expression, this refers to the field named x in the object being visualized, not to a local variable named x in the currently executing function. You cannot access local variables inside of natvis expressions, although you can access global variables.

  • Natvis expressions do not allow function evaluation or side effects. This means that function calls and assignment operators are ignored. Because debugger intrinsic functions are side-effect free, they may be freely called from any natvis expression, even though other function calls are disallowed.

To control how an expression is displayed in a variable window, you can use any of the format specifiers that are described in the Visual Studio 2012 format specifiers section of the Format Specifiers in C++ topic. Note that format specifiers are ignored in when the virtualization entry is used internally by natvis, such as the <Size> expression in in a ArrayItems expansion.

Condition attribute

The optional Condition attribute is available for many visualization elements and specifies when a visualization rule should be used. If the expression inside the condition attribute is false, then the visualization rule specified by the element is not applied. If it’s evaluated to true, or if there is no Condition attribute, then the visualization rule is applied to the type. You can use this attribute to have if-else logic in the visualization entries. For example, the visualization below defines two DisplayString elements (explained further below) for a smart pointer type:

<Type Name="std::auto_ptr&lt;*&gt;">
  <DisplayString Condition="_Myptr == 0">empty</DisplayString>
  <DisplayString>auto_ptr {*_Myptr}</DisplayString>
  <Expand>
    <ExpandedItem>_Myptr</ExpandedItem>
  </Expand>
</Type>

When the _Myptr member is null, the condition of the first DisplayString element will be true, therefore that element takes effect. When the _Myptr member is not null, the condition evaluates to false and the second DisplayString element takes effect.

AutoVisualizer

AutoVisualizer is the root node of the .natvis file and contains the xmlns: attribute.

<?xml version="1.0" encoding="utf-8"?>
<AutoVisualizer xmlns="https://schemas.microsoft.com/vstudio/debugger/natvis/2010">
.
.
</AutoVisualizer

Type

While the full syntax of a visualization entry can be found in the schema file, the structure of a basic visualization entry looks like this:

<Type Name="[fully qualified type name]">
  <DisplayString Condition="[Boolean expression]">[Display value]</DisplayString>
  <Expand>
    ...
  </Expand>
</Type>

The visualization specifies:

  1. What type this visualization should be used for (the Type Name attribute).

  2. What the value of an object of that type should look like the DisplayString element

  3. What the children of the object should look like when user expands it in a variable window (the Expand node).

Visualizer type matching

Here are the general rules governing how visualizations are matched with types to be viewed in the debugger windows:

  • A visualization entry is applicable for the type specified in its name attribute and for all the types that are derived from it. If there is a visualization for both a base class and the derived class, the derived class visualization takes precedence.

  • If a visualization entry fails to parse and validate than the next available visualization is used.

  • Templated classesThe Name attribute of the Type element accepts an asterisk * as a wildcard character that can be used for templated class names:

      <Type Name="ATL::CAtlArray&lt;*&gt;">
        <DisplayString>{{Count = {m_nSize}}}</DisplayString>
      </Type>
    

    In this example, the same visualization will be used whether the object is a CAtlArray<int> or a CAtlArray<float>. If there is a specific visualization entry for a CAtlArray<float> then it takes precedence over the generic one.

  • Note that template parameters can be referenced in the visualization entry by using macros $T1, $T2, and so forth. To find examples of these macros, see the .natvis files shipped with Visual Studio.

Versioning

Use the Version element to scope visualizations to specific modules and their versions so that name collisions can be minimized and different visualizations can be used for different versions of the types. For example:

  <Type Name="DirectUI::Border">
    <Version Name="Windows.UI.Xaml.dll" Min="1.0" Max="1.5"/>
    <DisplayString>{{Name = {*(m_pDO-&gt;m_pstrName)}}}</DisplayString>
    <Expand>
      <ExpandedItem>*(CBorder*)(m_pDO)</ExpandedItem>
    </Expand>
  </Type>

In this example, the visualization is only applicable for the DirectUI::Border type found in the Windows.UI.Xaml.dll from version 1.0 to 1.5. Note that while adding version elements will scope the visualization entry to a particular module and version and reduce inadvertent matches, if a type is defined in a common header file that is used by different modules, the versioned visualization is not applied when the type is not in the specified module.

DisplayString

A DisplayString element specifies the string to be shown as the value of the variable. It accepts arbitrary strings mixed with expressions. Everything inside curly braces is interpreted as an expression and gets evaluated. For instance, a DisplayString entry like this:

<Type Name="CPoint">
  <DisplayString>{{x={x} y={y}}}</DisplayString> 
</Type>

results in variables of type CPoint that look like this:

Using a DisplayString element

In the DisplayString expression, x and y, which are members of CPoint, are inside curly braces and so their values are evaluated. The expression also shows how can escape a curly brace by using double curly braces ( {{ or }} ).

Note

The DisplayString element is the only element that accepts arbitrary strings and the curly brace syntax. All other visualization elements accept only expressions that are evaluated by the debugger.

StringView

The StringView element defines the expression whose value is going to be sent to the built-in text visualizer. For example, suppose we have the following visualization for the ATL::CStringT type:

<Type Name="ATL::CStringT&lt;wchar_t,*&gt;">
  <DisplayString>{m_pszData,su}</DisplayString>
</Type>

The CStringT object looks like:

CStringT DisplayString element

The visualization displays a CStringT object in a variable window like this:

Adding a StringView element will indicate to the debugger that this value can be viewed by a text visualization:

<Type Name="ATL::CStringT&lt;wchar_t,*&gt;">
  <DisplayString>{m_pszData,su}</DisplayString>
  <StringView>m_pszData,su</StringView>
</Type>

Notice the magnifying glass icon shown next to the value below. Choosing the icon will launch the text visualizer which will display the string that m_pszData points to.

CStringT data with StringView visualizer

Note

Note that the expression {m_pszData,su} includes a C++ format specifier, su, to display the value as a Unicode string. See Format Specifiers in C++ for more information.

Expand

The Expand node is used to customize the children of the visualized type when the user expands it in the variable windows. It accepts a list of child nodes that define the child elements.

Note

The Expand node is optional.

  • If an Expand node is not specified in a visualization entry, Visual Studio’s default expansion rules are used.

  • If an Expand node is specified with no child nodes under it, the type won’t be expandable in the debugger windows.

Item expansion

The Item element is the most basic and the most common element to be used in an Expand node. Item defines a single child element. For example, suppose that you have a CRect class with top, left, right, and bottom as its fields and the following visualization entry:

<Type Name="CRect">
  <DisplayString>{{top={top} bottom={bottom} left={left} right={right}}}</DisplayString>
  <Expand>
    <Item Name="Width">right - left</Item>
    <Item Name="Height">bottom - top</Item>
  </Expand>
</Type>

then the CRect type is going to look like this:

CRect with Item element expansion

The expressions specified in Width and Height elements are evaluated and shown in the value column. The [Raw View] node is automatically created by the debugger for the user anytime a custom expansion is used. It is expanded in the screenshot above to show how the raw view of the object is different than its visualization. The Visual Studio default expansion creates a subtree for the base class and lists all the data members of the base class as children.

Note

If the expression of the item element points to a complex type the Item node itself will be expandable.

ArrayItems expansion

Use the ArrayItems node to have the Visual Studio debugger interpret the type as an array and display its individual elements. The visualization for std::vector is a good example using this node:

<Type Name="std::vector&lt;*&gt;">
  <DisplayString>{{size = {_Mylast - _Myfirst}}}</DisplayString>
  <Expand>
    <Item Name="[size]">_Mylast - _Myfirst</Item>
    <Item Name="[capacity]">(_Myend - _Myfirst)</Item>
    <ArrayItems>
      <Size>_Mylast - _Myfirst</Size>
      <ValuePointer>_Myfirst</ValuePointer>
    </ArrayItems>
  </Expand>
</Type>

A std::vector shows its individual elements when expanded in the variable window:

std::vector using ArrayItems expansion

At a minimum, the ArrayItems node must have:

  1. A Size expression (which must evaluate to an integer) for the debugger to understand the length of the array

  2. A ValuePointer expression that should point to the first element (which must be a pointer of an element type that is not void*).

The default value of the array lower bound 0. The value can be overridden by using a LowerBound element (examples can be found in the .natvis files shipped with Visual Studio).

Multi-dimensional arrays can also be specified. The debugger needs just a little bit more information to properly display child elements in that case:

<Type Name="Concurrency::array&lt;*,*&gt;">
  <DisplayString>extent = {_M_extent}</DisplayString>
  <Expand>
    <Item Name="extent">_M_extent</Item>
    <ArrayItems Condition="_M_buffer_descriptor._M_data_ptr != 0">
      <Direction>Forward</Direction>
      <Rank>$T2</Rank>
      <Size>_M_extent._M_base[$i]</Size>
      <ValuePointer>($T1*) _M_buffer_descriptor._M_data_ptr</ValuePointer>
    </ArrayItems>
  </Expand>
</Type>

Direction specifies whether the array is row-major or column-major order. Rank specifies the rank of the array. The Size element accepts the implicit $i parameter which it substitutes with the dimension index to find the length of the array in that dimension. For example, in the previous example, above the expression _M_extent.M_base[0] should give the length of the 0th dimension, _M_extent._M_base[1] the 1st and so on.

Here’s how a two dimensional Concurrency::array object looks in the debugger:

Two dimensional array with ArrayItems expansion

IndexListItems expansion

ArrayItems assume array elements are laid out contiguously in memory. The debugger gets to the next element by simply incrementing its pointer to the current element. To support cases where you need to manipulate the index to the value node, IndexListItems nodes can be used. Here’s a visualization using IndexListItems node:

<Type Name="Concurrency::multi_link_registry&lt;*&gt;">
  <DisplayString>{{size = {_M_vector._M_index}}}</DisplayString>
  <Expand>
    <Item Name="[size]">_M_vector._M_index</Item>
    <IndexListItems>
      <Size>_M_vector._M_index</Size>
      <ValueNode>*(_M_vector._M_array[$i])</ValueNode>
    </IndexListItems>
  </Expand>
</Type>

The only difference between ArrayItems and IndexListItems is that the ValueNode expects the full expression to the ith element with the implicit $i parameter.

LinkedListItems expansion

If the visualized type represents a linked list, the debugger can display its children by using a LinkedListItems node. Here’s the visualization for the CAtlList type using this feature:

<Type Name="ATL::CAtlList&lt;*,*&gt;">
  <DisplayString>{{Count = {m_nElements}}}</DisplayString>
  <Expand>
    <Item Name="Count">m_nElements</Item>
    <LinkedListItems>
      <Size>m_nElements</Size>
      <HeadPointer>m_pHead</HeadPointer>
      <NextPointer>m_pNext</NextPointer>
      <ValueNode>m_element</ValueNode>
    </LinkedListItems>
  </Expand>
</Type>

The Size element refers to the length of the list. HeadPointer points to the first element, NextPointer refers to the next element, and ValueNode refers to the value of the item.

Note

  • The NextPointer and ValueNode expressions are evaluated in the context of the linked list node element and not the parent list type. In the example above, CAtlList has a CNode class (found in atlcoll.h) that represents a node of the linked list. m_pNext and m_element are fields of that CNode class and not of CAtlList class.

  • The ValueNode can be left empty or have this to refer to the linked list node itself.

TreeItems expansion

If the visualized type represents a tree, the debugger can walk the tree and display its children by using a TreeItems node. Here’s the visualization for the std::map type using this feature:

<Type Name="std::map&lt;*&gt;">
  <DisplayString>{{size = {_Mysize}}}</DisplayString>
  <Expand>
    <Item Name="[size]">_Mysize</Item>
    <Item Name="[comp]">comp</Item>
    <TreeItems>
      <Size>_Mysize</Size>
      <HeadPointer>_Myhead-&gt;_Parent</HeadPointer>
      <LeftPointer>_Left</LeftPointer>
      <RightPointer>_Right</RightPointer>
      <ValueNode Condition="!((bool)_Isnil)">_Myval</ValueNode>
    </TreeItems>
  </Expand>
</Type>

The syntax is very similar to the LinkedListItems node. LeftPointer, RightPointer, and ValueNode are evaluated under the context of the tree node class, and ValueNode can be left empty or have this to refer to the tree node itself.

ExpandedItem expansion

The ExpandedItem element can be used to generate an aggregated child view by displaying properties of base classes or data members as if they were children of the visualized type. The specified expression is evaluated and the child nodes of the result are appended to the child list of the visualized type. For example, suppose we have a smart pointer type auto_ptr<vector<int>> which will typically be displayed as:

auto_ptr<vector<int>> default expansion

To see the values of the vector, you have to drill down two levels in the variable window passing through _Myptr member. By adding an ExpandedItem element, you can eliminate the _Myptr variable from the hierarchy and directly view the vector elements::

<Type Name="std::auto_ptr&lt;*&gt;">
  <DisplayString>auto_ptr {*_Myptr}</DisplayString>
  <Expand>
    <ExpandedItem>_Myptr</ExpandedItem>
  </Expand>
</Type> 

auto_ptr<vector<int>> ExpandedItem expansion

The example below shows how to aggregate properties from the base class in a derived class. Suppose the CPanel class derives from CFrameworkElement. Instead of repeating the properties that come from the base CFrameworkElement class, the ExpandedItem node allows those properties to be appended to the child list of the CPanel class. The nd format specifier which turns off visualization matching for the derived class is necessary here. Otherwise, the expression *(CFrameworkElement*)this will cause the CPanel visualization to be applied again because the default visualization type matching rules consider it the most appropriate one. Using the nd format specifier instructs the debugger to use the base class visualization or the base class default expansion if the base class doesn’t have a visualization.

<Type Name="CPanel">
  <DisplayString>{{Name = {*(m_pstrName)}}}</DisplayString>
  <Expand>
    <Item Name="IsItemsHost">(bool)m_bItemsHost</Item>
    <ExpandedItem>*(CFrameworkElement*)this,nd</ExpandedItem>
  </Expand>
</Type>

Synthetic Item expansion

Where the ExpandedItem element provides a flatter view of data by eliminating hierarchies, the Synthetic node does the opposite. It allows you to create an artificial child element (that is, a child element that is not a result of an expression). This child element can contain children elements of its own. In the following example, the visualization for the Concurrency::array type uses a Synthetic node to show a diagnostic message to the user:

<Type Name="Concurrency::array&lt;*,*&gt;">
  <DisplayString>extent = {_M_extent}</DisplayString>
  <Expand>
    <Item Name="extent" Condition="_M_buffer_descriptor._M_data_ptr == 0">_M_extent</Item>
    <ArrayItems Condition="_M_buffer_descriptor._M_data_ptr != 0">
      <Rank>$T2</Rank>
      <Size>_M_extent._M_base[$i]</Size>
      <ValuePointer>($T1*) _M_buffer_descriptor._M_data_ptr</ValuePointer>
    </ArrayItems>
    <Synthetic Name="Array" Condition="_M_buffer_descriptor._M_data_ptr == 0">
      <DisplayString>Array members can be viewed only under the GPU debugger</DisplayString>
    </Synthetic>
  </Expand>
</Type>

Concurrency::Array with Sythentic element expansio

HResult

The HResult element enables you to customize the information that is displayed for an HRESULT in debugger windows. The HRValue element must contain the 32-bit value of the HRESULT that is to be customized. The HRDescription element contains the information that is displayed in the debugger.

  <HResult Name="MY_E_COLLECTION_NOELEMENTS">
    <HRValue>0xABC0123</HRValue>
    <HRDescription>No elements in the collection.</HRDescription>
  </HResult>

UIVisualizer

A UIVisualizer element registers a graphical visualizer plug-in with the debugger. A graphical visualizer plug-in creates a dialog box or another interface to display a variable or object in a manner that is appropriate to its data type. The visualizer plug-in must be authored as a VSPackage and needs to expose a service that can be consumed by the debugger. The .natvis file contains registration information for the plug-in such as its name, the GUID of the service exposed, and also the types it can visualize.

Here's an example of a UIVisualizer element:

<?xml version="1.0" encoding="utf-8"?>
<AutoVisualizer xmlns="https://schemas.microsoft.com/vstudio/debugger/natvis/2010">
    <UIVisualizer ServiceId="{5452AFEA-3DF6-46BB-9177-C0B08F318025}" 
        Id="1" MenuName="Vector Visualizer"/>
    <UIVisualizer ServiceId="{5452AFEA-3DF6-46BB-9177-C0B08F318025}" 
        Id="2" MenuName="List Visualizer"/>
.
.
</AutoVisualizer>

A UIVisualizer is identified by a ServiceId - Id attribute pair. ServiceId is the GUID of the service exposed by the visualizer package, Id is a unique identifier that can be used to differentiate visualizers if a service provides more than one visualizer. In the example above, the same visualizer service provides two visualizers.

The MenuName attribute is what the users see as the name of the visualizer when they open the drop-down menu next to the magnifying glass icon in the debugger variable windows, for example:

UIVisualizer menu shortcut menu

Each type defined in the .natvis file must explicitly list the UI visualizers that can display them. The debugger matches the visualizer references in the type entries to match types with the registered visualizers. For example, the following type entry for std::vector references the UIVisualizer in our example above.

  <Type Name="std::vector&lt;int,*&gt;">
    <UIVisualizer ServiceId="{5452AFEA-3DF6-46BB-9177-C0B08F318025}" Id="1" />
  </Type>