Algorithm Search⌘K

Algorithmresearch

Dangling pointer nullification

Also called DangNull, pointer nullification on free.

Tracks which heap pointers refer to each object and sets them to a null value when the object is freed, so a use after free hits the null page.

Time
O(log t + d) worst
Space
Θ(t + s) extra
Where
d = the number of tracked pointers into or out of the freed object; s = the number of tracked pointers; t = the number of live heap objects
Properties
deterministiconlineiterative
Origin
Byoungyoung Lee, Chengyu Song, Yeongjin Jang, Tielei Wang, Taesoo Kim, Long Lu, Wenke Lee, 2015

Dangling pointer nullification removes dangling pointers at the moment they would be created. A run-time library keeps, for each live heap object, the set of heap locations that hold a pointer into it. The compiler adds a call after every store of a pointer into the heap that updates these sets. When the program frees an object, the library goes through its set and overwrites each location that still points into the object with a small null value. A later use of such a pointer reads or writes the null page and faults at once, and a second free of it is a free of null, which does nothing. The program does not need a check at each access. The cost is in pointer stores and in free, and pointers kept only in registers, on the stack or in globals are not changed.

In plain words

Think of a guest list for every room in a hotel: who has written down that room's number. Every time someone notes a room number in their own records, the hotel adds them to that room's list.

When a room is closed, the hotel goes down the list and crosses out the room number in each record, so it now says "no room". Anyone who later tries to use that record finds nothing there and stops, instead of walking into a room that may now belong to someone else.

The hotel only watches records kept in its own filing cabinets, the heap. Numbers someone holds in their head, or on scrap paper on the stack, are not on any list and are not crossed out.

The problem

The input is a C or C++ program that allocates and frees heap objects and stores pointers to them in other heap objects. A use after free happens when the program frees an object and later uses a pointer to it; by then the memory may hold a new object. The goal is to make each such use harmless without a check at every access, and without changing the layout of memory. Lock and key checking catches every use but checks every access; AddressSanitizer catches uses only while the freed memory is in its quarantine. Nullification makes the pointer itself invalid, so the reuse of the memory no longer matters.

The algorithm

A tree of shadow objects holds one entry per live heap object: its range [base,end)[\mathit{base}, \mathit{end}), an in-set of the heap locations that point into it, and an out-set of the locations inside it that point to other objects, each with its target. The paper uses a variant of a red-black tree for the objects and for each set. The search FIND(a)(a) returns the shadow object whose range holds aa. NULLIFY is a small non-negative value, such as 0, whose page is never mapped.

  1. TRACE(lhs, rhs) ▷ after each pointer store *lhs = rhs
  2. 1if lhs is not inside a live heap object then return ▷ stack and globals opt out
  3. 2remove the old relation of lhs from the out-set of its object and the in-set of its target
  4. 3s ← FIND(lhs); d ← FIND(rhs)
  5. 4if d = none then return
  6. 5add (lhs → d) to s.out and lhs to d.in
  7. ALLOC(n)
  8. 6b ← allocate n bytes; insert a shadow object [b, b + n) with empty sets
  9. 7return b
  10. FREE(p)
  11. 8o ← the shadow object with base p
  12. 9for each lhs in o.in do
  13. 10remove lhs from the out-set of FIND(lhs)
  14. 11if o.base ≤ M[lhs] < o.end then M[lhs] ← NULLIFY ▷ it still points into o
  15. 12for each (lhs → t) in o.out do remove lhs from t.in
  16. 13delete o from the tree; free the block

Tracing. Line L1 skips stores whose location is not in a heap object. The paper found that most pointers to heap objects that live long are themselves in the heap, while pointers on the stack are short-lived, so skipping the stack keeps the cost down. Line L2 drops the relation that lhs had before, because the store overwrites the old pointer. Line L3 finds the object of the location and the object that the new value points into. Because FIND uses ranges, pointer arithmetic needs no tracking: a pointer to the middle of an object is found by its range.

