Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
7353abc
Merge remote-tracking branch 'origin/main' into claude/r-level-finali…
billdenney Sep 27, 2026
57e3e26
Merge remote-tracking branch 'origin/claude/handle-lifetime-leftovers…
billdenney Sep 27, 2026
8178828
Merge remote-tracking branch 'origin/claude/handle-lifetime-leftovers…
billdenney Sep 27, 2026
6a4ab63
fix: make handle finalizers R functions that call in only while pdfiu…
billdenney Sep 27, 2026
e3827da
test: fail when anything but make_handle() attaches a finalizer
billdenney Sep 27, 2026
407ced6
docs: describe handle finalizers as R functions (ADR-031)
billdenney Sep 27, 2026
7d76760
Merge remote-tracking branch 'origin/main' into claude/r-level-finali…
billdenney Sep 27, 2026
b3f790e
docs: correct ADR-031's count of crashing unload scenarios
billdenney Sep 27, 2026
3716e84
docs: say which handle states crashed on each pkgload path in ADR-031
billdenney Sep 27, 2026
7c8d907
Merge branch 'main' into claude/r-level-finalizers
billdenney Sep 27, 2026
398c12a
docs: say how ADR-031 reproduced the load_all() reload crash
billdenney Sep 27, 2026
b4c725c
Merge remote-tracking branch 'origin/claude/r-level-finalizers' into …
billdenney Sep 27, 2026
8337e22
Merge branch 'main' into claude/r-level-finalizers
billdenney Sep 27, 2026
73d19f0
test: load the DLL again with DLLpath in the dll_reload scenario
billdenney Sep 27, 2026
de4f030
docs: say how Windows finds libpdfium.dll beside the package DLL
billdenney Sep 27, 2026
5cbeb4b
docs: correct how the r-universe evaluation says Windows finds libpdfium
billdenney Sep 27, 2026
ed37a68
test: tell a kept image from a fresh one in the dll_reload scenario
billdenney Sep 27, 2026
34ee985
docs: note in ADR-031 that -O0 builds survive dyn.unload()
billdenney Sep 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,15 +139,21 @@ for the rationale. The short version:
R `externalptr`. Every handle with a finalizer is in one registry,
`src/handle_registry.{h,cpp}` (ADR-024, ADR-025, ADR-028): annotation
contexts, pages, fonts and XObjects under their document; documents,
`pdf_clip_path_new()` clip paths, bitmaps and memory-document buffers
under the library.
`pdf_clip_path_new()` clip paths and bitmaps under the library.
- One mint and one release path per kind: `make_*_handle()` alone creates
the externalptr (finalizer attached, handle registered), and
`release_*_handle()` alone closes and clears it — the finalizer, the
explicit `pdf_*_close()` / `pdf_annot_delete()` and the owner's release
all call it, so every close is idempotent. Never close a handle
`make_*_handle()` made, or call `R_RegisterCFinalizerEx`, anywhere
else.
`make_*_handle()` made anywhere else.
- The finalizer is the R function `finalize_handle()` (ADR-031), which
`make_handle()` alone attaches. It calls into the shared library only
while the library is loaded, looking the routine up by name each time,
and the library releases only handles its own registry holds, so a
handle may outlive `unloadNamespace()`, `detach(unload = TRUE)` or a
`pkgload::load_all()` reload. Never attach a C finalizer
(`R_RegisterCFinalizerEx`): R calls it even after the library is
unloaded, and `test-finalizer.R` fails on one.
- Owners release their handles first: `pdf_doc_close()` closes the
document's annotations, pages, fonts and XObjects before
`FPDF_CloseDocument`, and `cpp_destroy_library()` closes every document,
Expand All @@ -157,6 +163,9 @@ for the rationale. The short version:
containers R does not scan, and the finalizer removes each one from the
registry before R frees it, so an unreachable handle is still collected
promptly.
- A document loaded from memory reads from a raw vector in its handle's
`prot` slot: PDFium reads the bytes until the document is closed, and
R frees the vector only after the handle.
- Children pin their immediate owner in `prot` (a page its document, an
annotation its page, a page-object its page, annotation or form, a clip
path its page-object), and both `validate_handle()` in C++ and
Expand Down
1 change: 1 addition & 0 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ Collate:
'utils.R'
'enum_codes.R'
'extract.R'
'finalizer.R'
'fonts.R'
'form_field_setters.R'
'forms.R'
Expand Down
10 changes: 10 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,16 @@
Closing, using or collecting one of them after the shutdown, or after
PDFium was initialised again by opening a document or by
`pdf_system_fonts_install_default()`, crashed R (ADR-028).
* Unloading the package no longer leaves handles that crash R when they
are collected or when R exits. After `unloadNamespace()`,
`detach(unload = TRUE)`, `pkgload::unload()` or a
`pkgload::load_all()` reload, every handle still around, whether open,
closed or waiting to be collected, kept a finalizer that pointed into
the unloaded compiled code. The finalizer is now an R function that
calls into pdfium's compiled code only while that code is loaded, and
the code releases only the handles it made itself (ADR-031).
`pdf_doc_open(source = )` now keeps its copy of the bytes as an R raw
vector, so R's memory accounting sees it.
* `pdf_form_fields()`'s documentation says what it returns, a
`pdfium_form_field_list` of form-field handles, instead of describing
a tibble; the tibble's columns are now documented on
Expand Down
12 changes: 12 additions & 0 deletions R/RcppExports.R
Original file line number Diff line number Diff line change
Expand Up @@ -609,6 +609,14 @@ cpp_text_char_font_info <- function(page_ptr) {
.Call(`_pdfium_cpp_text_char_font_info`, page_ptr)
}

cpp_set_handle_finalizer <- function(fun) {
invisible(.Call(`_pdfium_cpp_set_handle_finalizer`, fun))
}

cpp_finalize_handle <- function(ptr) {
invisible(.Call(`_pdfium_cpp_finalize_handle`, ptr))
}

cpp_doc_handle_counts <- function(doc_ptr) {
.Call(`_pdfium_cpp_doc_handle_counts`, doc_ptr)
}
Expand Down Expand Up @@ -653,6 +661,10 @@ cpp_image_filters <- function(obj_ptr) {
.Call(`_pdfium_cpp_image_filters`, obj_ptr)
}

cpp_load_generation <- function() {
.Call(`_pdfium_cpp_load_generation`)
}

cpp_init_library <- function() {
invisible(.Call(`_pdfium_cpp_init_library`))
}
Expand Down
14 changes: 7 additions & 7 deletions R/classes.R
Original file line number Diff line number Diff line change
Expand Up @@ -284,13 +284,13 @@ print.pdfium_obj_list <- function(x, ...) {
#' Construct a `pdfium_font` from an external pointer
#'
#' Internal helper. The `FPDF_FONT` handle has its own lifetime —
#' the externalptr carries a C finalizer that calls `FPDFFont_Close`,
#' registered C-side in `cpp_font_load_*`. The parent doc is pinned
#' in the externalptr's `prot` slot so R's GC cannot reclaim the doc
#' while any font handle is reachable. `name` is informational —
#' for standard fonts it's the spec name; for loaded TTF/Type1 fonts
#' it's the file's basename when the font was loaded from a path,
#' or `"<raw>"` for in-memory loads.
#' the externalptr carries the handle finalizer, which calls
#' `FPDFFont_Close`, attached C-side in `cpp_font_load_*`. The parent
#' doc is pinned in the externalptr's `prot` slot so R's GC cannot
#' reclaim the doc while any font handle is reachable. `name` is
#' informational — for standard fonts it's the spec name; for loaded
#' TTF/Type1 fonts it's the file's basename when the font was loaded
#' from a path, or `"<raw>"` for in-memory loads.
#'
#' @param ptr An `externalptr` to an `FPDF_FONT`.
#' @param doc Parent `pdfium_doc`.
Expand Down
20 changes: 20 additions & 0 deletions R/finalizer.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Internal: the finalizer of every handle the package makes
# (make_handle() in src/handle_registry.cpp, ADR-031). .onLoad hands it
# to the shared library.
#
# R keeps a handle's finalizer until the handle is collected, even
# after the package's shared library is unloaded, so the finalizer
# cannot be C code in that library. This one calls into the library
# only while a copy of it is loaded, and looks the routine up by name
# on every call, because a symbol captured before an unload does not
# survive it. Without a loaded copy there is nothing to release:
# unloading the package released every handle first (ADR-028), and
# anything a handle still points to belongs to the PDFium that was
# unloaded with it. With a loaded copy, cpp_finalize_handle() releases
# the handle only if that copy registered it.
finalize_handle <- function(ptr) {
if (is.loaded("_pdfium_cpp_finalize_handle", PACKAGE = "pdfium")) {
.Call("_pdfium_cpp_finalize_handle", ptr, PACKAGE = "pdfium")
}
invisible()
}
2 changes: 2 additions & 0 deletions R/zzz.R
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
# nocov start
.onLoad <- function(libname, pkgname) {
cpp_set_handle_finalizer(finalize_handle)
cpp_init_library()
invisible()
}

.onUnload <- function(libpath) {
cpp_destroy_library()
cpp_set_handle_finalizer(NULL)
library.dynam.unload("pdfium", libpath)
invisible()
}
Expand Down
26 changes: 16 additions & 10 deletions dev/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,11 @@ shared library is loaded once per session.
Read [ADR-005](decisions/ADR-005-memory-model.md) first. Summary:

1. Every PDFium handle (`FPDF_DOCUMENT`, `FPDF_PAGE`, etc.) lives
behind an R `externalptr`. Those PDFium closes carry a C finalizer
registered via `R_RegisterCFinalizerEx(ptr, finalizer, TRUE)`.
behind an R `externalptr`. Those PDFium closes carry the R
finalizer `finalize_handle()` (`R/finalizer.R`), registered via
`R_RegisterFinalizerEx(ptr, finalizer, TRUE)`. It calls into the
shared library only while it is loaded, and releases only the
handles the loaded library registered (ADR-031).
2. Each such kind has one minting and one releasing function in
`src/handle_registry.h`: `make_*_handle()` attaches the finalizer
and registers the handle, and `release_*_handle()`, which the
Expand All @@ -54,10 +57,11 @@ Read [ADR-005](decisions/ADR-005-memory-model.md) first. Summary:
5. Closing a document, explicitly or in its finalizer, first closes
the annotation, page, font and XObject handles still open on it:
each is registered under its document (ADR-024, ADR-025).
Documents, clip paths, bitmaps and memory-document buffers are
registered under the library, and `cpp_destroy_library()` releases
them, each document with its handles, before `FPDF_DestroyLibrary`
(ADR-028).
Documents, clip paths and bitmaps are registered under the
library, and `cpp_destroy_library()` releases them, each document
with its handles, before `FPDF_DestroyLibrary` (ADR-028). A
document loaded from memory reads from a raw vector in its
handle's `prot` slot, which needs no finalizer (ADR-031).
6. PDFium's library lifecycle (`FPDF_InitLibraryWithConfig` /
`FPDF_DestroyLibrary`) runs in `.onLoad` / `.onUnload`; opening a
document after a destroy initialises the library again.
Expand Down Expand Up @@ -108,10 +112,12 @@ package load (every R session)
- **GC order.** Finalizers are registered with `onexit = TRUE`, so
they run at R session shutdown. A handle collected after the library
was destroyed is harmless, because the destroy released it first
(ADR-028). A handle that survives `.onUnload`'s
`library.dynam.unload()` is not: its finalizer then points into the
unloaded shared library, and R crashes at the next collection or at
exit (ADR-028, to be fixed by ADR-031).
(ADR-028). So is a handle that survives `.onUnload`'s
`library.dynam.unload()`: its finalizer is R code that finds the
shared library gone, or a reloaded copy that never registered the
handle, and does nothing (ADR-031). Never attach a C finalizer: R
would call it after the library is unloaded, and
`test-finalizer.R` refuses one.
- **Parallel testthat + valgrind.** They don't compose. `valgrind.yaml`
and `cpp-asan.yaml` set `TESTTHAT_PARALLEL=false` to force serial
tests under instrumentation.
Expand Down
178 changes: 178 additions & 0 deletions dev/decisions/ADR-031-r-level-finalizers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
# ADR-031 — Handle finalizers are R functions that call in only while the shared library is loaded

