TExcelTAD
Home › Memory Safety & Binary Exploitation Concepts › Data Races and ThreadSanitizer (CWE-362)

Data Races and ThreadSanitizer (CWE-362)

A data race is two threads accessing the same memory at the same time, at least one of them writing, with nothing (a lock, an atomic operation) ordering the accesses. In C and C++ a data race is undefined behaviour, and in practice it produces lost updates, torn reads of half-written values, and objects observed in impossible states. Races become memory-safety bugs when the raced value controls memory: a reference count decremented twice by racing threads frees an object that another thread still uses (a use-after-free), a length read while another thread shrinks the buffer leads to an overflow, and a "check, then use" on a shared pointer can see the pointer change in between (time-of-check to time-of-use, TOCTOU). Kernel and browser exploits often start from such races. The threading model itself is taught in Operating Systems' Threads and Rust Concurrency.

Definitions

  • Read-modify-write: hits++ is three steps: load hits into a register, add 1, store it back. Another thread can run between any two of them.
  • Atomic operation: one indivisible step (atomic_fetch_add), with defined ordering between threads.
  • Mutex: a lock; code between lock and unlock runs in one thread at a time (a critical section).
  • Happens-before: the ordering relation that locks, atomics, pthread_create and pthread_join establish. Two accesses race if neither happens before the other.
  • ThreadSanitizer (TSan): -fsanitize=thread (GCC and Clang). It records, for every memory access, which thread made it and its vector clock, and reports two conflicting accesses not ordered by happens-before, even if the race didn't cause a wrong result in that run.

Why the result changes from run to run: a model

The scheduler decides when each thread runs, so a race's effect depends on timing. The model below makes the scheduler explicit. Two threads each perform one hits++ as its three steps; the program enumerates every possible interleaving of the six steps and counts the final values. It runs in your browser:

python · try it yourself
from itertools import combinations
from collections import Counter

STEPS = ["load", "add", "store"]

def run(schedule):
    """schedule: a tuple of thread ids, e.g. (0, 0, 1, 0, 1, 1)."""
    shared = 0
    reg = [0, 0]
    pc = [0, 0]
    for t in schedule:
        step = STEPS[pc[t]]
        if step == "load":  reg[t] = shared
        if step == "add":   reg[t] += 1
        if step == "store": shared = reg[t]
        pc[t] += 1
    return shared

schedules = []
for pos in combinations(range(6), 3):          # positions of thread 0's three steps
    s = [1] * 6
    for p in pos:
        s[p] = 0
    schedules.append(tuple(s))

results = Counter(run(s) for s in schedules)
print("interleavings:", len(schedules))
for value, n in sorted(results.items()):
    print(f"final hits = {value}: {n} interleavings")
lost = next(s for s in schedules if run(s) == 1)
print("one lost update:", " ".join(f"T{t}.{STEPS[sum(1 for u in lost[:i] if u == t)]}" for i, t in enumerate(lost)))
interleavings: 20
final hits = 1: 18 interleavings
final hits = 2: 2 interleavings
one lost update: T0.load T0.add T1.load T0.store T1.add T1.store

Only 2 of the 20 interleavings (one thread's three steps entirely before the other's) give the right answer. In all others both threads load the same old value and one increment is lost. On a real machine with 100,000 increments per thread, the number of lost updates varies with every run, and on a lightly loaded machine it can even be zero, which is why testing for a wrong result doesn't find races.

The bug, caught by ThreadSanitizer

TSan doesn't start in this course's sandbox: on this host's kernel it needs to restart the program without address randomisation, which Docker's security profile forbids (FATAL: ThreadSanitizer: unexpected memory mapping). The report below is therefore a recorded transcript: the toy program compiled with GCC 15.2 and -g -O1 -fsanitize=thread -pthread on Compiler Explorer. On your own Linux machine the same flags work directly.

c
#include <pthread.h>
#include <stdio.h>

static long hits;                          /* shared counter, no lock */

static void *worker(void *arg) {
    (void)arg;
    for (int i = 0; i < 100000; i++)
        hits++;                            /* BUG: unsynchronised read-modify-write */
    return NULL;
}

int main(void) {
    pthread_t a, b;
    pthread_create(&a, NULL, worker, NULL);
    pthread_create(&b, NULL, worker, NULL);
    pthread_join(a, NULL);
    pthread_join(b, NULL);
    printf("hits = %ld (expected 200000)\n", hits);
    return 0;
}
console
$ gcc -g -O1 -fsanitize=thread -pthread race.c -o race && ./race     # recorded on Compiler Explorer, gcc 15.2
hits = 200000 (expected 200000)
==================
WARNING: ThreadSanitizer: data race (pid=2)
  Read of size 8 at 0x000000404058 by thread T2:
    #0 worker /app/example.c:8 (output.s+0x4011b4)
    #1 <null> <null> (libtsan.so.2+0x54dd9)

  Previous write of size 8 at 0x000000404058 by thread T1:
    #0 worker /app/example.c:8 (output.s+0x4011e5)
    #1 <null> <null> (libtsan.so.2+0x54dd9)

  Location is global 'hits' of size 8 at 0x000000404058 (output.s+0x404058)

  Thread T2 (tid=5, running) created by main thread at:
    #0 pthread_create <null> (libtsan.so.2+0x5f090)
    #1 main /app/example.c:16 (output.s+0x40123b)

  Thread T1 (tid=4, finished) created by main thread at:
    #0 pthread_create <null> (libtsan.so.2+0x5f090)
    #1 main /app/example.c:15 (output.s+0x401224)

SUMMARY: ThreadSanitizer: data race /app/example.c:8 in worker
==================
ThreadSanitizer: reported 1 warnings
$ echo $?
66

(BuildIds removed for width.) Two lessons in one transcript. First, the result was correct: in this run the first thread finished before the second got going, so no update was lost, and a test that only checked the total would pass. Second, TSan reported the race anyway: a read by T2 and a previous write by T1 to the 8-byte global hits at line 8 (the hits++), with no synchronisation between them, plus where each thread was created (lines 15 and 16). TSan exits with code 66 when it reported anything, which fails a CI job.

Root cause

Shared mutable state with no rule about who may touch it when. The fix is to choose the rule: either only one thread owns the data (pass messages instead of sharing), or every access goes through an atomic operation or a lock.

The fix

For a counter, an atomic increment is the right tool; for anything bigger than one word (a struct, a list, "check and then update"), use a mutex around the whole operation. The program runs on Compiler Explorer:

c · try it yourself
#include <pthread.h>
#include <stdatomic.h>
#include <stdio.h>

static atomic_long hits;                   /* every ++ is one indivisible step */
static long total_len;                     /* protected by lock */
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

static void *worker(void *arg) {
    (void)arg;
    for (int i = 0; i < 100000; i++) {
        atomic_fetch_add_explicit(&hits, 1, memory_order_relaxed);
        pthread_mutex_lock(&lock);         /* a multi-step update needs a lock */
        total_len += 3;
        pthread_mutex_unlock(&lock);
    }
    return NULL;
}

int main(void) {
    pthread_t a, b;
    pthread_create(&a, NULL, worker, NULL);
    pthread_create(&b, NULL, worker, NULL);
    pthread_join(a, NULL);
    pthread_join(b, NULL);
    printf("hits = %ld, total_len = %ld\n", atomic_load(&hits), total_len);
    return 0;
}
hits = 200000, total_len = 600000

The output is the same on every run and TSan reports nothing for it. Rust enforces this at compile time: sharing a plain integer between threads for writing doesn't compile; it must be wrapped in an AtomicU64 or a Mutex (Rust Concurrency).

How races are detected

  • TSan in a dedicated CI build (it can't be combined with ASan), running the multi-threaded tests, ideally many times and under load.
  • Static analysis: Clang's -Wthread-safety with annotations (GUARDED_BY(lock)) checks at compile time that annotated data is only touched under its lock.
  • Review: every global or shared object written by more than one thread; reference counts that aren't atomic; "check then act" sequences (if (p) use(p); on a shared p); lazy initialisation without pthread_once / call_once.
  • Stress tests and schedule fuzzing (rr's chaos mode, CHESS-style tools) make rare interleavings likely.

The CWE

CWE-362: Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition'); CWE-367 is time-of-check to time-of-use. A race that frees an object still in use ends as CWE-416.

Pitfalls

  • volatile is not synchronisation. It stops the compiler from caching a value; it doesn't make ++ atomic or order accesses between threads.
  • "Benign" races on flags and counters are still undefined behaviour and still confuse optimisers. Use relaxed atomics; they cost almost nothing.
  • Atomic but not consistent: two atomic variables updated one after the other can still be observed in a mixed state. If they must change together, use one lock.

Practice

1. In the model, which two interleavings give the correct result?

T0 T0 T0 T1 T1 T1 and T1 T1 T1 T0 T0 T0: one thread's whole increment completes before the other's load.

2. Why did the TSan run print the correct total and still report a race?

TSan reports accesses that are not ordered by happens-before, whatever their effect in that run. The lost update didn't happen this time, but nothing prevented it.

3. Two threads call obj_release(o), which does if (--o->refs == 0) free(o); with a plain int refs starting at 2. Describe a bad interleaving.

Both threads load refs = 2, both compute 1, both store 1: neither frees, a leak. If other threads also take references (refs++) at the same time, a lost increment makes the count reach 0 while a reference is still held, and the object is freed while in use: a use-after-free. Make refs atomic and use the value returned by atomic_fetch_sub.

Test yourself

How many of the 20 interleavings of two hits++ gave the correct result?

  1. 0
  2. 2
  3. 10
  4. 20

Why is a correct total in a test no evidence that there is no race?

  1. The total is always right
  2. Whether an update is lost depends on timing; a lucky schedule hides the race
  3. Tests can't count
  4. TSan changes the total

Which tool reports data races?

  1. ASan
  2. MSan
  3. ThreadSanitizer (-fsanitize=thread)
  4. checksec

Which fix is right for a shared struct whose two fields must change together?

  1. Make each field atomic
  2. Protect the whole update with one mutex
  3. Declare it volatile
  4. Use more threads