Free. Lines L9 to L11 handle the pointers into the object. Line L11 checks the current value of the location again, because the program may have overwritten it with an integer since the trace, and an integer store is not traced. Line L12 removes the object's own pointers from the in-sets of their targets, so that a later free of a target does not write into memory that is no longer this object.

The null value. With NULLIFY = 0, code that checks for null before a use keeps working, and a use without a check faults. The paper also allows other small values, and maps nothing in the low addresses, so that an access at a small offset from the null value also faults.

Example

A memory of 128 bytes: the null page [0,16)[0, 16), globals at [16,32)[16, 32) and the heap from 32. Pointers take 4 bytes.

step operation result
1 a,b,ca, b, c ← ALLOC(8) three times a=32a = 32, b=40b = 40, c=48c = 48
2 STORE-PTR(bb, a+4a + 4) b[0]b[0] points into aa: a.in={40}a.\mathit{in} = \{40\}, b.out={40→a}b.\mathit{out} = \{40 \to a\}
3 STORE-PTR(c+4c + 4, aa) a.in={40,52}a.\mathit{in} = \{40, 52\}
4 STORE-PTR(16, aa) a global points to aa; line L1 skips it
5 rr ← LOAD-PTR(bb) a copy in a register: r=36r = 36
6 FREE(aa) locations 40 and 52 now hold 0; the out-sets of bb and cc are empty
7 LOAD(LOAD-PTR(bb), 1) the pointer is 0: a fault in the null page
8 LOAD-PTR(16), and rr still 32 and 36: these copies are dangling

Steps 6 and 7 are the point of the scheme: the two heap copies are null after the free, wherever they are in the heap. Step 8 shows its limit: the global and the register copy were never traced.

Correctness

The claim is about traced pointers. Call a location ℓ\ell linked to a live object oo if the last pointer store at ℓ\ell happened while ℓ\ell was inside a live heap object, and stored a value inside oo. The in-set of oo is exactly the set of locations linked to oo, and the out-sets mirror the in-sets; each TRACE and each FREE keeps this, by lines L2 and L5 and by lines L10 and L12. So FREE(o)(o) visits every linked location, and line L11 nullifies those that still hold a value inside oo. After the free, no heap location that was linked to oo and not overwritten since holds a pointer into oo. The proof is in the correctness proof.

Proof: Free nullifies every traced heap pointer that still points into the objectfull

Setting. The program runs a finite sequence of the operations ALLOC, FREE, STORE-PTR (which runs TRACE and then writes the word), integer STORE, and loads. Pointers are stored at word-aligned addresses, so two stored words never overlap. For a live object oo, a location ℓ\ell is linked to oo if the last STORE-PTR at ℓ\ell ran while ℓ\ell lay in a live heap object ss, stored a value inside oo, and both ss and oo have stayed live since then. Write rel(ℓ)=o\mathit{rel}(\ell) = o in that case.

Lemma 1 (invariant R). After each operation, for every live object oo and every location ℓ\ell: ℓ∈o.in\ell \in o.\mathit{in} if and only if rel(ℓ)=o\mathit{rel}(\ell) = o; and s.out[ℓ]=os.\mathit{out}[\ell] = o if and only if ℓ\ell lies in the live object ss and rel(ℓ)=o\mathit{rel}(\ell) = o. No set holds a location in a freed object or names a freed target.

