Skip to content

fix: make handle finalizers R functions that call in only while pdfium is loaded - #72

Merged
billdenney merged 18 commits into
mainfrom
claude/r-level-finalizers
Sep 27, 2026
Merged

billdenney merged 18 commits into
mainfrom
claude/r-level-finalizers

Conversation

@billdenney

Copy link
Copy Markdown
Member

Summary

  • Every handle's finalizer is now the R function finalize_handle(), which make_handle() registers with R_RegisterFinalizerEx(). It looks its native routine up by name on every call, and only while pdfium's shared library is loaded. The native side, cpp_finalize_handle(), releases a handle only if the loaded copy of the library registered it (ADR-031).
  • This fixes the segfault at the next gc(), or at R exit, when handles outlive an unload. Handles could be open, closed, or pending finalization. The unload paths are unloadNamespace(), detach(unload = TRUE), pkgload::unload(), a pkgload::load_all() reload of a changed build, and pkgload's fallback that unloads the shared library without .onUnload.
  • A document read from memory now reads from a raw vector held in its handle's prot slot. The new[] buffer and the finalizer behind it are gone, so the buffer registry kind from ADR-028 is removed.
  • A new source-tree test enforces that make_handle() is the only code that attaches a finalizer and that no C finalizer exists anywhere. A known-answer test checks the scan itself. Planting stray registrations turns it red, naming file:line.

Why R finalizers, and how they stay safe

  • R keeps a C finalizer's address until the handle is collected, and it has no API to remove one, so the address has to be kept out of the weak reference entirely.
  • An R_unload_pdfium() hook never runs. R looks it up through R_dlsym(), which honours R_useDynamicSymbols(dll, FALSE) from the Rcpp-generated init.
  • A NativeSymbolInfo captured before an unload has its address cleared by R 4.6, so .Call() through it raises an error (printed, from a finalizer). The finalizer therefore checks is.loaded() and calls .Call() by name, together about 1.6 µs per handle.
  • A flag cleared by .onUnload would be cheaper, but pkgload's fallback unloads without .onUnload. getLoadedDLLs() costs about 870 µs per call.
  • After a load_all() reload, the old copy's finalizers reach the new copy. The new copy's registry doesn't hold those handles, so it leaves them alone.
  • Both new exports use rng = false. Rcpp's default wrapper would create or rewrite .Random.seed from inside a finalizer; a test pins this.

Verification (Linux on picasso, R 4.6.1)

Reproducers. Each run is its own Rscript process that makes a handle of every kind (document from a file, from memory and new; page, annotation, font, XObject, clip path, bitmap). Handles are left open, closed, and pending (unreachable and marked for finalization, not yet run). The script then unloads, calls gc() and exits.

Unload path before: crashed / 4 states after valgrind "all" before valgrind "all" after
none (R exit) 0 / 4 0 / 4 exit 0, 0 invalid exit 0, 0 invalid
unloadNamespace() 4 / 4 (SIGSEGV) 0 / 4 139, 1 invalid jump 0, 0
detach(unload = TRUE) 4 / 4 0 / 4 139, 1 0, 0
load_all() reload, same build 0 / 4 * 0 / 4 0, 0 0, 0
load_all() reload, changed build 3 / 4 0 / 4 139 (crash in the wrong function) 0, 0
pkgload::unload() 3 / 4 0 / 4 139, 1 0, 0
unload without .onUnload 4 / 4 0 / 4 139, 1 0, 0
the same, then reload the library 3 / 4 0 / 4 139, 1 0, 0

* pkgload copies the library to a new temporary file on each load, and an identical copy maps back at the old address, so the stale address happens to hit the same function. A changed build crashes.

In total the base crashed in 21 of 32 scenarios, and this branch passes all 32.

Tests. tests/testthat/test-finalizer.R pins each unload path and R's exit in a subprocess (system2() running Rscript). The exit scenario checks that the library registry is empty after R's exit finalizers run.

Weekly valgrind job, exact invocation (TESTTHAT_PARALLEL=false R -d "valgrind … --leak-check=full --num-callers=40 --error-exitcode=0" --no-echo --vanilla -f testthat.R from tests/): definitely lost 0 bytes, indirectly lost 0 bytes (possibly lost 0), and 0 invalid read, write, free or jump. All 521 error contexts are the known "Mismatched free()" inside libpdfium. Tests: FAIL 0, PASS 3605.

MALLOC_CHECK_=3, with LD_PRELOAD=libc_malloc_debug.so.0, on the full suite: exit 0, FAIL 0, PASS 3605. Four source-tree-only tests skipped because the run used a copy of tests/; they pass under R CMD check.

R CMD check --as-cran --no-manual: 1 WARNING and 1 NOTE, the same as the base. Both come from this machine: no checkbashisms, and Ubuntu's -mno-omit-leaf-frame-pointer flag. checking foreign function calls accepts the by-name .Call(). Tests: FAIL 0, SKIP 1 (no encrypted fixture), PASS 3620; the base passes 3578.

devtools::test(): FAIL 0. lintr::lint_package(): 0 lints, the same as the base. No roxygen or compileAttributes() drift. The non-R pre-commit hooks pass. The pinned R hook environment can't be built on R 4.6 (its locked digest uses the removed Calloc), so CI's pre-commit job remains the authority for styler.

Cost. Load page 1 of shapes.pdf 10,000 times and read the type and bounds of each of its 5 objects. Each row is three runs, each the median of seven.

before after
pages left to the finalizer 8.32–8.45 s 8.36–8.43 s
pages closed explicitly 8.57–8.73 s 8.65–8.73 s
gc() finalizing 20,000 bitmaps 45 ms 44 ms