- Status: Supersedes ADR-005's C finalizers and ADR-028's memory-buffer handle
- Date: 2026-09-27
- Deciders: Bill Denney

## Context

Every handle the package closes carried a C finalizer, registered with
`R_RegisterCFinalizerEx(ptr, finalizer, TRUE)` in `make_handle()`
(ADR-005, ADR-028). That covered documents, pages, annotation contexts,
fonts, XObjects, clip paths, bitmaps, and the buffer a document loaded
from memory reads. R stores the finalizer's address in the handle's weak
reference until the handle is collected, and it has no API to remove a
finalizer once registered.

`.onUnload` destroys the library, which releases every registered
handle (ADR-028), and then unloads the package's shared library
(`library.dynam.unload()`). A handle that survives the unload, whether
open, closed, or unreachable but not yet finalized, still holds a
finalizer address into unmapped code. The next collection that finds
the handle unreachable, or R's exit finalizers, calls that address from
`R_RunWeakRefFinalizer()`, and R crashes.

Measured on Linux with R 4.6.1, using a handle of every kind in each of
those states, one R process per scenario:

- `unloadNamespace()` and `detach(unload = TRUE)`: SIGSEGV in every
state.
- `pkgload::unload()`: SIGSEGV for open and closed handles. Pending
ones survived only because pkgload's own R code happened to finalize
them before the unload. `pkgload::load_all()` loads a fresh copy of
the library from a new temporary file each time. Reloading an
unchanged build maps the copy at the old address, so the stale
address happens to hit the same function, and nothing crashes.
Reloading a build whose code has moved crashes just like
`pkgload::unload()`. The measurement reloaded a second build with
64 KB of padding placed ahead of its finalizers, which moves them as
an edit would.
- When `unloadNamespace()` fails, pkgload falls back to unregistering
the namespace and unloading the library without `.onUnload`. Nothing
releases the handles first, and the next collection crashes. If the
library is loaded again, only closed handles escape, because their
stale address lands on the same function in the new copy.

