[RFC] Introduction of DoubleFreeSanitizer (DSan)

::Introduction::

Double-free bugs, where a program frees the same allocation more than once, are a common cause of heap corruption and security vulnerabilities in C and C++ programs.

AddressSanitizer already detects double-free bugs. However, ASan detects a much broader set of memory-safety errors by instrumenting memory accesses and maintaining shadow memory and redzones. This can impose significant execution-time and memory overhead. In particular, resource-constrained embedded environments may not have sufficient memory or runtime budget to run ASan at all. For projects that only need double-free detection, this cost can be unnecessary.

This RFC proposes DoubleFreeSanitizer (DSan), a standalone compiler-rt sanitizer focused on detecting double-free errors. DSan intercepts allocation and free APIs, tracks per-allocation state and stack traces, and reports an error when an allocation is freed again.

DSan does not require an LLVM IR instrumentation pass. It consists of a compiler-rt runtime and the minimal Clang driver support needed for the new -fsanitize=doublefree option.

::Naming::

The original intended name was DFSan, standing for “Double-Free Sanitizer.” However, DFSan is already widely used for DataFlowSanitizer, whose Clang option is -fsanitize=dataflow.

To avoid that naming conflict, this implementation currently uses DSan and the runtime name dsan.

I am open to renaming the sanitizer if the community prefers another name.

::Proposal::

The patch adds a new sanitizer option:

-fsanitize=doublefree

The option links the standalone DSan runtime. The runtime tracks allocation state in allocator metadata. Each allocation records:

  • whether the allocation is currently allocated;
  • whether it has already been freed;
  • the allocation stack trace;
  • the first free stack trace; and
  • the requested allocation size.

When the program frees a pointer that DSan has already observed as freed, DSan reports the error and terminates the program.

For example:

ERROR: DoubleFreeSanitizer: double-free on address 0x…

Second free (the invalid free) of address 0x…:
#0 free
#1 main

First free of address 0x…:
#0 free
#1 main

Original allocation of address 0x…:
#0 malloc
#1 main

SUMMARY: DoubleFreeSanitizer: double-free on address 0x…

::Implementation::

The implementation follows the structure and conventions of existing standalone compiler-rt sanitizers.

::Clang::

The patch adds DoubleFreeSanitizer to Sanitizers.def and introduces the -fsanitize=doublefree command-line option.

The Clang driver links the dsan runtime when this option is enabled. DSan is handled as a standalone runtime, similarly to LeakSanitizer, rather than requiring compiler-inserted instrumentation.

::compiler-rt::

The patch adds compiler-rt/lib/dsan, which provides:

  • a standalone allocator with per-chunk metadata;
  • interceptors for malloc, calloc, realloc, free, aligned allocation APIs, and related allocation functions;
  • interceptors for C++ allocation and free operators;
  • stack-trace collection for allocations and frees;
  • runtime flags and default-option support;
  • optional user hooks such as __dsan_default_options and __dsan_is_turned_off;
  • thread, TLS, and fork support based on sanitizer_common infrastructure; and
  • CMake and GN build integration.

::Tests::

The patch adds a compiler-rt/test/dsan test suite, including coverage for allocator behavior, runtime options, suppressions, C++ allocation/free operators, threading, TLS, fork behavior, Linux-specific behavior, and Darwin-specific behavior.

::Motivation::

DSan is intended for users who want focused double-free detection without enabling the complete AddressSanitizer feature set.

Potential use cases include:

  • CI configurations where ASan’s execution-time or memory overhead is too high;
  • Embedded devices that need to detect double-free errors but cannot run ASan because of resource constraints; This is the situation faced by my company.

::Limitations::

DSan intentionally focuses on double-free detection. It is not a replacement for AddressSanitizer.

In particular, DSan does not aim to detect:

  • heap-buffer-overflow;
  • stack-buffer-overflow;
  • use-after-free reads or writes;
  • use-after-return;
  • use-after-scope; or
  • other invalid memory accesses that ASan detects.

Platform support follows the platforms supported by the DSan runtime and corresponding Clang driver integration. The initial implementation includes support for the sanitizer platforms and architectures covered by the added compiler-rt and driver configuration.

::Future work::

Possible future directions include:

  • expanding platform and allocator coverage;
  • revisiting whether DSan should remain a distinct sanitizer or eventually share more implementation with an existing sanitizer runtime.