Proof. By induction on the number of operations. At the start there are no objects. Assume R before an operation.

  • ALLOC. Line L6 inserts a new object with empty sets. No location was linked to it, since it was not live, and no location inside it was linked to anything, since the block was free and no live object held it. R holds.
  • STORE-PTR(ℓ,v)(\ell, v). If ℓ\ell is in no live heap object, line L1 returns and rel\mathit{rel} does not change, because ℓ\ell was not linked (it was in no live object). Otherwise let ss be its object. The store replaces the old relation of ℓ\ell: line L2 removes ℓ\ell from s.outs.\mathit{out} and from the in-set of the old target, which by R is exactly where it was. Line L3 finds the object dd that holds vv. If there is none, ℓ\ell is now linked to nothing, and line L4 returns. Otherwise rel(ℓ)=d\mathit{rel}(\ell) = d, and line L5 records it in both sets. Other locations do not change, because stored words do not overlap.
  • Integer STORE and loads change no relation and no set. The relation is defined by the last pointer store, so an integer store does not remove it.
  • FREE(p)(p) with oo the object at pp. After the free, no location is linked to oo, and no location inside oo is linked to anything. Lines L9 and L10 remove each ℓ∈o.in\ell \in o.\mathit{in} from the out-set of its source, which by R is the only other set that holds ℓ\ell with target oo. Line L12 removes each ℓ∈o.out\ell \in o.\mathit{out} from the in-set of its target, which by R is the only in-set that holds it. Line L13 deletes oo and its sets. Relations between other live objects do not change. □\square

Theorem. Let FREE(p)(p) free the object o=[b,e)o = [b, e). Afterwards, every location ℓ\ell with rel(ℓ)=o\mathit{rel}(\ell) = o before the free holds NULLIFY if its word lay in [b,e)[b, e), and holds its old word otherwise. No other location changes, apart from the release of the block.

Proof. By Lemma 1, the set o.ino.\mathit{in} that line L9 visits is exactly the set of locations linked to oo. For each of them, line L11 reads the current word and writes NULLIFY only if the word lies in [b,e)[b, e). Line L11 writes only to locations in o.ino.\mathit{in}, and since stored words do not overlap, each write changes only its own word, so the order of the loop does not matter. Lines L10, L12 and L13 change only the sets and the tree. ■\blacksquare

Corollary. If the program loads a pointer from a heap location that it last wrote with a traced pointer into oo before oo was freed, it gets NULLIFY, and a load or a store through it at an offset below the size of the null page faults. A FREE through it is a free of null and does nothing. Pointers in registers, on the stack or in globals are not linked, so the theorem says nothing about them, and the tests show that such copies stay dangling.

Termination. TRACE and ALLOC run a bounded number of lines plus one search of a finite list. FREE runs its two loops once over finite sets, and no line adds to the set that the loop visits.

Complexity

With balanced trees, FIND takes O(log⁡t)O(\log t) time for tt live objects, so a traced pointer store costs O(log⁡t)O(\log t) in the word RAM model. FREE costs O(log⁡t)O(\log t) to find the object plus O(dlog⁡t)O(d \log t) for the dd tracked pointers into and out of it, or O(log⁡t+d)O(\log t + d) with hash sets as in the Python code. The tree takes Θ(t)\Theta(t) space and the sets Θ(s)\Theta(s) for ss tracked pointers.

Measured costs depend on how often a program stores pointers. The paper reports, in 2015, an average slowdown of 80% on SPEC CPU2006, with a wide spread between benchmarks, and it ran the Chromium browser with the scheme.

Properties

  • No per-access check. Only pointer stores and frees cost extra.
  • Not complete. Pointers that live only in registers, on the stack or in globals are not nullified, and a pointer computed from a dangling register copy is not caught.
  • Turns double free into free of null. A second free through a nullified heap pointer does nothing.
  • Deterministic. The same program and input give the same nullifications.

Variants and improvements

  • Registering every pointer. FreeSentry registers pointers, including some on the stack, in a lookup table and invalidates them when the memory is released, with the same range test before it changes a location.
  • Cheaper bookkeeping. Later systems replace the trees with per-object logs that may hold stale entries, which makes the trace cheaper and pushes the clean-up to free, and they scale to programs with many threads.
  • Sweeping instead of tracing. Instead of tracing each store, a sweeper can scan memory for values that point into freed objects, as a mark-and-sweep collector scans for reachable ones, and delay the reuse of freed memory until the scan is done.
  • Checking instead of nullifying. Lock and key checking leaves the pointers alone and checks a key at each access, which also catches register and stack copies.

When to use it

