Definition
MemorySanitizer (MSan) is a sanitizer §10.21 in the Clang §12.17 compiler, checks added to a program when it is compiled, that finds uses of uninitialized memory in C and C++: reads of memory that the program has not written since obtaining it. For every bit of program memory, MSan keeps a shadow bit recording whether that bit is initialized, carries these records along as values are copied and computed, and reports when an uninitialized value decides a branch, forms an address, or is passed to or returned from a function.
The idea
A receiver fills a 16-byte header structure from a radio packet. A short packet carries only 12 bytes; the code forgets to set the last 4 and later tests a flags field stored in them. The memory is valid, so AddressSanitizer §10.22, which checks whether an address may be accessed, sees nothing wrong. The bytes hold whatever the previous user of that memory left there: part of an earlier packet, or a secret. Behavior now depends on history, so the failure comes and goes.
Reporting every read of uninitialized memory would bury such defects in noise. Copying a structure also copies its struct padding §4.27, the unused bytes between fields, and copying a partly filled buffer is normal. MSan instead lets a mark, ‘not yet written’, travel with every uninitialized bit, and it complains only when a marked bit can change what the program does: a branch, an address, or data handed to the outside. This is a form of taint tracking §3.19, which follows marked data through a computation. The simple picture differs from MSan in one respect: MSan computes the marks exactly for some operations and approximately for others.
How it works
Shadow memory. For each byte of program memory, MSan reserves a shadow byte at an address computed from the program address by a fixed formula. A shadow bit of 1 marks the matching bit as uninitialized, which MSan calls poisoned; a 0 marks it as initialized.
Poisoning. Memory from
mallocand every new stack variable start poisoned. Global and static variables, which C sets to zero, and memory fromcallocstart initialized.Propagation. A store copies the stored value’s shadow to the target, and storing a constant clears it;
memcpycopies the shadow with the data. For a computation, MSan derives the result’s shadow from the operands’ values and shadows. Bitwise AND §4.50 has an exact rule, sox & 0is initialized even whenxis not. For addition and most other arithmetic, a result bit is marked when the same bit of either operand is marked.Checks. MSan prints
WARNING: MemorySanitizer: use-of-uninitialized-valuewith a stack trace when a poisoned value is the condition of a branch, a pointer used for a memory access, an argument or return value of a function, or data given to certain C library calls, such as the buffer passed towrite. An option switches off the check on arguments and return values.Interceptors. The run-time library replaces more than 70 common C library functions with versions that update the shadow.
read, for example, marks the bytes it filled as initialized.
Programs are built and linked with -fsanitize=memory. The origin-tracking option
-fsanitize-memory-track-origins=2
also records where each uninitialized value was created and which stores it passed through, which makes a report far easier to act on. The Clang documentation gives a typical slowdown of 3 times, a further factor of 1.5 to 2 with origin tracking, and twice the normal memory use, 3 times with origin tracking. MSan runs on Linux and a few other Unix-like operating systems. It cannot share a build with AddressSanitizer or ThreadSanitizer §10.25, because each of the three needs its own layout of shadow memory.
Worked example
A program obtains a 4-byte buffer b from malloc. Its shadow is FF FF FF FF: all 32 bits poisoned. The program writes 0x10, 0x20 and 0x30 into b[0], b[1] and b[2], and forgets b[3]. The shadow becomes 00 00 00 FF.
memcpy(c, b, 4)copies the data and the shadow into a second bufferc. No report: copying is allowed.s = c[0] + c[3]adds 16, the value of0x10, to an unknown byte. The shadow ofsis not zero, but there is still no report.m = c[3] & 0x00is 0 whateverc[3]holds, and the exact AND rule givesmthe shadow 0.if (s > 100)branches ons. MSan reports, because the outcome depends on a byte nobody wrote. With origin tracking, the report names themalloccall as the origin.
Now let the bytes be written instead by fill(b, 4), a function in a prebuilt library that was not compiled with MSan, and let it write all 4 bytes, with b[3] set to 0x40. MSan never sees these stores, so the shadow stays FF FF FF FF, and the branch if (b[3] == 0x40) is reported although every byte is initialized: a false positive §1.22. The opposite error is also possible. Suppose fill leaves b[3] unwritten and copies it into a global variable, whose shadow is 0. The mark is lost, and a later branch on that global goes unreported: a false negative.
Stated precisely
Write for the bits of a value and for its shadow bits, where a 1 in marks the matching bit of as uninitialized. Write and for bitwise AND and OR. MSan maintains these rules:
copy and store: ;
bitwise AND, : , so a result bit is marked only if an uninitialized operand bit can change it;
most other arithmetic: , bit by bit.
At a checked use of a value , such as the condition of a branch, MSan reports exactly when .
These rules match the program only if MSan sees every write to memory, through instrumented code or through an interceptor. A result therefore rests on three assumptions: all code that writes the memory involved is instrumented or intercepted; no inline assembly writes memory; and the use executes in this run. Under these assumptions, a report means that an uninitialized bit reached a checked use. A clean run means only that no marked value reached a checked use on the paths that ran.
Limits and common mistakes
Initialized does not mean correct. A fully initialized length field chosen by an attacker can still be out of range; checking values against their rules is a separate job.
Uninstrumented code corrupts the shadow in both directions, as the worked example shows. Prebuilt libraries, the C++ standard library unless it is rebuilt with MSan, and hand-written assembly are the usual sources. The Clang documentation therefore requires all program code, libraries included, to be instrumented, with the interceptors covering the C library.
A blanket suppression is the wrong fix for a false positive. The function __msan_unpoison(p, n), declared in the header sanitizer/msan_interface.h, marks exactly bytes at address p as initialized. Use it only at a real boundary, such as a buffer that a hardware device or an assembly routine is documented to fill, and only for the bytes it fills. Marking more bytes hides real defects.
Writing a structure with uninitialized padding to a file or a network socket is reported through the write interceptor. Such a report usually marks a real information leak: old memory contents leave the program.
Only executed paths are checked, and only on a host operating system. Code for a microcontroller §6.1 must first be built for the host with its hardware replaced, and the result then covers that host build.
Valgrind’s Memcheck tool finds the same class of error in unmodified programs, uninstrumented libraries included, by translating machine code while the program runs, at a much higher slowdown.
Questions answered
Why do uninstrumented dependencies complicate the result?
Uninstrumented dependencies complicate the result because MemorySanitizer (MSan) learns which memory is initialized only from code it instrumented and from the C library functions its run-time library intercepts. A library compiled without MSan, or inline assembly, reads and writes memory without updating the shadow bits, MSan’s record of which bits have been written. Two kinds of wrong result follow.
False reports. The library fills a buffer, MSan still marks it as uninitialized, and the program’s next branch on that buffer is reported although the data is fine.
Missed reports. The library branches on uninitialized data where no check exists, or it copies uninitialized bytes into memory marked as initialized, which erases the mark, so later uses go unreported.
Near such a boundary, neither a report nor a clean run can be taken at face value. The remedy is to compile every dependency with -fsanitize=memory, the C++ standard library included; to rely on the interceptors only for the C library; to mark by hand, with __msan_unpoison, only the exact bytes that remaining external code is documented to write; and to record which code stayed uninstrumented.
Related entries: Sanitizer (§10.21), AddressSanitizer (§10.22), Static, stack, and heap storage (§4.11), Fuzz harness (§10.13), Struct padding and packing (§4.27), Taint analysis (§3.19). Further reading: [105].