::Feedback requested::

I would appreciate feedback on:

  • whether a standalone double-free-only sanitizer is useful to the LLVM community;
  • the proposed DSan name, especially suggestions for a better name that does not conflict with DataFlowSanitizer;
  • expected sanitizer-option compatibility;

Assisted-by: GPT-5.6 Terra

Since gwp-asan has similar scope/interception, would it make sense to add DSan as another capability of gwp-asan, instead of an independent “sanitizer”? IIRC gwp-asan already has runtime options to dial up/down the frequency of checks, maybe this is another knob?

It seems to match the philosophy/goals of gwp-asan well IIUC.

Thank you for the opinion. I agree that GWP-ASan can overlap with this
proposal.

My understanding is that GWP-ASan samples allocation events themselves and
tracks only the selected allocations using metadata in its guarded pool.
Allocations that are not sampled have no GWP-ASan metadata.

In contrast, DSan needs to retain at least the allocation state and first-free
information for every allocation in order to detect double-free errors
deterministically. Implementing this in GWP-ASan would therefore require a
separate metadata mechanism for allocations outside the guarded pool. This
seems like a more fundamental change than adding another sampling or frequency
option.

AddressSanitizer already detects double-free bugs. […]

What stops you from linking the ASan runtime, but disable compiler instrumentation?

I disagree with adding narrow tools that are a subset of existing tools, where the usecase is extremely narrow and can be achieved by a number of other ways.

For example, you can use ASan without instrumentation which makes non-allocator runtime overheads zero:

% cat test.cc
__attribute__((noinline)) int *foo() {
  return new int;
}

__attribute__((noinline)) void bar(int *i) {
  *i += 1;
  delete i;
}

int main(int argc, char *argv[])
{
  auto x = foo();
  delete x;
  bar(x);
  return 0;
}

% clang++ -c test.cc -o test.o # no instrumentation, no globals redzones!
% clang++ -fsanitize=address -o test test.o && ./test |& head -4
=================================================================
==3456569==ERROR: AddressSanitizer: attempting double-free on 0x7bff839e0010 in thread T0:
    #0 0x5600c0f297b6 in operator delete(void*, unsigned long) (/usr/local/google/home/elver/temp/asan-light/test+0x1177b6) (BuildId: 7cfd21c6ef1985d44091f494a3135f79b934668b)
    #1 0x5600c0f29ff2 in bar(int*) (/usr/local/google/home/elver/temp/asan-light/test+0x117ff2) (BuildId: 7cfd21c6ef1985d44091f494a3135f79b934668b)

If you are running in a memory-constrained system, chances are it’s an Arm-based system, where we have HWASan (less memory used): -fsanitize=hwaddress (same trick as above works).

Furthermore, if you do not require integration with Clang code instrumentation, you are able to build an out-of-tree tool easily. The flag -fsanitize=doublefree is a convenience, but not required. Even then, there are tools that use Clang instrumentation and perform standard library interception that are maintained out of tree (e.g. see how GWPSan does it).

3 Likes

Granted, ARM is pretty popular but there’s plenty of other architectures used in memory-constrained environments. Do 32-bit ARM uCs even have the necessary features (MTE/TBI?).

So I think approaches like GWP-ASan and this new proposal are valuable to consider. But yeah let’s see if DSan could be a feature/mode of scudo which IIRC is the allocator GWP-ASan depends on? Probably LLVM libc has an allocator too? Maybe this would fit there.

HWASan needs TBI, so 32-bit won’t have that. But before speculating that it might be useful there, I’d want evidence that the instrumentation-less (normal) ASan doesn’t work in that environment. And at some point we have to draw the line what we want to support; too many similar variants or subvariants of a feature that compete with each other doesn’t help. If anything, we should figure out how to optimize or enhance what we have.

I still think creating a whole new sanitizer for this is overkill. It can either live out-of-tree, or be part of Scudo, as you suggest, if that has a lot of the pieces needed already.

1 Like

Thank you for the detailed feedback and the example. I wasn’t aware that it was possible to link the ASan runtime without compile-time instrumentation. I had overlooked that.

I generally agree with your opinion that we should avoid adding narrow tools that are mere subsets of existing sanitizers when the use case can be covered by other means. However, determining whether a use case is “extremely narrow” is often very difficult in practice.