Use nullification to harden a large C++ program, such as a browser, against use after free when a check at every access is too slow and most long-lived pointers are in heap objects. It is a mitigation, not a full checker: a dangling copy on the stack or in a register can still be used, and pointers stored by code compiled without the trace are not tracked. It changes program values, so a program that compares a freed pointer with another value can behave differently. For finding bugs in testing, AddressSanitizer is simpler; if every use must be caught, use lock and key checking, and if the language can manage memory, reference counting or a garbage collector avoids the problem.

Pitfalls

  • Nullifying without the range test. If line L11 writes NULLIFY whatever the location holds, a location that the program has since overwritten with an integer or with a pointer stored by untraced code is corrupted. Test that the value still lies in [o.base,o.end)[o.\mathit{base}, o.\mathit{end}).
  • Not removing the old relation. Without line L2, a location that first pointed into oo and then into another object is still in o.ino.\mathit{in}, and the free of oo visits it. The range test saves the value, but the sets grow without bound.
  • Forgetting the out-set. Without line L12, the in-set of a target keeps locations inside the freed object. When that memory is reused and the target is freed, line L11 can write into the new object.
  • Overlapping stores. If pointers can be stored at unaligned addresses, two traced locations can overlap, and the result of line L11 depends on the order of the loop. Store pointers at word-aligned addresses.
  • A null value in mapped memory. If NULLIFY, or NULLIFY plus a small field offset, falls in mapped memory, a use of the nullified pointer reads real data instead of faulting.

Implementations

The Python code runs on a simulated memory, a bytearray with a null page, a global region and a first-fit heap, and never reads real memory. A sorted list stands in for the tree of shadow objects, and Python sets and dictionaries for the in-sets and out-sets. The tests run random programs of allocations, frees, pointer and integer stores and loads, and compare the whole memory after every step with an oracle that tracks the last traced pointer at each location. They also count the dangling copies in registers and globals that the scheme does not reach.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

dangling_pointer_nullification.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dangling-pointer-nullification/. The authors are listed in prov/2R0MXX.jsonl.

"""Dangling pointer nullification on a simulated memory.

Every heap object has a shadow object that records two sets: the heap
locations that hold a pointer into the object (in), and the locations inside
the object that hold a pointer to another object (out). Each pointer store
into the heap updates the sets. Free walks the in set and overwrites every
location that still points into the object with a null value, so a later use
of those pointers hits the null page and faults.

The memory is a Python bytearray, never real memory. It has a null page at
the bottom, a region for globals that is not tracked, and a heap. The shadow
objects are kept in a sorted list of bases; the original uses a red-black tree.
"""

from bisect import bisect_right, insort
from dataclasses import dataclass, field

WORD = 4  # bytes in a stored pointer
NULL_PAGE = 16  # any access below this address faults


class NullFault(Exception):
    """An access to the null page: a nullified pointer was used."""


class FreeError(Exception):
    """A free of an address that is not the base of a live heap object."""


@dataclass
class Shadow:
    """The shadow object of the heap object [base, end)."""

    base: int
    end: int
    inb: set[int] = field(default_factory=set)  # heap locations that point into this object
    outb: dict[int, int] = field(default_factory=dict)  # location in this object -> base of the target


