AddressSanitizer (ASan) for Windows with MSVC

Augustin Popa

This post was last updated on March 24th, 2021 with the latest information on ASan support.

Note: This feature is now generally available. To get started, take a look at the official AddressSanitizer for Windows with MSVC documentation. Many experience improvements have been made since this blog post was published, and our docs have the latest information.

 

We are pleased to announce AddressSanitizer (ASan) support for the MSVC toolset. ASan is a fast memory error detector that can find runtime memory issues such as use-after-free and perform out of bounds checks. Support for sanitizers has been one of our more popular suggestions on Developer Community, and we can now say that we have an experience for ASan on Windows, in addition to our existing support for Linux projects.

At Microsoft, we believe that developers should be able to use the tools of their choice, and we are glad to collaborate with the LLVM team to introduce more of their tooling into Visual Studio. In the past, we also incorporated tools like clang-format, and most recently, clang-tidy. MSVC support for ASan is available in our second Preview release of Visual Studio 2019 version 16.4.

To bring ASan to Windows and MSVC, we made the following changes:

  • The ASan runtime has been updated to better target Windows binaries
  • The MSVC compiler can now instrument binaries with ASan
  • CMake and MSBuild integrations have been updated to support enabling ASan
  • The Visual Studio debugger now can detect ASan errors in Windows binaries
  • ASan can be installed from the Visual Studio installer for the C++ Desktop workload

When you’re debugging your ASan-instrumented binary in Visual Studio, the IDE Exception Helper will be displayed when an issue is encountered, and program execution will stop. You can also view detailed ASan logging information in the Output window.

ASan Exception in Visual Studio

Installing ASan support for Windows

ASan is included with the C++ Desktop workload by default for new installations. However, if you are upgrading from an older version of Visual Studio 2019, you will need to enable ASan support in the Installer after the upgrade:

Visual Studio Installer with ASan checkbox

You can click Modify on your existing Visual Studio installation from the Visual Studio Installer to get to the screen above.

Note: if you run Visual Studio on the new update but have not installed ASan, you will get the following error when you run your code:

LNK 1356 – cannot find library ‘clang_rt.asan_dynamic-i386.lib’

 

Turning on ASan for Windows MSBuild projects

You can turn on ASan for an MSBuild project by right-clicking on the project in Solution Explorer, choosing Properties, navigating under C/C++ > General, and changing the Enable Address Sanitizer (Experimental) option. The same approach can be used to enable ASan for MSBuild Linux projects.

Enabling ASan in the MSBuild project properties

Note: Right now, this will only work for x86 Release targets, though we will be expanding to more architectures in the future.

 

Turning on ASan for Windows CMake projects

To enable ASan for CMake projects targeting Windows, do the following:

  1. Open the Configurations dropdown at the top of the IDE and click on Manage Configurations. This will open the CMake Project Settings UI, which is saved in a CMakeSettings.json file.
  2. Click the Edit JSON link in the UI. This will switch the view to raw .json.
  3. Under the x86-Release configuration, add the following property: “addressSanitizerEnabled”: true

You may get a green squiggle under the line above with the following warning: Property name is not allowed by the schema. This is a bug that will be fixed shortly – the property will in fact work.

Here is an image of the relevant section of the CMakeSettings.json file after the change:

Enabling ASan in the CMakeSettings.json file

We will further simplify the process for enabling ASan in CMake projects in a future update.

 

Contributions to ASan Runtime

To enable a great Windows experience, we decided to contribute to the LLVM compiler-rt project and reuse their runtime in our implementation of ASan. Our contributions to the ASan project include bug fixes and improved interception for HeapAlloc , RtlAllocateHeap , GlobalAlloc , and LocalAlloc , along with their corresponding Free , ReAllocate , and Size functions. Anyone can enable these features by adding the following to the ASAN_OPTIONS environment variable for either Clang or MSVC on Windows:

set ASAN_OPTIONS= windows_hook_rtl_allocators=true

Additional options can be added with a colon at the end of the line above.

 

Changes to MSVC to enable ASan

To enable ASan, c1.dll and c2.dll have been modified to add instrumentation to programs at compile time. For a 32-bit address space, about 200 MB of memory is allocated to represent (or ‘shadow’) the entire address space. When an allocation is made, the shadow memory is modified to represent that the allocation is now valid to access. When the allocation is freed or goes out of scope, the shadow memory is modified to show that this allocation is no longer valid. Memory accesses which are potentially dangerous are checked against their entry in the shadow memory to verify that the memory is safe to access at that time. Violations are reported to the user as output from either stderr or an exception window in Visual Studio. The allocation data in the shadow memory is checked before the access happens. The AddressSanitizer algorithm enables error reports to show exactly where the problem occurred and what went wrong.

This means that programs compiled with MSVC + ASan also have the appropriate clang_rt.asan library linked for their target. Each library has a specific use case and linking can be complicated if your program is complex.

 

Compiling with ASan from the console

If you are on Visual Studio version 16.9 Preview 3 or later, if thefsanitize=address compiler flag is specified, ASan libraries are automatically linked (both for console and IDE builds).

For console compilation, if you are on Visual Studio version 16.9 Preview 2 or earlier, you will have to link the ASan libraries manually. Here are the libraries required for an x86 target:

  • clang_rt.asan-i386.lib – static runtime compatible with /MT CRT.
  • clang_rt.asan_cxx-i386.lib -static runtime component which adds support for new and delete, also compatible with /MT CRT.
  • clang_rt.asan_dynamic-i386.lib – dynamic import library, compatible with /MD CRT.
  • clang_rt.asan_dynamic-i386.dll – dynamic runtime DLL, compatible with /MD.
  • clang_rt.asan_dynamic_runtime_thunk-i386.lib – dynamic library to import and intercept some /MD CRT functions manually.
  • clang_rt.asan_dll_thunk-i386.lib – import library which allows an ASAN instrumented DLL to use the static ASan library which is linked into the main executable. Compatible with /MT CRT.

Once you have selected the correct ASan runtime to use, you should add /wholearchive:<library to link> to your link line and add the appropriate library to your executables. The clang_rt.asan_dynamic_i386.dll is not installed into System32, so when running you should make sure it is available in your environment’s search path.

Some additional instructions:

  • When compiling a single static EXE: link the static runtime (asan-i386.lib) and the cxx library if it is needed.
  • When compiling an EXE with the /MT runtime which will use ASan-instrumented DLLs: the EXE needs to have asan-i386.lib linked and the DLLs need the clang_rt.asan_dll_thunk-i386.lib. This allows the DLLs to use the runtime linked into the main executable and avoid a shadow memory collision problem.
  • When compiling with the /MD dynamic runtime: all EXE and DLLs with instrumentation should be linked with copies of asan_dynamic-i386.lib and clang_rt.asan_dynamic_runtime_thunk-i386.lib. At runtime, these libraries will refer to the clang_rt.asan_dynamic-i386.dll shared ASan runtime.

The ASan runtime libraries patch memory management functions at run-time and redirect executions to an ASan wrapper function which manages the shadow memory. This can be unstable if the runtime environment differs from what the libraries have been written to expect. Please submit any compile or run time errors which you encounter while using ASan via the feedback channels below!

Note: Loading ASan-instrumented DLLs with an non-ASan-instrumented EXE without linking the clang_rt.asan_dynamic and clang_rt.asan_dynamic­_runtime_thunk library will result in false positive ASan reports. This is due to allocations being created in-between program initialization and whenever the ASan instrumented DLL is loaded. Any allocations which are created during this window will result in an erroneous bug report when they are passed into the newly intercepted CRT functions. These false positive reports are avoidable if you link the dynamic import libraries into the main executable; since linking the dynamic runtime libraries in this manner allows the interceptors to initialize at the proper time. Be sure to use the /wholearchive linker flag to ensure asan’s init routines are not optimized away in the main exe.

 

Send us feedback!

Your feedback is key for us to deliver the best experience running ASan in Visual Studio. We’d love for you to try out the latest Preview version of Visual Studio 2019 version 16.4 and let us know how it’s working for you, either in the comments below or via email. If you encounter problems with the experience or have suggestions for improvement, please Report A Problem or reach out via Developer Community. You can also find us on Twitter @VisualC.

62 comments