In my case at LG Electronics, many of our TV products still operate with a 32-bit user space, even on 64-bit capable hardware. This means HWASan is not available as an option. Given the severe memory constraints (typically around 2GB total system memory shared with GPU, 4K video processing, Linux kernel, and always-on AI features like voice recognition), even the instrumentation-less ASan imposes too much overhead from shadow memory, quarantine, and allocator metadata.

I believed there was no other practical solution for this environment, which is why I proposed a dedicated lightweight DoubleFreeSanitizer.

Regarding the suggestion to integrate this as part of Scudo: I hadn’t seriously considered that option yet. Since Scudo is heavier than a ptmalloc as far as I know.

So, I will evaluate the real-world memory overhead of both instrumentation-less ASan and a potential Scudo-based implementation on LG Electronics TV, and follow up with concrete data. We can discuss the best integration path (standalone vs Scudo vs no integration vs out-of-tree) again once I have those numbers.

Thanks again for the opinions!

Thank you for the feedback on linking the ASan runtime without compile-time instrumentation. I evaluated that approach and collected some concrete numbers, which I would like to share.

Measurement on x86-64 Ubuntu

I compared four configurations on the same allocation-heavy microbenchmark (500k malloc/free operations, many live objects):

Configuration Peak RSS (avg) vs Baseline Elapsed (approx.)
Baseline (no sanitizer) ~209 MB 1.00× ~0.40 s
DSan (`-fsanitize=doublefree`) ~231 MB ~1.10× ~0.76 s
Uninstrumented ASan (runtime only) ~617 MB ~2.95× ~1.17 s
Full ASan (`-fsanitize=address`) ~619 MB ~2.96× ~1.33 s

In this workload, removing instrumentation barely reduces ASan’s memory footprint. The dominant cost is the ASan allocator itself (redzones, quarantine, metadata, etc.). DSan stays close to the baseline (+10% RSS), while both ASan variants are nearly 3×.

I also tried reducing ASan memory with options such as:

ASAN_OPTIONS=quarantine_size_mb=0:thread_local_quarantine_size_kb=0:redzone=16:max_redzone=16:malloc_context_size=0:poison_heap=0

RSS drops substantially (to roughly ~250 MB in my run), but double-free reporting becomes incorrect: instead of a clear attempting double-free report with allocation/free stack traces, ASan reports something like attempting free on address which was not malloc()-ed / bad-free. So the memory saving comes at the cost of precise double-free diagnosis, which is exactly the capability I care about.

Experience on a real embedded product

I also tried uninstrumented ASan on a subset of applications on a real TV product (tight memory budget). The overhead was large enough to cause timeouts between services, so the system did not operate reliably. I have not rolled this out to other products yet, but many embedded devices leave almost no spare memory for cost reasons. In that class of systems, the memory overhead of uninstrumented ASan is often not acceptable.

Why a focused tool still makes sense

I see an analogy with LeakSanitizer. ASan can already detect leaks, yet LSan exists as a lighter, focused option for users who primarily care about leaks and cannot afford full ASan. The same argument applies to double-free:

  • Double-free is a security issue, so its severity is high.
  • A lightweight detector that reliably catches this class of bugs is still valuable when full ASan (or even uninstrumented ASan) is not affordable.

I am not arguing that uninstrumented ASan is useless in general—only that it is not a good fit for the memory-constrained environments I work with, and I believe other embedded developers are in a similar position. That is the motivation for a standalone, low-overhead DoubleFreeSanitizer.

How to reproduce the microbenchmark

Anyone can reproduce the numbers above on Linux as follows.

  1. Test program (alloc_bench.cpp):
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <random>
#include <chrono>
#include <string>

constexpr size_t NUM_ALLOCS = 500000;
constexpr size_t MAX_LIVE   = 100000;
constexpr size_t MIN_SIZE   = 16;
constexpr size_t MAX_SIZE   = 4096;