class DangNullHeap:
    """A first-fit heap with pointer tracking and nullification on free.

    With t live objects: a pointer store costs O(log t) to find the two shadow
    objects; free costs O(log t) plus O(1) per tracked pointer into or out of
    the object. Precondition: pointers are stored with store_ptr, so that
    trace runs on each pointer store, at addresses that are multiples of
    WORD, so that two stored pointers never overlap.
    """

    def __init__(self, size: int = 256, globals_size: int = 32, nullify_value: int = 0) -> None:
        if not 0 <= nullify_value < NULL_PAGE:
            raise ValueError("the null value must lie in the null page")
        self.heap_start = NULL_PAGE + globals_size
        if size <= self.heap_start:
            raise ValueError("no room for a heap")
        self.mem = bytearray(size)
        self.nullify_value = nullify_value
        self.holes: list[tuple[int, int]] = [(self.heap_start, size - self.heap_start)]
        self.bases: list[int] = []
        self.shadow: dict[int, Shadow] = {}

    def find(self, a: int) -> Shadow | None:
        """The shadow object of the live heap object that holds address a, or None."""
        i = bisect_right(self.bases, a) - 1
        if i >= 0:
            s = self.shadow[self.bases[i]]
            if a < s.end:
                return s
        return None

    def trace(self, lhs: int, rhs: int) -> None:
        """Record the store of the pointer value rhs at the location lhs."""
        src = self.find(lhs)
        if src is None:  # @line L1: not in a heap object, so not tracked
            return
        old = src.outb.pop(lhs, None)  # @line L2: drop the old relation of lhs
        if old is not None and old in self.shadow:
            self.shadow[old].inb.discard(lhs)
        dst = self.find(rhs)  # @line L3
        if dst is None:  # @line L4
            return
        src.outb[lhs] = dst.base  # @line L5
        dst.inb.add(lhs)

    def alloc(self, n: int) -> int:
        """Allocate n >= 1 zeroed bytes. Return 0 if no hole is large enough."""
        if n < 1:
            raise ValueError("n must be positive")
        for i, (start, length) in enumerate(self.holes):
            if length >= n:
                break
        else:
            return 0
        if length == n:
            del self.holes[i]
        else:
            self.holes[i] = (start + n, length - n)
        self.mem[start:start + n] = bytes(n)
        insort(self.bases, start)  # @line L6
        self.shadow[start] = Shadow(start, start + n)
        return start  # @line L7

    def free(self, p: int) -> None:
        """Free the object with base p and nullify the pointers into it."""
        if p < NULL_PAGE:
            return  # free of a null pointer does nothing, as in C
        o = self.shadow.get(p)  # @line L8
        if o is None:
            raise FreeError(f"free of {p}, which is not the base of a live object")
        for lhs in list(o.inb):  # @line L9
            src = self.find(lhs)
            if src is not None:
                src.outb.pop(lhs, None)  # @line L10
            if o.base <= self._word(lhs) < o.end:  # @line L11: still points into o
                self.mem[lhs:lhs + WORD] = self.nullify_value.to_bytes(WORD, "little")
        for lhs, target in o.outb.items():  # @line L12
            if target in self.shadow:
                self.shadow[target].inb.discard(lhs)
        del self.shadow[p]  # @line L13
        self.bases.remove(p)
        self._release(p, o.end - p)

    def _word(self, a: int) -> int:
        return int.from_bytes(self.mem[a:a + WORD], "little")

    def _touch(self, a: int, w: int) -> None:
        if a < NULL_PAGE or a + w > len(self.mem):
            raise NullFault(f"access of {w} bytes at {a}")

    def store_ptr(self, lhs: int, rhs: int) -> None:
        """The instrumented pointer store *lhs = rhs."""
        self._touch(lhs, WORD)
        self.trace(lhs, rhs)
        self.mem[lhs:lhs + WORD] = (rhs % (1 << (8 * WORD))).to_bytes(WORD, "little")

    def load_ptr(self, lhs: int) -> int:
        self._touch(lhs, WORD)
        return self._word(lhs)

    def store(self, a: int, w: int, v: int) -> None:
        """A store of an integer: not traced."""
        self._touch(a, w)
        self.mem[a:a + w] = (v % (1 << (8 * w))).to_bytes(w, "little")

    def load(self, a: int, w: int) -> int:
        self._touch(a, w)
        return int.from_bytes(self.mem[a:a + w], "little")

    def _release(self, base: int, n: int) -> None:
        holes = sorted(self.holes + [(base, n)])
        merged: list[tuple[int, int]] = []
        for s, l in holes:
            if merged and merged[-1][0] + merged[-1][1] == s:
                merged[-1] = (merged[-1][0], merged[-1][1] + l)
            else:
                merged.append((s, l))
        self.holes = merged

    def check_invariant(self) -> None:
        """The in and out sets mirror each other, and every location lies in its object."""
        assert self.bases == sorted(self.shadow)
        for s in self.shadow.values():
            for lhs, target in s.outb.items():
                assert s.base <= lhs < s.end and target in self.shadow
                assert lhs in self.shadow[target].inb
            for lhs in s.inb:
                src = self.find(lhs)
                assert src is not None and src.outb.get(lhs) == s.base
