Section 10.24

MemorySanitizer

Full name: MemorySanitizer, usually shortened to MSan. The name joins the words memory and sanitizer; it is not an abbreviation.

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

  1. 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.

  2. Poisoning. Memory from malloc and every new stack variable start poisoned. Global and static variables, which C sets to zero, and memory from calloc start initialized.

  3. Propagation. A store copies the stored value’s shadow to the target, and storing a constant clears it; memcpy copies 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, so x & 0 is initialized even when x is not. For addition and most other arithmetic, a result bit is marked when the same bit of either operand is marked.

  4. Checks. MSan prints WARNING: MemorySanitizer: use-of-uninitialized-value with 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 to write. An option switches off the check on arguments and return values.

  5. 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.

  1. memcpy(c, b, 4) copies the data and the shadow into a second buffer c. No report: copying is allowed.

  2. s = c[0] + c[3] adds 16, the value of 0x10, to an unknown byte. The shadow of s is not zero, but there is still no report.

  3. m = c[3] & 0x00 is 0 whatever c[3] holds, and the exact AND rule gives m the shadow 0.

  4. if (s > 100) branches on s. MSan reports, because the outcome depends on a byte nobody wrote. With origin tracking, the report names the malloc call 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 V(x)V(x) for the bits of a value xx and S(x)S(x) for its shadow bits, where a 1 in S(x)S(x) marks the matching bit of V(x)V(x) as uninitialized. Write &\mathbin{\&} and |\mathbin{|} for bitwise AND and OR. MSan maintains these rules:

At a checked use of a value xx, such as the condition of a branch, MSan reports exactly when S(x)≠0S(x) \ne 0.

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 nn 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.

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].