Discussion is closed. Login to edit/delete existing comments.

  • Mark de Wit 0

    I love the idea of this feature, but sadly cannot get it to work in my test console application:

    int* x = new int[100];
    x[100] = 1;

    I have both compiler and linker flags set, I see the runtime DLL being loaded in the debugger, but no run-time errors are being thrown…
    ‘apc.exe’ (Win32): Loaded ‘C:\test\build32\bin\RelWithDebInfo\clang_rt.asan_dynamic-i386.dll’.

    Visual Studio Version 16.4.1…

    Is there a way of testing whether this really is active?

    • Brian Brooks (US) 0

      I got AddressSanitizer to notice this buggy code…
      char* pszCrashme;
      pszCrashme = (char*)calloc(5, sizeof(char));
      pszCrashme[5] = “DIE”;
      free(pszCrashme);

  • Vyacheslav Lanovets 0

    This is a really cool feature, no slow 3rd party tools needed.

    Still, in our development practice the hardest to find bugs is UMR (Uninitialized Memory Read). The application may behave normally for years and then you change compiler option or move code around and it starts producing wrong answers. My understanding MSan sanitizer can find such bugs. So, please, don’t stop on Asan only.

  • Aron Yu 0

    I still get the link error:
    LNK 1356 – cannot find library ‘clang_rt.asan_dynamic-i386.lib’

    For WinRT C++ projects.

    • Matthew McGovernMicrosoft employee 0

      I would double check that your path is set correctly, check that you’re using the correct installation of VS (if you have multiple copies of VS installed it can be easy to mix them up; at least in my personal experience), and then finally check that the ASAN package is installed when you selected the c++ tools from the Vs installer.

  • Sohno Mehar 0

    The @HostListener decorator is used to set up an event binding on the host element and is applied to a method. The example directive relies on the browser’s DOM API to manipulate its host element, both to add and remove class memberships and to receive the click event. Working with the DOM API in an Angular application is a useful technique, but it does mean that your directive can be used only in applications that are run in a web browser. Angular is intended to be run in a range of different execution environments, and not all of them can be assumed to provide the DOM API. Read More!

  • gast128 0

    Nice addition though array bounds checking is already present for decades in Visual Studio when using debug crt. It only reports on freeing the memory. Then again the day of using raw arrays is mostly gone for me since using C++.

  • Daniel BocaMicrosoft employee 0

    Congratulation for this feature.

    I haven’t seen anywhere what are the exact cl.exe/link.exe/MsBuild options to enable the feature in a non-VS environment, can anyone share them ?

    Thanks,
    Daniel

  • Peter 0

    Hi!
    We found a few interesting issues in our source \o/
    But we use several SSE2 constructions in _asm {} blocks (image analysis) and we get a few weird exceptions in the middle of these short functions. Mostly “Access violation writing location 0xxxxxx”. They come probably from ASan, we think they are false alarm. Is there any pragma or attributes to turn off ASan on a function?
    __attribute__((no_sanitize(“address”)))
    or
    [[sanitize::no]]

    // downloaded ASan pdb from Symbol server, it started not to work. I had to remove the fresh pdb and disable to make to work again

    • Peter 0

      Environment variable:
      ASAN_OPTIONS=suppressions=project.supp

      and project.supp:
      src:source1.cpp

      ASan runtime crashes. If I remove ASAN_OPTIONS, ASan works again.

  • Vojtech Bubnik 0

    How does CMakeSettings.json relate to CMake parameters?

    How do I set this addressSanitizerEnabled flag when generating a ninja script by cmake executed from the command line?
    We need this to build asan builds on a build server.

    We are really looking forward to the 64bit ASAN builds. To me personally the ASAN builds may be a good reason to develop on Linux instead.

    Thank you.

  • Gyorgy Tamasi 0

    Example config: a VS-based project targeting a dll (with /fsanitize=address activated; the required libs are specified, everything is ready to work).
    MSVC-based AddressSanitizer: Is there any currently supported way (without explicitly splitting the original project into 2 separate parts – sanitized & ignored parts) to use any of the theoretically available solutions for compile-time blacklisting of some specific source files or functions in the code-base of the project?

    # The /fsanitize-blacklist=blacklist_fn compiler option seems to be unsupported now.
    # There is a default blacklist sample file (asan_blacklist.txt) in the directory of compiler binaries, but changing it does not seem to imply any effect.
    # The attribute based ([[no_sanitize(“address”)]] or similar) deactivation for some specific functions seems to be unsupported now.
    # The preprocessor based conditional compilation (__has_feature(address_sanitizer)) seems to be unsupported now.

    [The runtime suppression mode (ASAN_OPTIONS=suppressions=supp_fn) with its different capabilities comparing to the compile-time blacklisting seems to work.]

    • Matthew McGovernMicrosoft employee 0

      This is accurate at the moment. Suppressions should work, as always please report any bugs you encounter. The other options are coming but aren’t in the release yet. We will be adding something along the lines of _declspec(nosanitize) and supporting the addition of a denylist for compile-time function instrumentation as part of removing the ‘experimental’ tag on the feature.

      • Avi Sengupta 0

        Hi,

        It would be great if you could share when is x64 bit support planned for.

        Thanks – Avi

  • Terens Tare 0

    ASan for Windows looks like the news wee needed before C++20! It would be great if other sanitizers are ported for Visual Studio Support.
    However, I use CMake to build my project C++ using Visual Studio Build Tools (v142) and I thought using ASan would help me be more productive, but even thought I read this blog post several times, I can’t set up ASan with the MSVC compiler and CMake correctly (I don’t use Visual Studio, but Visual Studio Code). I have installed experimental ASan support “packages” and also tried using the /fsanitize=address, but cl.exe just ignores it.

Feedback usabilla icon