test_dangling_pointer_nullification.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dangling-pointer-nullification/. The authors are listed in prov/2R0MXX.jsonl.

import random

import pytest
from dangling_pointer_nullification import NULL_PAGE, WORD, DangNullHeap, FreeError, NullFault


def test_page_example() -> None:
    h = DangNullHeap(128, globals_size=16)  # null page [0, 16), globals [16, 32), heap from 32
    a = h.alloc(8)
    b = h.alloc(8)
    c = h.alloc(8)
    assert (a, b, c) == (32, 40, 48)
    h.store_ptr(b, a + 4)  # b[0] points into a
    h.store_ptr(c + 4, a)  # c[1] points to a
    h.store_ptr(16, a)  # a global points to a: not tracked
    assert h.shadow[a].inb == {40, 52}
    assert h.shadow[b].outb == {40: 32} and h.shadow[c].outb == {52: 32}
    reg = h.load_ptr(b)  # a copy in a register
    h.store(c + 4, 4, 7)  # an integer overwrites c[1]; the relation stays
    h.store_ptr(c + 4, a)  # and a pointer store puts it back
    h.free(a)
    assert h.load_ptr(b) == 0 and h.load_ptr(c + 4) == 0  # both heap copies are null
    with pytest.raises(NullFault):
        h.load(h.load_ptr(b), 1)
    assert h.load_ptr(16) == a  # the global copy is not nullified
    assert reg == a + 4  # nor is the register copy
    assert h.shadow[b].outb == {} and h.shadow[c].outb == {}
    h.check_invariant()


def test_stale_relation_is_checked_against_the_range() -> None:
    h = DangNullHeap(128, globals_size=16)
    a = h.alloc(8)
    b = h.alloc(8)
    h.store_ptr(b, a)
    h.store(b, 4, 99)  # an integer store is not traced
    h.free(a)
    assert h.load(b, 4) == 99  # 99 is not inside a, so it is left alone
    h.check_invariant()


def test_edges() -> None:
    h = DangNullHeap(64, globals_size=16, nullify_value=8)
    with pytest.raises(FreeError):
        h.free(40)
    h.free(0)  # free of null does nothing
    a = h.alloc(16)
    b = h.alloc(16)
    assert h.alloc(1) == 0
    h.store_ptr(b, a)
    h.store_ptr(a, a + 8)  # a self pointer
    h.free(a)
    assert h.load(b, 4) == 8 and h.load(a, 4) == 8
    with pytest.raises(NullFault):
        h.load(8, 1)
    with pytest.raises(ValueError):
        DangNullHeap(64, nullify_value=16)
    h.check_invariant()


