Skip to content

About

Experiment at using newly proposed dl_events_subscribe to implement dl_find_object and async-signal-safe dl_itereate_phdr

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

This project contains an example use of the dl_events_subscribe API.
Using that API, it implements an equivalent of _dl_find_object and an
async-signal-safe version of dl_iterate_phdr. It is a prototype, not
a finished implementation; see "Known limitations" below.

The API itself is a proposed dynamic linker extension: the libc calls
a callback for every currently loaded DSO (dynamic shared object)
when you subscribe, and then again, from inside dlopen and dlclose,
for every DSO loaded or unloaded afterwards. See "How
dl_events_subscribe is used" below. Draft patches adding it to glibc,
musl and NetBSD are in doc/.

Why: glibc's _dl_find_object is great, a fast and async-signal-safe
way to find the DSO containing an address. But it has two gaps.
First, it only answers lookups. Backtrace libraries such as
aw-backtrace (https://github.com/gperftools/aw-backtrace) and
libbacktrace (https://github.com/ianlancetaylor/libbacktrace) cache
per-DSO data, such as parsed unwind and debug info, and need to know
when DSOs are loaded and unloaded to fill and drop those caches.
_dl_find_object can't tell them that. Second, it is glibc-only.
Making it async-signal-safe takes RCU-like synchronization, and not
every libc is eager to maintain that inside its dynamic linker.

dl_events_subscribe covers both. Libraries get load and unload events
directly, and a libc only has to report them, while code like this
does the rest, synchronization included. If the API is accepted, this
prototype could grow into a _dl_find_object implementation that other
libcs could use.

dlfo.[ch] -- dl_find_object and dl_iterate_phdr
-----------------------------------------------

 * dlfo_find_object(address, &info) is the equivalent of glibc's
   _dl_find_object: O(log N), async-signal-safe, returns the DSO's
   address range, link map, PT_GNU_EH_FRAME and PT_GNU_SFRAME.

 * dlfo_iterate_phdr(callback, data) is dl_iterate_phdr, but from a
   snapshot, and it sees all DSOs (see the namespace note below).
   dlpi_adds / dlpi_subs are maintained here.

   It never waits. It does not take the loader lock and does not wait
   for a dlopen or dlclose in progress: it walks the tree as it was
   when the iteration started, before or after any concurrent change,
   never half of one. So it is async-signal-safe, even when the signal
   interrupts a dlopen or dlclose on the same thread. glibc's
   dl_iterate_phdr takes the loader lock, so it waits for a dlopen or
   dlclose in progress and cannot be used from a signal handler.

   The synchronization is one-way: dlopen and dlclose wait for
   iterations in progress to finish, so that the DSOs being reported
   stay mapped and their entries stay valid until the callback
   returns. See "Known limitations" for what that means for callbacks.

 * Per DSO, dlfo keeps what it needs from the program headers
   (extent of the PT_LOAD segments, PT_GNU_EH_FRAME and PT_GNU_SFRAME,
   the phdr pointer) in a heap entry. Entries are found through a
   B-tree keyed by address (see "Implementation").
   The DSO name and load bias are copied into a minimal link_map.

How dl_events_subscribe is used
-------------------------------

Code outside the dynamic linker can build the lookup structure
itself. What it cannot do on its own is learn when the set of DSOs
changes.

dl_events_subscribe(callback, data) provides that. The callback has
the same shape as a dl_iterate_phdr callback plus an is_unload flag.
The guarantees that matter here:

 * On subscription the callback is called for every DSO that is
   loaded right now, so there is no gap between "initial snapshot" and
   "start listening".
 * A load is announced before the DSO's constructors run. So from the
   first instruction of DSO code, even a constructor or a signal
   handler running in it, dlfo_find_object can find it.
 * An unload is announced after the DSO's destructors have finished
   and before it is unmapped, so the entry is gone before the address
   range can be reused for something else.
 * Loads may be reported twice and unloads may be reported without a
   load (aborted dlopen is allowed to just call its cleanup path).
   dlfo handles both: btree_interval_insert refuses an interval that is
   already there, so a repeated load is dropped, and an unload only
   removes an entry whose load bias matches.
 * The callback may be called with loader locks held and must not call
   dlopen, dlclose or dl_events_subscribe. dlfo's callback only takes
   its own tree mutex and uses malloc and free, which is the kind of
   thing the API is designed to allow.
 * There is no unsubscribe. A subscription belongs to the DSO
   containing the callback and goes away when that DSO is dlclosed
   (and at process exit). dlfo is fine with this: it subscribes from a
   constructor and lives as long as the code that uses it.

So dlfo.c is small. dlfo_init looks up dl_events_subscribe with dlsym
and, if the libc has it, subscribes and does nothing else. The callback
turns each event into a btree_interval_insert or btree_interval_remove.
All the concurrency complexity lives in btree_interval.c, and the loader
says exactly when to run it.

If dl_events_subscribe is not available, dlfo prints a warning and
takes a single dl_iterate_phdr snapshot at startup. That keeps the
rest of the code usable but the DSO list never updates after that.

Namespaces: dl_events_subscribe covers all dynamic linker namespaces
(dlmopen), like _dl_find_object and unlike dl_iterate_phdr, which only
looks at the caller's.

Known limitations
-----------------

 * Results are valid only while the DSO stays loaded, as with glibc.
   Unlike glibc, looking up an address in a DSO that is concurrently
   being unloaded is not safe: dlfo_find_object reads the DSO's entry
   after the tree lookup, and the unload event frees it. glibc copies the
   data inside its validated read, so there the call itself is always
   safe and only the returned pointers need the DSO alive. Here a
   racing lookup can read freed memory, or the reused memory of another
   DSO's entry. This matters for callers that classify arbitrary
   addresses and only look at map_start and map_end. It does not matter
   for the usual caller that unwinds from frames of code that is running.
 * dlfo_iterate_phdr never waits for dlopen or dlclose, but the
   synchronization is one-way: dlopen and dlclose wait for iterations
   in progress to finish. So a callback must not call dlopen or
   dlclose itself, nor wait for anything that may be blocked in the
   dynamic linker (such as another thread inside dlopen). Either
   would deadlock. See the dlfo.[ch] section above.
 * A DSO is one interval from the lowest PT_LOAD start to the highest
   PT_LOAD end, rounded to 4 KiB pages. That assumes the segments are
   mergeable into one contiguous range (holes between them are treated as
   part of the DSO) and that pages are 4 KiB, which is not right
   where the page size is larger.
 * Allocation failures are not handled (the tree aborts, dlfo does not
   check calloc).

Implementation
--------------

The implementation is layered. Each layer only knows about the one
below:

    dlfo.[ch]             dlfo_find_object, dlfo_iterate_phdr
      |                   (subscribes to DSO events, owns DSO metadata)
    btree_interval.[ch]   address interval -> value map, lock-free readers
      |                   (concrete nodes, memory reclamation, synchronization)
    btree.[ch]            generic copy-on-write B-tree insert and delete
                          (knows nothing about nodes)

btree.[ch] is the B-tree algorithm: keeping the invariants through
splits, merges and so on. It knows nothing about how nodes are
represented, or whether they exist in memory at all. Its node
operations are copy-on-write in style, but it does not require
copy-on-write. With some polish it could be reused for other kinds of
B-trees in other projects. The cost is a constant-factor overhead on
every modification (indirect calls through the node operations
table), which is fine here because modifications are rare.

btree_interval.[ch] is the B-tree that maps address ranges to
pointers, and it is where all of the RCU-like synchronization lives.
Despite the name, it is not an interval tree in the textbook sense:
ranges never overlap, and a range is only ever removed whole, as it
was inserted. So it needs none of the range merging and splitting
that, for example, the Linux kernel's VMA tree does.

btree.[ch] -- tree operations
-----------------------------

Strictly speaking, the tree is a B+tree: values live only in leaves,
and internal nodes hold only keys and child pointers. This README
just says B-tree throughout.

The B-tree algorithms (btree_upsert, btree_delete) are written against
an abstract interface and never look inside a node. A node is an
opaque struct btree_ptr: a pointer plus height, size and capacity, and
that is all the algorithms see. Everything else is delegated to a
table of node operations (struct btree_node_ops) supplied by the
client: how to find the index in a node, how to descend into a child,
upsert or delete in a leaf, split a child, replace a child, merge two
children, and so on.

Every node operation is written in copy-on-write style: it takes a
node and returns the node to use from now on, and the algorithm hands
nodes it no longer needs back to the engine (discard_ptr /
delete_node). So the generic code is just the shape of the algorithm,
in terms of "give me a new version of this node with that changed":

 * Insertion makes an optimistic pass down to the leaf and rebuilds
   the path on the way back up. Only if a node is full does it signal
   NEED_SPLIT upwards, to the nearest ancestor with room, which then
   retries the descent with proactive splits. Splits are rare, so the
   common case pays nothing for them. In the C++ version of this code
   (doc/suffix-btree-persistent.cc, from
   https://github.com/gperftools/gperftools-demo), this approach
   turned out both simpler and faster than splitting proactively on
   every descent.
 * Deletion rebuilds the path the same way, drops emptied children and
   merges small siblings.

What the engine does with the nodes it is handed is up to the engine.
btree_interval makes the tree persistent: a mutation never changes a
node that a reader might be looking at, it builds new ones and the
new root is published last. Nothing in btree.c depends on that,
though. The same algorithms could just as well be driven by
refcounted in-memory nodes, by an append-only on-disk engine, or by
plain mutable nodes that are changed in place and returned as is.
The C++ version mentioned above is an engine of the refcounted kind.

Splitting the code this way keeps the part that is hard to get right as
algorithm (splits, merges, bubbling up) separate from the part that is
hard to get right as concurrency (what may be overwritten and when).
The first can be tested on its own, with a trivial engine that has
nothing to do with lookups or signals (test-btree.c), and the second
only has to reason about a handful of small node primitives.

btree_interval.[ch] -- node operations, and everything concurrent
------------------------------------------------------------------

The one concrete engine. Keys are address ranges: struct btree_interval
is { map_start, map_end, value }, with fixed-width leaf and internal
nodes (LEAF_WIDTH, INTERNAL_WIDTH) kept on freelists.

 * Writers are serialized by a mutex. Mutations are rare (DSO load
   and unload), so this is not a bottleneck.
 * btree_interval_lookup is lock-free and async-signal-safe: no locks,
   no allocation, no waiting on the writer. Not even if the signal
   interrupted the writer thread itself.
 * btree_interval_iterate gives a consistent snapshot of the whole tree
   for as long as the callback runs.

How the readers stay correct while a writer runs:

 * Copy-on-write means a reader walking a node always sees a consistent
   node, if a slightly stale one.
 * There is one monotonically increasing version counter, bumped once
   per mutation. It is not a seqlock: there is no "odd means writing"
   state, because a reader in a signal handler interrupting a writer must
   not have to wait for it. A lookup reads the version, walks the tree
   and re-checks the version after each step, retrying if it changed.
 * The (root, height) pair has to be read as a unit, so there are two
   copies and the version's low bit chooses which is current. The writer
   fills the other copy and then bumps the version, which both publishes
   the new root and flips the slot.
 * Replaced nodes are not reused immediately. After the version bump the
   writer flips an epoch "turn" bit and waits until readers (iterators)
   registered on the previous turn are done, and only then puts the
   orphaned nodes on the freelists. That is what makes snapshots safe,
   and it also means a lookup can only ever see a recycled node
   *after* the version moved, so it notices and retries.
 * Lookups never delay a writer. Iteration does: a dlopen or dlclose
   that wants to recycle nodes waits for in-flight iterations (the
   one-way synchronization described in the dlfo section), so keep
   dlfo_iterate_phdr callbacks short.

The memory-ordering argument (relaxed atomics on node words, release
fence in begin_mutation, acquire fences before every version re-check)
is written out in the big comment at the top of btree_interval.c.

Other files
-----------

 doc/                  Patches adding dl_events_subscribe to glibc,
                       musl and NetBSD (work in progress), and the
                       persistent B-tree sketch mentioned above.
 events-test/          Test programs for the dl_events_subscribe
                       implementation itself (callback ordering,
                       what happens if a callback calls dlclose,
                       subscriptions dropped with their DSO).
                       Not about dlfo. Has its own Makefile.
 test-*.c              Tests for the above, see below.
 genbuild.rb,
 testrunner.rb         The build. See below.

Tests
-----

 test-btree.c          the generic algorithms from btree.c on a
                       test-local node engine, with and without
                       refcounting of shared nodes
                       (-DTEST_BTREE_NO_REFCOUNT)
 test-btree-interval.c the interval engine against a model: many sizes
                       and insert/remove orders, validating the tree
                       along the way. Also built with tiny node widths
                       (test-btree-interval-tiny)
 test-btree-torn.c     concurrency stress. A writer inserts and removes
                       intervals, readers and iterators check what they
                       see, and a thread sends the writer SIGALRM every
                       few microseconds so lookups also run from the
                       signal handler in the middle of a mutation, and
                       so see every intermediate state of the tree
 test-dlfo.c           dlfo_find_object against the libc's own
                       dl_find_object, dlopen/dlclose and iteration.
                       Needs a libc with dl_events_subscribe to pass
                       the dlopen part. With a stock libc it prints
                       a warning and fails.
 test-module.c         the DSO test-dlfo dlopens

Build and test
--------------

Needs ruby and ninja. genbuild.rb writes build.ninja:

    ./genbuild.rb            just generate build.ninja
    ./genbuild.rb ninja      generate, then build
    ./genbuild.rb check      generate, build, run all tests
    ./genbuild.rb check CC=clang

CC, CFLAGS, LDFLAGS and LIBS can be overridden like that or from the
environment. `ninja check` runs every test every time, prints a summary
and writes test-suite.log with the output of any test that failed.

test-dlfo (and events-test) need a libc with dl_events_subscribe.
Build glibc with the patches in doc/glibc/, configured with
--prefix=$GLIBC and installed there. No special compiler is needed;
just make the binaries use that glibc's dynamic linker, which finds
its own libc in $GLIBC/lib:

    ./genbuild.rb check \
      LDFLAGS="-Wl,--dynamic-linker=$GLIBC/lib/ld-linux-x86-64.so.2"

or run a single test binary through it:

    $GLIBC/lib/ld-linux-x86-64.so.2 ./test-dlfo

The dynamic linker name is per-architecture; ld-linux-x86-64.so.2 is
x86-64's. The binaries are still linked against the system libc, so
the patched glibc must be the same version or newer. With the stock
libc, test-dlfo prints a warning and fails; the other tests don't
care.

About

Experiment at using newly proposed dl_events_subscribe to implement dl_find_object and async-signal-safe dl_itereate_phdr

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages