Repository navigation
fix: make handle finalizers R functions that call in only while pdfium is loaded - #72
Merged
Merged
Conversation
…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>
…' into claude/r-level-finalizers
…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>
…claude/r-level-finalizers
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
finalize_handle(), whichmake_handle()registers withR_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).gc(), or at R exit, when handles outlive an unload. Handles could be open, closed, or pending finalization. The unload paths areunloadNamespace(),detach(unload = TRUE),pkgload::unload(), apkgload::load_all()reload of a changed build, and pkgload's fallback that unloads the shared library without.onUnload.protslot. Thenew[]buffer and the finalizer behind it are gone, so thebufferregistry kind from ADR-028 is removed.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, namingfile:line.Why R finalizers, and how they stay safe
R_unload_pdfium()hook never runs. R looks it up throughR_dlsym(), which honoursR_useDynamicSymbols(dll, FALSE)from the Rcpp-generated init.NativeSymbolInfocaptured 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 checksis.loaded()and calls.Call()by name, together about 1.6 µs per handle..onUnloadwould be cheaper, but pkgload's fallback unloads without.onUnload.getLoadedDLLs()costs about 870 µs per call.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.rng = false. Rcpp's default wrapper would create or rewrite.Random.seedfrom 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.unloadNamespace()detach(unload = TRUE)load_all()reload, same buildload_all()reload, changed buildpkgload::unload().onUnload* 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.Rpins each unload path and R's exit in a subprocess (system2()runningRscript). 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.Rfromtests/): 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, withLD_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 oftests/; they pass underR CMD check.R CMD check --as-cran --no-manual: 1 WARNING and 1 NOTE, the same as the base. Both come from this machine: nocheckbashisms, and Ubuntu's-mno-omit-leaf-frame-pointerflag.checking foreign function callsaccepts 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 orcompileAttributes()drift. The non-R pre-commit hooks pass. The pinned R hook environment can't be built on R 4.6 (its lockeddigestuses the removedCalloc), so CI's pre-commit job remains the authority for styler.Cost. Load page 1 of
shapes.pdf10,000 times and read the type and bounds of each of its 5 objects. Each row is three runs, each the median of seven.gc()finalizing 20,000 bitmapsNotes for review
claude/handle-lifetime-leftovers. That branch merged as PR 71, andorigin/mainis merged in, so the base ismain.claude/annot-object-remove-invalidate(ADR-032) touchessrc/handle_registry.cpptoo. Whichever lands second dropsfinalize_annot_objectand itskFinalizeentry, keepsclose_nothinginkClose, and dropsclose_buffer.🤖 Generated with Claude Code