int main(int argc, char\*\* argv) {
    bool do_double_free = (argc > 1 && std::string(argv\[1\]) == "--double-free");

    std::mt19937 rng(42);
    std::uniform_int_distribution<size_t> size_dist(MIN_SIZE, MAX_SIZE);
    std::uniform_int_distribution<size_t> idx_dist(0, MAX_LIVE - 1);

    std::vector<void\*> live;
    live.reserve(MAX_LIVE);

    auto start = std::chrono::steady_clock::now();

    for (size_t i = 0; i < NUM_ALLOCS; ++i) {
        if (!live.empty() && (rng() % 3 == 0)) {
            size_t idx = idx_dist(rng) % live.size();
            free(live\[idx\]);
            live\[idx\] = live.back();
            live.pop_back();
        }

        size_t sz = size_dist(rng);
        void\* p = malloc(sz);
        if (!p) {
            fprintf(stderr, "malloc failed\\n");
            return 1;
        }
        memset(p, 0xAB, sz);

        if (live.size() < MAX_LIVE)
            live.push_back(p);
        else
            free(p);
    }

    for (void\* p : live) free(p);
    live.clear();

    if (do_double_free) {
        void\* p = malloc(128);
        free(p);
        free(p);  // double-free
    }

    auto end = std::chrono::steady_clock::now();
    double sec = std::chrono::duration<double>(end - start).count();
    printf("Done. elapsed = %.3f sec, allocations = %zu\\n", sec, NUM_ALLOCS);
    return 0;
}
  1. Build (use following clang with DSan support):
    [sanitizer] Add DoubleFreeSanitizer (DSan) by Bojun-Seo · Pull Request #213846 · llvm/llvm-project · GitHub
# Baseline
clang++ -g -o bench_baseline alloc_bench.cpp

# DSan
clang++ -g -fsanitize=doublefree -o bench_dsan alloc_bench.cpp

# Uninstrumented ASan (no compile-time instrumentation)
clang++ -g -c alloc_bench.cpp -o alloc_bench.o
clang++ -g alloc_bench.o -fsanitize=address -o bench_asan_rt

# Full ASan
clang++ -g -fsanitize=address -fno-omit-frame-pointer -o bench_asan alloc_bench.cpp
  1. Measure peak RSS:
/usr/bin/time -f "Peak RSS: %M kB\\nElapsed: %e sec" ./bench_baseline
/usr/bin/time -f "Peak RSS: %M kB\\nElapsed: %e sec" ./bench_dsan
/usr/bin/time -f "Peak RSS: %M kB\\nElapsed: %e sec" ./bench_asan_rt
/usr/bin/time -f "Peak RSS: %M kB\\nElapsed: %e sec" ./bench_asan

These results are from x86-64 Ubuntu; absolute numbers will vary by machine, but the relative gap between DSan and ASan should be easy to reproduce.


Assisted-by: Grok

If all you need to catch is double frees, is it possible to do this with just --wrap flags? That is, you keep some static container of all pointers returned by malloc, mark them as available, then mark them as unavailable on free? If you need something dynamic, then I think you could also resize the container via __real_malloc/free.

The goal of doublefree sanitizer is not only to detect double-frees, but also to show how the double-free occurred.

With the proposed --wrap approach, detection at the second free is possible, but there is no information about the original allocation site and the first free site.

In a similar vein to what I mentioned earlier, uninstrumented ASan with quarantine_size_mb=0 option can detect double-free, but it doesn’t report the allocation stack backtrace and the first free stack.

I see. I suppose you could also technically record the original callsite info for malloc/free via __builtin_return_address then do the unwinding/printing mechanics yourself (along with the object size), but I guess there’s a point where you’d probably just want to reuse existing compiler-rt machinery rather than reinvent the wheel.

1 Like

Can you try scudo?

SCUDO_OPTIONS='GWP_ASAN_Enabled=true:GWP_ASAN_SampleRate=1' ./bench_scudo_O0 --double-free

gives you a stack trace.

Stepping back: I don’t think this benchmark supports conclusions about real applications, and I’d push back on it independently of the quarantine question. No real program has this loop.

More importantly, the headline ratio is a free parameter. MAX_LIVE and MAX_SIZE were chosen arbitrarily, and they, not ASan, determine the number:

MAX_LIVE baseline ASan rt ratio
1,000 6.2 MB 349.0 MB 56.3×
10,000 24.8 MB 372.2 MB 15.0×
100,000 204.8 MB 601.9 MB 2.94×
400,000 668.5 MB 1189.6 MB 1.78×

Same code, same ASan. The default quarantine is a fixed 256 MB, so this ratio is mostly measuring how large 256 MB happens to be relative to a live set you picked. 2.95× is not a property of ASan; it is MAX_LIVE = 100000.

