Ignoring Automatic Initialization for Code Analysis

Gabor Horvath

Reading uninitialized memory is one of the major sources of security vulnerabilities in C and C++ programs. Microsoft developed many tools to find such errors including compiler warnings, static analysis checks, and more recently: code instrumentation.  For a more detailed overview of uninitialized memory related vulnerabilities and mitigations please refer to Microsoft Security Response Center’s great blog post. This blog post summarizes the potential interactions between code analysis and code instrumentation and improvements we’ve made in Visual Studio 2019 version 16.9.1. 

When we turn on the automatic initialization features of MSVC it will initialize certain constructs on the stack with a pattern. This solution can help mitigate the risks of reading uninitialized memory. However, to keep the performance costs of this mitigation minimal, the compiler will not initialize everything. It is a best effort method that tries to hit a good balance in mitigating security risks and avoiding noticeable performance regressions. Moreover, this is a non-standard feature that might not be available (or might behave differently) in other compilers, or in other versions of the same compiler. As a result, users should never rely on such an instrumentation. The proper fix is to explicitly initialize memory in the source code and only use instrumentation as a mitigation for any error that slipped through the code reviews, static analysis or any other tools of the QA process. 

As a result, we want the compiler to warn on the following code regardless of the options used to compile the code: 

void g(int); 
void f() { 
    int l; 
    g(l); // Warning C6001 expected regardless of the build configuration. 
}

Starting from Visual Studio 2019 version 16.9.1, and 16.10 Preview 2 we ensured that the code analysis always sees the code as written as opposed to the instrumented version.  This behavior is in line with other toolchains and encourages developers to not rely on the automatic initialization feature.

Download the latest Visual Studio 2019 Preview today and give it a try. We’d love to hear from you to help us prioritize and build the right features for you. We can be reached via the comments below, Developer Community, and Twitter (@VisualC). The best way to file a bug or suggest a feature is via Developer Community.