def test_random_programs_against_relation_oracle() -> None:
    rng = random.Random(2015)
    counts = {"nullified": 0, "register_missed": 0, "global_missed": 0, "faults": 0}
    for _ in range(500):
        size = rng.choice([96, 160, 256])
        h = DangNullHeap(size, globals_size=16)
        mem = bytearray(size)
        objs: list[dict] = []
        rel: dict[int, int] = {}  # location -> object that the traced pointer there points into
        regs: list[int] = [0]

        def live_at(a: int) -> int | None:
            for k, o in enumerate(objs):
                if o["live"] and o["base"] <= a < o["base"] + o["n"]:
                    return k
            return None

        for _ in range(rng.randint(5, 50)):
            op = rng.random()
            if op < 0.2:
                n = rng.randint(4, 16)
                p = h.alloc(n)
                if p:
                    objs.append({"base": p, "n": n, "live": True})
                    mem[p:p + n] = bytes(n)
                    regs.append(p)
            elif op < 0.3:
                r = rng.choice(regs) + rng.randint(-4, 12)
                regs.append(max(r, 0))
            elif op < 0.6:
                live = [o for o in objs if o["live"]]
                if rng.random() < 0.15:
                    lhs = rng.randrange(NULL_PAGE, NULL_PAGE + 16 - WORD + 1)  # a global
                elif live and rng.random() < 0.7:
                    o = rng.choice(live)  # a word inside a live object
                    lhs = o["base"] + rng.randrange(o["n"] - WORD + 1)
                else:
                    lhs = rng.randrange(h.heap_start, size - WORD + 1)
                lhs -= lhs % WORD  # pointers are stored at aligned addresses
                rhs = rng.choice(regs)
                src = live_at(lhs)
                if src is not None:
                    rel.pop(lhs, None)
                    dst = live_at(rhs)
                    if dst is not None:
                        rel[lhs] = dst
                h.store_ptr(lhs, rhs)
                mem[lhs:lhs + WORD] = rhs.to_bytes(WORD, "little")
            elif op < 0.7:
                a = rng.randrange(NULL_PAGE, size - WORD + 1)
                v = rng.randrange(1 << 32) if rng.random() < 0.5 else rng.randrange(size)
                h.store(a, WORD, v)
                mem[a:a + WORD] = v.to_bytes(WORD, "little")
            elif op < 0.8:
                a = rng.randrange(NULL_PAGE, size - WORD + 1)
                assert h.load_ptr(a) == int.from_bytes(mem[a:a + WORD], "little")
                regs.append(h.load_ptr(a))
            elif op < 0.88:
                r = rng.choice(regs)
                if r < NULL_PAGE:
                    with pytest.raises(NullFault):
                        h.load(r, 1)
                    counts["faults"] += 1
                elif r < size:
                    assert h.load(r, 1) == mem[r]
            else:
                live = [k for k, o in enumerate(objs) if o["live"]]
                if not live:
                    continue
                x = rng.choice(live)
                o = objs[x]
                lo, hi = o["base"], o["base"] + o["n"]
                for lhs in [l for l, t in rel.items() if t == x]:
                    if lo <= int.from_bytes(mem[lhs:lhs + WORD], "little") < hi:
                        mem[lhs:lhs + WORD] = bytes(WORD)
                        counts["nullified"] += 1
                    del rel[lhs]
                for lhs in [l for l in rel if lo <= l < hi]:
                    del rel[lhs]
                h.free(lo)
                o["live"] = False
                counts["register_missed"] += sum(1 for r in regs if lo <= r < hi)
                counts["global_missed"] += sum(
                    1 for g in range(NULL_PAGE, NULL_PAGE + 16 - WORD + 1)
                    if lo <= int.from_bytes(mem[g:g + WORD], "little") < hi
                )
            assert h.mem == mem
            h.check_invariant()
    assert counts["nullified"] > 100 and counts["faults"] > 50
    assert counts["register_missed"] > 50 and counts["global_missed"] > 5

History

Lee, Song, Jang, Wang, Kim, Lu and Lee presented DangNull at NDSS 2015, with a study of use-after-free bugs in the Chromium browser as the motivation. Younan presented FreeSentry at the same conference with a closely related design. Later work made the tracking cheaper and safe for many threads, or replaced it with sweeps of memory, and the idea of delaying reuse of freed memory until no pointer to it remains links this line of work to garbage collection.

References

  1. Byoungyoung Lee, Chengyu Song, Yeongjin Jang, Tielei Wang, Taesoo Kim, Long Lu and Wenke Lee, Preventing use-after-free with dangling pointers nullification, NDSS 2015, Section III (the shadow object tree, trace and freeObj, the opt-out for stack locations, and the null value) and Section V (the evaluation on SPEC CPU2006 and Chromium)
  2. Yves Younan, FreeSentry, protecting against use-after-free vulnerabilities due to dangling pointers, NDSS 2015, the registration of pointers in a lookup table and their invalidation when the memory is released, including pointers on the stack

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example