4 Likes

I don’t like idea of having dedicated sanitizer for that, as in general extraction particular features from existing sanitizers into own one.

Scudo is a good option.
Maybe other allocators. E.g. TCMalloc hooks Implement new/delete hooks in TCMalloc (#44) · google/tcmalloc@61b60f4 · GitHub

Extending LSAN for that seems OK.

1 Like

Scudo with GWP-ASan can detect and report double-free errors for sampled allocations, including stack traces. However, even with GWP_ASAN_SampleRate=1, detection is not deterministic as far as I know. Therefore, it does not satisfy a requirement for deterministic detection.

I completely agree with your criticism of the microbenchmark. I think we should disregard its result. Thank you for pointing this out.

My intention in the earlier comment was not to rely solely on the microbenchmark. I also tried running several applications with uninstrumented ASan in our TV environment, but could not complete the experiments because of the overhead. The applications repeatedly timed out, making the TV system unstable. I wanted to show that uninstrumented ASan can be difficult to use in a real embedded environment, even when only double-free detection is needed.

I will try to repeat the experiments with the actual target environment and applications and report the results when available.

The requirements are:

  • deterministic detection of double-free errors;
  • a stack backtrace for the double-free event; and
  • low overhead.

These requirements exist in embedded environments. I agree that they may not represent the majority use case, but they are not nonexistent.

I will provide experimental results regarding the overhead, although this may take some time.

As for the implementation approach, I will follow the community’s consensus. I also spent considerable time considering whether to extend LSan or introduce a separate sanitizer. If the consensus is to implement this as an additional LSan feature, I will rework the implementation accordingly.

Thanks a lot for all the reviews.

On detection: Scudo’s chunk-header double-free check is not-sampled.It 100% catches immediate double free free(p); free(p);.
For p=malloc(16); free(p); q=malloc(16); free(p);, no allocator that reuses addresses can do better. I don’t think your “deterministic” is achievable, and your thing doesn’t achieve it either.

On diagnosis: Scudo prints a single line in-process on an invalid chunk state and links no symbolizer. On Android it supports stack traces (to a privileged out-of-process consumer). Your DoubleFreeSanitizer seems to print a stack trace unconditionally, which is not good when targeting untrusted users.

In addition, I am not sure why you put so much emphasis on double-free. use-after-free and heap overflow are more severe. The severity of double free is well down the list.

On detection: You are right. 100% detection is not achievable, and I used the wrong term “deterministic” in my earlier comment. Scudo and DoubleFreeSanitizer detect double-free at a comparable level. Both catch the immediate case, and both miss the case where the chunk is reused in between.

What I actually wanted to point out was the reporting difference. GWP-ASan only guards allocations up to one page, so larger allocations never get a backtrace regardless of configuration. DoubleFreeSanitizer records an allocation backtrace for every allocation, and reports the allocation and first-free backtraces.

On diagnosis: That is a fair concern, but it applies to most sanitizers, which print stack traces unconditionally. So I think it is acceptable as long as this tool is used in a development environment.

On why double-free: I fully agree that use-after-free and heap overflow are far more severe, and generally more frequent as well. However, detecting them requires monitoring memory accesses, which implies significant CPU and memory overhead. In our embedded environment, many tools simply do not run. A tool that does not run cannot help us, no matter how good it is. That is why LSan is the one we currently use most successfully. Double-free seemed detectable at a similarly low cost, which is why I started this work.

Again, I understand that double-free has lower severity and shows up less often. But when analyzing an issue, being able to rule it out with reasonable confidence, and getting the backtraces when it does occur, all with low overhead, meaningfully reduces analysis time.

Since many people are against adding a new standalone sanitizer, I’d like to hear the community’s preference between these two options:

  1. Extending LSan
  2. Maintaining it out-of-tree

I will follow the consensus.

Thanks a lot for all the feedback.

Maintaining it out-of-tree

1 Like

I have reimplemented this as an optional feature of stand-alone LeakSanitizer rather than a separate runtime, and updated the pull request. Enable it with LSAN_OPTIONS=detect_double_free=1; it is off by default.

The pull request also carries two pre-existing realloc() bug fixes that are independent of this proposal; I can send those separately if that is easier.