From 1a1b5a49cd6919131a6cec8b0a3d81b6b3cea611 Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Sun, 27 Sep 2026 16:51:09 +0000 Subject: [PATCH 1/2] fix: close the handles to an object pdf_annot_remove_object() removes pdf_annot_remove_object() destroys an object of an annotation's appearance stream, but the handles made to it earlier still pinned an open annotation, so they passed every check. Under valgrind, the removed object's handles read the freed object (4 invalid reads), a clip path read from it 1, and an object nested in a removed form 5. The handles pdf_annot_objects() returns are now registered under the annotation's document as a kind whose release only clears the handle, and cpp_annot_remove_object() releases those whose address is the removed object's once PDFium has removed it. The clip paths and nested objects read through them are then refused by the ADR-029 chain, with a message naming pdf_annot_remove_object(). A removal PDFium refuses leaves the handles open, and objects read through another handle to the same annotation are separate copies that stay valid. See ADR-032. Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 6 + R/RcppExports.R | 12 +- R/api_completion.R | 20 ++- R/obj_extras.R | 17 ++- ...notation-object-handles-close-on-remove.md | 87 ++++++++++++ dev/decisions/README.md | 1 + man/pdf_annot_objects.Rd | 3 +- man/pdf_annot_remove_object.Rd | 13 +- src/RcppExports.cpp | 30 ++-- src/api_completion.cpp | 26 +++- src/handle_registry.cpp | 70 +++++++-- src/handle_registry.h | 26 +++- tests/testthat/test-api-completion.R | 133 +++++++++++++++++- tests/testthat/test-clip.R | 2 +- tests/testthat/test-forms.R | 4 +- 15 files changed, 394 insertions(+), 56 deletions(-) create mode 100644 dev/decisions/ADR-032-annotation-object-handles-close-on-remove.md diff --git a/NEWS.md b/NEWS.md index 33a1456..d8b6a9b 100644 --- a/NEWS.md +++ b/NEWS.md @@ -174,6 +174,12 @@ move, read them again through `pdf_annot_objects()` and `pdf_form_objects()`. They used to read the freed objects once the form was destroyed (ADR-029). +* `pdf_annot_remove_object()` closes the handles to the object it + removes, from every earlier `pdf_annot_objects()` call on the + annotation handle, together with the clip paths and nested objects + read from them; they now fail with "The object was removed from its + annotation by pdf_annot_remove_object()." They used to read the freed + object (ADR-032). * Shutting PDFium down, as unloading the package does, first closes every open document together with its pages, annotations, fonts and XObjects, and every clip path and bitmap from `pdf_clip_path_new()` diff --git a/R/RcppExports.R b/R/RcppExports.R index 857c2f6..a9b34ec 100644 --- a/R/RcppExports.R +++ b/R/RcppExports.R @@ -197,8 +197,8 @@ cpp_annot_append_object <- function(annot_ptr, page_ptr, obj_ptr) { .Call(`_pdfium_cpp_annot_append_object`, annot_ptr, page_ptr, obj_ptr) } -cpp_annot_remove_object <- function(annot_ptr, index_zero) { - .Call(`_pdfium_cpp_annot_remove_object`, annot_ptr, index_zero) +cpp_annot_remove_object <- function(annot_ptr, doc_ptr, index_zero) { + .Call(`_pdfium_cpp_annot_remove_object`, annot_ptr, doc_ptr, index_zero) } cpp_annot_update_object <- function(annot_ptr, obj_ptr) { @@ -209,8 +209,8 @@ cpp_annot_object_count <- function(annot_ptr) { .Call(`_pdfium_cpp_annot_object_count`, annot_ptr) } -cpp_annot_get_object <- function(annot_ptr, index_zero) { - .Call(`_pdfium_cpp_annot_get_object`, annot_ptr, index_zero) +cpp_annot_get_object <- function(annot_ptr, doc_ptr, index_zero) { + .Call(`_pdfium_cpp_annot_get_object`, annot_ptr, doc_ptr, index_zero) } cpp_annot_set_uri <- function(annot_ptr, uri) { @@ -613,6 +613,10 @@ cpp_doc_handle_counts <- function(doc_ptr) { .Call(`_pdfium_cpp_doc_handle_counts`, doc_ptr) } +cpp_annot_object_handle_count <- function(doc_ptr) { + .Call(`_pdfium_cpp_annot_object_handle_count`, doc_ptr) +} + cpp_library_handle_counts <- function() { .Call(`_pdfium_cpp_library_handle_counts`) } diff --git a/R/api_completion.R b/R/api_completion.R index aa1238a..3ddb04c 100644 --- a/R/api_completion.R +++ b/R/api_completion.R @@ -592,7 +592,8 @@ pdf_annot_object_count <- function(annot) { #' from the annotation's normal (`/AP /N`) appearance stream. Returns a #' list of `pdfium_obj` handles; each handle's externalptr pins the #' parent annotation, so the embedded objects can't dangle past the -#' annot's lifetime. +#' annot's lifetime, and [pdf_annot_remove_object()] closes the handles +#' to the object it removes. #' #' Each handle's `type` is the object's own type (`"path"`, `"text"`, #' `"image"`, `"shading"` or `"form"`), as in [pdf_page_objects()] and @@ -628,7 +629,7 @@ pdf_annot_objects <- function(annot) { out <- vector("list", n) page <- annot$page for (i in seq_len(n)) { - ptr <- cpp_annot_get_object(annot$ptr, i - 1L) + ptr <- cpp_annot_get_object(annot$ptr, page$doc$ptr, i - 1L) type_int <- cpp_obj_type(ptr) out[[i]] <- new_pdfium_obj(ptr, page, i, pdfium_obj_type_name(type_int), parent_annot = annot) @@ -700,10 +701,15 @@ pdf_annot_append_object <- function(annot, obj) { #' Wraps `FPDFAnnot_RemoveObject`. The object is identified by its #' position within the annotation's embedded content (one-based, #' matching [pdf_annot_objects()]). PDFium destroys the object and -#' regenerates the annotation's appearance stream, so handles to it -#' from an earlier [pdf_annot_objects()] call, and the clip paths and -#' nested objects read from them, are stale and must not be used; call -#' [pdf_annot_objects()] again for the remaining ones. +#' regenerates the annotation's appearance stream. The handles to the +#' object from earlier [pdf_annot_objects()] calls on `annot` are +#' closed, and so are the clip paths and nested objects read from +#' them: further calls on them error cleanly. The handles to the +#' remaining objects stay valid, but their positions shift down by +#' one; call [pdf_annot_objects()] again for the new positions. +#' Objects read through another handle to the same annotation, for +#' example from a second [pdf_annotations()] call, are separate copies +#' and are not affected. #' #' @param annot A `pdfium_annot` of subtype `"ink"` or `"stamp"`, the #' only subtypes PDFium edits embedded objects of. Parent doc must @@ -716,7 +722,7 @@ pdf_annot_remove_object <- function(annot, index) { checkmate::assert_int(index, lower = 1L) ctx <- assert_annot_writable(annot) expect_setter_ok( - cpp_annot_remove_object(annot$ptr, as.integer(index) - 1L), + cpp_annot_remove_object(annot$ptr, annot$page$doc$ptr, as.integer(index) - 1L), "FPDFAnnot_RemoveObject") finalize_annot_setter(ctx) } diff --git a/R/obj_extras.R b/R/obj_extras.R index 4d093eb..4be240c 100644 --- a/R/obj_extras.R +++ b/R/obj_extras.R @@ -27,8 +27,9 @@ check_pdfium_obj <- function(obj, allowed_types = NULL, arg = "obj") { # document was closed, which closes its pages (ADR-025); "annotation" # when the annotation whose appearance stream holds it was deleted # with pdf_annot_delete(); "form" when a form object it is nested in -# was closed by a mutator; otherwise "page" (its page was closed, or a -# mutator cleared the handle itself). +# was closed by a mutator; "removed" when pdf_annot_remove_object() +# removed it from its annotation (ADR-032); otherwise "page" (its page +# was closed, or a mutator cleared the handle itself). obj_closed_cause <- function(obj) { if (!is_open(obj$page$doc)) { return("document") @@ -47,6 +48,9 @@ obj_closed_cause <- function(obj) { } form <- form$parent_form } + if (!is.null(obj$parent_annot) && !cpp_handle_is_valid(obj$ptr)) { + return("removed") + } "page" } @@ -64,8 +68,13 @@ closed_cause_message <- function(cause, what) { ), form = paste0( "Parent form object has been closed: it was deleted, removed ", - "from its form or moved into an annotation. The ", what, - " is no longer valid." + "from its form or annotation, or moved into an annotation. The ", + what, " is no longer valid." + ), + removed = paste0( + if (what == "clip path") "The clip path's page-object" else "The object", + " was removed from its annotation by pdf_annot_remove_object(). ", + "The ", what, " is no longer valid." ) ) } diff --git a/dev/decisions/ADR-032-annotation-object-handles-close-on-remove.md b/dev/decisions/ADR-032-annotation-object-handles-close-on-remove.md new file mode 100644 index 0000000..6d89bc1 --- /dev/null +++ b/dev/decisions/ADR-032-annotation-object-handles-close-on-remove.md @@ -0,0 +1,87 @@ +# ADR-032 โ€” Removing an annotation's page-object closes its handles + +- Status: Accepted (extends ADR-029) +- Date: 2026-09-27 +- Deciders: Bill Denney + +## Context + +ADR-029 refuses a handle once any of its owners is closed, but left +one path open: `pdf_annot_remove_object()` destroys an object of an +annotation's appearance stream by position (`FPDFAnnot_RemoveObject`), +and nothing could find the handles made to that object earlier. They +still pinned an open annotation, so they, and the clip paths and nested +objects read through them, passed every check and read the freed +object. Under valgrind on the ADR-029 branch: + +- the removed object's own handle, and a second handle to it from + another `pdf_annot_objects()` call: 4 invalid reads; +- a clip path read from the object: 1 invalid read; +- an object nested in a form removed from its annotation: 5 invalid + reads. + +Each annotation handle has its own annotation context, which parses the +appearance stream into its own objects: objects read through another +handle to the same annotation are separate copies, at other addresses, +and the removal does not touch them. + +## Decision + +1. The handles `pdf_annot_objects()` returns are registered in the + ADR-025 registry, under the annotation's document, as a new kind + whose release only clears the handle: the annotation owns the + object. `make_annot_object_handle()` mints them; like every other + registered handle they are released by their finalizer and by their + document's close. +2. After `FPDFAnnot_RemoveObject` succeeds, `cpp_annot_remove_object()` + releases every handle of that kind registered under the document + whose address is the removed object's, with + `release_annot_object_handles()`. Only addresses are compared, so + the object being freed already does not matter; a removal PDFium + refuses leaves the handles open. The clip paths and nested objects + read through the released handles are then refused by the ADR-029 + chain. +3. As with annotation handles (ADR-024), the shims take the document + from R: `cpp_annot_get_object()` and `cpp_annot_remove_object()` + gain a document argument. +4. The closed-handle messages name the cause: "The object was removed + from its annotation by pdf_annot_remove_object()." + +## Consequences + +- No handle reachable from `pdf_annot_objects()` outlives the object it + points to. +- Every annotation page-object handle carries a finalizer, which only + deregisters it. +- A second handle to one page-object of a page or form, from a separate + `pdf_page_objects()` or `pdf_form_objects()` call, still stays stale + after the object is deleted through the first. Those objects have no + registry entry; registering them the same way would close that gap + too. +- `cpp_annot_object_handle_count()` reports the registered annotation + page-object handles of a document, for tests; + `cpp_doc_handle_counts()` is unchanged. + +## Alternatives considered + +- **Document the handles as stale**, as ADR-029 did: leaves a + use-after-free one call away from an exported function. +- **Register the handles under their annotation handle** instead of the + document: the registry is keyed by document, and the address already + tells the removed object's handles apart from those of other + annotation contexts. +- **Release the handles before the removal**: a removal PDFium refuses, + for an annotation subtype that cannot hold objects, would close + handles to an object that still exists. + +## References + +- ADR-024, ADR-025, ADR-029. +- `src/handle_registry.h`, `src/handle_registry.cpp`, + `src/api_completion.cpp` (`cpp_annot_get_object`, + `cpp_annot_remove_object`). +- PDFium `public/fpdf_annot.h` (`FPDFAnnot_GetObject`, + `FPDFAnnot_RemoveObject`). +- `tests/testthat/test-api-completion.R`, section + "pdf_annot_remove_object() closes the removed object's handles + (ADR-032)". diff --git a/dev/decisions/README.md b/dev/decisions/README.md index 5624204..1992d4c 100644 --- a/dev/decisions/README.md +++ b/dev/decisions/README.md @@ -36,6 +36,7 @@ Markdown ADR following the | [026](ADR-026-no-cran-release.md) | Supersedes ADR-008's release targeting and ADR-003's CRAN-submission wording | No CRAN release: keep ADR-008's CRAN-quality bar, ship binaries through r-universe and source through GitHub | | [028](ADR-028-library-destroy-closes-every-handle.md) | Accepted (extends ADR-025) | Destroying the library closes every handle first: documents, standalone clip paths, bitmaps and memory-document buffers are registered under the library and released before `FPDF_DestroyLibrary`; every finalizer is attached in one place | | [029](ADR-029-handles-follow-their-owners.md) | Accepted (extends ADR-020 ยง4 and ADR-025) | A handle is refused once any of its owners is closed: clip paths pin their page-object and nested objects their form, and `validate_handle()` and `is_open()` walk the whole ownership chain | +| [032](ADR-032-annotation-object-handles-close-on-remove.md) | Accepted (extends ADR-029) | Removing an annotation's page-object closes its handles: `pdf_annot_objects()` handles are registered under their document, and `pdf_annot_remove_object()` releases those whose address is the removed object's | ## Policy diff --git a/man/pdf_annot_objects.Rd b/man/pdf_annot_objects.Rd index 7962a3b..812fc2e 100644 --- a/man/pdf_annot_objects.Rd +++ b/man/pdf_annot_objects.Rd @@ -19,7 +19,8 @@ Wraps \code{FPDFAnnot_GetObject} over the full count and from the annotation's normal (\verb{/AP /N}) appearance stream. Returns a list of \code{pdfium_obj} handles; each handle's externalptr pins the parent annotation, so the embedded objects can't dangle past the -annot's lifetime. +annot's lifetime, and \code{\link[=pdf_annot_remove_object]{pdf_annot_remove_object()}} closes the handles +to the object it removes. } \details{ Each handle's \code{type} is the object's own type (\code{"path"}, \code{"text"}, diff --git a/man/pdf_annot_remove_object.Rd b/man/pdf_annot_remove_object.Rd index 07deca7..be088f0 100644 --- a/man/pdf_annot_remove_object.Rd +++ b/man/pdf_annot_remove_object.Rd @@ -20,10 +20,15 @@ Invisibly returns the parent \code{pdfium_doc}. Wraps \code{FPDFAnnot_RemoveObject}. The object is identified by its position within the annotation's embedded content (one-based, matching \code{\link[=pdf_annot_objects]{pdf_annot_objects()}}). PDFium destroys the object and -regenerates the annotation's appearance stream, so handles to it -from an earlier \code{\link[=pdf_annot_objects]{pdf_annot_objects()}} call, and the clip paths and -nested objects read from them, are stale and must not be used; call -\code{\link[=pdf_annot_objects]{pdf_annot_objects()}} again for the remaining ones. +regenerates the annotation's appearance stream. The handles to the +object from earlier \code{\link[=pdf_annot_objects]{pdf_annot_objects()}} calls on \code{annot} are +closed, and so are the clip paths and nested objects read from +them: further calls on them error cleanly. The handles to the +remaining objects stay valid, but their positions shift down by +one; call \code{\link[=pdf_annot_objects]{pdf_annot_objects()}} again for the new positions. +Objects read through another handle to the same annotation, for +example from a second \code{\link[=pdf_annotations]{pdf_annotations()}} call, are separate copies +and are not affected. } \seealso{ \code{\link[=pdf_annot_append_object]{pdf_annot_append_object()}}, \code{\link[=pdf_annot_objects]{pdf_annot_objects()}}. diff --git a/src/RcppExports.cpp b/src/RcppExports.cpp index 01a3b71..5c3ae32 100644 --- a/src/RcppExports.cpp +++ b/src/RcppExports.cpp @@ -629,14 +629,15 @@ BEGIN_RCPP END_RCPP } // cpp_annot_remove_object -bool cpp_annot_remove_object(SEXP annot_ptr, int index_zero); -RcppExport SEXP _pdfium_cpp_annot_remove_object(SEXP annot_ptrSEXP, SEXP index_zeroSEXP) { +bool cpp_annot_remove_object(SEXP annot_ptr, SEXP doc_ptr, int index_zero); +RcppExport SEXP _pdfium_cpp_annot_remove_object(SEXP annot_ptrSEXP, SEXP doc_ptrSEXP, SEXP index_zeroSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< SEXP >::type annot_ptr(annot_ptrSEXP); + Rcpp::traits::input_parameter< SEXP >::type doc_ptr(doc_ptrSEXP); Rcpp::traits::input_parameter< int >::type index_zero(index_zeroSEXP); - rcpp_result_gen = Rcpp::wrap(cpp_annot_remove_object(annot_ptr, index_zero)); + rcpp_result_gen = Rcpp::wrap(cpp_annot_remove_object(annot_ptr, doc_ptr, index_zero)); return rcpp_result_gen; END_RCPP } @@ -664,14 +665,15 @@ BEGIN_RCPP END_RCPP } // cpp_annot_get_object -SEXP cpp_annot_get_object(SEXP annot_ptr, int index_zero); -RcppExport SEXP _pdfium_cpp_annot_get_object(SEXP annot_ptrSEXP, SEXP index_zeroSEXP) { +SEXP cpp_annot_get_object(SEXP annot_ptr, SEXP doc_ptr, int index_zero); +RcppExport SEXP _pdfium_cpp_annot_get_object(SEXP annot_ptrSEXP, SEXP doc_ptrSEXP, SEXP index_zeroSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< SEXP >::type annot_ptr(annot_ptrSEXP); + Rcpp::traits::input_parameter< SEXP >::type doc_ptr(doc_ptrSEXP); Rcpp::traits::input_parameter< int >::type index_zero(index_zeroSEXP); - rcpp_result_gen = Rcpp::wrap(cpp_annot_get_object(annot_ptr, index_zero)); + rcpp_result_gen = Rcpp::wrap(cpp_annot_get_object(annot_ptr, doc_ptr, index_zero)); return rcpp_result_gen; END_RCPP } @@ -1856,6 +1858,17 @@ BEGIN_RCPP return rcpp_result_gen; END_RCPP } +// cpp_annot_object_handle_count +int cpp_annot_object_handle_count(SEXP doc_ptr); +RcppExport SEXP _pdfium_cpp_annot_object_handle_count(SEXP doc_ptrSEXP) { +BEGIN_RCPP + Rcpp::RObject rcpp_result_gen; + Rcpp::RNGScope rcpp_rngScope_gen; + Rcpp::traits::input_parameter< SEXP >::type doc_ptr(doc_ptrSEXP); + rcpp_result_gen = Rcpp::wrap(cpp_annot_object_handle_count(doc_ptr)); + return rcpp_result_gen; +END_RCPP +} // cpp_library_handle_counts Rcpp::IntegerVector cpp_library_handle_counts(); RcppExport SEXP _pdfium_cpp_library_handle_counts() { @@ -3367,10 +3380,10 @@ static const R_CallMethodDef CallEntries[] = { {"_pdfium_cpp_annot_add_ink_stroke", (DL_FUNC) &_pdfium_cpp_annot_add_ink_stroke, 2}, {"_pdfium_cpp_annot_remove_ink_list", (DL_FUNC) &_pdfium_cpp_annot_remove_ink_list, 1}, {"_pdfium_cpp_annot_append_object", (DL_FUNC) &_pdfium_cpp_annot_append_object, 3}, - {"_pdfium_cpp_annot_remove_object", (DL_FUNC) &_pdfium_cpp_annot_remove_object, 2}, + {"_pdfium_cpp_annot_remove_object", (DL_FUNC) &_pdfium_cpp_annot_remove_object, 3}, {"_pdfium_cpp_annot_update_object", (DL_FUNC) &_pdfium_cpp_annot_update_object, 2}, {"_pdfium_cpp_annot_object_count", (DL_FUNC) &_pdfium_cpp_annot_object_count, 1}, - {"_pdfium_cpp_annot_get_object", (DL_FUNC) &_pdfium_cpp_annot_get_object, 2}, + {"_pdfium_cpp_annot_get_object", (DL_FUNC) &_pdfium_cpp_annot_get_object, 3}, {"_pdfium_cpp_annot_set_uri", (DL_FUNC) &_pdfium_cpp_annot_set_uri, 2}, {"_pdfium_cpp_annot_set_appearance", (DL_FUNC) &_pdfium_cpp_annot_set_appearance, 3}, {"_pdfium_cpp_annot_add_file_attachment", (DL_FUNC) &_pdfium_cpp_annot_add_file_attachment, 3}, @@ -3471,6 +3484,7 @@ static const R_CallMethodDef CallEntries[] = { {"_pdfium_cpp_text_obj_font_metrics", (DL_FUNC) &_pdfium_cpp_text_obj_font_metrics, 2}, {"_pdfium_cpp_text_char_font_info", (DL_FUNC) &_pdfium_cpp_text_char_font_info, 1}, {"_pdfium_cpp_doc_handle_counts", (DL_FUNC) &_pdfium_cpp_doc_handle_counts, 1}, + {"_pdfium_cpp_annot_object_handle_count", (DL_FUNC) &_pdfium_cpp_annot_object_handle_count, 1}, {"_pdfium_cpp_library_handle_counts", (DL_FUNC) &_pdfium_cpp_library_handle_counts, 0}, {"_pdfium_cpp_image_new_from_jpeg", (DL_FUNC) &_pdfium_cpp_image_new_from_jpeg, 3}, {"_pdfium_cpp_image_new_blank", (DL_FUNC) &_pdfium_cpp_image_new_blank, 2}, diff --git a/src/api_completion.cpp b/src/api_completion.cpp index 6fd8f2f..599d2bd 100644 --- a/src/api_completion.cpp +++ b/src/api_completion.cpp @@ -528,10 +528,20 @@ int cpp_annot_append_object(SEXP annot_ptr, SEXP page_ptr, SEXP obj_ptr) { return 0; } +// Remove the page-object at `index_zero` from the annotation. PDFium +// destroys it, so the handles made to it, registered under the +// document behind `doc_ptr`, are cleared once the removal succeeded +// (ADR-032); a refused removal leaves them open. // [[Rcpp::export(name = "cpp_annot_remove_object")]] -bool cpp_annot_remove_object(SEXP annot_ptr, int index_zero) { +bool cpp_annot_remove_object(SEXP annot_ptr, SEXP doc_ptr, int index_zero) { FPDF_ANNOTATION annot = acomp_annot_from_ptr(annot_ptr); - return FPDFAnnot_RemoveObject(annot, index_zero) != 0; + FPDF_DOCUMENT doc = acomp_doc_from_ptr(doc_ptr); + FPDF_PAGEOBJECT obj = FPDFAnnot_GetObject(annot, index_zero); + if (!FPDFAnnot_RemoveObject(annot, index_zero)) { + return false; + } + pdfium_r::release_annot_object_handles(doc, obj); + return true; } // [[Rcpp::export(name = "cpp_annot_update_object")]] @@ -547,18 +557,20 @@ int cpp_annot_object_count(SEXP annot_ptr) { return FPDFAnnot_GetObjectCount(annot); } -// Returns the page-object at the given index. The annotation owns it -// (no finalizer); the externalptr's prot slot pins the annot so the -// page-obj reference can't dangle. +// Returns the page-object at the given index. The annotation owns it; +// the externalptr's prot slot pins the annot so the page-obj reference +// can't dangle, and the handle is registered under the document behind +// `doc_ptr` so that cpp_annot_remove_object() can clear it (ADR-032). // [[Rcpp::export(name = "cpp_annot_get_object")]] -SEXP cpp_annot_get_object(SEXP annot_ptr, int index_zero) { +SEXP cpp_annot_get_object(SEXP annot_ptr, SEXP doc_ptr, int index_zero) { FPDF_ANNOTATION annot = acomp_annot_from_ptr(annot_ptr); + FPDF_DOCUMENT doc = acomp_doc_from_ptr(doc_ptr); FPDF_PAGEOBJECT obj = FPDFAnnot_GetObject(annot, index_zero); if (obj == nullptr) { Rcpp::stop("FPDFAnnot_GetObject returned NULL for index %d", index_zero); } - return R_MakeExternalPtr(obj, R_NilValue, annot_ptr); + return pdfium_r::make_annot_object_handle(obj, annot_ptr, doc); } // [[Rcpp::export(name = "cpp_annot_set_uri")]] diff --git a/src/handle_registry.cpp b/src/handle_registry.cpp index 1a8b9a8..cfb91e1 100644 --- a/src/handle_registry.cpp +++ b/src/handle_registry.cpp @@ -1,7 +1,8 @@ // pdfium R package โ€” registry of live handles. See handle_registry.h, -// ADR-024, ADR-025 and ADR-028. +// ADR-024, ADR-025, ADR-028 and ADR-032. #include +#include #include #include #include @@ -17,22 +18,26 @@ namespace { // Also the order in which the handles registered under one owner are -// released. Annotation contexts, pages, fonts and XObjects are -// registered under their document; documents, clip paths, bitmaps and -// memory-document buffers under the library, the buffers last because -// a document reads its buffer until it is closed. +// released. Annotation contexts, pages, fonts, XObjects and annotation +// page-objects are registered under their document, the page-objects +// last because releasing one only clears it; documents, clip paths, +// bitmaps and memory-document buffers under the library, the buffers +// last because a document reads its buffer until it is closed. enum Kind : int { kAnnot = 0, kPage, kFont, kXObject, + kAnnotObject, kDocument, kClipPath, kBitmap, kBuffer, kKindCount }; -constexpr int kDocKindCount = kDocument; +// The document kinds count_doc_handles() reports: annotation, page, +// font and XObject. +constexpr int kDocCountedKinds = kXObject + 1; constexpr int kLibraryKindCount = kKindCount - kDocument; // The owner the library's handles are registered under. No document @@ -80,6 +85,8 @@ void close_font(void* addr) { FPDFFont_Close(static_cast(addr)); } void close_xobject(void* addr) { FPDF_CloseXObject(static_cast(addr)); } +// An annotation page-object belongs to its annotation, which frees it. +void close_nothing(void*) {} void close_document(void* addr) { FPDF_DOCUMENT doc = static_cast(addr); release_owned(doc); @@ -96,7 +103,8 @@ void close_buffer(void* addr) { delete[] static_cast(addr); } using CloseFn = void (*)(void*); const std::array kClose = { close_annot, close_page, close_font, close_xobject, - close_document, close_clip_path, close_bitmap, close_buffer}; + close_nothing, close_document, close_clip_path, close_bitmap, + close_buffer}; void release(SEXP ptr, Kind kind) noexcept { if (TYPEOF(ptr) != EXTPTRSXP) return; @@ -123,15 +131,16 @@ void finalize_annot(SEXP ptr) { release(ptr, kAnnot); } void finalize_page(SEXP ptr) { release(ptr, kPage); } void finalize_font(SEXP ptr) { release(ptr, kFont); } void finalize_xobject(SEXP ptr) { release(ptr, kXObject); } +void finalize_annot_object(SEXP ptr) { release(ptr, kAnnotObject); } void finalize_document(SEXP ptr) { release(ptr, kDocument); } void finalize_clip_path(SEXP ptr) { release(ptr, kClipPath); } void finalize_bitmap(SEXP ptr) { release(ptr, kBitmap); } void finalize_buffer(SEXP ptr) { release(ptr, kBuffer); } const std::array kFinalize = { - finalize_annot, finalize_page, finalize_font, - finalize_xobject, finalize_document, finalize_clip_path, - finalize_bitmap, finalize_buffer}; + finalize_annot, finalize_page, finalize_font, + finalize_xobject, finalize_annot_object, finalize_document, + finalize_clip_path, finalize_bitmap, finalize_buffer}; SEXP make_handle(void* addr, SEXP prot, FPDF_DOCUMENT owner, Kind kind) { SEXP ptr = PROTECT(R_MakeExternalPtr(addr, R_NilValue, prot)); @@ -195,6 +204,11 @@ SEXP make_xobject_handle(FPDF_XOBJECT xobject, SEXP doc_ptr) { return make_handle(xobject, doc_ptr, document_of(doc_ptr), kXObject); } +SEXP make_annot_object_handle(FPDF_PAGEOBJECT obj, SEXP annot_ptr, + FPDF_DOCUMENT doc) { + return make_handle(obj, annot_ptr, doc, kAnnotObject); +} + SEXP make_clip_path_handle(FPDF_CLIPPATH clip_path) { return make_handle(clip_path, R_NilValue, kLibrary, kClipPath); } @@ -239,13 +253,34 @@ void release_buffer_handle(SEXP buffer_ptr) noexcept { release(buffer_ptr, kBuffer); } +void release_annot_object_handles(FPDF_DOCUMENT doc, + FPDF_PAGEOBJECT obj) noexcept { + // Releasing a handle removes it from the set, and the document's entry + // once all its sets are empty, so look the set up again each time. + for (;;) { + auto doc_it = g_handles.find(doc); + if (doc_it == g_handles.end()) return; + const auto& handles = doc_it->second[kAnnotObject]; + auto hit = std::find_if(handles.begin(), handles.end(), [obj](SEXP ptr) { + return R_ExternalPtrAddr(ptr) == obj; + }); + if (hit == handles.end()) return; + release(*hit, kAnnotObject); + } +} + void release_library_handles() noexcept { release_owned(kLibrary); } std::vector count_doc_handles(FPDF_DOCUMENT doc) { // A closed document's address reads as NULL, which is the library's // key; it has no handles of its own. - if (doc == kLibrary) return std::vector(kDocKindCount, 0); - return count_owned(doc, 0, kDocKindCount); + if (doc == kLibrary) return std::vector(kDocCountedKinds, 0); + return count_owned(doc, kAnnot, kDocCountedKinds); +} + +int count_annot_object_handles(FPDF_DOCUMENT doc) { + if (doc == kLibrary) return 0; + return count_owned(doc, kAnnotObject, 1)[0]; } std::vector count_library_handles() { @@ -269,6 +304,17 @@ Rcpp::IntegerVector cpp_doc_handle_counts(SEXP doc_ptr) { return out; } +// Test hook: the annotation page-object handles registered under a +// document. A closed document has none. +// [[Rcpp::export(name = "cpp_annot_object_handle_count")]] +int cpp_annot_object_handle_count(SEXP doc_ptr) { + if (TYPEOF(doc_ptr) != EXTPTRSXP) { + Rcpp::stop("Expected an external pointer for the document."); + } + return pdfium_r::count_annot_object_handles( + static_cast(R_ExternalPtrAddr(doc_ptr))); +} + // Test hook: the handles registered under the library, per kind. // [[Rcpp::export(name = "cpp_library_handle_counts")]] Rcpp::IntegerVector cpp_library_handle_counts() { diff --git a/src/handle_registry.h b/src/handle_registry.h index f935874..6b3f528 100644 --- a/src/handle_registry.h +++ b/src/handle_registry.h @@ -1,12 +1,14 @@ // pdfium R package โ€” lifetime of every handle with a finalizer -// (ADR-024, ADR-025, ADR-028). +// (ADR-024, ADR-025, ADR-028, ADR-032). // // PDFium expects every page, annotation context, font and XObject to // be closed before the document it belongs to, and every document, // clip path and bitmap before FPDF_DestroyLibrary(). The package keeps // that order in every teardown: each live handle is registered under // what it must be closed before. Annotation contexts, pages, fonts and -// XObjects are registered under their FPDF_DOCUMENT; documents, the +// XObjects are registered under their FPDF_DOCUMENT, as are the +// handles to the page-objects of annotations, which PDFium frees with +// their annotation and whose release only clears them; documents, the // clip paths of pdf_clip_path_new(), bitmaps and the buffers that // documents loaded from memory read from are registered under the // library. Closing a document releases the handles registered under it @@ -58,6 +60,14 @@ SEXP make_page_handle(FPDF_PAGE page, SEXP doc_ptr); SEXP make_font_handle(FPDF_FONT font, SEXP doc_ptr); SEXP make_xobject_handle(FPDF_XOBJECT xobject, SEXP doc_ptr); +// Wrap `obj`, a page-object of the appearance stream of the annotation +// behind `annot_ptr`, in an externalptr that pins `annot_ptr` in its +// prot slot and is registered under `doc`, the open document the +// annotation belongs to. The annotation owns the object, so releasing +// the handle only clears it. +SEXP make_annot_object_handle(FPDF_PAGEOBJECT obj, SEXP annot_ptr, + FPDF_DOCUMENT doc); + // Wrap a clip path from FPDF_CreateClipPath(), or a bitmap from // FPDFBitmap_Create(), in an externalptr with its finalizer, registered // under the library. Neither belongs to a document. @@ -82,15 +92,23 @@ void release_clip_path_handle(SEXP clip_path_ptr) noexcept; void release_bitmap_handle(SEXP bitmap_ptr) noexcept; void release_buffer_handle(SEXP buffer_ptr) noexcept; +// Release the annotation page-object handles registered under `doc` +// whose address is `obj`, an object FPDFAnnot_RemoveObject() has just +// destroyed. Only addresses are compared. +void release_annot_object_handles(FPDF_DOCUMENT doc, + FPDF_PAGEOBJECT obj) noexcept; + // Release every handle registered under the library: documents, each // after the handles registered under it, then clip paths, bitmaps and // buffers. Must run before FPDF_DestroyLibrary(). void release_library_handles() noexcept; // Number of handles registered under the document `doc`, per kind, in -// the order annotation, page, font, XObject; and under the library, in -// the order document, clip path, bitmap, buffer. +// the order annotation, page, font, XObject; of annotation page-object +// handles registered under it; and of handles registered under the +// library, in the order document, clip path, bitmap, buffer. std::vector count_doc_handles(FPDF_DOCUMENT doc); +int count_annot_object_handles(FPDF_DOCUMENT doc); std::vector count_library_handles(); } // namespace pdfium_r diff --git a/tests/testthat/test-api-completion.R b/tests/testthat/test-api-completion.R index bcf8298..e7d0aff 100644 --- a/tests/testthat/test-api-completion.R +++ b/tests/testthat/test-api-completion.R @@ -1359,7 +1359,7 @@ test_that("cpp_annot_get_object errors on out-of-bounds index", { # 0-based for the shim; the annot has no embedded objects so # any non-negative index fails. expect_error( - pdfium:::cpp_annot_get_object(a$ptr, 0L), + pdfium:::cpp_annot_get_object(a$ptr, s$doc$ptr, 0L), "FPDFAnnot_GetObject returned NULL" ) }) @@ -1398,7 +1398,7 @@ test_that("cpp_annot_remove_object returns FALSE on a bad index", { # reaches PDFium, which returns false. s <- annot_blank_page() a <- pdf_annot_new(s$page, "stamp", bounds = c(0, 0, 50, 50)) - out <- pdfium:::cpp_annot_remove_object(a$ptr, 99L) + out <- pdfium:::cpp_annot_remove_object(a$ptr, s$doc$ptr, 99L) expect_false(out) }) @@ -1581,3 +1581,132 @@ test_that("cpp_page_transform_with_clip rejects bad-shape inputs at C boundary", "length-4" ) }) + +# pdf_annot_remove_object() closes the removed object's handles (ADR-032) +# +# PDFium destroys the object it removes. The handles made to it, and the +# clip paths and nested objects read through them, close with it; the +# handles to the other objects stay usable. + +annot_removed_obj_msg <- paste0( + "^The object was removed from its annotation by ", + "pdf_annot_remove_object\\(\\)\\. The object handle is no longer valid\\.$" +) + +# A stamp annotation whose appearance stream paints a red square clipped +# to the 50 x 50 square at (10, 10), then a green square. +annot_two_objects <- function(envir = parent.frame()) { + s <- annot_blank_page(envir) + s$annot <- pdf_annot_new(s$page, "stamp", bounds = c(0, 0, 100, 100)) + pdf_annot_set_appearance( + s$annot, "normal", + "q 10 10 50 50 re W n 1 0 0 rg 0 0 100 100 re f Q 0 1 0 rg 70 70 20 20 re f" + ) + s +} + +test_that("pdf_annot_remove_object() closes every handle to the object", { + s <- annot_two_objects() + objs <- pdf_annot_objects(s$annot) + again <- pdf_annot_objects(s$annot)[[1L]] + clip <- pdf_obj_clip_path(objs[[1L]]) + removed_bounds <- pdf_obj_bounds(objs[[1L]]) + kept_bounds <- pdf_obj_bounds(objs[[2L]]) + # Another handle to the same annotation reads its own copies. + copy <- pdf_annot_objects(pdf_annotations(s$page)[[1L]])[[1L]] + pdf_annot_remove_object(s$annot, 1L) + for (obj in list(objs[[1L]], again)) { + expect_false(is_open(obj)) + expect_identical( + format(obj), "" + ) + expect_error(pdf_obj_bounds(obj), annot_removed_obj_msg) + expect_error( + pdfium:::cpp_obj_bounds(obj$ptr), + "^Page-object handle is NULL \\(closed\\?\\)\\.$" + ) + } + expect_false(is_open(clip)) + expect_error( + pdf_clip_path_count(clip), + paste0( + "^The clip path's page-object was removed from its annotation by ", + "pdf_annot_remove_object\\(\\)\\. The clip path is no longer valid\\.$" + ) + ) + expect_error( + pdfium:::cpp_clip_path_count_paths(clip$ptr), + "^Clip-path handle's parent has been closed" + ) + # The other object keeps its handle; its position moves down by one. + expect_true(is_open(objs[[2L]])) + expect_identical(pdf_obj_bounds(objs[[2L]]), kept_bounds) + remaining <- pdf_annot_objects(s$annot) + expect_length(remaining, 1L) + expect_identical(pdf_obj_bounds(remaining[[1L]]), kept_bounds) + expect_true(is_open(copy)) + expect_identical(pdf_obj_bounds(copy), removed_bounds) +}) + +test_that("removing a form from an annotation closes the objects read from it", { + doc <- pdf_doc_open(source = inline_annot_objects_pdf(), readwrite = TRUE) + on.exit(pdf_doc_close(doc), add = TRUE) + page <- pdf_page_load(doc, 1L) + a <- pdf_annotations(page)[[1L]] + form <- pdf_annot_objects(a)[[5L]] + child <- pdf_form_objects(form)[[1L]] + pdf_annot_remove_object(a, 5L) + expect_error(pdf_obj_bounds(form), annot_removed_obj_msg) + expect_false(is_open(child)) + expect_error( + pdf_text_font_size(child), + paste0( + "^Parent form object has been closed: it was deleted, removed from ", + "its form or annotation, or moved into an annotation\\. The object ", + "handle is no longer valid\\.$" + ) + ) + expect_error( + pdfium:::cpp_text_font_size(child$ptr), + "^Page-object handle's parent has been closed" + ) + expect_length(pdf_annot_objects(a), 4L) +}) + +test_that("a removal PDFium refuses leaves the object's handles open", { + # PDFium removes objects from ink and stamp annotations only. + s <- annot_blank_page() + a <- pdf_annot_new(s$page, "square", bounds = c(0, 0, 100, 100)) + pdf_annot_set_appearance(a, "normal", "0 0 1 rg 10 10 40 40 re f") + obj <- pdf_annot_objects(a)[[1L]] + expect_error( + pdf_annot_remove_object(a, 1L), + "^FPDFAnnot_RemoveObject failed\\.$" + ) + expect_true(is_open(obj)) + expect_identical(unname(pdf_obj_bounds(obj)), c(10, 10, 50, 50)) +}) + +test_that("annotation page-object handles are registered under their document", { + s <- annot_two_objects() + count <- function() pdfium:::cpp_annot_object_handle_count(s$doc$ptr) + expect_identical(count(), 0L) + objs <- pdf_annot_objects(s$annot) + expect_identical(count(), 2L) + # Removing an object releases its handles; collecting a handle does too. + pdf_annot_remove_object(s$annot, 1L) + expect_identical(count(), 1L) + rm(objs) + for (i in 1:2) invisible(gc()) + expect_identical(count(), 0L) + # Closing the document releases the rest. + kept <- pdf_annot_objects(s$annot)[[1L]] + expect_identical(count(), 1L) + pdf_doc_close(s$doc) + expect_false(pdfium:::cpp_handle_is_valid(kept$ptr)) + expect_identical(count(), 0L) + expect_error( + pdfium:::cpp_annot_object_handle_count("doc"), + "^Expected an external pointer for the document\\.$" + ) +}) diff --git a/tests/testthat/test-clip.R b/tests/testthat/test-clip.R index 0d5a175..438e887 100644 --- a/tests/testthat/test-clip.R +++ b/tests/testthat/test-clip.R @@ -284,7 +284,7 @@ test_that("a nested object's clip path closes when its form is deleted", { pdf_obj_delete(form) expect_clip_refused(clip, clip_closed_msg(paste0( "Parent form object has been closed: it was deleted, removed from ", - "its form or moved into an annotation\\." + "its form or annotation, or moved into an annotation\\." ))) }) diff --git a/tests/testthat/test-forms.R b/tests/testthat/test-forms.R index 249b7b9..3f8b4c2 100644 --- a/tests/testthat/test-forms.R +++ b/tests/testthat/test-forms.R @@ -244,8 +244,8 @@ test_that("objects of a form in an annotation follow the annotation", { form_closed_obj_msg <- paste0( "^Parent form object has been closed: it was deleted, removed from ", - "its form or moved into an annotation\\. The object handle is no ", - "longer valid\\.$" + "its form or annotation, or moved into an annotation\\. The object ", + "handle is no longer valid\\.$" ) test_that("pdf_obj_delete() on a form closes the objects read from it", { From 4c8e3187c540d2f8a3764bab19535ebe12f6cfa5 Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Sun, 27 Sep 2026 16:51:09 +0000 Subject: [PATCH 2/2] docs: note the annotation page-object handles in the memory model CLAUDE.md's memory-model section, dev/architecture.md and the architecture vignette now mention that the handles to an annotation's page-objects are registered under their document and that pdf_annot_remove_object() closes them (ADR-032). Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 5 +++-- dev/architecture.md | 4 +++- vignettes/architecture.Rmd | 4 +++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 66e5c8d..1c3169b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -137,8 +137,9 @@ for the rationale. The short version: - Every PDFium handle (`FPDF_DOCUMENT`, `FPDF_PAGE`, etc.) lives behind an 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, + `src/handle_registry.{h,cpp}` (ADR-024, ADR-025, ADR-028, ADR-032): + annotation contexts, pages, fonts, XObjects and annotation + page-objects under their document; documents, `pdf_clip_path_new()` clip paths, bitmaps and memory-document buffers under the library. - One mint and one release path per kind: `make_*_handle()` alone creates diff --git a/dev/architecture.md b/dev/architecture.md index 9daed4b..ebebefd 100644 --- a/dev/architecture.md +++ b/dev/architecture.md @@ -53,7 +53,9 @@ Read [ADR-005](decisions/ADR-005-memory-model.md) first. Summary: chain is closed (ADR-029). 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). + each is registered under its document (ADR-024, ADR-025). So are + the handles to an annotation's page-objects, which + `pdf_annot_remove_object()` clears by address (ADR-032). 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` diff --git a/vignettes/architecture.Rmd b/vignettes/architecture.Rmd index 03f6eb2..9d043fc 100644 --- a/vignettes/architecture.Rmd +++ b/vignettes/architecture.Rmd @@ -109,7 +109,9 @@ pdf_text_runs(page) The same holds further down. Deleting an annotation with `pdf_annot_delete()` closes the page-objects read from its appearance -stream with `pdf_annot_objects()`, and deleting a form object with +stream with `pdf_annot_objects()`, removing one of them with +`pdf_annot_remove_object()` closes the handles to it, and deleting a +form object with `pdf_obj_delete()` closes the objects read from it with `pdf_form_objects()`. A clip path from `pdf_obj_clip_path()` closes with its page-object.