Two facts about R limit the options:

- R would call an `R_unload_pdfium()` on every unload, but it looks the
function up through `R_dlsym()`. That honours
`R_useDynamicSymbols(dll, FALSE)`, which the Rcpp-generated
`R_init_pdfium()` sets, so R never finds it.
- A `NativeSymbolInfo` taken before an unload is useless after it. R
4.6 clears its address when the library is unloaded, so `.Call()`
through it raises an error. An error in a finalizer is printed at
whatever point in the session the finalizer happens to run.

## Decision

1. Every handle's finalizer is the R function `finalize_handle()` in
`R/finalizer.R`. `make_handle()` is still the only code that attaches
a finalizer, and it registers this one with
`R_RegisterFinalizerEx(ptr, fun, TRUE)`. `.onLoad` hands the function
to the library through `cpp_set_handle_finalizer()`, which preserves
it. `.onUnload` releases it after destroying the library and before
unloading the shared library.
2. `finalize_handle()` calls into the library only while a copy of it is
loaded, and it looks the routine up by name on every call: first
`is.loaded("_pdfium_cpp_finalize_handle", PACKAGE = "pdfium")`, then
`.Call("_pdfium_cpp_finalize_handle", ptr, PACKAGE = "pdfium")`. It
never holds a symbol across an unload.
3. `cpp_finalize_handle()` releases a handle only if the loaded copy of
the library registered it. It leaves any other handle alone. Such a
handle was either released already, by its close, its owner's release
or the library destroy on unload, or it was made by an earlier copy
of the library, whose PDFium owns whatever it points to.
4. A document loaded from memory reads from a copy of the caller's bytes,
held as a raw vector in the prot slot of the document's handle. The
copy has no finalizer and is not a registry kind, which supersedes
the buffer handle in ADR-028 decisions 1 and 2. R never moves a
vector, nothing else can reach the copy, and R frees it only after
the document's handle, so only after the document is closed.
5. `cpp_finalize_handle()` and `cpp_set_handle_finalizer()` are exported
with `rng = false`. Rcpp's default wrapper reads `.Random.seed` and
writes it back, creating it if it is absent, and a finalizer must not
do that.
6. A source-tree test enforces the single registration site. `src/` must
contain no `R_RegisterCFinalizer*()` or `R_MakeWeakRef*()` call, and
an `R_RegisterFinalizer*()` call only in `src/handle_registry.cpp`.
`R/` must contain no `reg.finalizer()` call, and a
`cpp_set_handle_finalizer()` call only in `R/zzz.R`.

## Consequences

- No unload path calls into an unloaded library. The paths covered are
`unloadNamespace()`, `detach(unload = TRUE)`, `pkgload::unload()`,
`load_all()` reloads of the same or a changed build, and unloading the
shared library without `.onUnload`, with or without loading it again.
All 32 scenarios (8 paths × open, closed, pending and all) now exit
cleanly. Before this change, 21 crashed.
- The weak-registry invariant of ADR-024 and ADR-025 still holds. R
keeps a handle until its finalizer has run, and the finalizer
deregisters the handle while the library that registered it is still
loaded. Once that library is gone, so is its registry.
- At exit, R does not unload namespaces, so the library is still loaded
when the exit finalizers run. They release every handle through the
registry as before, and a document releases its annotation contexts,
pages, fonts and XObjects before itself.
- Unloading the shared library without `.onUnload` leaks the PDFium
objects of handles that are still open. Nothing may close them once
their library is gone, and a later copy of the library must not. The
finalizer function also stays preserved, keeping its namespace in
memory. pkgload's fallback is the one known path.
- Cost: running `finalize_handle()` costs about 1.6 µs per handle. The
benchmark loads page 1 of `shapes.pdf` 10,000 times and reads the type
and bounds of each of its 5 objects. With pages left to the finalizer
it took 8.32–8.45 s before and 8.36–8.43 s after. With pages closed
explicitly it took 8.57–8.73 s before and 8.65–8.73 s after. These
are three runs per build, each the median of seven, and the
differences are within run-to-run noise. A `gc()` that finalizes
20,000 unreachable bitmaps took 45 ms before and 44 ms after.
- `dyn.unload()` cannot unmap a build that exports a GNU-unique
symbol: glibc keeps it loaded. covr's and pkgbuild's `-O0` builds
export `std::piecewise_construct`; the `-O2` build exports none.
Loading the same file again then returns the same image, registry and
all, and the registry releases the handles it still holds when they
are collected. `tests/testthat/test-finalizer.R` tells the two cases
apart by a load generation that `R_init_pdfium()` counts. pkgload
loads each build from a new temporary file, so its reloads always get
a fresh image.
- The finalizer resolves `"pdfium"` to the most recently loaded shared
library of that name (`R_FindSymbol()`). Having two copies loaded at
once is unsupported, and only a hand-made `dyn.load()` of a second
copy can cause it. The finalizers of one copy's handles would then
reach the other copy, which would leave them alone (decision 3), so
the first copy's registry would keep entries that R has freed. For
the same reason, loading a kept image again by hand after its handles
were collected while it was unloaded is unsupported.
- The memory buffer is now an R vector, so R's garbage collector counts
it, and a large document read from memory makes R collect sooner. The
`new[]` buffer it replaces was invisible to R.
- `tests/testthat/test-finalizer.R` pins each unload path, and R's exit,
each in a fresh R process, so a regression fails a test instead of
ending the test run.

## Alternatives considered

- **Keep the shared library mapped**, by not calling
`library.dynam.unload()`: pkgload unloads the library itself, so
reloads would still crash. On Windows a loaded DLL cannot be replaced,
so reinstalling after an unload would fail.
- **`R_unload_pdfium()`** to release everything: R never calls it while
dynamic symbols are disabled, and it could not remove the finalizer
addresses anyway.
- **A captured `NativeSymbolInfo` plus a flag that `.onUnload`
clears**: cheaper (a `.Call()` through a held symbol takes about
0.25 µs, against about 1 µs by name), but only as safe as `.onUnload`
running before every unload, which pkgload's fallback skips.
- **Checking `getLoadedDLLs()`**: correct, but it builds the whole table
of loaded libraries, at about 870 µs per call.
- **`reg.finalizer()` from R, or an environment wrapping each
externalptr**: the same R finalizer, at the price of an extra R call
or allocation per handle. Registering it in `make_handle()` keeps the
single site that ADR-028 set up.
- **A C finalizer in a helper library the package never unloads**: this
keeps a library mapped after all, with the same Windows problem.

## References

- ADR-005 (memory model), ADR-024, ADR-025, and ADR-028, whose known
limitation this resolves.
- `R/finalizer.R`, `R/zzz.R`, `src/handle_registry.h`,
`src/handle_registry.cpp`, `src/init.cpp`.
- R sources: `src/main/memory.c` (`R_RegisterFinalizerEx()`,
`R_RunWeakRefFinalizer()`, `RunFinalizers()`,
`R_RunExitFinalizers()`) and `src/main/Rdynload.c`
(`R_callDLLUnload()`, `DeleteDLL()`, `R_FindSymbol()`).
- `tests/testthat/test-finalizer.R`,
`tests/testthat/scripts/unload-scenario.R`.
Loading
Loading