Notes for review

  • This was stacked on claude/handle-lifetime-leftovers. That branch merged as PR 71, and origin/main is merged in, so the base is main.
  • claude/annot-object-remove-invalidate (ADR-032) touches src/handle_registry.cpp too. Whichever lands second drops finalize_annot_object and its kFinalize entry, keeps close_nothing in kClose, and drops close_buffer.
  • Known limits, recorded in ADR-031: pkgload's fallback leaks the PDFium objects of handles still open (no library is left to close them), and loading two copies of the library at once by hand is unsupported.

🤖 Generated with Claude Code

billdenney and others added 18 commits September 27, 2026 16:20
…zers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…' into claude/r-level-finalizers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…m is loaded

Every handle carried a C finalizer. R keeps a finalizer's address until
the handle is collected, so a handle that outlived the shared library,
open, closed or pending finalization, made R jump into unmapped code at
the next collection or at exit. unloadNamespace(), detach(unload =
TRUE), pkgload::unload(), a pkgload::load_all() reload of a changed
build, and pkgload's unload without .onUnload all crashed.

make_handle() now registers the R function finalize_handle(), which
.onLoad hands to the library. It looks its native routine up by name on
every call, and only while a copy of the library is loaded. The native
side releases a handle only if the loaded copy registered it, so a
reloaded copy leaves an unloaded copy's handles alone. Both exports skip
Rcpp's RNG scope, so a finalizer never touches .Random.seed.

A document read from memory now reads from a raw vector in its handle's
prot slot instead of a new[] buffer behind its own finalizer.

Tests run each unload path, and R's exit, in a fresh R process.
ADR-031 records the decision.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The one-registration-site rule of ADR-028 and ADR-031 lived only in
prose. A source-tree test now scans src/ and R/: no C finalizer or raw
weak reference anywhere, R_RegisterFinalizerEx() only in
handle_registry.cpp, no reg.finalizer(), and the finalizer set only by
the load hooks. A known-answer test plants each kind of registration,
and a commented-out one, to show the scan finds the first and skips the
second.

source_tree_path() generalises the source-tree lookup that
download_pdfium_script() did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The architecture vignette, dev/architecture.md, CLAUDE.md's memory
model and a few comments still said every handle carries a C finalizer
registered with R_RegisterCFinalizerEx(), and that memory documents
register their buffer. The vignette now also says handles that outlive
an unload or a pkgload reload are safe to collect, and CLAUDE.md warns
against attaching a C finalizer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Recounted from the reproducer logs: the base crashed in 21 of the 32
scenarios, not 24.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pkgload::unload() and a changed-build load_all() reload crashed for
open and closed handles; pending ones were finalized by pkgload's own
code first. Loading the library again after an unload without
.onUnload spared closed handles only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Reloading an unchanged build maps the new copy at the old address, so
the stale finalizer addresses stay valid and nothing crashes. The crash
needs a build whose code moved; the measurement padded the code ahead
of the finalizers, as an edit would move them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On Windows the package's DLL finds libpdfium.dll beside it only through
DLLpath (SetDllDirectory), which library.dynam() passes; the scenario's
bare dyn.load() failed there with "LoadLibrary failure: The specified
module could not be found". Other platforms ignore DLLpath.

The scenario now also shows the state it tests: the copy loaded again
registered none of the handles, and an unreleased document still holds
its address into the unloaded copy's PDFium. It calls the new copy by
name, since the unload took the namespace's routines with it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
src/install.libs.R and src/Makevars.win said library.dynam() loads the
package DLL with LoadLibraryEx(LOAD_WITH_ALTERED_SEARCH_PATH), so Windows
searches that DLL's own directory for libpdfium.dll. R's R_loadLibrary()
calls a plain LoadLibrary() inside SetDllDirectory(DLLpath), and
library.dynam() prepends the libs directory to PATH and passes it as
DLLpath. A bare dyn.load() without DLLpath does not find libpdfium.dll,
as the dll_reload test showed on Windows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
dev/r-universe-evaluation.md said library.dynam() loads the package DLL
through LoadLibraryEx(LOAD_WITH_ALTERED_SEARCH_PATH), which searches the
DLL's own directory first. Windows does not search it: library.dynam()
prepends the libs directory to PATH and passes it to dyn.load() as
DLLpath, which R_loadLibrary() sets with SetDllDirectory() around a
plain LoadLibrary(). The conclusion stands: binaries carry libpdfium and
load without a system PDFium.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
covr's -O0 build exports a GNU-unique symbol (std::piecewise_construct),
so glibc cannot unmap it: dyn.unload() is a no-op and dyn.load() of the
same file returns the same image, registry and all. The scenario
asserted a fresh image's empty registry and failed in the coverage
jobs.

A test hook now reports the image's load generation, which an
Rcpp::init function counts on every R_init_pdfium(): 1 for a fresh
image, 2 for a kept one. The test asserts the exact output for either
case, and that nothing is left registered once the handles are
collected; a kept image then records a skip, so its runs show which
case they took.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A build exporting a GNU-unique symbol stays mapped, so loading the same
file again returns the same image and its registry, which releases the
handles as usual. pkgload loads each build from a new file, so its
reloads get a fresh image. Reloading a kept image by hand after its
handles were collected is unsupported, like two copies at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@billdenney
billdenney merged commit 7b9f998 into main Sep 27, 2026
14 checks passed
@billdenney
billdenney deleted the claude/r-level-finalizers branch September 27, 2026 20:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant