From f05c0fb2b2d7bd43e7de6c45ca22047f83e9fce8 Mon Sep 17 00:00:00 2001 From: Bob Singor Date: Thu, 19 Nov 2026 22:49:23 +0200 Subject: [PATCH] Free the page a raw annotation handle is built on Every handle from EPDFPage_GetAnnotRaw() or EPDFPage_CreateAnnotRaw() leaked one CPDF_Page (11 blocks, about 1.4 KB), on native and WASM, since 61181c3ecd (Aug 6 2025). The page was held by RawAnnotContext, a subclass of CPDF_AnnotContext. FPDFPage_CloseAnnot() deletes a handle as CPDF_AnnotContext, whose destructor is not virtual, so the subclass's member was never destroyed. Reported in embedpdf/embed-pdf-viewer#1124. CPDF_AnnotContext now owns the page itself, and is final: - CreateOwningPage() makes a handle that keeps the page it was built on. The two raw functions use it, and RawAnnotContext is gone. The page is the first member, so it is destroyed last, after the members that point at it. - CreateLinked() makes the handle FPDFAnnot_GetLinkedAnnot() returns. It shares a page its parent owns, so the two close in either order. A linked handle that only borrowed the page would dangle once its parent closed first; the leak hid that. - GetWidget() and FORM_SetFocusedAnnot() return early for a handle that owns its page. They failed for it already, since its page view is never valid, but only after making a view keyed by that page, which would now outlive the page. No return value changes. A handle for a loaded page borrows it, as before. Tests in epdf_annot_raw_embeddertest.cpp, all failing without the change: ClosingAHandleFreesItsPage, ALinkedHandleSharesThePage and FormFillCallsMakeNoViewForAHandleWithoutAPage. The first two are listed as layer-mode writers. A caller that worked around the leak by closing the page it read at handle + 0x40 must stop with this change: that releases the page a second time, and the offset no longer holds the page. --- core/fpdfapi/page/cpdf_annotcontext.cpp | 21 +++++ core/fpdfapi/page/cpdf_annotcontext.h | 28 ++++++- docs/embedpdf/fork-ledger.md | 9 +- fpdfsdk/epdf_annot.cpp | 39 +++------ fpdfsdk/epdf_annot_raw_embeddertest.cpp | 105 ++++++++++++++++++++++++ fpdfsdk/fpdf_annot.cpp | 6 +- fpdfsdk/fpdf_formfill.cpp | 9 +- public/epdf_annot.h | 18 ++-- testing/embedpdf_layer_mode_writers.txt | 2 + 9 files changed, 195 insertions(+), 42 deletions(-) diff --git a/core/fpdfapi/page/cpdf_annotcontext.cpp b/core/fpdfapi/page/cpdf_annotcontext.cpp index 72329292df..baf9992b85 100644 --- a/core/fpdfapi/page/cpdf_annotcontext.cpp +++ b/core/fpdfapi/page/cpdf_annotcontext.cpp @@ -70,6 +70,27 @@ CPDF_AnnotContext::CPDF_AnnotContext(RetainPtr pAnnotDict, CPDF_AnnotContext::~CPDF_AnnotContext() = default; +// EmbedPDF(epdf-api): see the header. +// static +std::unique_ptr CPDF_AnnotContext::CreateOwningPage( + RetainPtr annot_dict, + RetainPtr page, + int annot_index) { + auto context = std::make_unique(std::move(annot_dict), + page.Get(), annot_index); + context->owned_page_ = std::move(page); + return context; +} + +// EmbedPDF(epdf-api): see the header. +std::unique_ptr CPDF_AnnotContext::CreateLinked( + RetainPtr linked_dict) const { + auto linked = + std::make_unique(std::move(linked_dict), GetPage()); + linked->owned_page_ = owned_page_; + return linked; +} + void CPDF_AnnotContext::SetForm(RetainPtr pStream) { CHECK(pStream); // EmbedPDF(view-scope, reads-dont-write): parse the appearance through the diff --git a/core/fpdfapi/page/cpdf_annotcontext.h b/core/fpdfapi/page/cpdf_annotcontext.h index 0818ad9ccf..2850fe5221 100644 --- a/core/fpdfapi/page/cpdf_annotcontext.h +++ b/core/fpdfapi/page/cpdf_annotcontext.h @@ -21,7 +21,10 @@ class CPDF_Form; class CPDF_Stream; class IPDF_Page; -class CPDF_AnnotContext { +// EmbedPDF(epdf-api): final. FPDFPage_CloseAnnot() deletes a handle as this +// type and the destructor is not virtual, so a subclass's members would never +// be destroyed: how a *Raw handle used to leak its page. +class CPDF_AnnotContext final { public: // EmbedPDF(measurement): owned SDK measurement state; never part of the // PDF graph. @@ -39,6 +42,25 @@ class CPDF_AnnotContext { int annot_index = -1); ~CPDF_AnnotContext(); + // EmbedPDF(epdf-api): a handle for a page nobody loaded (the *Raw calls). + // It keeps |page|, the page object it was built on, and closing the handle + // frees that page. Every other handle borrows a page its caller keeps open. + static std::unique_ptr CreateOwningPage( + RetainPtr annot_dict, + RetainPtr page, + int annot_index); + + // EmbedPDF(epdf-api): a handle to another annotation reached from this one + // (/Popup, /IRT, /Parent), on the same page. It shares a page this handle + // owns, so the two handles close in either order. + std::unique_ptr CreateLinked( + RetainPtr linked_dict) const; + + // EmbedPDF(epdf-api): whether the handle keeps its own page (see + // CreateOwningPage()). No form environment shows such a page, so the + // form-fill calls fail for the handle without making a view for the page. + bool OwnsPage() const { return !!owned_page_; } + void SetForm(RetainPtr pStream); bool HasForm() const { return !!annot_form_; } CPDF_Form* GetForm() const { return annot_form_.get(); } @@ -67,6 +89,10 @@ class CPDF_AnnotContext { int GetAnnotIndex() const { return annot_index_; } private: + // EmbedPDF(epdf-api): the page a *Raw handle keeps, else null. Declared + // first so that it is destroyed last: the page outlives every member below + // that points at it. + RetainPtr owned_page_; // EmbedPDF(measurement): see GetMeasureStorage(). std::unique_ptr measure_storage_; // EmbedPDF(overlay-epoch): re-resolve the annotation when the overlay diff --git a/docs/embedpdf/fork-ledger.md b/docs/embedpdf/fork-ledger.md index b39e3954e8..fd88d852ae 100644 --- a/docs/embedpdf/fork-ledger.md +++ b/docs/embedpdf/fork-ledger.md @@ -542,10 +542,11 @@ component builds; don't bring back the empty `#else` branch. **Why.** It was put there when the API was added. **Where.** The implementations still in `fpdf_view.cpp`, `fpdf_doc.cpp`, `fpdf_attachment.cpp`, `fpdf_save.cpp` and `fpdf_text.cpp`; the two colour types `public/fpdf_annot.h` adds for -`public/epdf_annot.h`; core helpers such as `CPDF_Dest::GetPageObjectNumber`. Every declaration we -added to a public header now lives in our own: `public/epdf_.h` next to upstream's -`public/fpdf_.h` (`epdf_view.h` and `epdf_layer.h` for `fpdfview.h`), and the annotation API -in `fpdfsdk/epdf_annot.cpp`. +`public/epdf_annot.h`; core helpers such as `CPDF_Dest::GetPageObjectNumber` and +`CPDF_AnnotContext::CreateOwningPage` (a `*Raw` annotation handle keeps its page, and closing the +handle frees it). Every declaration we added to a public header now lives in our own: +`public/epdf_.h` next to upstream's `public/fpdf_.h` (`epdf_view.h` and `epdf_layer.h` +for `fpdfview.h`), and the annotation API in `fpdfsdk/epdf_annot.cpp`. **Guarded by.** The embedder tests of each API. `epdf.CApiTest` (`fpdfsdk/epdf_c_api_test.c`) takes every `EPDF*` function's address from C, so each header compiles as C and each declaration links; `check-c-api.py` keeps its list complete. diff --git a/fpdfsdk/epdf_annot.cpp b/fpdfsdk/epdf_annot.cpp index 6624e68b0c..27281cf708 100644 --- a/fpdfsdk/epdf_annot.cpp +++ b/fpdfsdk/epdf_annot.cpp @@ -314,20 +314,6 @@ static_assert(static_cast(CPDF_Annot::ReplyType::kGroup) == FPDF_ANNOT_RT_GROUP, "ReplyType::kGroup mismatch"); -class RawAnnotContext final : public CPDF_AnnotContext { - public: - // Takes ownership of |unparsed_page| by value (RetainPtr). - RawAnnotContext(RetainPtr dict, - RetainPtr unparsed_page, - int annot_index) - : CPDF_AnnotContext(dict, unparsed_page.Get(), annot_index), - owned_page_(std::move(unparsed_page)) {} - - private: - // Keeps the page alive as long as the annot context lives. - const RetainPtr owned_page_; -}; - // Checks if an annotation subtype can have a /Name entry. bool IsNameSubtype(FPDF_ANNOTATION_SUBTYPE subtype) { return subtype == FPDF_ANNOT_TEXT || subtype == FPDF_ANNOT_FILEATTACHMENT || @@ -2821,16 +2807,13 @@ EPDFPage_GetAnnotRaw(FPDF_DOCUMENT doc, int page_index, int index) { return nullptr; } - // Use the standard MakeRetain to create the page object. - // This works because of the CONSTRUCT_VIA_MAKE_RETAIN macro in cpdf_page.h. + // Built from the dictionary alone: its content is never parsed. The handle + // keeps the page, and closing the handle frees it. auto page = pdfium::MakeRetain(pdf, page_dict); - - // Create the context, which now takes the RetainPtr directly. - auto ctx = std::make_unique(std::move(annot_dict), - std::move(page), index); - - // The lifetime is now perfectly managed by smart pointers. - return FPDFAnnotationFromCPDFAnnotContext(ctx.release()); + return FPDFAnnotationFromCPDFAnnotContext( + CPDF_AnnotContext::CreateOwningPage(std::move(annot_dict), + std::move(page), index) + .release()); } FPDF_EXPORT FPDF_ANNOTATION FPDF_CALLCONV @@ -2855,7 +2838,8 @@ EPDFPage_CreateAnnotRaw(FPDF_DOCUMENT doc, if (!CPDF_Document::IsPageTreeLeaf(page_dict.Get())) { return nullptr; } - // Built from the dictionary alone: its content is never parsed. + // Built from the dictionary alone: its content is never parsed. The handle + // keeps the page, and closing the handle frees it. auto page = pdfium::MakeRetain(pdf, page_dict); RetainPtr dict = @@ -2876,9 +2860,10 @@ EPDFPage_CreateAnnotRaw(FPDF_DOCUMENT doc, annots->AppendNew(pdf, dict->GetObjNum()); const int index = fxcrt::CollectionSize(*annots) - 1; - auto ctx = - std::make_unique(std::move(dict), std::move(page), index); - return FPDFAnnotationFromCPDFAnnotContext(ctx.release()); + return FPDFAnnotationFromCPDFAnnotContext( + CPDF_AnnotContext::CreateOwningPage(std::move(dict), std::move(page), + index) + .release()); } FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV EPDFPage_RemoveAnnotRaw(FPDF_DOCUMENT doc, diff --git a/fpdfsdk/epdf_annot_raw_embeddertest.cpp b/fpdfsdk/epdf_annot_raw_embeddertest.cpp index 361fb6e255..33ad0837e3 100644 --- a/fpdfsdk/epdf_annot_raw_embeddertest.cpp +++ b/fpdfsdk/epdf_annot_raw_embeddertest.cpp @@ -4,11 +4,15 @@ // Annotation calls that work on a page's dictionaries without loading or // parsing the page (the *Raw calls in public/epdf_annot.h). +#include "core/fpdfapi/page/cpdf_annotcontext.h" +#include "core/fpdfapi/page/cpdf_page.h" #include "core/fpdfapi/parser/cpdf_array.h" #include "core/fpdfapi/parser/cpdf_dictionary.h" #include "core/fpdfapi/parser/cpdf_document.h" #include "core/fpdfapi/parser/cpdf_name.h" #include "core/fpdfapi/parser/cpdf_string.h" +#include "core/fxcrt/retain_ptr.h" +#include "fpdfsdk/cpdfsdk_formfillenvironment.h" #include "fpdfsdk/cpdfsdk_helpers.h" #include "fpdfsdk/epdf_edit_test_util.h" #include "public/cpp/fpdf_scopers.h" @@ -16,6 +20,7 @@ #include "public/epdf_view.h" #include "public/fpdf_annot.h" #include "public/fpdf_edit.h" +#include "public/fpdf_formfill.h" #include "public/fpdf_ppo.h" #include "public/fpdfview.h" #include "testing/embedder_test.h" @@ -49,6 +54,12 @@ uint32_t PageNamedByFirstAnnot(FPDF_DOCUMENT doc, int page_index) { return named ? named->GetObjNum() : 0; } +// The page object the handle |annot| works on, kept alive by the caller. +RetainPtr PageOf(FPDF_ANNOTATION annot) { + return pdfium::WrapRetain( + CPDFAnnotContextFromFPDFAnnotation(annot)->GetPage()); +} + } // namespace class EPDFAnnotRawEmbedderTest : public EmbedderTest {}; @@ -183,3 +194,97 @@ TEST_F(EPDFAnnotRawEmbedderTest, NewAnnotationsNameTheirPage) { ASSERT_NE(0u, copied_page); EXPECT_EQ(copied_page, PageNamedByFirstAnnot(copy.get(), 0)); } + +// A handle opened without a page is built on a page object of its own, and +// closing the handle frees it. Each handle used to leak that page. +TEST_F(EPDFAnnotRawEmbedderTest, ClosingAHandleFreesItsPage) { + embedpdf_test::ScopedTestDocument doc(NewTestDocument()); + ASSERT_TRUE(doc); + { + ScopedFPDFPage page(FPDFPage_New(doc.get(), 0, 612, 792)); + ASSERT_TRUE(page); + } + + FPDF_ANNOTATION created = + EPDFPage_CreateAnnotRaw(doc.get(), 0, FPDF_ANNOT_SQUARE, 0); + ASSERT_TRUE(created); + RetainPtr created_page = PageOf(created); + EXPECT_FALSE(created_page->HasOneRef()); // the handle holds it too + FPDFPage_CloseAnnot(created); + EXPECT_TRUE(created_page->HasOneRef()); + + FPDF_ANNOTATION opened = EPDFPage_GetAnnotRaw(doc.get(), 0, 0); + ASSERT_TRUE(opened); + RetainPtr opened_page = PageOf(opened); + EXPECT_FALSE(opened_page->HasOneRef()); + FPDFPage_CloseAnnot(opened); + EXPECT_TRUE(opened_page->HasOneRef()); +} + +// A linked handle works on the page of the handle it came from. When that +// handle owns the page the linked one shares it, so either can close first. +TEST_F(EPDFAnnotRawEmbedderTest, ALinkedHandleSharesThePage) { + embedpdf_test::ScopedTestDocument doc(NewTestDocument()); + ASSERT_TRUE(doc); + { + ScopedFPDFPage page(FPDFPage_New(doc.get(), 0, 612, 792)); + ASSERT_TRUE(page); + } + { + ScopedFPDFAnnotation note( + EPDFPage_CreateAnnotRaw(doc.get(), 0, FPDF_ANNOT_TEXT, 0)); + ASSERT_TRUE(note); + ScopedFPDFAnnotation popup( + EPDFPage_CreateAnnotRaw(doc.get(), 0, FPDF_ANNOT_POPUP, 0)); + ASSERT_TRUE(popup); + ASSERT_TRUE(EPDFAnnot_SetLinkedAnnot(note.get(), "Popup", popup.get())); + } + + FPDF_ANNOTATION note = EPDFPage_GetAnnotRaw(doc.get(), 0, 0); + ASSERT_TRUE(note); + FPDF_ANNOTATION popup = FPDFAnnot_GetLinkedAnnot(note, "Popup"); + ASSERT_TRUE(popup); + RetainPtr page = PageOf(note); + EXPECT_EQ(page.Get(), PageOf(popup).Get()); + + // The handle it came from closes first: the popup's still has its page. + FPDFPage_CloseAnnot(note); + EXPECT_FALSE(page->HasOneRef()); + EXPECT_EQ(FPDF_ANNOT_POPUP, FPDFAnnot_GetSubtype(popup)); + FPDFPage_CloseAnnot(popup); + EXPECT_TRUE(page->HasOneRef()); + + // On a loaded page both handles borrow the page their caller keeps open. + ScopedFPDFPage loaded(FPDF_LoadPage(doc.get(), 0)); + ASSERT_TRUE(loaded); + ScopedFPDFAnnotation loaded_note(FPDFPage_GetAnnot(loaded.get(), 0)); + ASSERT_TRUE(loaded_note); + ScopedFPDFAnnotation loaded_popup( + FPDFAnnot_GetLinkedAnnot(loaded_note.get(), "Popup")); + ASSERT_TRUE(loaded_popup); + EXPECT_TRUE(CPDFPageFromFPDFPage(loaded.get())->HasOneRef()); +} + +// The form-fill calls work on a page the form environment shows. A handle +// opened without a page is on none: they fail for it, and make no view for +// the page it owns, which that page would not outlive. +TEST_F(EPDFAnnotRawEmbedderTest, + FormFillCallsMakeNoViewForAHandleWithoutAPage) { + ASSERT_TRUE(OpenDocument("text_form.pdf")); + CPDFSDK_FormFillEnvironment* environment = + CPDFSDKFormFillEnvironmentFromFPDFFormHandle(form_handle()); + ASSERT_TRUE(environment); + + ScopedFPDFAnnotation field(EPDFPage_GetAnnotRaw(document(), 0, 0)); + ASSERT_TRUE(field); + ASSERT_EQ(FPDF_ANNOT_WIDGET, FPDFAnnot_GetSubtype(field.get())); + RetainPtr page = PageOf(field.get()); + + EXPECT_FALSE(FORM_SetFocusedAnnot(form_handle(), field.get())); + EXPECT_FALSE(environment->GetPageView(page.Get())); + EXPECT_EQ(FPDF_TEXTDIR_UNKNOWN, + FORM_GetTextDirection(form_handle(), field.get())); + EXPECT_FALSE( + FORM_SetTextDirection(form_handle(), field.get(), FPDF_TEXTDIR_RTL)); + EXPECT_FALSE(environment->GetPageView(page.Get())); +} diff --git a/fpdfsdk/fpdf_annot.cpp b/fpdfsdk/fpdf_annot.cpp index 6da29b5ee5..0fe4477b6c 100644 --- a/fpdfsdk/fpdf_annot.cpp +++ b/fpdfsdk/fpdf_annot.cpp @@ -1341,8 +1341,10 @@ FPDFAnnot_GetLinkedAnnot(FPDF_ANNOTATION annot, FPDF_BYTESTRING key) { return nullptr; } - auto pLinkedAnnot = std::make_unique( - std::move(pLinkedDict), pAnnot->GetPage()); + // EmbedPDF(epdf-api): on |annot|'s page, sharing that page when |annot| owns + // it (a *Raw handle), so either handle can be closed first. + std::unique_ptr pLinkedAnnot = + pAnnot->CreateLinked(std::move(pLinkedDict)); // Caller takes ownership. return FPDFAnnotationFromCPDFAnnotContext(pLinkedAnnot.release()); diff --git a/fpdfsdk/fpdf_formfill.cpp b/fpdfsdk/fpdf_formfill.cpp index 6fc2aac8b2..e82a6d32de 100644 --- a/fpdfsdk/fpdf_formfill.cpp +++ b/fpdfsdk/fpdf_formfill.cpp @@ -176,7 +176,11 @@ CPDFSDK_Widget* GetWidget(FPDF_FORMHANDLE handle, FPDF_ANNOTATION annot) { return nullptr; } auto* annot_context = CPDFAnnotContextFromFPDFAnnotation(annot); - if (!annot_context) { + // EmbedPDF(epdf-api): a handle that owns its page (a *Raw one) is on no page + // the form environment shows. Its view was never valid, so this failed + // below already, but only after a view was made for a page that the view + // then outlived. + if (!annot_context || annot_context->OwnsPage()) { return nullptr; } auto* page_view = @@ -750,7 +754,8 @@ FORM_SetFocusedAnnot(FPDF_FORMHANDLE handle, FPDF_ANNOTATION annot) { } CPDF_AnnotContext* annot_context = CPDFAnnotContextFromFPDFAnnotation(annot); - if (!annot_context) { + // EmbedPDF(epdf-api): see GetWidget(). + if (!annot_context || annot_context->OwnsPage()) { return false; } diff --git a/public/epdf_annot.h b/public/epdf_annot.h index 76d2613550..9a70f5d6c5 100644 --- a/public/epdf_annot.h +++ b/public/epdf_annot.h @@ -859,13 +859,19 @@ FPDF_EXPORT int FPDF_CALLCONV EPDFPage_GetAnnotCountRaw(FPDF_DOCUMENT doc, int page_index); // Experimental EmbedPDF Extension API. -// Get the annotation by index. +// Open the annotation at |index| in a page's /Annots, without loading or +// parsing the page. // -// doc - handle to a document. +// doc - handle to a document. // page_index - the index of the page. -// index - the index of the annotation. -// -// Returns the annotation. +// index - the index of the annotation. +// +// Returns a handle to the annotation, which the caller closes with +// FPDFPage_CloseAnnot(), or NULL on error. There is no page to close: the +// handle keeps what it needs of the page, and closing it frees that. A +// handle FPDFAnnot_GetLinkedAnnot() returns for it may be closed before or +// after it. The handle is on no loaded page, so FORM_SetFocusedAnnot(), +// FORM_GetTextDirection() and FORM_SetTextDirection() fail for it. FPDF_EXPORT FPDF_ANNOTATION FPDF_CALLCONV EPDFPage_GetAnnotRaw(FPDF_DOCUMENT doc, int page_index, int index); @@ -918,7 +924,7 @@ EPDFPage_GetAnnotIndexByObjectNumberRaw(FPDF_DOCUMENT doc, // // Returns a handle to the new annotation, which the caller closes with // FPDFPage_CloseAnnot(), or NULL on error, including a number that isn't -// free. +// free. The handle is like the one EPDFPage_GetAnnotRaw() returns. FPDF_EXPORT FPDF_ANNOTATION FPDF_CALLCONV EPDFPage_CreateAnnotRaw(FPDF_DOCUMENT doc, int page_index, diff --git a/testing/embedpdf_layer_mode_writers.txt b/testing/embedpdf_layer_mode_writers.txt index d5affdb7ea..8b7ffc529e 100644 --- a/testing/embedpdf_layer_mode_writers.txt +++ b/testing/embedpdf_layer_mode_writers.txt @@ -177,6 +177,8 @@ EPDFAnnotEmbedderTest.VariableFontIsInstancedAtRegistration 13 EPDFAnnotEmbedderTest.WidgetRegisteredFontInstallsRealDrEntry 25 EPDFAnnotEmbedderTest.WidgetTextAlignment 2 EPDFAnnotEmbedderTest.WidthZeroDrawsAHairline 9 +EPDFAnnotRawEmbedderTest.ALinkedHandleSharesThePage 5 +EPDFAnnotRawEmbedderTest.ClosingAHandleFreesItsPage 4 EPDFAnnotRawEmbedderTest.FindsANameOnAnAnnotationWrittenInPlace 3 EPDFAnnotRawEmbedderTest.FindsAnAnnotationByNameOnItsPage 9 EPDFAnnotRawEmbedderTest.FindsAnAnnotationByObjectNumber 5