From 8ebce9f265a884d64320228ce83b383d7d5b6c06 Mon Sep 17 00:00:00 2001 From: "pdfium-autoroll@skia-public.iam.gserviceaccount.com" Date: Sun, 8 Nov 2026 20:49:03 -0800 Subject: [PATCH 01/47] Roll Memory Tools from 3d4610fc0dd4 to db1b13009b4a (5 revisions) https://chromium.googlesource.com/chromium/src/tools/memory.git/+log/3d4610fc0dd4..db1b13009b4a If this roll has caused a breakage, revert this CL and set the roller to dry run mode using the controls here: https://autoroll.skia.org/r/memory-tools-pdfium Please CC thestig@chromium.org,thestig@google.com on the revert to ensure that a human is aware of the problem. To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md Bug: None Change-Id: I43b3b127ecc497bbbfcd460bfe5c13d822aa5ecb Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163710 Bot-Commit: pdfium-autoroll@skia-public.iam.gserviceaccount.com Commit-Queue: pdfium-autoroll@skia-public.iam.gserviceaccount.com --- DEPS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DEPS b/DEPS index e51f3204e..dec000371 100644 --- a/DEPS +++ b/DEPS @@ -256,7 +256,7 @@ vars = { # Three lines of non-changing comments so that # the commit queue can handle CLs rolling tools_memory # and whatever else without interference from each other. - 'tools_memory_revision': '3d4610fc0dd49053c0395bc2825dfc6ac72ab64e', + 'tools_memory_revision': 'db1b13009b4ae8a321f7055bcce8e7267ef74729', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling tools_rust # and whatever else without interference from each other. From 96b71fa413f9fd9231bdc3e0a09e16ffcc5766f4 Mon Sep 17 00:00:00 2001 From: "pdfium-autoroll@skia-public.iam.gserviceaccount.com" Date: Sun, 8 Nov 2026 20:50:13 -0800 Subject: [PATCH 02/47] Roll Depot Tools from a03dfbf7f2d1 to 96a7c1418eed (125 revisions) https://chromium.googlesource.com/chromium/tools/depot_tools.git/+log/a03dfbf7f2d1..96a7c1418eed If this roll has caused a breakage, revert this CL and set the roller to dry run mode using the controls here: https://autoroll.skia.org/r/depot-tools-pdfium Please CC thestig@chromium.org,thestig@google.com on the revert to ensure that a human is aware of the problem. To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md Bug: None Change-Id: I02382693ee9274f74674882e6480dda619baf902 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163690 Commit-Queue: pdfium-autoroll@skia-public.iam.gserviceaccount.com Bot-Commit: pdfium-autoroll@skia-public.iam.gserviceaccount.com --- DEPS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DEPS b/DEPS index dec000371..bc799f7de 100644 --- a/DEPS +++ b/DEPS @@ -126,7 +126,7 @@ vars = { # Three lines of non-changing comments so that # the commit queue can handle CLs rolling depot_tools # and whatever else without interference from each other. - 'depot_tools_revision': 'a03dfbf7f2d1cefa2795d81d59ca4f16c8616a8f', + 'depot_tools_revision': '96a7c1418eedaa6bea333a8941e8a0078681b4d0', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling dragonbox # and whatever else without interference from each other. From e24d49c9fa644259c6cd92933d35fdd1b2ca7131 Mon Sep 17 00:00:00 2001 From: Lei Zhang Date: Mon, 9 Nov 2026 10:47:47 -0800 Subject: [PATCH 03/47] Add span-based wrapper functions for libyuv calls Introduce core/fxge/fx_libyuv_wrappers.h and fx_libyuv_wrappers.cpp to wrap libyuv calls in namespace pdfium with functions that take pdfium::span arguments. Provide both 2D plane functions and single-row helpers. Centralize width, height, stride, and span size validation in the wrappers so callers can pass spans directly instead of converting spans to raw pointers. Update all libyuv callers in CFX_DIBBase, CFX_DIBitmap, CFX_ScanlineCompositor, CreateSkiaImageFrom24BppDib(), and ReverseRGB() to use the new wrappers, and restrict third_party/libyuv includes to fx_libyuv_wrappers.cpp in DEPS. This CL is AI generated. Bug: 579492484 Change-Id: I28c99c0429abea2a24415f3e96be88f67bb50430 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163210 Commit-Queue: Lei Zhang Reviewed-by: Tom Sepez --- core/fxcodec/BUILD.gn | 4 - core/fxcodec/DEPS | 3 - core/fxcodec/fx_codec.cpp | 12 +- core/fxge/BUILD.gn | 4 + core/fxge/DEPS | 7 +- core/fxge/dib/cfx_dibbase.cpp | 120 +++++------ core/fxge/dib/cfx_dibitmap.cpp | 11 +- core/fxge/dib/cfx_scanlinecompositor.cpp | 36 ++-- core/fxge/fx_libyuv_wrappers.cpp | 261 +++++++++++++++++++++++ core/fxge/fx_libyuv_wrappers.h | 125 +++++++++++ core/fxge/skia/cfx_dibbase_skia.cpp | 27 ++- 11 files changed, 501 insertions(+), 109 deletions(-) create mode 100644 core/fxge/fx_libyuv_wrappers.cpp create mode 100644 core/fxge/fx_libyuv_wrappers.h diff --git a/core/fxcodec/BUILD.gn b/core/fxcodec/BUILD.gn index 61205392f..77d827d84 100644 --- a/core/fxcodec/BUILD.gn +++ b/core/fxcodec/BUILD.gn @@ -251,10 +251,6 @@ source_set("fxcodec") { public_deps += [ "//third_party/libjpeg_turbo:libjpeg_headers" ] deps += [ "//third_party:jpeg" ] } - - if (pdf_use_libyuv) { - deps += [ "//third_party/libyuv" ] - } visibility = [ "../../*" ] } diff --git a/core/fxcodec/DEPS b/core/fxcodec/DEPS index 1e9528069..0574db2f8 100644 --- a/core/fxcodec/DEPS +++ b/core/fxcodec/DEPS @@ -5,7 +5,4 @@ specific_include_rules = { "codec_memory_sk_stream_unittest\\.cpp": [ '+third_party/skia/include', ], - "fx_codec\\.cpp": [ - '+third_party/libyuv/include/libyuv/planar_functions.h', - ], } diff --git a/core/fxcodec/fx_codec.cpp b/core/fxcodec/fx_codec.cpp index ec182cc2f..35537d5aa 100644 --- a/core/fxcodec/fx_codec.cpp +++ b/core/fxcodec/fx_codec.cpp @@ -11,7 +11,7 @@ #include "core/fxge/dib/fx_dib.h" #if defined(PDF_USE_LIBYUV) -#include "third_party/libyuv/include/libyuv/planar_functions.h" +#include "core/fxge/fx_libyuv_wrappers.h" #else #include @@ -51,14 +51,16 @@ void ReverseRGB(pdfium::span pDestBuf, auto dst_span = fxcrt::reinterpret_span>(pDestBuf).first(count); +#if defined(PDF_USE_LIBYUV) + const auto src_span = + fxcrt::reinterpret_span>(pSrcBuf).first( + count); + pdfium::RGB24ToRAWRow(src_span, dst_span); +#else const auto src_span = fxcrt::reinterpret_span>(pSrcBuf).first( count); -#if defined(PDF_USE_LIBYUV) - libyuv::RGB24ToRAW(pdfium::as_bytes(src_span).data(), 0, - pdfium::as_writable_bytes(dst_span).data(), 0, pixels, 1); -#else if (dst_span.data() == src_span.data()) { for (auto& pix : dst_span) { std::swap(pix.red, pix.blue); diff --git a/core/fxge/BUILD.gn b/core/fxge/BUILD.gn index 93de99d1b..e8436791c 100644 --- a/core/fxge/BUILD.gn +++ b/core/fxge/BUILD.gn @@ -220,6 +220,10 @@ source_set("fxge") { } if (pdf_use_libyuv) { + sources += [ + "fx_libyuv_wrappers.cpp", + "fx_libyuv_wrappers.h", + ] deps += [ "//third_party/libyuv" ] } diff --git a/core/fxge/DEPS b/core/fxge/DEPS index a25eb15df..2bc595584 100644 --- a/core/fxge/DEPS +++ b/core/fxge/DEPS @@ -1,5 +1,10 @@ include_rules = [ - '+third_party/libyuv/include', '+third_party/rust', '+third_party/skia/include', ] + +specific_include_rules = { + "fx_libyuv_wrappers\\.cpp": [ + '+third_party/libyuv/include', + ], +} diff --git a/core/fxge/dib/cfx_dibbase.cpp b/core/fxge/dib/cfx_dibbase.cpp index 39a5744de..26a03a95c 100644 --- a/core/fxge/dib/cfx_dibbase.cpp +++ b/core/fxge/dib/cfx_dibbase.cpp @@ -30,11 +30,7 @@ #include "core/fxge/dib/cfx_imagetransformer.h" #if defined(PDF_USE_LIBYUV) -#include "third_party/libyuv/include/libyuv/convert_argb.h" -#include "third_party/libyuv/include/libyuv/convert_from_argb.h" -#include "third_party/libyuv/include/libyuv/planar_functions.h" -#include "third_party/libyuv/include/libyuv/rotate.h" -#include "third_party/libyuv/include/libyuv/rotate_argb.h" +#include "core/fxge/fx_libyuv_wrappers.h" #endif namespace { @@ -49,21 +45,19 @@ void ConvertBuffer_RgbToArgbPremul( #if defined(PDF_USE_LIBYUV) pdfium::span src_buffer = src_bitmap->GetBuffer(); if (!src_buffer.empty()) { - libyuv::RGB24ToARGB(src_buffer.data(), src_bitmap->GetPitch(), - dest_buf.data(), dest_pitch, width, height); + pdfium::RGB24ToARGB(src_buffer, src_bitmap->GetPitch(), dest_buf, + dest_pitch, width, height); return; } +#endif - for (int row = 0; row < height; ++row) { - auto dest_span = dest_buf.subspan(Fx2DSizeOrDie(row, dest_pitch)); - auto src_span = src_bitmap->GetScanline(row); - libyuv::RGB24ToARGB(src_span.data(), 0, dest_span.data(), 0, width, 1); - } -#else for (int row = 0; row < height; ++row) { auto dest_span = fxcrt::reinterpret_span>( dest_buf.subspan(Fx2DSizeOrDie(row, dest_pitch))); auto src_span = src_bitmap->GetScanlineAs>(row); +#if defined(PDF_USE_LIBYUV) + pdfium::RGB24ToARGBRow(src_span, dest_span); +#else for (auto [input, output] : fxcrt::Zip(src_span, dest_span)) { // Avoid interleaved load/stores. const uint8_t blue = input.blue; @@ -74,8 +68,8 @@ void ConvertBuffer_RgbToArgbPremul( output.red = red; output.alpha = 255; } - } #endif + } } void ConvertBuffer_ArgbPremulToRgb( @@ -432,19 +426,23 @@ void ConvertBuffer_32bppRgbToRgb24( #if defined(PDF_USE_LIBYUV) pdfium::span src_buffer = pSrcBitmap->GetBuffer(); if (!src_buffer.empty()) { - libyuv::ARGBToRGB24(src_buffer.data(), pSrcBitmap->GetPitch(), - dest_buf.data(), dest_pitch, width, height); + pdfium::ARGBToRGB24(src_buffer, pSrcBitmap->GetPitch(), dest_buf, + dest_pitch, width, height); return; } #endif for (int row = 0; row < height; ++row) { - uint8_t* dest_scan = - dest_buf.subspan(Fx2DSizeOrDie(row, dest_pitch)).data(); - const uint8_t* src_scan = pSrcBitmap->GetScanline(row).data(); + auto dest_span = fxcrt::reinterpret_span>( + dest_buf.subspan(Fx2DSizeOrDie(row, dest_pitch))); + auto src_span = + pSrcBitmap->GetScanlineAs>(row).first( + static_cast(width)); #if defined(PDF_USE_LIBYUV) - libyuv::ARGBToRGB24(src_scan, 0, dest_scan, 0, width, 1); + pdfium::ARGBToRGB24Row(src_span, dest_span); #else + uint8_t* dest_scan = pdfium::as_writable_bytes(dest_span).data(); + const uint8_t* src_scan = pdfium::as_bytes(src_span).data(); UNSAFE_TODO({ for (int col = 0; col < width; ++col) { FXSYS_memcpy(dest_scan, src_scan, 3); @@ -875,9 +873,9 @@ RetainPtr CFX_DIBBase::CloneAlphaMask() const { } #if defined(PDF_USE_LIBYUV) - if (!GetBuffer().empty()) { - libyuv::ARGBExtractAlpha(GetBuffer().data(), GetPitch(), - pMask->GetWritableBuffer().data(), + pdfium::span src_buffer = GetBuffer(); + if (!src_buffer.empty()) { + pdfium::ARGBExtractAlpha(src_buffer, GetPitch(), pMask->GetWritableBuffer(), pMask->GetPitch(), GetWidth(), GetHeight()); return pMask; } @@ -885,9 +883,8 @@ RetainPtr CFX_DIBBase::CloneAlphaMask() const { for (int row = 0; row < GetHeight(); ++row) { #if defined(PDF_USE_LIBYUV) - libyuv::ARGBExtractAlpha(GetScanline(row).data(), 0, - pMask->GetWritableScanline(row).data(), 0, - GetWidth(), 1); + pdfium::ARGBExtractAlphaRow(GetScanlineAs>(row), + pMask->GetWritableScanlineAs(row)); #else const uint8_t* src_scan = GetScanline(row).subspan<3u>().data(); uint8_t* dest_scan = pMask->GetWritableScanline(row).data(); @@ -943,11 +940,13 @@ RetainPtr CFX_DIBBase::FlipImage(bool bXFlip, bool bYFlip) const { return pFlipped; } +#if defined(PDF_USE_LIBYUV) + pdfium::span src_buffer = GetBuffer(); +#endif if (bytes_per_pixel == 1) { #if defined(PDF_USE_LIBYUV) - if (!GetBuffer().empty()) { - libyuv::MirrorPlane(GetBuffer().data(), GetPitch(), - pFlipped->GetWritableBuffer().data(), + if (!src_buffer.empty()) { + pdfium::MirrorPlane(src_buffer, GetPitch(), pFlipped->GetWritableBuffer(), pFlipped->GetPitch(), GetWidth(), bYFlip ? -GetHeight() : GetHeight()); return pFlipped; @@ -955,14 +954,15 @@ RetainPtr CFX_DIBBase::FlipImage(bool bXFlip, bool bYFlip) const { #endif for (int row = 0; row < GetHeight(); ++row) { - const uint8_t* src_scan = GetScanline(row).data(); - uint8_t* dest_scan = - pFlipped->GetWritableScanline(bYFlip ? GetHeight() - row - 1 : row) - .data(); + auto src_span = GetScanlineAs(row); + auto dest_span = pFlipped->GetWritableScanlineAs( + bYFlip ? GetHeight() - row - 1 : row); #if defined(PDF_USE_LIBYUV) - libyuv::MirrorPlane(src_scan, 0, dest_scan, 0, GetWidth(), 1); + pdfium::MirrorPlaneRow(src_span, dest_span); #else UNSAFE_TODO({ + const uint8_t* src_scan = src_span.data(); + uint8_t* dest_scan = dest_span.data(); dest_scan += (GetWidth() - 1) * bytes_per_pixel; for (int col = 0; col < GetWidth(); ++col) { *dest_scan = *src_scan; @@ -977,9 +977,8 @@ RetainPtr CFX_DIBBase::FlipImage(bool bXFlip, bool bYFlip) const { if (bytes_per_pixel == 3) { #if defined(PDF_USE_LIBYUV) - if (!GetBuffer().empty()) { - libyuv::RGB24Mirror(GetBuffer().data(), GetPitch(), - pFlipped->GetWritableBuffer().data(), + if (!src_buffer.empty()) { + pdfium::RGB24Mirror(src_buffer, GetPitch(), pFlipped->GetWritableBuffer(), pFlipped->GetPitch(), GetWidth(), bYFlip ? -GetHeight() : GetHeight()); return pFlipped; @@ -987,14 +986,15 @@ RetainPtr CFX_DIBBase::FlipImage(bool bXFlip, bool bYFlip) const { #endif for (int row = 0; row < GetHeight(); ++row) { - const uint8_t* src_scan = GetScanline(row).data(); - uint8_t* dest_scan = - pFlipped->GetWritableScanline(bYFlip ? GetHeight() - row - 1 : row) - .data(); + auto src_span = GetScanlineAs>(row); + auto dest_span = pFlipped->GetWritableScanlineAs>( + bYFlip ? GetHeight() - row - 1 : row); #if defined(PDF_USE_LIBYUV) - libyuv::RGB24Mirror(src_scan, 0, dest_scan, 0, GetWidth(), 1); + pdfium::RGB24MirrorRow(src_span, dest_span); #else UNSAFE_TODO({ + const uint8_t* src_scan = pdfium::as_bytes(src_span).data(); + uint8_t* dest_scan = pdfium::as_writable_bytes(dest_span).data(); dest_scan += (GetWidth() - 1) * bytes_per_pixel; for (int col = 0; col < GetWidth(); ++col) { FXSYS_memcpy(dest_scan, src_scan, 3); @@ -1009,23 +1009,24 @@ RetainPtr CFX_DIBBase::FlipImage(bool bXFlip, bool bYFlip) const { CHECK_EQ(bytes_per_pixel, 4); #if defined(PDF_USE_LIBYUV) - if (!GetBuffer().empty()) { - libyuv::ARGBMirror( - GetBuffer().data(), GetPitch(), pFlipped->GetWritableBuffer().data(), - pFlipped->GetPitch(), GetWidth(), bYFlip ? -GetHeight() : GetHeight()); + if (!src_buffer.empty()) { + pdfium::ARGBMirror(src_buffer, GetPitch(), pFlipped->GetWritableBuffer(), + pFlipped->GetPitch(), GetWidth(), + bYFlip ? -GetHeight() : GetHeight()); return pFlipped; } #endif for (int row = 0; row < GetHeight(); ++row) { - const uint8_t* src_scan = GetScanline(row).data(); - uint8_t* dest_scan = - pFlipped->GetWritableScanline(bYFlip ? GetHeight() - row - 1 : row) - .data(); + auto src_span = GetScanlineAs>(row); + auto dest_span = pFlipped->GetWritableScanlineAs>( + bYFlip ? GetHeight() - row - 1 : row); #if defined(PDF_USE_LIBYUV) - libyuv::ARGBMirror(src_scan, 0, dest_scan, 0, GetWidth(), 1); + pdfium::ARGBMirrorRow(src_span, dest_span); #else UNSAFE_TODO({ + const uint8_t* src_scan = pdfium::as_bytes(src_span).data(); + uint8_t* dest_scan = pdfium::as_writable_bytes(dest_span).data(); dest_scan += (GetWidth() - 1) * bytes_per_pixel; for (int col = 0; col < GetWidth(); ++col) { const auto* src_scan32 = reinterpret_cast(src_scan); @@ -1114,19 +1115,16 @@ RetainPtr CFX_DIBBase::SwapXY(bool bXFlip, bool bYFlip) const { pdfium::span src_buffer = GetBuffer(); if (!src_buffer.empty()) { const int height = bXFlip == bYFlip ? -GetHeight() : GetHeight(); - const libyuv::RotationMode mode = - bYFlip ? libyuv::kRotate270 : libyuv::kRotate90; + const pdfium::RotationMode mode = + bYFlip ? pdfium::kRotate270 : pdfium::kRotate90; if (bytes_per_pixel == 1) { - if (libyuv::RotatePlane(src_buffer.data(), GetPitch(), dest_span.data(), - dest_pitch, GetWidth(), height, mode) == 0) { - return pTransBitmap; - } + pdfium::RotatePlane(src_buffer, GetPitch(), dest_span, dest_pitch, + GetWidth(), height, mode); } else { - if (libyuv::ARGBRotate(src_buffer.data(), GetPitch(), dest_span.data(), - dest_pitch, GetWidth(), height, mode) == 0) { - return pTransBitmap; - } + pdfium::ARGBRotate(src_buffer, GetPitch(), dest_span, dest_pitch, + GetWidth(), height, mode); } + return pTransBitmap; } } #endif diff --git a/core/fxge/dib/cfx_dibitmap.cpp b/core/fxge/dib/cfx_dibitmap.cpp index 6bc06c7e6..6d63bc7d6 100644 --- a/core/fxge/dib/cfx_dibitmap.cpp +++ b/core/fxge/dib/cfx_dibitmap.cpp @@ -29,8 +29,7 @@ #include "core/fxge/dib/cfx_scanlinecompositor.h" #if defined(PDF_USE_LIBYUV) -#include "third_party/libyuv/include/libyuv/convert_argb.h" -#include "third_party/libyuv/include/libyuv/planar_functions.h" +#include "core/fxge/fx_libyuv_wrappers.h" #endif namespace { @@ -352,8 +351,8 @@ bool CFX_DIBitmap::MultiplyAlphaMask(RetainPtr mask) { // `FXDIB_Format::kBgraPremul` #if defined(PDF_USE_LIBYUV) SetFormat(FXDIB_Format::kBgra); - libyuv::ARGBCopyYToAlpha(mask->GetBuffer().data(), mask->GetPitch(), - GetWritableBuffer().data(), GetPitch(), GetWidth(), + pdfium::ARGBCopyYToAlpha(mask->GetBuffer(), mask->GetPitch(), + GetWritableBuffer(), GetPitch(), GetWidth(), GetHeight()); #else if (!ConvertFormat(FXDIB_Format::kBgra)) { @@ -1011,8 +1010,8 @@ bool CFX_DIBitmap::ConvertFormat(FXDIB_Format dest_format) { const uint32_t dest_pitch = pitch_size.value().pitch; #if defined(PDF_USE_LIBYUV) if (dest_format == FXDIB_Format::kBgra && GetFormat() == FXDIB_Format::kBgr) { - libyuv::RGB24ToARGB(GetBuffer().data(), GetPitch(), dest_span.data(), - dest_pitch, GetWidth(), GetHeight()); + pdfium::RGB24ToARGB(GetBuffer(), GetPitch(), dest_span, dest_pitch, + GetWidth(), GetHeight()); palette_.clear(); } else { #endif diff --git a/core/fxge/dib/cfx_scanlinecompositor.cpp b/core/fxge/dib/cfx_scanlinecompositor.cpp index b3f255951..fc2b9f4ee 100644 --- a/core/fxge/dib/cfx_scanlinecompositor.cpp +++ b/core/fxge/dib/cfx_scanlinecompositor.cpp @@ -23,7 +23,7 @@ #include "core/fxge/dib/fx_dib.h" #if defined(PDF_USE_LIBYUV) -#include "third_party/libyuv/include/libyuv/convert_argb.h" +#include "core/fxge/fx_libyuv_wrappers.h" #endif #if defined(PDF_USE_SKIA) @@ -449,14 +449,17 @@ void CompositeRow_Bgr2Bgra_NoBlend_NoClip( fxcrt::reinterpret_span>(src_span).first( width); #if defined(PDF_USE_LIBYUV) - const int pixel_count = pdfium::checked_cast(width); - const uint8_t* src_bytes = pdfium::as_bytes(bgr_span).data(); - uint8_t* dest_bytes = pdfium::as_writable_bytes(dest_span).data(); if constexpr (std::is_same_v>) { - libyuv::RGB24ToARGB(src_bytes, 0, dest_bytes, 0, pixel_count, 1); + pdfium::RGB24ToARGBRow(bgr_span, dest_span); } else { static_assert(std::is_same_v>); - libyuv::RAWToARGB(src_bytes, 0, dest_bytes, 0, pixel_count, 1); + // Treating BGR as RGB and RGBA as BGRA achieves the same channel swap. + auto rgb_src = + fxcrt::reinterpret_span>(src_span).first( + width); + auto bgra_dest = + fxcrt::reinterpret_span>(dest_span); + pdfium::RAWToARGBRow(rgb_src, bgra_dest); } #else CopyRowToOpaqueBgra(dest_span, bgr_span); @@ -835,6 +838,19 @@ void CompositeRow_Rgb2Rgb_NoBlend_NoClip(pdfium::span dest_span, int width, int dest_Bpp, int src_Bpp) { +#if defined(PDF_USE_LIBYUV) + if (src_Bpp == 3 && dest_Bpp == 4) { + // BGR24 -> BGRx expand; libyuv stamps 4th byte 0xFF vs scalar's + // untouched. kBgrx padding, non-displayed: no output impact. + auto bgr_src = + fxcrt::reinterpret_span>(src_span).first( + pdfium::checked_cast(width)); + auto bgra_dest = + fxcrt::reinterpret_span>(dest_span); + pdfium::RGB24ToARGBRow(bgr_src, bgra_dest); + return; + } +#endif uint8_t* dest_scan = dest_span.data(); const uint8_t* src_scan = src_span.data(); UNSAFE_TODO({ @@ -842,14 +858,6 @@ void CompositeRow_Rgb2Rgb_NoBlend_NoClip(pdfium::span dest_span, FXSYS_memcpy(dest_scan, src_scan, width * dest_Bpp); return; } -#if defined(PDF_USE_LIBYUV) - if (src_Bpp == 3 && dest_Bpp == 4) { - // BGR24 -> BGRx expand; libyuv stamps 4th byte 0xFF vs scalar's - // untouched. kBgrx padding, non-displayed: no output impact. - libyuv::RGB24ToARGB(src_scan, width * 3, dest_scan, width * 4, width, 1); - return; - } -#endif for (int col = 0; col < width; col++) { FXSYS_memcpy(dest_scan, src_scan, 3); dest_scan += dest_Bpp; diff --git a/core/fxge/fx_libyuv_wrappers.cpp b/core/fxge/fx_libyuv_wrappers.cpp new file mode 100644 index 000000000..009b3658f --- /dev/null +++ b/core/fxge/fx_libyuv_wrappers.cpp @@ -0,0 +1,261 @@ +// Copyright 2026 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "core/fxge/fx_libyuv_wrappers.h" + +#include +#include + +#include "core/fxcrt/check.h" +#include "core/fxcrt/check_op.h" +#include "core/fxcrt/fx_2d_size.h" +#include "core/fxcrt/fx_safe_types.h" +#include "core/fxcrt/notreached.h" +#include "core/fxcrt/numerics/safe_conversions.h" +#include "third_party/libyuv/include/libyuv/convert_argb.h" +#include "third_party/libyuv/include/libyuv/convert_from_argb.h" +#include "third_party/libyuv/include/libyuv/planar_functions.h" +#include "third_party/libyuv/include/libyuv/rotate.h" +#include "third_party/libyuv/include/libyuv/rotate_argb.h" + +namespace pdfium { + +namespace { + +int GetAbsHeight(int height) { + FX_SAFE_INT32 safe_height = height; + int abs_height = safe_height.Abs().ValueOrDie(); + CHECK_GT(abs_height, 0); + return abs_height; +} + +template +int ValidateRowWidthsAndGetSrcRowWidth(pdfium::span src_span, + pdfium::span dst_span) { + CHECK(!src_span.empty()); + CHECK_LE(src_span.size(), dst_span.size()); + return pdfium::checked_cast(src_span.size()); +} + +size_t GetPlaneBytes(int stride, int width, int rows, int bytes_per_pixel) { + CHECK_GT(width, 0); + CHECK_GT(rows, 0); + CHECK_GT(bytes_per_pixel, 0); + const size_t row_bytes = Fx2DSizeOrDie(width, bytes_per_pixel); + CHECK_GE(stride, 0); + CHECK_GE(static_cast(stride), row_bytes); + // A subspan starting at a non-zero column offset has `stride` bytes for each + // of the first `rows - 1` rows, and only `row_bytes` bytes on the final row. + FX_SAFE_SIZE_T plane_bytes = rows - 1; + plane_bytes *= stride; + plane_bytes += row_bytes; + return plane_bytes.ValueOrDie(); +} + +libyuv::RotationMode ToLibyuvRotationMode(RotationMode mode) { + switch (mode) { + case kRotate90: + return libyuv::kRotate90; + case kRotate270: + return libyuv::kRotate270; + } + NOTREACHED(); +} + +} // namespace + +void RGB24ToARGB(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height) { + CHECK_GE(src_span.size(), GetPlaneBytes(src_stride, width, height, 3)); + CHECK_GE(dst_span.size(), GetPlaneBytes(dst_stride, width, height, 4)); + int ret = libyuv::RGB24ToARGB(src_span.data(), src_stride, dst_span.data(), + dst_stride, width, height); + CHECK_EQ(ret, 0); +} + +void ARGBToRGB24(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height) { + CHECK_GE(src_span.size(), GetPlaneBytes(src_stride, width, height, 4)); + CHECK_GE(dst_span.size(), GetPlaneBytes(dst_stride, width, height, 3)); + int ret = libyuv::ARGBToRGB24(src_span.data(), src_stride, dst_span.data(), + dst_stride, width, height); + CHECK_EQ(ret, 0); +} + +void ARGBExtractAlpha(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height) { + CHECK_GE(src_span.size(), GetPlaneBytes(src_stride, width, height, 4)); + CHECK_GE(dst_span.size(), GetPlaneBytes(dst_stride, width, height, 1)); + int ret = libyuv::ARGBExtractAlpha( + src_span.data(), src_stride, dst_span.data(), dst_stride, width, height); + CHECK_EQ(ret, 0); +} + +void ARGBCopyYToAlpha(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height) { + CHECK_GE(src_span.size(), GetPlaneBytes(src_stride, width, height, 1)); + CHECK_GE(dst_span.size(), GetPlaneBytes(dst_stride, width, height, 4)); + int ret = libyuv::ARGBCopyYToAlpha( + src_span.data(), src_stride, dst_span.data(), dst_stride, width, height); + CHECK_EQ(ret, 0); +} + +void MirrorPlane(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height) { + const int abs_height = GetAbsHeight(height); + CHECK_GE(src_span.size(), GetPlaneBytes(src_stride, width, abs_height, 1)); + CHECK_GE(dst_span.size(), GetPlaneBytes(dst_stride, width, abs_height, 1)); + libyuv::MirrorPlane(src_span.data(), src_stride, dst_span.data(), dst_stride, + width, height); +} + +void RGB24Mirror(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height) { + const int abs_height = GetAbsHeight(height); + CHECK_GE(src_span.size(), GetPlaneBytes(src_stride, width, abs_height, 3)); + CHECK_GE(dst_span.size(), GetPlaneBytes(dst_stride, width, abs_height, 3)); + int ret = libyuv::RGB24Mirror(src_span.data(), src_stride, dst_span.data(), + dst_stride, width, height); + CHECK_EQ(ret, 0); +} + +void ARGBMirror(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height) { + const int abs_height = GetAbsHeight(height); + CHECK_GE(src_span.size(), GetPlaneBytes(src_stride, width, abs_height, 4)); + CHECK_GE(dst_span.size(), GetPlaneBytes(dst_stride, width, abs_height, 4)); + int ret = libyuv::ARGBMirror(src_span.data(), src_stride, dst_span.data(), + dst_stride, width, height); + CHECK_EQ(ret, 0); +} + +void RotatePlane(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height, + RotationMode mode) { + const int abs_height = GetAbsHeight(height); + CHECK_GE(src_span.size(), GetPlaneBytes(src_stride, width, abs_height, 1)); + CHECK_GE(dst_span.size(), GetPlaneBytes(dst_stride, abs_height, width, 1)); + int ret = libyuv::RotatePlane(src_span.data(), src_stride, dst_span.data(), + dst_stride, width, height, + ToLibyuvRotationMode(mode)); + CHECK_EQ(ret, 0); +} + +void ARGBRotate(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height, + RotationMode mode) { + const int abs_height = GetAbsHeight(height); + CHECK_GE(src_span.size(), GetPlaneBytes(src_stride, width, abs_height, 4)); + CHECK_GE(dst_span.size(), GetPlaneBytes(dst_stride, abs_height, width, 4)); + int ret = + libyuv::ARGBRotate(src_span.data(), src_stride, dst_span.data(), + dst_stride, width, height, ToLibyuvRotationMode(mode)); + CHECK_EQ(ret, 0); +} + +void RGB24ToRAWRow(pdfium::span> src_span, + pdfium::span> dst_span) { + const int width = ValidateRowWidthsAndGetSrcRowWidth(src_span, dst_span); + int ret = libyuv::RGB24ToRAW(pdfium::as_bytes(src_span).data(), 0, + pdfium::as_writable_bytes(dst_span).data(), 0, + width, 1); + CHECK_EQ(ret, 0); +} + +void RGB24ToARGBRow(pdfium::span> src_span, + pdfium::span> dst_span) { + const int width = ValidateRowWidthsAndGetSrcRowWidth(src_span, dst_span); + int ret = libyuv::RGB24ToARGB(pdfium::as_bytes(src_span).data(), 0, + pdfium::as_writable_bytes(dst_span).data(), 0, + width, 1); + CHECK_EQ(ret, 0); +} + +void RAWToARGBRow(pdfium::span> src_span, + pdfium::span> dst_span) { + const int width = ValidateRowWidthsAndGetSrcRowWidth(src_span, dst_span); + int ret = libyuv::RAWToARGB(pdfium::as_bytes(src_span).data(), 0, + pdfium::as_writable_bytes(dst_span).data(), 0, + width, 1); + CHECK_EQ(ret, 0); +} + +void ARGBToRGB24Row(pdfium::span> src_span, + pdfium::span> dst_span) { + const int width = ValidateRowWidthsAndGetSrcRowWidth(src_span, dst_span); + int ret = libyuv::ARGBToRGB24(pdfium::as_bytes(src_span).data(), 0, + pdfium::as_writable_bytes(dst_span).data(), 0, + width, 1); + CHECK_EQ(ret, 0); +} + +void ARGBExtractAlphaRow(pdfium::span> src_span, + pdfium::span dst_span) { + const int width = ValidateRowWidthsAndGetSrcRowWidth(src_span, dst_span); + int ret = libyuv::ARGBExtractAlpha(pdfium::as_bytes(src_span).data(), 0, + dst_span.data(), 0, width, 1); + CHECK_EQ(ret, 0); +} + +void MirrorPlaneRow(pdfium::span src_span, + pdfium::span dst_span) { + const int width = ValidateRowWidthsAndGetSrcRowWidth(src_span, dst_span); + libyuv::MirrorPlane(src_span.data(), 0, dst_span.data(), 0, width, 1); +} + +void RGB24MirrorRow(pdfium::span> src_span, + pdfium::span> dst_span) { + const int width = ValidateRowWidthsAndGetSrcRowWidth(src_span, dst_span); + int ret = libyuv::RGB24Mirror(pdfium::as_bytes(src_span).data(), 0, + pdfium::as_writable_bytes(dst_span).data(), 0, + width, 1); + CHECK_EQ(ret, 0); +} + +void ARGBMirrorRow(pdfium::span> src_span, + pdfium::span> dst_span) { + const int width = ValidateRowWidthsAndGetSrcRowWidth(src_span, dst_span); + int ret = libyuv::ARGBMirror(pdfium::as_bytes(src_span).data(), 0, + pdfium::as_writable_bytes(dst_span).data(), 0, + width, 1); + CHECK_EQ(ret, 0); +} + +} // namespace pdfium diff --git a/core/fxge/fx_libyuv_wrappers.h b/core/fxge/fx_libyuv_wrappers.h new file mode 100644 index 000000000..859490e7c --- /dev/null +++ b/core/fxge/fx_libyuv_wrappers.h @@ -0,0 +1,125 @@ +// Copyright 2026 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CORE_FXGE_FX_LIBYUV_WRAPPERS_H_ +#define CORE_FXGE_FX_LIBYUV_WRAPPERS_H_ + +#if !defined(PDF_USE_LIBYUV) +#error "PDF_USE_LIBYUV must be defined." +#endif + +#include + +#include "core/fxcrt/span.h" +#include "core/fxge/dib/fx_dib.h" + +namespace pdfium { + +enum RotationMode { + kRotate90 = 90, + kRotate270 = 270, +}; + +// Span-based wrappers around functions in third_party/libyuv/include/libyuv/. +// See the corresponding libyuv headers for detailed documentation. + +// 2D plane operations. +void RGB24ToARGB(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height); + +void ARGBToRGB24(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height); + +void ARGBExtractAlpha(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height); + +void ARGBCopyYToAlpha(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height); + +// For mirror and rotate functions below, negative `height` inverts the image +// vertically. +void MirrorPlane(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height); + +void RGB24Mirror(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height); + +void ARGBMirror(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height); + +void RotatePlane(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height, + RotationMode mode); + +void ARGBRotate(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height, + RotationMode mode); + +// Single-row operations. Each function processes `src_span.size()` pixels. +// `src_span` must not be empty, and `dst_span` must have at least +// `src_span.size()` elements (any extra elements in `dst_span` are left +// unmodified). +void RGB24ToRAWRow(pdfium::span> src_span, + pdfium::span> dst_span); + +void RGB24ToARGBRow(pdfium::span> src_span, + pdfium::span> dst_span); + +void RAWToARGBRow(pdfium::span> src_span, + pdfium::span> dst_span); + +void ARGBToRGB24Row(pdfium::span> src_span, + pdfium::span> dst_span); + +void ARGBExtractAlphaRow(pdfium::span> src_span, + pdfium::span dst_span); + +void MirrorPlaneRow(pdfium::span src_span, + pdfium::span dst_span); + +void RGB24MirrorRow(pdfium::span> src_span, + pdfium::span> dst_span); + +void ARGBMirrorRow(pdfium::span> src_span, + pdfium::span> dst_span); + +} // namespace pdfium + +#endif // CORE_FXGE_FX_LIBYUV_WRAPPERS_H_ diff --git a/core/fxge/skia/cfx_dibbase_skia.cpp b/core/fxge/skia/cfx_dibbase_skia.cpp index 71d06fd4e..f11a1aed3 100644 --- a/core/fxge/skia/cfx_dibbase_skia.cpp +++ b/core/fxge/skia/cfx_dibbase_skia.cpp @@ -19,6 +19,7 @@ #include "core/fxcrt/numerics/safe_conversions.h" #include "core/fxcrt/retain_ptr.h" #include "core/fxcrt/span.h" +#include "core/fxcrt/span_util.h" #include "core/fxge/calculate_pitch.h" #include "core/fxge/dib/cfx_dibitmap.h" #include "core/fxge/dib/fx_dib.h" @@ -31,7 +32,7 @@ #include "third_party/skia/include/core/SkRefCnt.h" #if defined(PDF_USE_LIBYUV) -#include "third_party/libyuv/include/libyuv/convert_argb.h" +#include "core/fxge/fx_libyuv_wrappers.h" #endif namespace { @@ -152,22 +153,18 @@ sk_sp CreateSkiaImageFrom24BppDib(const CFX_DIBBase& source) { return nullptr; } - const size_t min_row_bytes = - fxge::CalculatePitch8OrDie(source.GetBPP(), /*components=*/1, width); - DCHECK_LE(min_row_bytes, source.GetPitch()); - - if (!source.GetBuffer().empty()) { - libyuv::RGB24ToARGB( - source.GetBuffer().data(), source.GetPitch(), output.span().data(), - pdfium::checked_cast(dst_row_bytes), width, height); + pdfium::span src_buffer = source.GetBuffer(); + if (!src_buffer.empty()) { + pdfium::RGB24ToARGB(src_buffer, source.GetPitch(), output, + pdfium::checked_cast(dst_row_bytes), width, + height); } else { + auto dst_span = + fxcrt::reinterpret_span>(output.span()); for (int row = 0; row < height; ++row) { - pdfium::span scanline = source.GetScanline(row); - ValidateScanlineSize(scanline, min_row_bytes); - libyuv::RGB24ToARGB( - scanline.data(), 0, - output.subspan(Fx2DSizeOrDie(row, dst_row_bytes)).data(), 0, width, - 1); + pdfium::RGB24ToARGBRow(source.GetScanlineAs>(row), + dst_span); + dst_span = dst_span.subspan(static_cast(width)); } } From 57726eeba47f2ae4ea93a020790d9b8b718b2be2 Mon Sep 17 00:00:00 2001 From: Nithya V S Date: Mon, 9 Nov 2026 11:52:05 -0800 Subject: [PATCH 04/47] Fixes scalar build for cfx_scanlinecompositor_hwy The u8<->u32 BitCast in the kernels fails to compile on HWY_SCALAR. So add a scalar-loop fallback. Bug: 581790991 Change-Id: I1649569bbc4b171543f4c78f91ad82c288627bab Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163330 Reviewed-by: Lei Zhang Reviewed-by: Andy Phan Commit-Queue: Lei Zhang --- core/fxge/dib/cfx_scanlinecompositor_hwy.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/core/fxge/dib/cfx_scanlinecompositor_hwy.cpp b/core/fxge/dib/cfx_scanlinecompositor_hwy.cpp index d4f304f8a..848685981 100644 --- a/core/fxge/dib/cfx_scanlinecompositor_hwy.cpp +++ b/core/fxge/dib/cfx_scanlinecompositor_hwy.cpp @@ -67,6 +67,8 @@ inline uint32_t CompositePixelBgra2Bgra(uint32_t src, uint32_t back) { // src a == 0 -> keep dest else AlphaMerge/AlphaUnion over // Byte spans bitcast to u32 lanes -> no 4-byte scanline alignment needed. void RunBgra2Bgra(pdfium::span src, pdfium::span dest) { + size_t count = src.size() / 4; +#if HWY_TARGET != HWY_SCALAR const hn::ScalableTag d; const hn::ScalableTag d8; const size_t n = hn::Lanes(d); // pixels/vector @@ -74,7 +76,6 @@ void RunBgra2Bgra(pdfium::span src, pdfium::span dest) { const auto one = hn::Set(d, 1); const auto zero = hn::Zero(d); - size_t count = src.size() / 4; while (count >= n) { const auto s = hn::BitCast(d, hn::LoadU(d8, src.data())); const auto back = hn::BitCast(d, hn::LoadU(d8, dest.data())); @@ -119,6 +120,7 @@ void RunBgra2Bgra(pdfium::span src, pdfium::span dest) { dest = dest.subspan(n * 4); count -= n; } +#endif // HWY_TARGET != HWY_SCALAR for (size_t i = 0; i < count; ++i) { const uint32_t s = FXARGB_GetDIB(src.first<4u>()); const uint32_t back = FXARGB_GetDIB(dest.first<4u>()); @@ -132,12 +134,13 @@ void RunBgra2Bgra(pdfium::span src, pdfium::span dest) { // order required: src and dest both packed BGRA. void RunBgra2BgrxForceOpaque(pdfium::span src, pdfium::span dest) { + size_t count = src.size() / 4; +#if HWY_TARGET != HWY_SCALAR const hn::ScalableTag d; const hn::ScalableTag d8; const size_t n = hn::Lanes(d); const auto alpha_ff = hn::Set(d, 0xFF000000u); - size_t count = src.size() / 4; while (count >= n) { const auto v = hn::BitCast(d, hn::LoadU(d8, src.data())); hn::StoreU(hn::BitCast(d8, hn::Or(v, alpha_ff)), d8, dest.data()); @@ -145,6 +148,7 @@ void RunBgra2BgrxForceOpaque(pdfium::span src, dest = dest.subspan(n * 4); count -= n; } +#endif // HWY_TARGET != HWY_SCALAR for (size_t i = 0; i < count; ++i) { dest[0] = src[0]; dest[1] = src[1]; From 144dfc5a61812d30deb1a0bf021c6ad008052fd3 Mon Sep 17 00:00:00 2001 From: Lei Zhang Date: Mon, 9 Nov 2026 12:25:09 -0800 Subject: [PATCH 05/47] Delete unused CPDF_IconFit copy ctor It's not used. Disallow copy and assignment. Change-Id: I9ef9b2f2bfcc3023b48265eec6c45e0162284835 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163731 Reviewed-by: Tom Sepez Commit-Queue: Tom Sepez Commit-Queue: Lei Zhang --- core/fpdfdoc/cpdf_iconfit.cpp | 2 -- core/fpdfdoc/cpdf_iconfit.h | 3 ++- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/core/fpdfdoc/cpdf_iconfit.cpp b/core/fpdfdoc/cpdf_iconfit.cpp index c09135d64..dfe87cf78 100644 --- a/core/fpdfdoc/cpdf_iconfit.cpp +++ b/core/fpdfdoc/cpdf_iconfit.cpp @@ -22,8 +22,6 @@ constexpr float kDefaultPosition = 0.5f; CPDF_IconFit::CPDF_IconFit(RetainPtr dict) : dict_(std::move(dict)) {} -CPDF_IconFit::CPDF_IconFit(const CPDF_IconFit& that) = default; - CPDF_IconFit::~CPDF_IconFit() = default; CPDF_IconFit::ScaleMethod CPDF_IconFit::GetScaleMethod() const { diff --git a/core/fpdfdoc/cpdf_iconfit.h b/core/fpdfdoc/cpdf_iconfit.h index 7aa20646b..bc0bb4935 100644 --- a/core/fpdfdoc/cpdf_iconfit.h +++ b/core/fpdfdoc/cpdf_iconfit.h @@ -17,7 +17,8 @@ class CPDF_IconFit { enum class ScaleMethod { kAlways = 0, kBigger, kSmaller, kNever }; explicit CPDF_IconFit(RetainPtr dict); - CPDF_IconFit(const CPDF_IconFit& that); + CPDF_IconFit(const CPDF_IconFit&) = delete; + CPDF_IconFit& operator=(const CPDF_IconFit&) = delete; ~CPDF_IconFit(); ScaleMethod GetScaleMethod() const; From 0880b61b2c5164ac4ff0723f9451af828fb4e3f3 Mon Sep 17 00:00:00 2001 From: Tom Sepez Date: Mon, 9 Nov 2026 14:12:24 -0800 Subject: [PATCH 06/47] Add unit tests for CPDF_IconFit Add comprehensive unit tests covering all methods in CPDF_IconFit: GetScaleMethod, IsProportionalScale, GetFittingBounds, GetIconBottomLeftPosition, GetScale, and GetImageOffset. Change-Id: Ic3543c3e9bfdf685ab10a3d11734c8d6089d251f Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163590 Commit-Queue: Tom Sepez Reviewed-by: Lei Zhang --- core/fpdfdoc/BUILD.gn | 1 + core/fpdfdoc/cpdf_iconfit_unittest.cpp | 188 +++++++++++++++++++++++++ 2 files changed, 189 insertions(+) create mode 100644 core/fpdfdoc/cpdf_iconfit_unittest.cpp diff --git a/core/fpdfdoc/BUILD.gn b/core/fpdfdoc/BUILD.gn index aef114dd2..872a4bbd2 100644 --- a/core/fpdfdoc/BUILD.gn +++ b/core/fpdfdoc/BUILD.gn @@ -107,6 +107,7 @@ pdfium_unittest_source_set("unittests") { "cpdf_dest_unittest.cpp", "cpdf_filespec_unittest.cpp", "cpdf_formfield_unittest.cpp", + "cpdf_iconfit_unittest.cpp", "cpdf_interactiveform_unittest.cpp", "cpdf_metadata_unittest.cpp", "cpdf_nametree_unittest.cpp", diff --git a/core/fpdfdoc/cpdf_iconfit_unittest.cpp b/core/fpdfdoc/cpdf_iconfit_unittest.cpp new file mode 100644 index 000000000..891782068 --- /dev/null +++ b/core/fpdfdoc/cpdf_iconfit_unittest.cpp @@ -0,0 +1,188 @@ +// Copyright 2026 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "core/fpdfdoc/cpdf_iconfit.h" + +#include "core/fpdfapi/parser/cpdf_array.h" +#include "core/fpdfapi/parser/cpdf_boolean.h" +#include "core/fpdfapi/parser/cpdf_dictionary.h" +#include "core/fpdfapi/parser/cpdf_number.h" +#include "core/fpdfapi/parser/cpdf_string.h" +#include "core/fxcrt/fx_coordinates.h" +#include "testing/gtest/include/gtest/gtest.h" + +TEST(CPDFIconFitTest, NullDict) { + CPDF_IconFit icon_fit(nullptr); + EXPECT_EQ(CPDF_IconFit::ScaleMethod::kAlways, icon_fit.GetScaleMethod()); + EXPECT_TRUE(icon_fit.IsProportionalScale()); + EXPECT_FALSE(icon_fit.GetFittingBounds()); + EXPECT_EQ(CFX_PointF(0.5f, 0.5f), icon_fit.GetIconBottomLeftPosition()); + + const CFX_SizeF image_size(100.0f, 50.0f); + const CFX_FloatRect plate(0.0f, 0.0f, 200.0f, 200.0f); + const CFX_VectorF scale = icon_fit.GetScale(image_size, plate); + EXPECT_FLOAT_EQ(2.0f, scale.x); + EXPECT_FLOAT_EQ(2.0f, scale.y); + + const CFX_VectorF offset = icon_fit.GetImageOffset(image_size, scale, plate); + EXPECT_FLOAT_EQ(0.0f, offset.x); + EXPECT_FLOAT_EQ(0.0f, offset.y); +} + +TEST(CPDFIconFitTest, ScaleMethod) { + auto dict = pdfium::MakeRetain(); + CPDF_IconFit icon_fit(dict); + + EXPECT_EQ(CPDF_IconFit::ScaleMethod::kAlways, icon_fit.GetScaleMethod()); + + dict->SetNewFor("SW", "A"); + EXPECT_EQ(CPDF_IconFit::ScaleMethod::kAlways, icon_fit.GetScaleMethod()); + + dict->SetNewFor("SW", "B"); + EXPECT_EQ(CPDF_IconFit::ScaleMethod::kBigger, icon_fit.GetScaleMethod()); + + dict->SetNewFor("SW", "S"); + EXPECT_EQ(CPDF_IconFit::ScaleMethod::kSmaller, icon_fit.GetScaleMethod()); + + dict->SetNewFor("SW", "N"); + EXPECT_EQ(CPDF_IconFit::ScaleMethod::kNever, icon_fit.GetScaleMethod()); + + dict->SetNewFor("SW", "unknown"); + EXPECT_EQ(CPDF_IconFit::ScaleMethod::kAlways, icon_fit.GetScaleMethod()); +} + +TEST(CPDFIconFitTest, IsProportionalScale) { + auto dict = pdfium::MakeRetain(); + CPDF_IconFit icon_fit(dict); + + EXPECT_TRUE(icon_fit.IsProportionalScale()); + + dict->SetNewFor("S", "P"); + EXPECT_TRUE(icon_fit.IsProportionalScale()); + + dict->SetNewFor("S", "A"); + EXPECT_FALSE(icon_fit.IsProportionalScale()); +} + +TEST(CPDFIconFitTest, GetFittingBounds) { + auto dict = pdfium::MakeRetain(); + CPDF_IconFit icon_fit(dict); + + EXPECT_FALSE(icon_fit.GetFittingBounds()); + + dict->SetNewFor("FB", true); + EXPECT_TRUE(icon_fit.GetFittingBounds()); + + dict->SetNewFor("FB", false); + EXPECT_FALSE(icon_fit.GetFittingBounds()); +} + +TEST(CPDFIconFitTest, GetIconBottomLeftPosition) { + auto dict = pdfium::MakeRetain(); + CPDF_IconFit icon_fit(dict); + + EXPECT_EQ(CFX_PointF(0.5f, 0.5f), icon_fit.GetIconBottomLeftPosition()); + + auto arr = dict->SetNewFor("A"); + EXPECT_EQ(CFX_PointF(0.5f, 0.5f), icon_fit.GetIconBottomLeftPosition()); + + arr->AppendNew(0.25f); + EXPECT_EQ(CFX_PointF(0.25f, 0.5f), icon_fit.GetIconBottomLeftPosition()); + + arr->AppendNew(0.75f); + EXPECT_EQ(CFX_PointF(0.25f, 0.75f), icon_fit.GetIconBottomLeftPosition()); +} + +TEST(CPDFIconFitTest, GetScaleAlways) { + auto dict = pdfium::MakeRetain(); + dict->SetNewFor("SW", "A"); + dict->SetNewFor("S", "A"); // Anamorphic. + CPDF_IconFit icon_fit(dict); + + const CFX_SizeF image_size(100.0f, 50.0f); + const CFX_FloatRect plate(0.0f, 0.0f, 300.0f, 200.0f); + const CFX_VectorF scale_anamorphic = icon_fit.GetScale(image_size, plate); + EXPECT_FLOAT_EQ(3.0f, scale_anamorphic.x); + EXPECT_FLOAT_EQ(4.0f, scale_anamorphic.y); + + dict->SetNewFor("S", "P"); // Proportional. + const CFX_VectorF scale_proportional = icon_fit.GetScale(image_size, plate); + EXPECT_FLOAT_EQ(3.0f, scale_proportional.x); + EXPECT_FLOAT_EQ(3.0f, scale_proportional.y); + + // Clamping for zero/negative image dimension. + const CFX_VectorF scale_clamped = + icon_fit.GetScale(CFX_SizeF(0.0f, 0.0f), plate); + EXPECT_FLOAT_EQ(200.0f, scale_clamped.x); + EXPECT_FLOAT_EQ(200.0f, scale_clamped.y); +} + +TEST(CPDFIconFitTest, GetScaleBigger) { + auto dict = pdfium::MakeRetain(); + dict->SetNewFor("SW", "B"); + dict->SetNewFor("S", "A"); // Anamorphic. + CPDF_IconFit icon_fit(dict); + + // Plate smaller than image: scales down. + const CFX_SizeF large_image(400.0f, 200.0f); + const CFX_FloatRect small_plate(0.0f, 0.0f, 200.0f, 50.0f); + const CFX_VectorF scale_down = icon_fit.GetScale(large_image, small_plate); + EXPECT_FLOAT_EQ(0.5f, scale_down.x); + EXPECT_FLOAT_EQ(0.25f, scale_down.y); + + // Plate larger than image: remains 1.0f. + const CFX_FloatRect large_plate(0.0f, 0.0f, 800.0f, 400.0f); + const CFX_VectorF scale_none = icon_fit.GetScale(large_image, large_plate); + EXPECT_FLOAT_EQ(1.0f, scale_none.x); + EXPECT_FLOAT_EQ(1.0f, scale_none.y); +} + +TEST(CPDFIconFitTest, GetScaleSmaller) { + auto dict = pdfium::MakeRetain(); + dict->SetNewFor("SW", "S"); + dict->SetNewFor("S", "A"); // Anamorphic. + CPDF_IconFit icon_fit(dict); + + // Plate larger than image: scales up. + const CFX_SizeF small_image(50.0f, 100.0f); + const CFX_FloatRect large_plate(0.0f, 0.0f, 200.0f, 300.0f); + const CFX_VectorF scale_up = icon_fit.GetScale(small_image, large_plate); + EXPECT_FLOAT_EQ(4.0f, scale_up.x); + EXPECT_FLOAT_EQ(3.0f, scale_up.y); + + // Plate smaller than image: remains 1.0f. + const CFX_FloatRect small_plate(0.0f, 0.0f, 25.0f, 50.0f); + const CFX_VectorF scale_none = icon_fit.GetScale(small_image, small_plate); + EXPECT_FLOAT_EQ(1.0f, scale_none.x); + EXPECT_FLOAT_EQ(1.0f, scale_none.y); +} + +TEST(CPDFIconFitTest, GetScaleNever) { + auto dict = pdfium::MakeRetain(); + dict->SetNewFor("SW", "N"); + CPDF_IconFit icon_fit(dict); + + const CFX_SizeF image_size(100.0f, 50.0f); + const CFX_FloatRect plate(0.0f, 0.0f, 500.0f, 500.0f); + const CFX_VectorF scale = icon_fit.GetScale(image_size, plate); + EXPECT_FLOAT_EQ(1.0f, scale.x); + EXPECT_FLOAT_EQ(1.0f, scale.y); +} + +TEST(CPDFIconFitTest, GetImageOffset) { + auto dict = pdfium::MakeRetain(); + auto arr = dict->SetNewFor("A"); + arr->AppendNew(0.5f); + arr->AppendNew(0.5f); + CPDF_IconFit icon_fit(dict); + + const CFX_SizeF image_size(100.0f, 50.0f); + const CFX_VectorF scale(1.0f, 1.0f); + const CFX_FloatRect plate(0.0f, 0.0f, 200.0f, 200.0f); + const CFX_VectorF offset = icon_fit.GetImageOffset(image_size, scale, plate); + // (200 - 100) * 0.5 = 50 + // (200 - 50) * 0.5 = 75 + EXPECT_FLOAT_EQ(50.0f, offset.x); + EXPECT_FLOAT_EQ(75.0f, offset.y); +} From a6d26535798a2db4b31e180590b990f45d12ae03 Mon Sep 17 00:00:00 2001 From: Tom Sepez Date: Mon, 9 Nov 2026 14:48:55 -0800 Subject: [PATCH 07/47] Clear render context in FPDFPage_GenerateContent Mutating a page's content invalidates any active progressive rendering context associated with that page. Call ClearRenderContext() in FPDFPage_GenerateContent() so that an in-flight progressive render terminates cleanly, causing subsequent calls to FPDF_RenderPage_Continue() to return FPDF_RENDER_FAILED rather than operating on stale page state. Add an embedder test verifying that calling FPDFPage_GenerateContent() causes subsequent FPDF_RenderPage_Continue() to fail cleanly. First step towards fixing related bug. Bug: 582607114 Change-Id: I1a1176b61c7f9a42e848804bc0050a0613a851ef Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163750 Reviewed-by: Lei Zhang Commit-Queue: Tom Sepez --- fpdfsdk/fpdf_editpage.cpp | 3 +++ fpdfsdk/fpdf_editpage_embeddertest.cpp | 32 ++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/fpdfsdk/fpdf_editpage.cpp b/fpdfsdk/fpdf_editpage.cpp index 033572048..f19bc930f 100644 --- a/fpdfsdk/fpdf_editpage.cpp +++ b/fpdfsdk/fpdf_editpage.cpp @@ -859,6 +859,9 @@ FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV FPDFPage_GenerateContent(FPDF_PAGE page) { return false; } + // Invalidate any in-flight progressive render context on `pPage` since + // mutating page content invalidates the active render state. + pPage->ClearRenderContext(); CPDF_PageContentGenerator CG(pPage); CG.GenerateContent(); return true; diff --git a/fpdfsdk/fpdf_editpage_embeddertest.cpp b/fpdfsdk/fpdf_editpage_embeddertest.cpp index ca5908dd5..08969612b 100644 --- a/fpdfsdk/fpdf_editpage_embeddertest.cpp +++ b/fpdfsdk/fpdf_editpage_embeddertest.cpp @@ -9,6 +9,7 @@ #include "core/fxcrt/fx_system.h" #include "core/fxge/cfx_renderdevice.h" +#include "public/fpdf_progressive.h" #include "testing/embedder_test.h" #include "testing/gmock/include/gmock/gmock.h" @@ -17,6 +18,18 @@ using ::testing::Eq; using ::testing::FloatEq; using ::testing::Gt; +namespace { + +struct FakePause : public IFSDK_PAUSE { + FakePause() { + version = 1; + user = nullptr; + NeedToPauseNow = [](IFSDK_PAUSE*) -> FPDF_BOOL { return true; }; + } +}; + +} // namespace + class FPDFEditPageEmbedderTest : public EmbedderTest {}; TEST_F(FPDFEditPageEmbedderTest, Rotation) { @@ -703,3 +716,22 @@ TEST_F(FPDFEditPageEmbedderTest, Bug378464305) { EXPECT_EQ(kObjectCountWithNewPath, FPDFPage_CountObjects(saved_page.get())); } } + +TEST_F(FPDFEditPageEmbedderTest, GenerateContentClearsRenderContext) { + ASSERT_TRUE(OpenDocument("rectangles.pdf")); + ScopedPage page = LoadScopedPage(0); + ASSERT_TRUE(page); + + ScopedFPDFBitmap bitmap(FPDFBitmap_Create(200, 300, 0)); + ASSERT_TRUE(bitmap); + + FakePause pause; + int rv = FPDF_RenderPageBitmap_Start(bitmap.get(), page.get(), 0, 0, 200, 300, + 0, 0, &pause); + EXPECT_EQ(rv, FPDF_RENDER_TOBECONTINUED); + + EXPECT_TRUE(FPDFPage_GenerateContent(page.get())); + + int cont_rv = FPDF_RenderPage_Continue(page.get(), &pause); + EXPECT_EQ(cont_rv, FPDF_RENDER_FAILED); +} From fc08db6a73d199eb1653e4fe9bdab2def7fc26f2 Mon Sep 17 00:00:00 2001 From: Tom Sepez Date: Mon, 9 Nov 2026 14:50:21 -0800 Subject: [PATCH 08/47] Use GCedVector for resolve processor candidate collections Hold candidate collections in `CFXJSE_Engine::ResolveObjectsWithBindNode()` and `CFXJSE_ResolveProcessor::DoPredicateFilter()` via `cppgc::Persistent>` instead of untraced stack-local vectors of `cppgc::Member<>`. This keeps candidate nodes alive across arbitrary script execution during predicate evaluation and nested resolution loops in face of synchronous garbage collection. Bug: 575092240 Change-Id: I9d02e9d0c83fcdf5be611d616190065ad231590e Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163490 Reviewed-by: Lei Zhang Commit-Queue: Tom Sepez --- fxjs/xfa/cfxjse_engine.cpp | 51 +++++++++++++++++----------- fxjs/xfa/cfxjse_resolveprocessor.cpp | 13 +++++-- 2 files changed, 41 insertions(+), 23 deletions(-) diff --git a/fxjs/xfa/cfxjse_engine.cpp b/fxjs/xfa/cfxjse_engine.cpp index 15f4bc94b..fd2d605be 100644 --- a/fxjs/xfa/cfxjse_engine.cpp +++ b/fxjs/xfa/cfxjse_engine.cpp @@ -790,12 +790,18 @@ CFXJSE_Engine::ResolveObjectsWithBindNode(CXFA_Object* refObject, int32_t nStart = 0; int32_t nLevel = 0; - std::vector> findObjects; - findObjects.emplace_back(refObject ? refObject : document_->GetRoot()); + cppgc::Persistent> find_objects = + cppgc::MakeGarbageCollected>( + document_->GetHeap()->GetAllocationHandle()); + find_objects->storage.emplace_back(refObject ? refObject + : document_->GetRoot()); + cppgc::Persistent> ret_objects = + cppgc::MakeGarbageCollected>( + document_->GetHeap()->GetAllocationHandle()); int32_t nNodes = 0; CFXJSE_ScopeUtil_IsolateHandleContext scope(GetJseContext()); while (true) { - nNodes = fxcrt::CollectionSize(findObjects); + nNodes = fxcrt::CollectionSize(find_objects->storage); int32_t i = 0; rndFind.styles_ = dwStyles; resolve_processor_->SetCurStart(nStart); @@ -805,21 +811,22 @@ CFXJSE_Engine::ResolveObjectsWithBindNode(CXFA_Object* refObject, CXFA_Node* pDataNode = nullptr; nStart = node_helper_->cur_all_start_; if (nStart != -1) { - pDataNode = document_->GetNotBindNode(findObjects); + pDataNode = document_->GetNotBindNode(find_objects->storage); if (pDataNode) { - findObjects.clear(); - findObjects.emplace_back(pDataNode); + find_objects->storage.clear(); + find_objects->storage.emplace_back(pDataNode); break; } } else { - pDataNode = findObjects.front()->AsNode(); - findObjects.clear(); - findObjects.emplace_back(pDataNode); + pDataNode = find_objects->storage.front()->AsNode(); + find_objects->storage.clear(); + find_objects->storage.emplace_back(pDataNode); break; } dwStyles |= XFA_ResolveFlag::kBind; - findObjects.clear(); - findObjects.emplace_back(node_helper_->all_start_parent_.Get()); + find_objects->storage.clear(); + find_objects->storage.emplace_back( + node_helper_->all_start_parent_.Get()); continue; } break; @@ -833,7 +840,10 @@ CFXJSE_Engine::ResolveObjectsWithBindNode(CXFA_Object* refObject, } break; } - std::vector> retObjects; + // Could make a new `ret_objects` every time through here, execpt + // that would generate needless cppgc heap garbage when only the + // backing-store has to change. + ret_objects->storage.clear(); while (i < nNodes) { bool bDataBind = false; if (((dwStyles & XFA_ResolveFlag::kBind) || @@ -844,7 +854,7 @@ CFXJSE_Engine::ResolveObjectsWithBindNode(CXFA_Object* refObject, i = resolve_processor_->IndexForDataBind(rndBind.condition_, nNodes); bDataBind = true; } - rndFind.cur_object_ = findObjects[i++].Get(); + rndFind.cur_object_ = find_objects->storage[i++].Get(); rndFind.level_ = nLevel; rndFind.result_.type = ResolveResult::Type::kNodes; if (!resolve_processor_->Resolve(GetIsolate(), rndFind)) { @@ -866,16 +876,17 @@ CFXJSE_Engine::ResolveObjectsWithBindNode(CXFA_Object* refObject, if (!up_object_array_.empty()) { up_object_array_.pop_back(); } - retObjects.insert(retObjects.end(), rndFind.result_.objects.begin(), - rndFind.result_.objects.end()); + ret_objects->storage.insert(ret_objects->storage.end(), + rndFind.result_.objects.begin(), + rndFind.result_.objects.end()); rndFind.result_.objects.clear(); if (bDataBind) { break; } } - findObjects.clear(); + find_objects->storage.clear(); - nNodes = fxcrt::CollectionSize(retObjects); + nNodes = fxcrt::CollectionSize(ret_objects->storage); if (nNodes < 1) { if (dwStyles & XFA_ResolveFlag::kCreateNode) { bNextCreate = true; @@ -893,7 +904,7 @@ CFXJSE_Engine::ResolveObjectsWithBindNode(CXFA_Object* refObject, break; } - findObjects = std::move(retObjects); + find_objects->storage = std::move(ret_objects->storage); rndFind.result_.objects.clear(); if (nLevel == 0) { dwStyles.Clear(XFA_ResolveFlag::kParent); @@ -905,8 +916,8 @@ CFXJSE_Engine::ResolveObjectsWithBindNode(CXFA_Object* refObject, if (!bNextCreate) { result.type = rndFind.result_.type; if (nNodes > 0) { - result.objects.insert(result.objects.end(), findObjects.begin(), - findObjects.end()); + result.objects.insert(result.objects.end(), find_objects->storage.begin(), + find_objects->storage.end()); } if (rndFind.result_.type == ResolveResult::Type::kAttribute) { result.script_attribute = rndFind.result_.script_attribute; diff --git a/fxjs/xfa/cfxjse_resolveprocessor.cpp b/fxjs/xfa/cfxjse_resolveprocessor.cpp index b74733d6e..96cec1b38 100644 --- a/fxjs/xfa/cfxjse_resolveprocessor.cpp +++ b/fxjs/xfa/cfxjse_resolveprocessor.cpp @@ -15,10 +15,12 @@ #include "core/fxcrt/containers/to_vector.h" #include "core/fxcrt/fx_extension.h" #include "fxjs/fxv8.h" +#include "fxjs/gc/containers.h" #include "fxjs/xfa/cfxjse_engine.h" #include "fxjs/xfa/cfxjse_isolatetracker.h" #include "fxjs/xfa/cfxjse_nodehelper.h" #include "fxjs/xfa/cjx_object.h" +#include "v8/include/cppgc/persistent.h" #include "xfa/fxfa/parser/cxfa_document.h" #include "xfa/fxfa/parser/cxfa_localemgr.h" #include "xfa/fxfa/parser/cxfa_node.h" @@ -763,13 +765,17 @@ void CFXJSE_ResolveProcessor::DoPredicateFilter(v8::Isolate* pIsolate, } else { return; } - WideString wsExpression = wsCondition.Substr(2, wsCondition.GetLength() - 3); + + cppgc::Persistent> candidates = + cppgc::MakeGarbageCollected>( + engine_->GetDocument()->GetHeap()->GetAllocationHandle()); + candidates->storage = std::move(pRnd->result_.objects); for (size_t i = iFoundCount; i > 0; --i) { bool bool_val = false; CFXJSE_Context::ExecutionResult exec_result = engine_->RunScript(eLangType, wsExpression.AsStringView(), - pRnd->result_.objects[i - 1].Get()); + candidates->storage[i - 1].Get()); if (exec_result.status) { CFXJSE_ScopeUtil_IsolateHandleRootContext scope(pIsolate); v8::Local local_val = @@ -777,9 +783,10 @@ void CFXJSE_ResolveProcessor::DoPredicateFilter(v8::Isolate* pIsolate, bool_val = fxv8::ReentrantToBooleanHelper(pIsolate, local_val); } if (!bool_val) { - pRnd->result_.objects.erase(pRnd->result_.objects.begin() + i - 1); + candidates->storage.erase(candidates->storage.begin() + i - 1); } } + pRnd->result_.objects = std::move(candidates->storage); } CFXJSE_ResolveProcessor::NodeData::NodeData() = default; From 885983432ee8810a40b28aff098bd2fd4772bbda Mon Sep 17 00:00:00 2001 From: Lei Zhang Date: Mon, 9 Nov 2026 15:40:27 -0800 Subject: [PATCH 09/47] Borrow Chromium's base::Extend() Add a copy of Chromium's base::Extend() as pdfium::Extend(), with a template parameter to support DataVector. Then use it in CPDF_CMapParser::HandleCodeSpaceRange() and SetupStrokePaint() to simplify/improve the code. This CL is AI generated. Change-Id: I89bbb13460228a9061201fd71b0e9d29890c1818 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163810 Commit-Queue: Lei Zhang Reviewed-by: Tom Sepez --- core/fpdfapi/font/cpdf_cmapparser.cpp | 6 +- core/fxcrt/BUILD.gn | 2 + core/fxcrt/containers/extend.h | 50 ++++++ core/fxcrt/containers/extend_unittest.cc | 197 +++++++++++++++++++++++ core/fxge/skia/fx_skia_device.cpp | 12 +- 5 files changed, 256 insertions(+), 11 deletions(-) create mode 100644 core/fxcrt/containers/extend.h create mode 100644 core/fxcrt/containers/extend_unittest.cc diff --git a/core/fpdfapi/font/cpdf_cmapparser.cpp b/core/fpdfapi/font/cpdf_cmapparser.cpp index 3597bc36a..4ea5c74a1 100644 --- a/core/fpdfapi/font/cpdf_cmapparser.cpp +++ b/core/fpdfapi/font/cpdf_cmapparser.cpp @@ -14,6 +14,7 @@ #include "core/fpdfapi/parser/cpdf_dictionary.h" #include "core/fpdfapi/parser/cpdf_simple_parser.h" #include "core/fxcrt/check.h" +#include "core/fxcrt/containers/extend.h" #include "core/fxcrt/fx_extension.h" #include "core/fxcrt/fx_safe_types.h" #include "core/fxcrt/to_underlying.h" @@ -134,10 +135,7 @@ void CPDF_CMapParser::HandleCodeSpaceRange(ByteStringView word) { : CPDF_CMap::OneByte); } else if (nSegs > 1) { cmap_->SetCodingScheme(CPDF_CMap::MixedFourBytes); - ranges_.reserve(nSegs); - std::move(pending_ranges_.begin(), pending_ranges_.end(), - std::back_inserter(ranges_)); - pending_ranges_.clear(); + pdfium::Extend(ranges_, std::move(pending_ranges_)); } status_ = kStart; } diff --git a/core/fxcrt/BUILD.gn b/core/fxcrt/BUILD.gn index 976b1b5a7..9c806cb0c 100644 --- a/core/fxcrt/BUILD.gn +++ b/core/fxcrt/BUILD.gn @@ -54,6 +54,7 @@ source_set("fxcrt") { "component_export.h", "containers/adapters.h", "containers/contains.h", + "containers/extend.h", "containers/to_vector.h", "containers/unique_ptr_adapters.h", "data_vector.h", @@ -246,6 +247,7 @@ pdfium_unittest_source_set("unittests") { "cfx_seekablestreamproxy_unittest.cpp", "cfx_timer_unittest.cpp", "code_point_view_unittest.cpp", + "containers/extend_unittest.cc", "containers/to_vector_unittest.cpp", "data_vector_unittest.cpp", "fixed_size_data_vector_unittest.cpp", diff --git a/core/fxcrt/containers/extend.h b/core/fxcrt/containers/extend.h new file mode 100644 index 000000000..9617ecfe0 --- /dev/null +++ b/core/fxcrt/containers/extend.h @@ -0,0 +1,50 @@ +// Copyright 2026 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CORE_FXCRT_CONTAINERS_EXTEND_H_ +#define CORE_FXCRT_CONTAINERS_EXTEND_H_ + +#include +#include +#include +#include +#include +#include + +// This is Chromium's base/containers/extend.h, adapted to work with PDFium's +// codebase with the following modifications: +// +// - Updated include guards. +// - Replaced namespace base with namespace pdfium. +// - Added template parameter `Alloc` to support `DataVector`. + +namespace pdfium { + +// Append to `dst` all elements of `src` by std::move-ing them out of `src`. +// After this operation, `src` will be empty. +template +void Extend(std::vector& dst, std::vector&& src) { + dst.insert(dst.end(), std::make_move_iterator(src.begin()), + std::make_move_iterator(src.end())); + src.clear(); +} + +// Appends `range` to `dst`, copying them out of `range`. +template + requires std::ranges::range && + std::indirectly_unary_invocable> +void Extend(std::vector& dst, Range&& range, Proj proj = {}) { + if constexpr (std::ranges::sized_range) { + dst.reserve(dst.size() + std::ranges::size(range)); + } + std::ranges::transform(std::forward(range), std::back_inserter(dst), + std::move(proj)); +} + +} // namespace pdfium + +#endif // CORE_FXCRT_CONTAINERS_EXTEND_H_ diff --git a/core/fxcrt/containers/extend_unittest.cc b/core/fxcrt/containers/extend_unittest.cc new file mode 100644 index 000000000..1ae04c52b --- /dev/null +++ b/core/fxcrt/containers/extend_unittest.cc @@ -0,0 +1,197 @@ +// Copyright 2026 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "core/fxcrt/containers/extend.h" + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "core/fxcrt/containers/adapters.h" +#include "core/fxcrt/data_vector.h" +#include "core/fxcrt/span.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace pdfium { + +namespace { + +using testing::ElementsAre; + +struct NonCopyable { + char c_; + explicit NonCopyable(char c) : c_(c) {} + NonCopyable(NonCopyable&&) = default; + NonCopyable& operator=(NonCopyable&& other) = default; + + NonCopyable(const NonCopyable&) = delete; + NonCopyable& operator=(const NonCopyable&) = delete; +}; + +bool operator==(const NonCopyable& a, const NonCopyable& b) { + return a.c_ == b.c_; +} + +static_assert(std::is_move_constructible_v, ""); +static_assert(!std::is_copy_constructible_v, ""); + +struct CopyableMovable { + bool copied_ = false; + char c_; + explicit CopyableMovable(char c) : c_(c) {} + CopyableMovable(const CopyableMovable& other) : copied_(true), c_(other.c_) {} + + CopyableMovable& operator=(const CopyableMovable&) = default; + CopyableMovable(CopyableMovable&&) = default; + CopyableMovable& operator=(CopyableMovable&& other) = default; +}; + +bool operator==(const CopyableMovable& a, const CopyableMovable& b) { + return a.c_ == b.c_; +} + +} // namespace + +TEST(ExtendTest, ExtendWithMove) { + std::vector dst; + for (char c : {'a', 'b', 'c', 'd'}) { + dst.emplace_back(c); + } + std::vector src; + for (char c : {'e', 'f', 'g'}) { + src.emplace_back(c); + } + std::vector expected; + for (char c : {'a', 'b', 'c', 'd', 'e', 'f', 'g'}) { + expected.emplace_back(c); + } + + Extend(dst, std::move(src)); + EXPECT_EQ(dst, expected); + EXPECT_TRUE(src.empty()); // NOLINT(bugprone-use-after-move) +} + +TEST(ExtendTest, ExtendCopyableWithMove) { + std::vector dst; + for (char c : {'a', 'b', 'c', 'd'}) { + dst.emplace_back(c); + } + std::vector src; + for (char c : {'e', 'f', 'g'}) { + src.emplace_back(c); + } + std::vector expected; + for (char c : {'a', 'b', 'c', 'd', 'e', 'f', 'g'}) { + expected.emplace_back(c); + } + + Extend(dst, std::move(src)); + EXPECT_EQ(dst, expected); + EXPECT_TRUE(src.empty()); // NOLINT(bugprone-use-after-move) +} + +TEST(ExtendTest, ExtendWithCopy) { + std::vector dst; + for (char c : {'a', 'b', 'c', 'd'}) { + dst.emplace_back(c); + } + std::vector src; + for (char c : {'e', 'f', 'g'}) { + src.emplace_back(c); + } + std::vector expected; + for (char c : {'a', 'b', 'c', 'd', 'e', 'f', 'g'}) { + expected.emplace_back(c); + } + + EXPECT_FALSE(dst[0].copied_); + Extend(dst, src); + EXPECT_EQ(dst, expected); + EXPECT_FALSE(dst[0].copied_); + EXPECT_TRUE(dst[dst.size() - 1].copied_); +} + +TEST(ExtendTest, ExtendWithSpan) { + static constexpr uint8_t kRawArray[] = {3, 4, 5}; + + static constexpr auto kVectorGenerator = []() -> std::vector { + return {9, 10, 11}; + }; + + const std::vector kConstVector = kVectorGenerator(); + std::vector kMutVector = kVectorGenerator(); + + std::vector dst; + + // Selects overload for span. + Extend(dst, span(kRawArray)); + EXPECT_THAT(dst, ElementsAre(3, 4, 5)); + + // Selects overload for span. + static std::array kArray = {6, 7, 8}; + Extend(dst, span(kArray)); + EXPECT_THAT(dst, ElementsAre(3, 4, 5, 6, 7, 8)); + + // Selects overload for span. + Extend(dst, span(kConstVector)); + EXPECT_THAT(dst, ElementsAre(3, 4, 5, 6, 7, 8, 9, 10, 11)); + + // Selects overload for span. + Extend(dst, span(kMutVector)); + EXPECT_THAT(dst, ElementsAre(3, 4, 5, 6, 7, 8, 9, 10, 11, 9, 10, 11)); + + // Input is convertible to span. + Extend(dst, kRawArray); + EXPECT_THAT(dst, + ElementsAre(3, 4, 5, 6, 7, 8, 9, 10, 11, 9, 10, 11, 3, 4, 5)); +} + +TEST(ExtendTest, ExtendWithRanges) { + std::set set = {1, 2, 3}; + std::deque deque = {4, 5, 6}; + { + std::vector dst; + Extend(dst, Reversed(set)); + EXPECT_THAT(dst, ElementsAre(3, 2, 1)); + Extend(dst, Reversed(deque)); + EXPECT_THAT(dst, ElementsAre(3, 2, 1, 6, 5, 4)); + } + + { + std::vector dst; + Extend(dst, set, [](int val) { return -val; }); + EXPECT_THAT(dst, ElementsAre(-1, -2, -3)); + Extend(dst, deque, [](int val) { return val + 1; }); + EXPECT_THAT(dst, ElementsAre(-1, -2, -3, 5, 6, 7)); + } + + { + std::vector dst; + Extend(dst, Reversed(set), [](int val) { return val * val; }); + EXPECT_THAT(dst, ElementsAre(9, 4, 1)); + Extend(dst, Reversed(deque), [](int val) { return val - 1; }); + EXPECT_THAT(dst, ElementsAre(9, 4, 1, 5, 4, 3)); + } +} + +TEST(ExtendTest, ExtendDataVector) { + DataVector dst = {1, 2, 3}; + DataVector src = {4, 5}; + Extend(dst, std::move(src)); + EXPECT_THAT(dst, ElementsAre(1, 2, 3, 4, 5)); + EXPECT_TRUE(src.empty()); // NOLINT(bugprone-use-after-move) + + static constexpr int kArray[] = {6, 7}; + Extend(dst, kArray, [](int val) { return val * 10; }); + EXPECT_THAT(dst, ElementsAre(1, 2, 3, 4, 5, 60, 70)); +} + +} // namespace pdfium diff --git a/core/fxge/skia/fx_skia_device.cpp b/core/fxge/skia/fx_skia_device.cpp index ebf768461..774442ba5 100644 --- a/core/fxge/skia/fx_skia_device.cpp +++ b/core/fxge/skia/fx_skia_device.cpp @@ -29,6 +29,7 @@ #include "core/fxcrt/cfx_bitstream.h" #include "core/fxcrt/check.h" #include "core/fxcrt/check_op.h" +#include "core/fxcrt/containers/extend.h" #include "core/fxcrt/data_vector.h" #include "core/fxcrt/fx_2d_size.h" #include "core/fxcrt/fx_coordinates.h" @@ -541,14 +542,11 @@ void SetupStrokePaint(SkPaint* stroke_paint, bool is_even_sized = count % 2 == 0; DataVector intervals; intervals.reserve(is_even_sized ? count : count * 2); - for (float dash_len : dash_array) { - if (dash_len <= 0.000001f) { - dash_len = 0.1f; - } - intervals.push_back(dash_len); - } + pdfium::Extend(intervals, dash_array, [](float dash_len) { + return dash_len <= 0.000001f ? 0.1f : dash_len; + }); if (!is_even_sized) { - intervals.insert(intervals.end(), intervals.begin(), intervals.end()); + pdfium::Extend(intervals, intervals); } stroke_paint->setPathEffect( SkDashPathEffect::Make(intervals, stroke_options->dash_phase())); From 701bec96dbd1e33f5aab6d608d965177548ccf60 Mon Sep 17 00:00:00 2001 From: Lei Zhang Date: Mon, 9 Nov 2026 15:57:00 -0800 Subject: [PATCH 10/47] Switch C-arrays constants inside fx_unicode.cpp to std::array Since std::array is hardened by default, use that and get rid of the UNSAFE_BUFFERS() and CHECK_LT() usage. This CL is AI generated. Change-Id: I234059ed2c8c6ee1eeeb165529027c6c69042316 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163830 Reviewed-by: Tom Sepez Commit-Queue: Lei Zhang --- core/fxcrt/fx_unicode.cpp | 48 ++++++++++++++++----------------------- 1 file changed, 19 insertions(+), 29 deletions(-) diff --git a/core/fxcrt/fx_unicode.cpp b/core/fxcrt/fx_unicode.cpp index 6683934a7..d724be252 100644 --- a/core/fxcrt/fx_unicode.cpp +++ b/core/fxcrt/fx_unicode.cpp @@ -8,16 +8,14 @@ #include -#include +#include #include -#include "core/fxcrt/check.h" #include "core/fxcrt/check_op.h" -#include "core/fxcrt/compiler_specific.h" namespace { -// Format of uint16_t values in kTextLayoutCodeProperties[]. +// Format of uint16_t values in `kTextLayoutCodeProperties`. constexpr uint16_t kBidiClassBitPos = 0; constexpr uint16_t kBidiClassBitCount = 5; constexpr uint16_t kBidiClassBitMask = @@ -31,26 +29,23 @@ constexpr uint16_t kMirrorMax = (1 << kMirrorBitCount) - 1; #define CHARPROP____(mirror, ct, bd, bt) \ ((mirror << kMirrorBitPos) | \ (static_cast(BidiClass::bd) << kBidiClassBitPos)), -constexpr uint16_t kTextLayoutCodeProperties[] = { +constexpr auto kTextLayoutCodeProperties = std::to_array({ #include "core/fxcrt/fx_ucddata.inc" // NOLINT(build/include) -}; +}); #undef CHARPROP____ -static_assert(std::size(kTextLayoutCodeProperties) == 65536, - "missing characters"); +static_assert(kTextLayoutCodeProperties.size() == 65536, "missing characters"); std::optional GetUnicodeProperties(wchar_t wch) { size_t idx = static_cast(wch); - if (idx < std::size(kTextLayoutCodeProperties)) { - // SAFETY: `std::size(kTextLayoutCodeProperties)` is the size of the table, - // so the condition above verifies `idx` is in range. - return UNSAFE_BUFFERS(kTextLayoutCodeProperties[idx]); + if (idx < kTextLayoutCodeProperties.size()) { + return kTextLayoutCodeProperties[idx]; } return std::nullopt; } #ifdef PDF_ENABLE_XFA -// Format of uint16_t values in kExtendedTextLayoutCodeProperties[]. +// Format of uint16_t values in `kExtendedTextLayoutCodeProperties`. constexpr uint16_t kBreakTypeBitPos = 0; constexpr uint16_t kBreakTypeBitCount = 6; constexpr uint16_t kBreakTypeBitMask = @@ -65,27 +60,25 @@ constexpr uint16_t kCharTypeBitMask = #define CHARPROP____(mirror, ct, bd, bt) \ ((static_cast(CharType::ct) << kCharTypeBitPos) | \ (static_cast(BreakProperty::bt) << kBreakTypeBitPos)), -constexpr uint16_t kExtendedTextLayoutCodeProperties[] = { +constexpr auto kExtendedTextLayoutCodeProperties = std::to_array({ #include "core/fxcrt/fx_ucddata.inc" // NOLINT(build/include) -}; +}); #undef CHARPROP____ -static_assert(std::size(kExtendedTextLayoutCodeProperties) == 65536, +static_assert(kExtendedTextLayoutCodeProperties.size() == 65536, "missing characters"); uint16_t GetExtendedUnicodeProperties(wchar_t wch) { size_t idx = static_cast(wch); - if (idx < std::size(kExtendedTextLayoutCodeProperties)) { - // SAFETY: `std::size(kExtendedTextLayoutCodeProperties)` is the size of - // the table, so the condition above verifies `idx` is in range. - return UNSAFE_BUFFERS(kExtendedTextLayoutCodeProperties[idx]); + if (idx < kExtendedTextLayoutCodeProperties.size()) { + return kExtendedTextLayoutCodeProperties[idx]; } return 0; } #endif // PDF_ENABLE_XFA -constexpr uint16_t kFXTextLayoutBidiMirror[] = { +constexpr auto kFXTextLayoutBidiMirror = std::to_array({ 0x0029, 0x0028, 0x003E, 0x003C, 0x005D, 0x005B, 0x007D, 0x007B, 0x00BB, 0x00AB, 0x0F3B, 0x0F3A, 0x0F3D, 0x0F3C, 0x169C, 0x169B, 0x2019, 0x2018, 0x201D, 0x201C, 0x203A, 0x2039, 0x2046, 0x2045, 0x207E, 0x207D, 0x208E, @@ -127,13 +120,13 @@ constexpr uint16_t kFXTextLayoutBidiMirror[] = { 0x3019, 0x3018, 0x301B, 0x301A, 0xFE5A, 0xFE59, 0xFE5C, 0xFE5B, 0xFE5E, 0xFE5D, 0xFE65, 0xFE64, 0xFF09, 0xFF08, 0xFF1E, 0xFF1C, 0xFF3D, 0xFF3B, 0xFF5D, 0xFF5B, 0xFF60, 0xFF5F, 0xFF63, 0xFF62, -}; +}); // Check that the mirror indicies in the fx_ucddata.inc table are in bounds. #undef CHARPROP____ -#define CHARPROP____(mirror, ct, bd, bt) \ - static_assert( \ - mirror == kMirrorMax || mirror < std::size(kFXTextLayoutBidiMirror), \ +#define CHARPROP____(mirror, ct, bd, bt) \ + static_assert( \ + mirror == kMirrorMax || mirror < kFXTextLayoutBidiMirror.size(), \ "Bad mirror index"); #include "core/fxcrt/fx_ucddata.inc" // NOLINT(build/include) #undef CHARPROP____ @@ -151,10 +144,7 @@ wchar_t GetMirrorChar(wchar_t wch) { if (idx == kMirrorMax) { return wch; } - CHECK_LT(idx, std::size(kFXTextLayoutBidiMirror)); - // SAFETY: `std::size(kFXTextLayoutBidiMirror)` is the size of the table, so - // the CHECK() above verifies `idx` is in range. - return UNSAFE_BUFFERS(kFXTextLayoutBidiMirror[idx]); + return kFXTextLayoutBidiMirror[idx]; } BidiClass GetBidiClass(wchar_t wch) { From c0643c756021f77e4f88899e134712ddf0a02f66 Mon Sep 17 00:00:00 2001 From: Tom Sepez Date: Mon, 9 Nov 2026 15:59:33 -0800 Subject: [PATCH 11/47] Add unit tests for fx_date_helpers - Add tests for FX_GetHourFromTime, FX_GetMinFromTime, FX_GetSecFromTime. - Add tests for FX_IsValidMonth, FX_IsValidDay, FX_IsValid24Hour, FX_IsValidMinute, and FX_IsValidSecond. - Add tests for FX_MakeDay, FX_MakeTime, FX_MakeDate, and FX_ParseStringInteger. - Add tests for FX_ParseDateUsingFormat covering full month names (mmmm), abbreviated month names (mmm), numeric month fallbacks, 2-digit year heuristics, multi-character literal handling, interchangeable separators, and error validation paths. Change-Id: I855d7bd1825671474f4e623ac476d88a1bc607ae Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163511 Commit-Queue: Tom Sepez Reviewed-by: Lei Zhang --- fxjs/fx_date_helpers_unittest.cpp | 395 +++++++++++++++++++++++++++++- 1 file changed, 382 insertions(+), 13 deletions(-) diff --git a/fxjs/fx_date_helpers_unittest.cpp b/fxjs/fx_date_helpers_unittest.cpp index 9a4efc472..3b6aa9426 100644 --- a/fxjs/fx_date_helpers_unittest.cpp +++ b/fxjs/fx_date_helpers_unittest.cpp @@ -4,6 +4,8 @@ #include "fxjs/fx_date_helpers.h" +#include + #include "core/fxcrt/fake_time_test.h" #include "testing/gtest/include/gtest/gtest.h" @@ -185,6 +187,118 @@ TEST(FXDateHelperTest, GetDayOfWeekFromTime) { } } +TEST(FXDateHelperTest, GetHourFromTime) { + EXPECT_EQ(0, FX_GetHourFromTime(0)); + EXPECT_EQ(1, FX_GetHourFromTime(3'600'000)); + EXPECT_EQ(12, FX_GetHourFromTime(12 * 3'600'000)); + EXPECT_EQ(23, FX_GetHourFromTime(23 * 3'600'000)); + EXPECT_EQ(0, FX_GetHourFromTime(24 * 3'600'000)); + EXPECT_EQ(23, FX_GetHourFromTime(-1)); + EXPECT_EQ(23, FX_GetHourFromTime(-3'600'000)); + EXPECT_EQ(22, FX_GetHourFromTime(-3'600'001)); +} + +TEST(FXDateHelperTest, GetMinFromTime) { + EXPECT_EQ(0, FX_GetMinFromTime(0)); + EXPECT_EQ(1, FX_GetMinFromTime(60'000)); + EXPECT_EQ(30, FX_GetMinFromTime(30 * 60'000)); + EXPECT_EQ(59, FX_GetMinFromTime(59 * 60'000)); + EXPECT_EQ(0, FX_GetMinFromTime(60 * 60'000)); + EXPECT_EQ(59, FX_GetMinFromTime(-1)); + EXPECT_EQ(59, FX_GetMinFromTime(-60'000)); + EXPECT_EQ(58, FX_GetMinFromTime(-60'001)); +} + +TEST(FXDateHelperTest, GetSecFromTime) { + EXPECT_EQ(0, FX_GetSecFromTime(0)); + EXPECT_EQ(1, FX_GetSecFromTime(1'000)); + EXPECT_EQ(45, FX_GetSecFromTime(45 * 1'000)); + EXPECT_EQ(59, FX_GetSecFromTime(59 * 1'000)); + EXPECT_EQ(0, FX_GetSecFromTime(60 * 1'000)); + EXPECT_EQ(59, FX_GetSecFromTime(-1)); + EXPECT_EQ(59, FX_GetSecFromTime(-1'000)); + EXPECT_EQ(58, FX_GetSecFromTime(-1'001)); +} + +TEST(FXDateHelperTest, ValidationHelpers) { + EXPECT_FALSE(FX_IsValidMonth(0)); + EXPECT_TRUE(FX_IsValidMonth(1)); + EXPECT_TRUE(FX_IsValidMonth(12)); + EXPECT_FALSE(FX_IsValidMonth(13)); + EXPECT_FALSE(FX_IsValidMonth(-1)); + + EXPECT_FALSE(FX_IsValidDay(0)); + EXPECT_TRUE(FX_IsValidDay(1)); + EXPECT_TRUE(FX_IsValidDay(31)); + EXPECT_FALSE(FX_IsValidDay(32)); + EXPECT_FALSE(FX_IsValidDay(-1)); + + EXPECT_FALSE(FX_IsValid24Hour(-1)); + EXPECT_TRUE(FX_IsValid24Hour(0)); + EXPECT_TRUE(FX_IsValid24Hour(24)); + EXPECT_FALSE(FX_IsValid24Hour(25)); + + EXPECT_FALSE(FX_IsValidMinute(-1)); + EXPECT_TRUE(FX_IsValidMinute(0)); + EXPECT_TRUE(FX_IsValidMinute(60)); + EXPECT_FALSE(FX_IsValidMinute(61)); + + EXPECT_FALSE(FX_IsValidSecond(-1)); + EXPECT_TRUE(FX_IsValidSecond(0)); + EXPECT_TRUE(FX_IsValidSecond(60)); + EXPECT_FALSE(FX_IsValidSecond(61)); +} + +TEST(FXDateHelperTest, MakeDay) { + EXPECT_DOUBLE_EQ(0.0, FX_MakeDay(1970, 0, 1)); + EXPECT_DOUBLE_EQ(1.0, FX_MakeDay(1970, 0, 2)); + EXPECT_DOUBLE_EQ(31.0, FX_MakeDay(1970, 1, 1)); + EXPECT_DOUBLE_EQ(2 * 365 + 31 + 28, FX_MakeDay(1972, 1, 29)); + EXPECT_DOUBLE_EQ(2 * 365 + 31 + 29, FX_MakeDay(1972, 2, 1)); + EXPECT_DOUBLE_EQ(365.0, FX_MakeDay(1970, 12, 1)); + EXPECT_DOUBLE_EQ(-31.0, FX_MakeDay(1970, -1, 1)); +} + +TEST(FXDateHelperTest, MakeTime) { + EXPECT_DOUBLE_EQ(0.0, FX_MakeTime(0, 0, 0, 0)); + EXPECT_DOUBLE_EQ(3'723'004.0, FX_MakeTime(1, 2, 3, 4)); +} + +TEST(FXDateHelperTest, MakeDate) { + EXPECT_DOUBLE_EQ(0.0, FX_MakeDate(0, 0)); + EXPECT_DOUBLE_EQ(86'400'500.0, FX_MakeDate(1, 500)); + EXPECT_TRUE(isnan(FX_MakeDate(nan(""), 0))); + EXPECT_TRUE(isnan(FX_MakeDate(0, nan("")))); + EXPECT_TRUE(isnan(FX_MakeDate(INFINITY, 0))); + EXPECT_TRUE(isnan(FX_MakeDate(0, INFINITY))); +} + +TEST(FXDateHelperTest, ParseStringInteger) { + size_t skip = 0; + EXPECT_EQ(123, FX_ParseStringInteger(L"12345", 0, &skip, 3)); + EXPECT_EQ(3u, skip); + + skip = 0; + EXPECT_EQ(12, FX_ParseStringInteger(L"12345", 0, &skip, 2)); + EXPECT_EQ(2u, skip); + + skip = 0; + EXPECT_EQ(12, FX_ParseStringInteger(L"12abc", 0, &skip, 4)); + EXPECT_EQ(2u, skip); + + skip = 1; + EXPECT_EQ(0, FX_ParseStringInteger(L"abc", 0, &skip, 2)); + EXPECT_EQ(0u, skip); + + skip = 1; + EXPECT_EQ(0, FX_ParseStringInteger(L"123", 5, &skip, 2)); + EXPECT_EQ(0u, skip); + + skip = 0; + EXPECT_EQ(123456789, FX_ParseStringInteger(L"123456789abc", 0, &skip, 15)); + EXPECT_EQ(9u, skip); +} + using FXDateHelperFakeTimeTest = FakeTimeTest; TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatWithEmptyParams) { @@ -192,9 +306,13 @@ TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatWithEmptyParams) { EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"", L"", &result)); EXPECT_DOUBLE_EQ(1'587'654'321'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"value", L"", &result)); EXPECT_DOUBLE_EQ(1'587'654'321'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"", L"format", &result)); EXPECT_DOUBLE_EQ(1'587'654'321'000, result); @@ -205,29 +323,43 @@ TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatForValidMonthDay) { EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"01/02/2000", L"mm/dd/yyyy", &result)); EXPECT_DOUBLE_EQ(946'825'521'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"1/2/2000", L"m/d/yyyy", &result)); EXPECT_DOUBLE_EQ(946'825'521'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"1-2-2000", L"m-d-yyyy", &result)); EXPECT_DOUBLE_EQ(946'825'521'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2-1-2000", L"d-m-yyyy", &result)); EXPECT_DOUBLE_EQ(946'825'521'000, result); + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"11/12/2000", L"mm/dd/yyyy", &result)); EXPECT_DOUBLE_EQ(974'041'521'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"11/12/2000", L"m/d/yyyy", &result)); EXPECT_DOUBLE_EQ(974'041'521'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"11-12-2000", L"m-d-yyyy", &result)); EXPECT_DOUBLE_EQ(974'041'521'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"12-11-2000", L"d-m-yyyy", &result)); EXPECT_DOUBLE_EQ(974'041'521'000, result); + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"02/29/2000", L"mm/dd/yyyy", &result)); EXPECT_DOUBLE_EQ(951'836'721'000, result); @@ -235,77 +367,314 @@ TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatForValidMonthDay) { TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatFor12HourTime) { double result = 0.0; - const double kBaseDay = FX_MakeDay(2020, 3, 23); // 12:30:00 PM is 12:30. EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 12:30:00 pm", L"yyyy/mm/dd hh:MM:ss tt", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(12, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'645'000'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 12:30:00 PM", L"yyyy/mm/dd hh:MM:ss tt", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(12, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'645'000'000, result); // 12:30:00 AM is 00:30. + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 12:30:00 am", L"yyyy/mm/dd hh:MM:ss tt", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(0, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'601'800'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 12:30:00 AM", L"yyyy/mm/dd hh:MM:ss tt", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(0, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'601'800'000, result); // 1:30:00 PM is 13:30. + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 1:30:00 pm", L"yyyy/mm/dd h:MM:ss tt", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(13, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'648'600'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 1:30:00 PM", L"yyyy/mm/dd h:MM:ss tt", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(13, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'648'600'000, result); // 1:30:00 AM is 01:30. + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 1:30:00 am", L"yyyy/mm/dd h:MM:ss tt", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(1, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'605'400'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 1:30:00 AM", L"yyyy/mm/dd h:MM:ss tt", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(1, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'605'400'000, result); // Single 't' marker. // 12:30:00 P is 12:30. + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 12:30:00 p", L"yyyy/mm/dd hh:MM:ss t", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(12, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'645'000'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 12:30:00 P", L"yyyy/mm/dd hh:MM:ss t", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(12, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'645'000'000, result); // 12:30:00 A is 00:30. + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 12:30:00 a", L"yyyy/mm/dd hh:MM:ss t", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(0, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'601'800'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 12:30:00 A", L"yyyy/mm/dd hh:MM:ss t", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(0, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'601'800'000, result); // Malformed AM/PM markers should return kBadFormat. + result = 0.0; EXPECT_EQ(ConversionStatus::kBadFormat, FX_ParseDateUsingFormat(L"2020/04/23 1:30:00 xm", L"yyyy/mm/dd h:MM:ss tt", &result)); + result = 0.0; EXPECT_EQ(ConversionStatus::kBadFormat, FX_ParseDateUsingFormat(L"2020/04/23 1:30:00 px", L"yyyy/mm/dd h:MM:ss tt", &result)); + result = 0.0; EXPECT_EQ(ConversionStatus::kBadFormat, FX_ParseDateUsingFormat(L"2020/04/23 1:30:00 x", L"yyyy/mm/dd h:MM:ss t", &result)); } + +TEST_F(FXDateHelperFakeTimeTest, GetDateTime) { + EXPECT_DOUBLE_EQ(1'587'654'321'000.0, FX_GetDateTime()); +} + +TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatForFullMonthNames) { + double result = 0.0; + static constexpr struct { + const wchar_t* input; + double expected; + } kTests[] = { + {L"January 15, 2020", 1'579'100'721'000}, + {L"February 15, 2020", 1'581'779'121'000}, + {L"March 15, 2020", 1'584'284'721'000}, + {L"April 15, 2020", 1'586'963'121'000}, + {L"May 15, 2020", 1'589'555'121'000}, + {L"June 15, 2020", 1'592'233'521'000}, + {L"July 15, 2020", 1'594'825'521'000}, + {L"August 15, 2020", 1'597'503'921'000}, + {L"September 15, 2020", 1'600'182'321'000}, + {L"October 15, 2020", 1'602'774'321'000}, + {L"November 15, 2020", 1'605'452'721'000}, + {L"December 15, 2020", 1'608'044'721'000}, + }; + + for (const auto& test : kTests) { + result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(test.input, L"mmmm dd, yyyy", &result)) + << test.input; + EXPECT_DOUBLE_EQ(test.expected, result) << test.input; + } +} + +TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatForAbbreviatedMonthNames) { + double result = 0.0; + static constexpr struct { + const wchar_t* input; + double expected; + } kTests[] = { + {L"Jan 15, 2020", 1'579'100'721'000}, + {L"feb 15, 2020", 1'581'779'121'000}, + {L"MAR 15, 2020", 1'584'284'721'000}, + {L"Apr 15, 2020", 1'586'963'121'000}, + {L"May 15, 2020", 1'589'555'121'000}, + {L"Jun 15, 2020", 1'592'233'521'000}, + {L"Jul 15, 2020", 1'594'825'521'000}, + {L"Aug 15, 2020", 1'597'503'921'000}, + {L"Sep 15, 2020", 1'600'182'321'000}, + {L"Oct 15, 2020", 1'602'774'321'000}, + {L"Nov 15, 2020", 1'605'452'721'000}, + {L"Dec 15, 2020", 1'608'044'721'000}, + }; + + for (const auto& test : kTests) { + result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(test.input, L"mmm dd, yyyy", &result)) + << test.input; + EXPECT_DOUBLE_EQ(test.expected, result) << test.input; + } +} + +TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatNumericMonthFallback) { + double result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"03 15, 2020", L"mmm dd, yyyy", &result)); + EXPECT_DOUBLE_EQ(1'584'284'721'000, result); + + result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"07 15, 2020", L"mmmm dd, yyyy", &result)); + EXPECT_DOUBLE_EQ(1'594'825'521'000, result); +} + +TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatTwoDigitYear) { + double result = 0.0; + // Year < 50 maps to 2000s. + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"04/23/20", L"mm/dd/yy", &result)); + EXPECT_DOUBLE_EQ(1'587'654'321'000, result); + + result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"04/23/49", L"mm/dd/yy", &result)); + EXPECT_DOUBLE_EQ(2'502'803'121'000, result); + + // Year >= 50 maps to 1900s. + result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"04/23/50", L"mm/dd/yy", &result)); + EXPECT_DOUBLE_EQ(-621'420'879'000, result); + + result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"04/23/99", L"mm/dd/yy", &result)); + EXPECT_DOUBLE_EQ(924'879'921'000, result); + + // 1-digit year 'y' skips 1 character, retaining current year. + result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"x 04/23", L"y mm/dd", &result)); + EXPECT_DOUBLE_EQ(1'587'654'321'000, result); +} + +TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatSeparatorsAndLiterals) { + double result = 0.0; + // Dots, colons, and 24-hour 'HH'. + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"2020.04.23 18:30:45", + L"yyyy.mm.dd HH:MM:ss", &result)); + EXPECT_DOUBLE_EQ(1'587'666'645'000, result); + + // Backslashes. + result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"2020\\04\\23", L"yyyy\\mm\\dd", &result)); + EXPECT_DOUBLE_EQ(1'587'654'321'000, result); + + // token_len == 3 with non-m/y format character skips 3 characters. + result = 0.0; + EXPECT_EQ( + ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"abc/04/23/2020", L"ddd/mm/dd/yyyy", &result)); + EXPECT_DOUBLE_EQ(1'587'654'321'000, result); + + // token_len == 4 with non-m/y format character skips 4 characters. + result = 0.0; + EXPECT_EQ( + ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"abcd/04/23/2020", L"dddd/mm/dd/yyyy", &result)); + EXPECT_DOUBLE_EQ(1'587'654'321'000, result); + + // token_len > 4 matching literal characters. + result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"ddddd/04/23/2020", L"ddddd/mm/dd/yyyy", + &result)); + EXPECT_DOUBLE_EQ(1'587'654'321'000, result); + + // Separators are interchangeable: '-' in value matches '/' in format. + result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"2020-04-23", L"yyyy/mm/dd", &result)); + EXPECT_DOUBLE_EQ(1'587'654'321'000, result); + + // Trailing format characters when value ends are ignored. + result = 0.0; + EXPECT_EQ( + ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"2020/04/23", L"yyyy/mm/dd Extra", &result)); + EXPECT_DOUBLE_EQ(1'587'654'321'000, result); +} + +TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatErrors) { + double result = 0.0; + // Literal mismatch. + EXPECT_EQ(ConversionStatus::kBadFormat, + FX_ParseDateUsingFormat(L"2020/04/23 X 12:00:00", + L"yyyy/mm/dd T HH:MM:ss", &result)); + + // token_len > 4 literal mismatch. + result = 0.0; + EXPECT_EQ(ConversionStatus::kBadFormat, + FX_ParseDateUsingFormat(L"12345/04/23/2020", L"ddddd/mm/dd/yyyy", + &result)); + + // 'yyy' token in format does not advance value_idx, triggering bad format. + result = 0.0; + EXPECT_EQ( + ConversionStatus::kBadFormat, + FX_ParseDateUsingFormat(L"abc 04/23/2020", L"yyy mm/dd/yyyy", &result)); + + // Long non-month word exceeding kLongestFullMonthLength. + result = 0.0; + EXPECT_EQ(ConversionStatus::kBadFormat, + FX_ParseDateUsingFormat(L"Superlonginvalidmonth 15, 2020", + L"mmmm dd, yyyy", &result)); + + // Invalid date components (kBadDate): + // Month out of range (13). + result = 0.0; + EXPECT_EQ(ConversionStatus::kBadDate, + FX_ParseDateUsingFormat(L"2020/13/15", L"yyyy/mm/dd", &result)); + + // Month 0. + result = 0.0; + EXPECT_EQ(ConversionStatus::kBadDate, + FX_ParseDateUsingFormat(L"2020/00/15", L"yyyy/mm/dd", &result)); + + // Day out of range (32). + result = 0.0; + EXPECT_EQ(ConversionStatus::kBadDate, + FX_ParseDateUsingFormat(L"2020/04/32", L"yyyy/mm/dd", &result)); + + // Day 0. + result = 0.0; + EXPECT_EQ(ConversionStatus::kBadDate, + FX_ParseDateUsingFormat(L"2020/04/00", L"yyyy/mm/dd", &result)); + + // Hour out of range (25). + result = 0.0; + EXPECT_EQ(ConversionStatus::kBadDate, + FX_ParseDateUsingFormat(L"2020/04/23 25:00:00", + L"yyyy/mm/dd HH:MM:ss", &result)); + + // Minute out of range (61). + result = 0.0; + EXPECT_EQ(ConversionStatus::kBadDate, + FX_ParseDateUsingFormat(L"2020/04/23 12:61:00", + L"yyyy/mm/dd HH:MM:ss", &result)); + + // Second out of range (61). + result = 0.0; + EXPECT_EQ(ConversionStatus::kBadDate, + FX_ParseDateUsingFormat(L"2020/04/23 12:00:61", + L"yyyy/mm/dd HH:MM:ss", &result)); +} From ec2df7e47df0648304f7985c85fc9368c51f4345 Mon Sep 17 00:00:00 2001 From: Lei Zhang Date: Mon, 9 Nov 2026 16:42:24 -0800 Subject: [PATCH 12/47] Get rid of count variables inside cfx_scanlinecompositor_hwy.cpp Instead of having a separate counter, just keep track of whether `src` has sufficient number of elements. To avoid repeated `n * 4` calculations, save that value as `n4`. Change-Id: I9362e607229be2e5bfe86aecffa36372f24a079a Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163850 Reviewed-by: Andy Phan Commit-Queue: Lei Zhang --- core/fxge/dib/cfx_scanlinecompositor_hwy.cpp | 27 +++++++++----------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/core/fxge/dib/cfx_scanlinecompositor_hwy.cpp b/core/fxge/dib/cfx_scanlinecompositor_hwy.cpp index 848685981..5b47c79de 100644 --- a/core/fxge/dib/cfx_scanlinecompositor_hwy.cpp +++ b/core/fxge/dib/cfx_scanlinecompositor_hwy.cpp @@ -67,16 +67,16 @@ inline uint32_t CompositePixelBgra2Bgra(uint32_t src, uint32_t back) { // src a == 0 -> keep dest else AlphaMerge/AlphaUnion over // Byte spans bitcast to u32 lanes -> no 4-byte scanline alignment needed. void RunBgra2Bgra(pdfium::span src, pdfium::span dest) { - size_t count = src.size() / 4; #if HWY_TARGET != HWY_SCALAR const hn::ScalableTag d; const hn::ScalableTag d8; const size_t n = hn::Lanes(d); // pixels/vector + const size_t n4 = n * 4; const auto m255 = hn::Set(d, 0xFF); // byte mask and the value 255 const auto one = hn::Set(d, 1); const auto zero = hn::Zero(d); - while (count >= n) { + while (src.size() >= n4) { const auto s = hn::BitCast(d, hn::LoadU(d8, src.data())); const auto back = hn::BitCast(d, hn::LoadU(d8, dest.data())); const auto sa = hn::ShiftRight<24>(s); @@ -89,9 +89,8 @@ void RunBgra2Bgra(pdfium::span src, pdfium::span dest) { if (hn::AllTrue(d, hn::Or(copy_src, keep_dest))) { const auto result = hn::IfThenElse(copy_src, s, back); hn::StoreU(hn::BitCast(d8, result), d8, dest.data()); - src = src.subspan(n * 4); - dest = dest.subspan(n * 4); - count -= n; + src = src.subspan(n4); + dest = dest.subspan(n4); continue; } @@ -116,12 +115,11 @@ void RunBgra2Bgra(pdfium::span src, pdfium::span dest) { result = hn::IfThenElse(copy_src, s, result); hn::StoreU(hn::BitCast(d8, result), d8, dest.data()); - src = src.subspan(n * 4); - dest = dest.subspan(n * 4); - count -= n; + src = src.subspan(n4); + dest = dest.subspan(n4); } #endif // HWY_TARGET != HWY_SCALAR - for (size_t i = 0; i < count; ++i) { + while (!src.empty()) { const uint32_t s = FXARGB_GetDIB(src.first<4u>()); const uint32_t back = FXARGB_GetDIB(dest.first<4u>()); FXARGB_SetDIB(dest.first<4u>(), CompositePixelBgra2Bgra(s, back)); @@ -134,22 +132,21 @@ void RunBgra2Bgra(pdfium::span src, pdfium::span dest) { // order required: src and dest both packed BGRA. void RunBgra2BgrxForceOpaque(pdfium::span src, pdfium::span dest) { - size_t count = src.size() / 4; #if HWY_TARGET != HWY_SCALAR const hn::ScalableTag d; const hn::ScalableTag d8; const size_t n = hn::Lanes(d); + const size_t n4 = n * 4; const auto alpha_ff = hn::Set(d, 0xFF000000u); - while (count >= n) { + while (src.size() >= n4) { const auto v = hn::BitCast(d, hn::LoadU(d8, src.data())); hn::StoreU(hn::BitCast(d8, hn::Or(v, alpha_ff)), d8, dest.data()); - src = src.subspan(n * 4); - dest = dest.subspan(n * 4); - count -= n; + src = src.subspan(n4); + dest = dest.subspan(n4); } #endif // HWY_TARGET != HWY_SCALAR - for (size_t i = 0; i < count; ++i) { + while (!src.empty()) { dest[0] = src[0]; dest[1] = src[1]; dest[2] = src[2]; From 2697090b6b414b253807434fc85893fed4c6a265 Mon Sep 17 00:00:00 2001 From: Lei Zhang Date: Mon, 9 Nov 2026 17:39:32 -0800 Subject: [PATCH 13/47] Fix UNSAFE_TODO() in CPDF_Image::SetImage() Split the 24-bpp and 32-bpp cases into separate branches instead of using raw pointer arithmetic in a single loop: - For the 24-bpp case, use fxcodec::ReverseRGB() per row. (Which can use libyuv internally.) - For the 32-bpp case, use libyuv::ARGBToRAW() when libyuv is available, or fall back to fxcrt::Zip() per row. Access to ARGBToRAW() goes through core/fxge/fx_libyuv_wrappers.h. This CL is AI generated. Change-Id: I6d42975104def182b07fe66535cea82d84c809e2 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/162750 Reviewed-by: Tom Sepez Commit-Queue: Lei Zhang --- core/fpdfapi/page/cpdf_image.cpp | 40 ++++++++++++++++++++++---------- core/fxge/fx_libyuv_wrappers.cpp | 13 +++++++++++ core/fxge/fx_libyuv_wrappers.h | 7 ++++++ 3 files changed, 48 insertions(+), 12 deletions(-) diff --git a/core/fpdfapi/page/cpdf_image.cpp b/core/fpdfapi/page/cpdf_image.cpp index bcc169229..affcaf026 100644 --- a/core/fpdfapi/page/cpdf_image.cpp +++ b/core/fpdfapi/page/cpdf_image.cpp @@ -26,10 +26,10 @@ #include "core/fpdfapi/parser/cpdf_reference.h" #include "core/fpdfapi/parser/cpdf_stream.h" #include "core/fpdfapi/parser/cpdf_string.h" +#include "core/fxcodec/fx_codec.h" #include "core/fxcodec/jpeg/jpegmodule.h" #include "core/fxcrt/check.h" #include "core/fxcrt/check_op.h" -#include "core/fxcrt/compiler_specific.h" #include "core/fxcrt/data_vector.h" #include "core/fxcrt/fx_2d_size.h" #include "core/fxcrt/fx_ceil_div.h" @@ -40,6 +40,12 @@ #include "core/fxge/dib/cfx_dibitmap.h" #include "core/fxge/dib/fx_dib.h" +#if defined(PDF_USE_LIBYUV) +#include "core/fxge/fx_libyuv_wrappers.h" +#else +#include "core/fxcrt/zip.h" +#endif + // static bool CPDF_Image::IsValidJpegComponent(int32_t comps) { return comps == 1 || comps == 3 || comps == 4; @@ -295,23 +301,33 @@ void CPDF_Image::SetImage(const RetainPtr& pBitmap) { dest_span = fxcrt::spancpy(dest_span, src_span.first(dest_pitch)); src_span = src_span.subspan(static_cast(src_pitch)); } + } else if (bpp == 24) { + for (int32_t row = 0; row < BitmapHeight; row++) { + fxcodec::ReverseRGB(dest_span, src_span, BitmapWidth); + dest_span = dest_span.subspan(dest_pitch); + src_span = src_span.subspan(static_cast(src_pitch)); + } } else { - const size_t src_step = bpp == 24 ? 3 : 4; +#if defined(PDF_USE_LIBYUV) + pdfium::ARGBToRAW(src_span, src_pitch, dest_span, + pdfium::checked_cast(dest_pitch), BitmapWidth, + BitmapHeight); +#else for (int32_t row = 0; row < BitmapHeight; row++) { - uint8_t* dest_ptr = dest_span.data(); - const uint8_t* src_ptr = src_span.data(); - for (int32_t column = 0; column < BitmapWidth; column++) { - UNSAFE_TODO({ - dest_ptr[0] = src_ptr[2]; - dest_ptr[1] = src_ptr[1]; - dest_ptr[2] = src_ptr[0]; - dest_ptr += 3; - src_ptr += src_step; - }); + auto src_row = + fxcrt::reinterpret_span>(src_span) + .first(static_cast(BitmapWidth)); + auto dest_row = + fxcrt::reinterpret_span>(dest_span); + for (auto [input, output] : fxcrt::Zip(src_row, dest_row)) { + output.red = input.red; + output.green = input.green; + output.blue = input.blue; } dest_span = dest_span.subspan(dest_pitch); src_span = src_span.subspan(static_cast(src_pitch)); } +#endif } stream_ = diff --git a/core/fxge/fx_libyuv_wrappers.cpp b/core/fxge/fx_libyuv_wrappers.cpp index 009b3658f..67625eaf5 100644 --- a/core/fxge/fx_libyuv_wrappers.cpp +++ b/core/fxge/fx_libyuv_wrappers.cpp @@ -91,6 +91,19 @@ void ARGBToRGB24(pdfium::span src_span, CHECK_EQ(ret, 0); } +void ARGBToRAW(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height) { + CHECK_GE(src_span.size(), GetPlaneBytes(src_stride, width, height, 4)); + CHECK_GE(dst_span.size(), GetPlaneBytes(dst_stride, width, height, 3)); + int ret = libyuv::ARGBToRAW(src_span.data(), src_stride, dst_span.data(), + dst_stride, width, height); + CHECK_EQ(ret, 0); +} + void ARGBExtractAlpha(pdfium::span src_span, int src_stride, pdfium::span dst_span, diff --git a/core/fxge/fx_libyuv_wrappers.h b/core/fxge/fx_libyuv_wrappers.h index 859490e7c..36c737589 100644 --- a/core/fxge/fx_libyuv_wrappers.h +++ b/core/fxge/fx_libyuv_wrappers.h @@ -39,6 +39,13 @@ void ARGBToRGB24(pdfium::span src_span, int width, int height); +void ARGBToRAW(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height); + void ARGBExtractAlpha(pdfium::span src_span, int src_stride, pdfium::span dst_span, From e3fba831d9ecaa1cb2c5f133b8713ba62816e3d2 Mon Sep 17 00:00:00 2001 From: Tom Sepez Date: Tue, 10 Nov 2026 09:11:52 -0800 Subject: [PATCH 14/47] Reduce total number of persistents in cfxjse_engine.h Instead of vector of persistent, use a single persistent into a wrapped vector of members. Change-Id: Ic44ae0cb1adbf81dc8c7cc2fe3b9f28b742d0ea1 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163831 Commit-Queue: Tom Sepez Reviewed-by: Lei Zhang --- fxjs/xfa/cfxjse_engine.cpp | 15 +++++++++------ fxjs/xfa/cfxjse_engine.h | 2 +- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/fxjs/xfa/cfxjse_engine.cpp b/fxjs/xfa/cfxjse_engine.cpp index fd2d605be..01a362e0c 100644 --- a/fxjs/xfa/cfxjse_engine.cpp +++ b/fxjs/xfa/cfxjse_engine.cpp @@ -151,6 +151,8 @@ CFXJSE_Engine::CFXJSE_Engine(CXFA_Document* document, v8::Isolate* isolate) &kGlobalClassDescriptor, document->GetRoot()->JSObject(), nullptr)), + up_object_array_(cppgc::MakeGarbageCollected>( + document->GetHeap()->GetAllocationHandle())), node_helper_(std::make_unique()), resolve_processor_( std::make_unique(this, node_helper_.get())) { @@ -615,11 +617,12 @@ CXFA_Script::Type CFXJSE_Engine::GetType() { } void CFXJSE_Engine::AddObjectToUpArray(CXFA_Node* pNode) { - up_object_array_.push_back(pNode); + up_object_array_->storage.push_back(pNode); } CXFA_Node* CFXJSE_Engine::LastObjectFromUpArray() { - return !up_object_array_.empty() ? up_object_array_.back() : nullptr; + return !up_object_array_->storage.empty() ? up_object_array_->storage.back() + : nullptr; } CFXJSE_Context* CFXJSE_Engine::CreateVariablesContext(CXFA_Script* pScriptNode, @@ -771,10 +774,10 @@ CFXJSE_Engine::ResolveObjectsWithBindNode(CXFA_Object* refObject, !!(dwStyles & Mask{XFA_ResolveFlag::kParent, XFA_ResolveFlag::kSiblings}); if (script_type_ != CXFA_Script::Type::Formcalc || bParentOrSiblings) { - up_object_array_.clear(); + up_object_array_->storage.clear(); } if (refObject && refObject->IsNode() && bParentOrSiblings) { - up_object_array_.push_back(refObject->AsNode()); + up_object_array_->storage.push_back(refObject->AsNode()); } ResolveResult result; @@ -873,8 +876,8 @@ CFXJSE_Engine::ResolveObjectsWithBindNode(CXFA_Object* refObject, rndFind.result_.objects.front() = ToObject(GetIsolate(), pValue); } } - if (!up_object_array_.empty()) { - up_object_array_.pop_back(); + if (!up_object_array_->storage.empty()) { + up_object_array_->storage.pop_back(); } ret_objects->storage.insert(ret_objects->storage.end(), rndFind.result_.objects.begin(), diff --git a/fxjs/xfa/cfxjse_engine.h b/fxjs/xfa/cfxjse_engine.h index 683b849d8..758b111f0 100644 --- a/fxjs/xfa/cfxjse_engine.h +++ b/fxjs/xfa/cfxjse_engine.h @@ -225,7 +225,7 @@ class CFXJSE_Engine final : public CFX_IsolateWrapper { map_variable_to_context_; cppgc::Persistent target_; UnownedPtr event_param_; - std::vector> up_object_array_; + cppgc::Persistent> up_object_array_; cppgc::Persistent> script_node_array_; std::unique_ptr const node_helper_; std::unique_ptr const resolve_processor_; From b2c765e325bffc15b3d61bef84483000127ff50d Mon Sep 17 00:00:00 2001 From: Tom Sepez Date: Tue, 10 Nov 2026 10:45:03 -0800 Subject: [PATCH 15/47] Add unit tests for FormCalc loops and control flow expressions Test FormCalc parser and AST code generation for while loops, for-loops (upto with step, and downto), foreach-in loops, do-blocks, and break/continue statements. Also add error parsing test cases for malformed loop and block syntax. Change-Id: I201fc3587b8f3e5d02120a1cfce512e2ebc54fca Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163470 Commit-Queue: Tom Sepez Reviewed-by: Lei Zhang --- .../formcalc/cxfa_fmexpression_unittest.cpp | 39 ++ xfa/fxfa/formcalc/cxfa_fmparser_unittest.cpp | 421 +++++++++++++++--- 2 files changed, 407 insertions(+), 53 deletions(-) diff --git a/xfa/fxfa/formcalc/cxfa_fmexpression_unittest.cpp b/xfa/fxfa/formcalc/cxfa_fmexpression_unittest.cpp index f68c599b5..545f1a173 100644 --- a/xfa/fxfa/formcalc/cxfa_fmexpression_unittest.cpp +++ b/xfa/fxfa/formcalc/cxfa_fmexpression_unittest.cpp @@ -171,3 +171,42 @@ s = pfm_rt.var_filter(s); )***", accumulator.MakeString()); } + +TEST_F(FMExpressionTest, BreakExpression) { + CXFA_FMToJavaScriptDepth::Reset(); + WideTextBuffer accumulator; + + auto* expr = cppgc::MakeGarbageCollected( + heap()->GetAllocationHandle()); + EXPECT_TRUE(expr->ToJavaScript( + &accumulator, CXFA_FMAssignExpression::ReturnType::kInferred)); + EXPECT_EQ(L"pfm_ret = 0;\nbreak;\n", accumulator.MakeString()); +} + +TEST_F(FMExpressionTest, ContinueExpression) { + CXFA_FMToJavaScriptDepth::Reset(); + WideTextBuffer accumulator; + + auto* expr = cppgc::MakeGarbageCollected( + heap()->GetAllocationHandle()); + EXPECT_TRUE(expr->ToJavaScript( + &accumulator, CXFA_FMAssignExpression::ReturnType::kInferred)); + EXPECT_EQ(L"pfm_ret = 0;\ncontinue;\n", accumulator.MakeString()); +} + +TEST_F(FMExpressionTest, DoExpression) { + CXFA_FMToJavaScriptDepth::Reset(); + WideTextBuffer accumulator; + + std::vector> expressions; + expressions.push_back(cppgc::MakeGarbageCollected( + heap()->GetAllocationHandle())); + auto* block = cppgc::MakeGarbageCollected( + heap()->GetAllocationHandle(), std::move(expressions)); + auto* expr = cppgc::MakeGarbageCollected( + heap()->GetAllocationHandle(), block); + + EXPECT_TRUE(expr->ToJavaScript( + &accumulator, CXFA_FMAssignExpression::ReturnType::kInferred)); + EXPECT_EQ(L"{\npfm_ret = 0;\nbreak;\n}\n", accumulator.MakeString()); +} diff --git a/xfa/fxfa/formcalc/cxfa_fmparser_unittest.cpp b/xfa/fxfa/formcalc/cxfa_fmparser_unittest.cpp index 53dc9aab5..b2653e534 100644 --- a/xfa/fxfa/formcalc/cxfa_fmparser_unittest.cpp +++ b/xfa/fxfa/formcalc/cxfa_fmparser_unittest.cpp @@ -41,7 +41,7 @@ TEST_F(CXFAFMParserTest, CommentOnlyIsError) { } TEST_F(CXFAFMParserTest, CommentThenValue) { - const wchar_t ret[] = + constexpr wchar_t kExpected[] = LR"***((function() { let pfm_method_runner = function(obj, cb) { if (pfm_rt.is_ary(obj)) { @@ -67,11 +67,11 @@ return pfm_rt.get_val(pfm_ret); CXFA_FMToJavaScriptDepth::Reset(); std::optional buf = ast->ToJavaScript(); ASSERT_TRUE(buf.has_value()); - EXPECT_EQ(ret, buf.value().MakeString()); + EXPECT_EQ(kExpected, buf.value().MakeString()); } TEST_F(CXFAFMParserTest, Parse) { - const wchar_t input[] = + constexpr wchar_t kInput[] = LR"***($ = Avg (-3, 5, -6, 12, -13); $ = Avg (Table2..Row[*].Cell1); if ($ ne -1)then @@ -83,7 +83,7 @@ else endif $)***"; - const wchar_t ret[] = + constexpr wchar_t kExpected[] = LR"***((function() { let pfm_method_runner = function(obj, cb) { if (pfm_rt.is_ary(obj)) { @@ -128,7 +128,7 @@ pfm_ret = this; return pfm_rt.get_val(pfm_ret); }).call(this);)***"; - CXFA_FMLexer lexer(input); + CXFA_FMLexer lexer(kInput); CXFA_FMParser parser(heap(), &lexer); CXFA_FMAST* ast = parser.Parse(); ASSERT_TRUE(ast); @@ -137,7 +137,7 @@ return pfm_rt.get_val(pfm_ret); CXFA_FMToJavaScriptDepth::Reset(); std::optional buf = ast->ToJavaScript(); ASSERT_TRUE(buf.has_value()); - EXPECT_EQ(ret, buf.value().AsStringView()); + EXPECT_EQ(kExpected, buf.value().AsStringView()); } TEST_F(CXFAFMParserTest, MaxParseDepth) { @@ -168,12 +168,12 @@ TEST_F(CXFAFMParserTest, MultipleAssignmentIsNotAllowed) { } TEST_F(CXFAFMParserTest, ParseFuncWithParams) { - const wchar_t input[] = + constexpr wchar_t kInput[] = LR"***(func MyFunction(param1, param2) do param1 * param2 endfunc)***"; - const wchar_t ret[] = + constexpr wchar_t kExpected[] = LR"***((function() { let pfm_method_runner = function(obj, cb) { if (pfm_rt.is_ary(obj)) { @@ -194,7 +194,7 @@ return pfm_ret; return pfm_rt.get_val(pfm_ret); }).call(this);)***"; - CXFA_FMLexer lexer(input); + CXFA_FMLexer lexer(kInput); CXFA_FMParser parser(heap(), &lexer); CXFA_FMAST* ast = parser.Parse(); ASSERT_TRUE(ast); @@ -203,16 +203,16 @@ return pfm_rt.get_val(pfm_ret); CXFA_FMToJavaScriptDepth::Reset(); std::optional buf = ast->ToJavaScript(); ASSERT_TRUE(buf.has_value()); - EXPECT_EQ(ret, buf.value().MakeString()); + EXPECT_EQ(kExpected, buf.value().MakeString()); } TEST_F(CXFAFMParserTest, ParseFuncWithoutParams) { - const wchar_t input[] = + constexpr wchar_t kInput[] = LR"***(func MyFunction() do 42 endfunc)***"; - const wchar_t ret[] = + constexpr wchar_t kExpected[] = LR"***((function() { let pfm_method_runner = function(obj, cb) { if (pfm_rt.is_ary(obj)) { @@ -233,7 +233,7 @@ return pfm_ret; return pfm_rt.get_val(pfm_ret); }).call(this);)***"; - CXFA_FMLexer lexer(input); + CXFA_FMLexer lexer(kInput); CXFA_FMParser parser(heap(), &lexer); CXFA_FMAST* ast = parser.Parse(); ASSERT_TRUE(ast); @@ -242,16 +242,16 @@ return pfm_rt.get_val(pfm_ret); CXFA_FMToJavaScriptDepth::Reset(); std::optional buf = ast->ToJavaScript(); ASSERT_TRUE(buf.has_value()); - EXPECT_EQ(ret, buf.value().MakeString()); + EXPECT_EQ(kExpected, buf.value().MakeString()); } TEST_F(CXFAFMParserTest, ParseFuncWithBadParamsList) { - const wchar_t input[] = + constexpr wchar_t kInput[] = LR"***(func MyFunction(param1,) do param1 * param2 endfunc)***"; - CXFA_FMLexer lexer(input); + CXFA_FMLexer lexer(kInput); CXFA_FMParser parser(heap(), &lexer); CXFA_FMAST* ast = parser.Parse(); ASSERT_TRUE(ast == nullptr); @@ -259,8 +259,8 @@ endfunc)***"; } TEST_F(CXFAFMParserTest, ParseBadIfExpression) { - const wchar_t input[] = L"if ( then"; - CXFA_FMLexer lexer(input); + constexpr wchar_t kInput[] = L"if ( then"; + CXFA_FMLexer lexer(kInput); CXFA_FMParser parser(heap(), &lexer); CXFA_FMAST* ast = parser.Parse(); ASSERT_TRUE(ast == nullptr); @@ -268,11 +268,11 @@ TEST_F(CXFAFMParserTest, ParseBadIfExpression) { } TEST_F(CXFAFMParserTest, ParseBadElseIfExpression) { - const wchar_t input[] = + constexpr wchar_t kInput[] = LR"***(if ($ ne -1) then" elseif( then)***"; - CXFA_FMLexer lexer(input); + CXFA_FMLexer lexer(kInput); CXFA_FMParser parser(heap(), &lexer); CXFA_FMAST* ast = parser.Parse(); ASSERT_TRUE(ast == nullptr); @@ -280,10 +280,11 @@ elseif( then)***"; } TEST_F(CXFAFMParserTest, ParseDepthWithWideTree) { - const wchar_t input[] = L"a <> b <> c <> d <> e <> f <> g <> h <> i <> j"; + constexpr wchar_t kInput[] = + L"a <> b <> c <> d <> e <> f <> g <> h <> i <> j"; { - CXFA_FMLexer lexer(input); + CXFA_FMLexer lexer(kInput); CXFA_FMParser parser(heap(), &lexer); CXFA_FMAST* ast = parser.Parse(); ASSERT_TRUE(ast); @@ -291,7 +292,7 @@ TEST_F(CXFAFMParserTest, ParseDepthWithWideTree) { } { - CXFA_FMLexer lexer(input); + CXFA_FMLexer lexer(kInput); CXFA_FMParser parser(heap(), &lexer); parser.SetMaxParseDepthForTest(5); CXFA_FMAST* ast = parser.Parse(); @@ -301,8 +302,8 @@ TEST_F(CXFAFMParserTest, ParseDepthWithWideTree) { } TEST_F(CXFAFMParserTest, ParseCallSmall) { - const wchar_t input[] = L"i.f(O)"; - const wchar_t ret[] = + constexpr wchar_t kInput[] = L"i.f(O)"; + constexpr wchar_t kExpected[] = LR"***((function() { let pfm_method_runner = function(obj, cb) { if (pfm_rt.is_ary(obj)) { @@ -323,7 +324,7 @@ pfm_ret = pfm_rt.get_val((function() { return pfm_rt.get_val(pfm_ret); }).call(this);)***"; - CXFA_FMLexer lexer(input); + CXFA_FMLexer lexer(kInput); CXFA_FMParser parser(heap(), &lexer); CXFA_FMAST* ast = parser.Parse(); EXPECT_FALSE(parser.HasError()); @@ -331,12 +332,12 @@ return pfm_rt.get_val(pfm_ret); CXFA_FMToJavaScriptDepth::Reset(); std::optional buf = ast->ToJavaScript(); ASSERT_TRUE(buf.has_value()); - EXPECT_EQ(ret, buf.value().MakeString()); + EXPECT_EQ(kExpected, buf.value().MakeString()); } TEST_F(CXFAFMParserTest, ParseCallBig) { - const wchar_t input[] = L"i.f(O.e(O.e(O)))"; - const wchar_t ret[] = + constexpr wchar_t kInput[] = L"i.f(O.e(O.e(O)))"; + constexpr wchar_t kExpected[] = LR"***((function() { let pfm_method_runner = function(obj, cb) { if (pfm_rt.is_ary(obj)) { @@ -365,7 +366,7 @@ pfm_ret = pfm_rt.get_val((function() { return pfm_rt.get_val(pfm_ret); }).call(this);)***"; - CXFA_FMLexer lexer(input); + CXFA_FMLexer lexer(kInput); CXFA_FMParser parser(heap(), &lexer); CXFA_FMAST* ast = parser.Parse(); EXPECT_FALSE(parser.HasError()); @@ -373,12 +374,12 @@ return pfm_rt.get_val(pfm_ret); CXFA_FMToJavaScriptDepth::Reset(); std::optional buf = ast->ToJavaScript(); ASSERT_TRUE(buf.has_value()); - EXPECT_EQ(ret, buf.value().MakeString()); + EXPECT_EQ(kExpected, buf.value().MakeString()); } TEST_F(CXFAFMParserTest, ParseVar) { - const wchar_t input[] = LR"(var s = "")"; - const wchar_t ret[] = + constexpr wchar_t kInput[] = LR"(var s = "")"; + constexpr wchar_t kExpected[] = LR"***((function() { let pfm_method_runner = function(obj, cb) { if (pfm_rt.is_ary(obj)) { @@ -397,7 +398,7 @@ pfm_ret = s; return pfm_rt.get_val(pfm_ret); }).call(this);)***"; - CXFA_FMLexer lexer(input); + CXFA_FMLexer lexer(kInput); CXFA_FMParser parser(heap(), &lexer); CXFA_FMAST* ast = parser.Parse(); EXPECT_FALSE(parser.HasError()); @@ -405,12 +406,12 @@ return pfm_rt.get_val(pfm_ret); CXFA_FMToJavaScriptDepth::Reset(); std::optional buf = ast->ToJavaScript(); ASSERT_TRUE(buf.has_value()); - EXPECT_EQ(ret, buf.value().MakeString()); + EXPECT_EQ(kExpected, buf.value().MakeString()); } TEST_F(CXFAFMParserTest, ParseFunctionCallNoArguments) { - const wchar_t input[] = L"P.x()"; - const wchar_t ret[] = + constexpr wchar_t kInput[] = L"P.x()"; + constexpr wchar_t kExpected[] = LR"***((function() { let pfm_method_runner = function(obj, cb) { if (pfm_rt.is_ary(obj)) { @@ -431,7 +432,7 @@ pfm_ret = pfm_rt.get_val((function() { return pfm_rt.get_val(pfm_ret); }).call(this);)***"; - CXFA_FMLexer lexer(input); + CXFA_FMLexer lexer(kInput); CXFA_FMParser parser(heap(), &lexer); CXFA_FMAST* ast = parser.Parse(); EXPECT_FALSE(parser.HasError()); @@ -439,12 +440,12 @@ return pfm_rt.get_val(pfm_ret); CXFA_FMToJavaScriptDepth::Reset(); std::optional buf = ast->ToJavaScript(); ASSERT_TRUE(buf.has_value()); - EXPECT_EQ(ret, buf.value().MakeString()); + EXPECT_EQ(kExpected, buf.value().MakeString()); } TEST_F(CXFAFMParserTest, ParseFunctionCallSingleArgument) { - const wchar_t input[] = L"P.x(foo)"; - const wchar_t ret[] = + constexpr wchar_t kInput[] = L"P.x(foo)"; + constexpr wchar_t kExpected[] = LR"***((function() { let pfm_method_runner = function(obj, cb) { if (pfm_rt.is_ary(obj)) { @@ -465,7 +466,7 @@ pfm_ret = pfm_rt.get_val((function() { return pfm_rt.get_val(pfm_ret); }).call(this);)***"; - CXFA_FMLexer lexer(input); + CXFA_FMLexer lexer(kInput); CXFA_FMParser parser(heap(), &lexer); CXFA_FMAST* ast = parser.Parse(); EXPECT_FALSE(parser.HasError()); @@ -473,12 +474,12 @@ return pfm_rt.get_val(pfm_ret); CXFA_FMToJavaScriptDepth::Reset(); std::optional buf = ast->ToJavaScript(); ASSERT_TRUE(buf.has_value()); - EXPECT_EQ(ret, buf.value().MakeString()); + EXPECT_EQ(kExpected, buf.value().MakeString()); } TEST_F(CXFAFMParserTest, ParseFunctionCallMultipleArguments) { - const wchar_t input[] = L"P.x(foo, bar, baz)"; - const wchar_t ret[] = + constexpr wchar_t kInput[] = L"P.x(foo, bar, baz)"; + constexpr wchar_t kExpected[] = LR"***((function() { let pfm_method_runner = function(obj, cb) { if (pfm_rt.is_ary(obj)) { @@ -499,7 +500,7 @@ pfm_ret = pfm_rt.get_val((function() { return pfm_rt.get_val(pfm_ret); }).call(this);)***"; - CXFA_FMLexer lexer(input); + CXFA_FMLexer lexer(kInput); CXFA_FMParser parser(heap(), &lexer); CXFA_FMAST* ast = parser.Parse(); EXPECT_FALSE(parser.HasError()); @@ -507,12 +508,12 @@ return pfm_rt.get_val(pfm_ret); CXFA_FMToJavaScriptDepth::Reset(); std::optional buf = ast->ToJavaScript(); ASSERT_TRUE(buf.has_value()); - EXPECT_EQ(ret, buf.value().MakeString()); + EXPECT_EQ(kExpected, buf.value().MakeString()); } TEST_F(CXFAFMParserTest, ParseFunctionCallMissingCommas) { - const wchar_t input[] = L"P.x(!foo!bar!baz)"; - CXFA_FMLexer lexer(input); + constexpr wchar_t kInput[] = L"P.x(!foo!bar!baz)"; + CXFA_FMLexer lexer(kInput); CXFA_FMParser parser(heap(), &lexer); CXFA_FMAST* ast = parser.Parse(); ASSERT_TRUE(ast == nullptr); @@ -520,8 +521,8 @@ TEST_F(CXFAFMParserTest, ParseFunctionCallMissingCommas) { } TEST_F(CXFAFMParserTest, ParseFunctionCallTrailingComma) { - const wchar_t input[] = L"P.x(foo,bar,baz,)"; - CXFA_FMLexer lexer(input); + constexpr wchar_t kInput[] = L"P.x(foo,bar,baz,)"; + CXFA_FMLexer lexer(kInput); CXFA_FMParser parser(heap(), &lexer); CXFA_FMAST* ast = parser.Parse(); ASSERT_TRUE(ast == nullptr); @@ -529,10 +530,324 @@ TEST_F(CXFAFMParserTest, ParseFunctionCallTrailingComma) { } TEST_F(CXFAFMParserTest, ParseFunctionCallExtraComma) { - const wchar_t input[] = L"P.x(foo,bar,,baz)"; - CXFA_FMLexer lexer(input); + constexpr wchar_t kInput[] = L"P.x(foo,bar,,baz)"; + CXFA_FMLexer lexer(kInput); CXFA_FMParser parser(heap(), &lexer); CXFA_FMAST* ast = parser.Parse(); ASSERT_TRUE(ast == nullptr); EXPECT_TRUE(parser.HasError()); } + +TEST_F(CXFAFMParserTest, ParseWhileLoop) { + constexpr wchar_t kInput[] = L"while (i < 10) do\n i = i + 1\nendwhile"; + constexpr wchar_t kExpected[] = + LR"***((function() { +let pfm_method_runner = function(obj, cb) { + if (pfm_rt.is_ary(obj)) { + let pfm_method_return = null; + for (var idx = obj.length -1; idx > 1; idx--) { + pfm_method_return = cb(obj[idx]); + } + return pfm_method_return; + } + return cb(obj); +}; +var pfm_ret = null; +pfm_ret = 0; +while (pfm_rt.lt_op(i, 10)) +{ +if (pfm_rt.is_obj(i)) +{ +pfm_ret = pfm_rt.asgn_val_op(i, pfm_rt.plus_op(i, 1)); +} +else +{ +pfm_ret = i = pfm_rt.asgn_val_op(i, pfm_rt.plus_op(i, 1)); +} +} +return pfm_rt.get_val(pfm_ret); +}).call(this);)***"; + CXFA_FMLexer lexer(kInput); + CXFA_FMParser parser(heap(), &lexer); + CXFA_FMAST* ast = parser.Parse(); + ASSERT_TRUE(ast); + EXPECT_FALSE(parser.HasError()); + + CXFA_FMToJavaScriptDepth::Reset(); + std::optional buf = ast->ToJavaScript(); + ASSERT_TRUE(buf.has_value()); + EXPECT_EQ(kExpected, buf.value().MakeString()); +} + +TEST_F(CXFAFMParserTest, ParseWhileWithBreakAndContinue) { + constexpr wchar_t kInput[] = + L"while (i < 10) do\n if (i == 5) then\n break\n endif\n " + L"continue\nendwhile"; + constexpr wchar_t kExpected[] = + LR"***((function() { +let pfm_method_runner = function(obj, cb) { + if (pfm_rt.is_ary(obj)) { + let pfm_method_return = null; + for (var idx = obj.length -1; idx > 1; idx--) { + pfm_method_return = cb(obj[idx]); + } + return pfm_method_return; + } + return cb(obj); +}; +var pfm_ret = null; +pfm_ret = 0; +while (pfm_rt.lt_op(i, 10)) +{ +if (pfm_rt.get_val(pfm_rt.eq_op(i, 5))) +{ +pfm_ret = 0; +break; +} +pfm_ret = 0; +continue; +} +return pfm_rt.get_val(pfm_ret); +}).call(this);)***"; + CXFA_FMLexer lexer(kInput); + CXFA_FMParser parser(heap(), &lexer); + CXFA_FMAST* ast = parser.Parse(); + ASSERT_TRUE(ast); + EXPECT_FALSE(parser.HasError()); + + CXFA_FMToJavaScriptDepth::Reset(); + std::optional buf = ast->ToJavaScript(); + ASSERT_TRUE(buf.has_value()); + EXPECT_EQ(kExpected, buf.value().MakeString()); +} + +TEST_F(CXFAFMParserTest, ParseForLoopUptoWithStep) { + constexpr wchar_t kInput[] = + L"for i = 1 upto 10 step 2 do\n sum = sum + i\nendfor"; + constexpr wchar_t kExpected[] = + LR"***((function() { +let pfm_method_runner = function(obj, cb) { + if (pfm_rt.is_ary(obj)) { + let pfm_method_return = null; + for (var idx = obj.length -1; idx > 1; idx--) { + pfm_method_return = cb(obj[idx]); + } + return pfm_method_return; + } + return cb(obj); +}; +var pfm_ret = null; +pfm_ret = 0; +{ +var i = null; +for (i = pfm_rt.get_val(1); i <= pfm_rt.get_val(10); i += pfm_rt.get_val(2)) +{ +if (pfm_rt.is_obj(sum)) +{ +pfm_ret = pfm_rt.asgn_val_op(sum, pfm_rt.plus_op(sum, i)); +} +else +{ +pfm_ret = sum = pfm_rt.asgn_val_op(sum, pfm_rt.plus_op(sum, i)); +} +} +} +return pfm_rt.get_val(pfm_ret); +}).call(this);)***"; + CXFA_FMLexer lexer(kInput); + CXFA_FMParser parser(heap(), &lexer); + CXFA_FMAST* ast = parser.Parse(); + ASSERT_TRUE(ast); + EXPECT_FALSE(parser.HasError()); + + CXFA_FMToJavaScriptDepth::Reset(); + std::optional buf = ast->ToJavaScript(); + ASSERT_TRUE(buf.has_value()); + EXPECT_EQ(kExpected, buf.value().MakeString()); +} + +TEST_F(CXFAFMParserTest, ParseForLoopDownto) { + constexpr wchar_t kInput[] = + L"for i = 10 downto 1 do\n sum = sum + i\nendfor"; + constexpr wchar_t kExpected[] = + LR"***((function() { +let pfm_method_runner = function(obj, cb) { + if (pfm_rt.is_ary(obj)) { + let pfm_method_return = null; + for (var idx = obj.length -1; idx > 1; idx--) { + pfm_method_return = cb(obj[idx]); + } + return pfm_method_return; + } + return cb(obj); +}; +var pfm_ret = null; +pfm_ret = 0; +{ +var i = null; +for (i = pfm_rt.get_val(10); i >= pfm_rt.get_val(1); i -= 1) +{ +if (pfm_rt.is_obj(sum)) +{ +pfm_ret = pfm_rt.asgn_val_op(sum, pfm_rt.plus_op(sum, i)); +} +else +{ +pfm_ret = sum = pfm_rt.asgn_val_op(sum, pfm_rt.plus_op(sum, i)); +} +} +} +return pfm_rt.get_val(pfm_ret); +}).call(this);)***"; + CXFA_FMLexer lexer(kInput); + CXFA_FMParser parser(heap(), &lexer); + CXFA_FMAST* ast = parser.Parse(); + ASSERT_TRUE(ast); + EXPECT_FALSE(parser.HasError()); + + CXFA_FMToJavaScriptDepth::Reset(); + std::optional buf = ast->ToJavaScript(); + ASSERT_TRUE(buf.has_value()); + EXPECT_EQ(kExpected, buf.value().MakeString()); +} + +TEST_F(CXFAFMParserTest, ParseForeachLoop) { + constexpr wchar_t kInput[] = + L"foreach item in (1, 2, 3)\n sum = sum + item\nendfor"; + constexpr wchar_t kExpected[] = + LR"***((function() { +let pfm_method_runner = function(obj, cb) { + if (pfm_rt.is_ary(obj)) { + let pfm_method_return = null; + for (var idx = obj.length -1; idx > 1; idx--) { + pfm_method_return = cb(obj[idx]); + } + return pfm_method_return; + } + return cb(obj); +}; +var pfm_ret = null; +pfm_ret = 0; +{ +var item = null; +var pfm_ary = pfm_rt.concat_obj(1, 2, 3); +var pfm_ary_idx = 0; +while(pfm_ary_idx < pfm_ary.length) +{ +item = pfm_ary[pfm_ary_idx++]; +{ +if (pfm_rt.is_obj(sum)) +{ +pfm_ret = pfm_rt.asgn_val_op(sum, pfm_rt.plus_op(sum, item)); +} +else +{ +pfm_ret = sum = pfm_rt.asgn_val_op(sum, pfm_rt.plus_op(sum, item)); +} +} +} +} +return pfm_rt.get_val(pfm_ret); +}).call(this);)***"; + CXFA_FMLexer lexer(kInput); + CXFA_FMParser parser(heap(), &lexer); + CXFA_FMAST* ast = parser.Parse(); + ASSERT_TRUE(ast); + EXPECT_FALSE(parser.HasError()); + + CXFA_FMToJavaScriptDepth::Reset(); + std::optional buf = ast->ToJavaScript(); + ASSERT_TRUE(buf.has_value()); + EXPECT_EQ(kExpected, buf.value().MakeString()); +} + +TEST_F(CXFAFMParserTest, ParseDoBlock) { + constexpr wchar_t kInput[] = L"do\n x = 1\nend"; + constexpr wchar_t kExpected[] = + LR"***((function() { +let pfm_method_runner = function(obj, cb) { + if (pfm_rt.is_ary(obj)) { + let pfm_method_return = null; + for (var idx = obj.length -1; idx > 1; idx--) { + pfm_method_return = cb(obj[idx]); + } + return pfm_method_return; + } + return cb(obj); +}; +var pfm_ret = null; +{ +if (pfm_rt.is_obj(x)) +{ +pfm_ret = pfm_rt.asgn_val_op(x, 1); +} +else +{ +pfm_ret = x = pfm_rt.asgn_val_op(x, 1); +} +} +return pfm_rt.get_val(pfm_ret); +}).call(this);)***"; + CXFA_FMLexer lexer(kInput); + CXFA_FMParser parser(heap(), &lexer); + CXFA_FMAST* ast = parser.Parse(); + ASSERT_TRUE(ast); + EXPECT_FALSE(parser.HasError()); + + CXFA_FMToJavaScriptDepth::Reset(); + std::optional buf = ast->ToJavaScript(); + ASSERT_TRUE(buf.has_value()); + EXPECT_EQ(kExpected, buf.value().MakeString()); +} + +TEST_F(CXFAFMParserTest, ParseWhileErrors) { + { + CXFA_FMLexer lexer(L"while do endwhile"); + CXFA_FMParser parser(heap(), &lexer); + EXPECT_FALSE(parser.Parse()); + EXPECT_TRUE(parser.HasError()); + } + { + CXFA_FMLexer lexer(L"while (i < 10) do i = 1"); + CXFA_FMParser parser(heap(), &lexer); + EXPECT_FALSE(parser.Parse()); + EXPECT_TRUE(parser.HasError()); + } +} + +TEST_F(CXFAFMParserTest, ParseForErrors) { + { + CXFA_FMLexer lexer(L"for i = 1 to 10 do endfor"); + CXFA_FMParser parser(heap(), &lexer); + EXPECT_FALSE(parser.Parse()); + EXPECT_TRUE(parser.HasError()); + } + { + CXFA_FMLexer lexer(L"for i = 1 upto 10 do i = 1"); + CXFA_FMParser parser(heap(), &lexer); + EXPECT_FALSE(parser.Parse()); + EXPECT_TRUE(parser.HasError()); + } +} + +TEST_F(CXFAFMParserTest, ParseForeachErrors) { + { + CXFA_FMLexer lexer(L"foreach item (1, 2) endfor"); + CXFA_FMParser parser(heap(), &lexer); + EXPECT_FALSE(parser.Parse()); + EXPECT_TRUE(parser.HasError()); + } + { + CXFA_FMLexer lexer(L"foreach item in () endfor"); + CXFA_FMParser parser(heap(), &lexer); + EXPECT_FALSE(parser.Parse()); + EXPECT_TRUE(parser.HasError()); + } +} + +TEST_F(CXFAFMParserTest, ParseDoErrors) { + CXFA_FMLexer lexer(L"do x = 1"); + CXFA_FMParser parser(heap(), &lexer); + EXPECT_FALSE(parser.Parse()); + EXPECT_TRUE(parser.HasError()); +} From d340036bb312602b9680b645fc9935c611462601 Mon Sep 17 00:00:00 2001 From: Tom Sepez Date: Tue, 10 Nov 2026 11:20:22 -0800 Subject: [PATCH 16/47] Support conservative stack scanning in standalone cppgc heap Neccessary but vastly insufficient step for turning on heap per document mode in PDFium. In doing so, pick up a few pointers on the heap which could not hurt. Earlier versions of cppgc suffered from bugs when tracing partially- constructed objects during stack scans, leading to the selection of `kNoConservativeStackScan`. Modern cppgc safely handles in-construction objects without invoking `Trace()` on uninitialized members. Change-Id: Ifb9259d36f892a5e185e74dd4969e8ea6fa7f0ef Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163570 Commit-Queue: Tom Sepez Reviewed-by: Lei Zhang --- fxjs/gc/heap.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/fxjs/gc/heap.cpp b/fxjs/gc/heap.cpp index 119e9cdf0..ba3baa9d8 100644 --- a/fxjs/gc/heap.cpp +++ b/fxjs/gc/heap.cpp @@ -139,10 +139,10 @@ FXGCScopedHeap FXGC_CreateHeap(v8::Isolate* isolate) { std::make_shared(), cppgc::Heap::HeapOptions{ {}, - // Do not enable conservative stack scanning. STL containers have - // backing stores that are "malloc'd" and therefore scanning will - // *not* try to trace them. - cppgc::Heap::StackSupport::kNoConservativeStackScan, + // Note that STL containers have backing stores that are "malloc'd" + // and scanning will *not* try to trace them. So this is not a + // sufficient defense while STL containers still exist on the stack. + cppgc::Heap::StackSupport::kSupportsConservativeStackScan, cppgc::Heap::MarkingType::kAtomic, cppgc::Heap::SweepingType::kIncrementalAndConcurrent, {}}); From eb694da549836b2f278c709b6348c8e667c56d57 Mon Sep 17 00:00:00 2001 From: Tom Sepez Date: Tue, 10 Nov 2026 11:23:00 -0800 Subject: [PATCH 17/47] Add unit tests for core/fxcrt/xml parser Add test cases in cfx_xmlparser_unittest.cpp covering empty inputs, invalid tag names (starting with digits), and processing instructions containing question marks. Change-Id: Ia9defd7d1bfba5063bd85fdcb1ed5ef692df2794 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163611 Reviewed-by: Lei Zhang Commit-Queue: Tom Sepez --- core/fxcrt/xml/cfx_xmlparser_unittest.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/core/fxcrt/xml/cfx_xmlparser_unittest.cpp b/core/fxcrt/xml/cfx_xmlparser_unittest.cpp index 98235cf4c..173ec2ca1 100644 --- a/core/fxcrt/xml/cfx_xmlparser_unittest.cpp +++ b/core/fxcrt/xml/cfx_xmlparser_unittest.cpp @@ -355,3 +355,24 @@ TEST_F(CFXXMLParserTest, BadEntity) { ""; ASSERT_TRUE(Parse(input) == nullptr); } + +TEST_F(CFXXMLParserTest, EmptyInput) { + std::unique_ptr doc = Parse(""); + ASSERT_TRUE(doc); + EXPECT_FALSE(doc->GetRoot()->GetFirstChild()); +} + +TEST_F(CFXXMLParserTest, InvalidTagNames) { + EXPECT_FALSE(Parse("<1tag>")); + EXPECT_FALSE(Parse("")); + EXPECT_FALSE(Parse("")); +} + +TEST_F(CFXXMLParserTest, InstructionWithQuestionMarks) { + constexpr char kInput[] = ""; + std::unique_ptr doc = Parse(kInput); + ASSERT_TRUE(doc); + CFX_XMLNode* first = doc->GetRoot()->GetFirstChild(); + ASSERT_TRUE(first); + EXPECT_EQ(CFX_XMLNode::Type::kInstruction, first->GetType()); +} From b07efcd2ebc28b160b3ef4f5c6d66f8eac976f4b Mon Sep 17 00:00:00 2001 From: Lei Zhang Date: Tue, 10 Nov 2026 11:35:08 -0800 Subject: [PATCH 18/47] Use FX_BGRA_STRUCT spans inside cfx_scanlinecompositor_hwy.cpp Change DispatchBgra2Bgra(), DispatchBgra2BgrxForceOpaque(), RunBgra2Bgra(), and RunBgra2BgrxForceOpaque() to accept FX_BGRA_STRUCT spans instead of uint8_t spans. This avoids calling fxcrt::reinterpret_span() in CompositeRowBgra2BgraSimd() and CompositeRowBgra2BgrxForceOpaqueSimd(), and eliminates the `n4` byte count variable in the SIMD loops. The spans now iterate 1 element at a time, while still providing the same pointers to Highway. Also update CompositePixelBgra2Bgra() to operate on FX_BGRA_STRUCT directly instead of packing and unpacking pixels with FXARGB_GetDIB() and FXARGB_SetDIB(), and use fxcrt::Zip() for the scalar tail loops in RunBgra2Bgra() and RunBgra2BgrxForceOpaque(). This CL is partly AI generated. Change-Id: I9a658158650ed15a1411e5f264c8b8c3e06b3633 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163870 Reviewed-by: Andy Phan Commit-Queue: Lei Zhang --- core/fxge/dib/cfx_scanlinecompositor_hwy.cpp | 117 +++++++++---------- 1 file changed, 57 insertions(+), 60 deletions(-) diff --git a/core/fxge/dib/cfx_scanlinecompositor_hwy.cpp b/core/fxge/dib/cfx_scanlinecompositor_hwy.cpp index 5b47c79de..59a2fcb64 100644 --- a/core/fxge/dib/cfx_scanlinecompositor_hwy.cpp +++ b/core/fxge/dib/cfx_scanlinecompositor_hwy.cpp @@ -10,7 +10,7 @@ #include "core/fxcrt/check_op.h" #include "core/fxcrt/compiler_specific.h" #include "core/fxcrt/span.h" -#include "core/fxcrt/span_util.h" +#include "core/fxcrt/zip.h" #undef HWY_TARGET_INCLUDE #define HWY_TARGET_INCLUDE "core/fxge/dib/cfx_scanlinecompositor_hwy.cpp" @@ -40,45 +40,48 @@ HWY_INLINE V AlphaMergeLanes(V back, V src, V alpha, V v255) { hn::Add(hn::Mul(back, hn::Sub(v255, alpha)), hn::Mul(src, alpha))); } -// scalar tail; bit-exact with CompositeRowBgra2Bgra normal/no-clip -inline uint32_t CompositePixelBgra2Bgra(uint32_t src, uint32_t back) { - const uint32_t back_alpha = FXARGB_A(back); - if (back_alpha == 0) { - return src; +// scalar tail; bit-exact with CompositeRowBgra2Bgra() normal/no-clip +inline void CompositePixelBgra2Bgra(const FX_BGRA_STRUCT& src, + FX_BGRA_STRUCT& dest) { + if (dest.alpha == 0) { + dest = src; + return; } - const uint32_t src_alpha = FXARGB_A(src); - if (src_alpha == 0) { - return back; + if (src.alpha == 0) { + return; } - if (src_alpha == 255) { - return src; + if (src.alpha == 255) { + dest = src; + return; } const uint32_t dest_alpha = - back_alpha + src_alpha - (back_alpha * src_alpha / 255); - const uint32_t ratio = src_alpha * 255 / dest_alpha; - return ArgbEncode(dest_alpha, - AlphaMerge(FXARGB_R(back), FXARGB_R(src), ratio), - AlphaMerge(FXARGB_G(back), FXARGB_G(src), ratio), - AlphaMerge(FXARGB_B(back), FXARGB_B(src), ratio)); + dest.alpha + src.alpha - (dest.alpha * src.alpha / 255); + const uint32_t ratio = src.alpha * 255 / dest_alpha; + dest.blue = AlphaMerge(dest.blue, src.blue, ratio); + dest.green = AlphaMerge(dest.green, src.green, ratio); + dest.red = AlphaMerge(dest.red, src.red, ratio); + dest.alpha = dest_alpha; } // Porter-Duff over, packed BGRA, normal, no clip. Per pixel: // dest a == 0 -> copy src src a == 255 -> copy src // src a == 0 -> keep dest else AlphaMerge/AlphaUnion over -// Byte spans bitcast to u32 lanes -> no 4-byte scanline alignment needed. -void RunBgra2Bgra(pdfium::span src, pdfium::span dest) { +// Byte loads bitcast to u32 lanes -> no 4-byte scanline alignment needed. +void RunBgra2Bgra(pdfium::span> src, + pdfium::span> dest) { #if HWY_TARGET != HWY_SCALAR const hn::ScalableTag d; const hn::ScalableTag d8; const size_t n = hn::Lanes(d); // pixels/vector - const size_t n4 = n * 4; const auto m255 = hn::Set(d, 0xFF); // byte mask and the value 255 const auto one = hn::Set(d, 1); const auto zero = hn::Zero(d); - while (src.size() >= n4) { - const auto s = hn::BitCast(d, hn::LoadU(d8, src.data())); - const auto back = hn::BitCast(d, hn::LoadU(d8, dest.data())); + while (src.size() >= n) { + const auto s = hn::BitCast( + d, hn::LoadU(d8, reinterpret_cast(src.data()))); + const auto back = hn::BitCast( + d, hn::LoadU(d8, reinterpret_cast(dest.data()))); const auto sa = hn::ShiftRight<24>(s); const auto da = hn::ShiftRight<24>(back); @@ -88,9 +91,10 @@ void RunBgra2Bgra(pdfium::span src, pdfium::span dest) { // all copy/keep -> skip divide; copy_src ? src : dest if (hn::AllTrue(d, hn::Or(copy_src, keep_dest))) { const auto result = hn::IfThenElse(copy_src, s, back); - hn::StoreU(hn::BitCast(d8, result), d8, dest.data()); - src = src.subspan(n4); - dest = dest.subspan(n4); + hn::StoreU(hn::BitCast(d8, result), d8, + reinterpret_cast(dest.data())); + src = src.subspan(n); + dest = dest.subspan(n); continue; } @@ -113,46 +117,42 @@ void RunBgra2Bgra(pdfium::span src, pdfium::span dest) { auto result = hn::IfThenElse(keep_dest, back, gen); result = hn::IfThenElse(copy_src, s, result); - hn::StoreU(hn::BitCast(d8, result), d8, dest.data()); + hn::StoreU(hn::BitCast(d8, result), d8, + reinterpret_cast(dest.data())); - src = src.subspan(n4); - dest = dest.subspan(n4); + src = src.subspan(n); + dest = dest.subspan(n); } #endif // HWY_TARGET != HWY_SCALAR - while (!src.empty()) { - const uint32_t s = FXARGB_GetDIB(src.first<4u>()); - const uint32_t back = FXARGB_GetDIB(dest.first<4u>()); - FXARGB_SetDIB(dest.first<4u>(), CompositePixelBgra2Bgra(s, back)); - src = src.subspan(4u); - dest = dest.subspan(4u); + for (auto [src_elem, dest_elem] : fxcrt::Zip(src, dest)) { + CompositePixelBgra2Bgra(src_elem, dest_elem); } } // Opaque BGRA(4) -> BGRA, alpha forced 0xFF (src alpha ignored). Same byte // order required: src and dest both packed BGRA. -void RunBgra2BgrxForceOpaque(pdfium::span src, - pdfium::span dest) { +void RunBgra2BgrxForceOpaque(pdfium::span> src, + pdfium::span> dest) { #if HWY_TARGET != HWY_SCALAR const hn::ScalableTag d; const hn::ScalableTag d8; const size_t n = hn::Lanes(d); - const size_t n4 = n * 4; const auto alpha_ff = hn::Set(d, 0xFF000000u); - while (src.size() >= n4) { - const auto v = hn::BitCast(d, hn::LoadU(d8, src.data())); - hn::StoreU(hn::BitCast(d8, hn::Or(v, alpha_ff)), d8, dest.data()); - src = src.subspan(n4); - dest = dest.subspan(n4); + while (src.size() >= n) { + const auto v = hn::BitCast( + d, hn::LoadU(d8, reinterpret_cast(src.data()))); + hn::StoreU(hn::BitCast(d8, hn::Or(v, alpha_ff)), d8, + reinterpret_cast(dest.data())); + src = src.subspan(n); + dest = dest.subspan(n); } #endif // HWY_TARGET != HWY_SCALAR - while (!src.empty()) { - dest[0] = src[0]; - dest[1] = src[1]; - dest[2] = src[2]; - dest[3] = 0xFF; - src = src.subspan(4u); - dest = dest.subspan(4u); + for (auto [src_elem, dest_elem] : fxcrt::Zip(src, dest)) { + dest_elem.blue = src_elem.blue; + dest_elem.green = src_elem.green; + dest_elem.red = src_elem.red; + dest_elem.alpha = 0xFF; } } @@ -169,14 +169,15 @@ HWY_EXPORT(RunBgra2BgrxForceOpaque); // Unqualified name, in-namespace: a qualified name breaks single-target // HWY_STATIC_DISPATCH. -void DispatchBgra2Bgra(pdfium::span src, - pdfium::span dest) { +void DispatchBgra2Bgra(pdfium::span> src, + pdfium::span> dest) { // SAFETY: dispatch indexes Highway's per-target table; no span macro form. UNSAFE_BUFFERS(HWY_DYNAMIC_DISPATCH(RunBgra2Bgra)(src, dest)); } -void DispatchBgra2BgrxForceOpaque(pdfium::span src, - pdfium::span dest) { +void DispatchBgra2BgrxForceOpaque( + pdfium::span> src, + pdfium::span> dest) { // SAFETY: see DispatchBgra2Bgra(). UNSAFE_BUFFERS(HWY_DYNAMIC_DISPATCH(RunBgra2BgrxForceOpaque)(src, dest)); } @@ -188,9 +189,7 @@ void CompositeRowBgra2BgraSimd( pdfium::span> dest_span) { // `src_span.size()` pixels, like `fxcrt::Zip(src_span, dest_span)`. CHECK_LE(src_span.size(), dest_span.size()); - fxge_composite_simd::DispatchBgra2Bgra( - fxcrt::reinterpret_span(src_span), - fxcrt::reinterpret_span(dest_span)); + fxge_composite_simd::DispatchBgra2Bgra(src_span, dest_span); } void CompositeRowBgra2BgrxForceOpaqueSimd( @@ -198,8 +197,6 @@ void CompositeRowBgra2BgrxForceOpaqueSimd( pdfium::span> dest_span) { // `src_span.size()` pixels, like `fxcrt::Zip(src_span, dest_span)`. CHECK_LE(src_span.size(), dest_span.size()); - fxge_composite_simd::DispatchBgra2BgrxForceOpaque( - fxcrt::reinterpret_span(src_span), - fxcrt::reinterpret_span(dest_span)); + fxge_composite_simd::DispatchBgra2BgrxForceOpaque(src_span, dest_span); } #endif // HWY_ONCE From 497e33afb22724307d75b3168adb9e426adef317 Mon Sep 17 00:00:00 2001 From: Tom Sepez Date: Tue, 10 Nov 2026 11:47:46 -0800 Subject: [PATCH 19/47] Add unit tests for CPVT_FontMap Test CPVT_FontMap methods: GetPDFFont and GetPDFFontAlias across valid, boundary, and invalid font indices (default font index 0, out-of-range indices -1 and 2). Also test system font resolution via GetPDFFont(1) and GetPDFFontAlias(1) with null document, null resource dictionary, and valid resource dictionary with font cache. Change-Id: Iffecd4db100624af56c4fc88157034aabecf8201 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163610 Reviewed-by: Lei Zhang Commit-Queue: Tom Sepez --- core/fpdfdoc/BUILD.gn | 1 + core/fpdfdoc/cpvt_fontmap_unittest.cpp | 86 ++++++++++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 core/fpdfdoc/cpvt_fontmap_unittest.cpp diff --git a/core/fpdfdoc/BUILD.gn b/core/fpdfdoc/BUILD.gn index 872a4bbd2..c7f6d663a 100644 --- a/core/fpdfdoc/BUILD.gn +++ b/core/fpdfdoc/BUILD.gn @@ -112,6 +112,7 @@ pdfium_unittest_source_set("unittests") { "cpdf_metadata_unittest.cpp", "cpdf_nametree_unittest.cpp", "cpdf_pagelabel_unittest.cpp", + "cpvt_fontmap_unittest.cpp", "cpvt_section_unittest.cpp", "cpvt_stub_provider.cpp", "cpvt_stub_provider.h", diff --git a/core/fpdfdoc/cpvt_fontmap_unittest.cpp b/core/fpdfdoc/cpvt_fontmap_unittest.cpp new file mode 100644 index 000000000..cdadfdd70 --- /dev/null +++ b/core/fpdfdoc/cpvt_fontmap_unittest.cpp @@ -0,0 +1,86 @@ +// Copyright 2026 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "core/fpdfdoc/cpvt_fontmap.h" + +#include + +#include "core/fpdfapi/font/cpdf_font.h" +#include "core/fpdfapi/page/cpdf_pagemodule.h" +#include "core/fpdfapi/parser/cpdf_dictionary.h" +#include "core/fpdfapi/parser/cpdf_test_document.h" +#include "core/fxcrt/retain_ptr.h" +#include "testing/gtest/include/gtest/gtest.h" + +class CPVT_FontMapTest : public testing::Test { + public: + void SetUp() override { + pdfium::InitializePageModule(); + test_doc_ = std::make_unique(); + test_doc_->SetRoot(pdfium::MakeRetain()); + def_font_ = CPDF_Font::GetStockFont(test_doc_.get(), "Helvetica"); + ASSERT_TRUE(def_font_); + } + + void TearDown() override { + def_font_.Reset(); + test_doc_.reset(); + pdfium::DestroyPageModule(); + } + + CPDF_TestDocument* doc() { return test_doc_.get(); } + RetainPtr def_font() { return def_font_; } + + private: + std::unique_ptr test_doc_; + RetainPtr def_font_; +}; + +TEST_F(CPVT_FontMapTest, DefaultFontAndBounds) { + CPVT_FontMap font_map(doc(), nullptr, def_font(), "Helvetica"); + + EXPECT_EQ(def_font(), font_map.GetPDFFont(0)); + EXPECT_EQ("Helvetica", font_map.GetPDFFontAlias(0)); + + EXPECT_FALSE(font_map.GetPDFFont(-1)); + EXPECT_TRUE(font_map.GetPDFFontAlias(-1).IsEmpty()); + + EXPECT_FALSE(font_map.GetPDFFont(2)); + EXPECT_TRUE(font_map.GetPDFFontAlias(2).IsEmpty()); +} + +TEST_F(CPVT_FontMapTest, NullDocumentSysFont) { + auto res_dict = pdfium::MakeRetain(); + CPVT_FontMap font_map(nullptr, res_dict, def_font(), "Helvetica"); + + EXPECT_FALSE(font_map.GetPDFFont(1)); + EXPECT_TRUE(font_map.GetPDFFontAlias(1).IsEmpty()); +} + +TEST_F(CPVT_FontMapTest, NullResDictSysFont) { + CPVT_FontMap font_map(doc(), nullptr, def_font(), "Helvetica"); + + EXPECT_FALSE(font_map.GetPDFFont(1)); + EXPECT_TRUE(font_map.GetPDFFontAlias(1).IsEmpty()); +} + +TEST_F(CPVT_FontMapTest, ValidResDictSysFont) { + auto res_dict = pdfium::MakeRetain(); + auto font_list = res_dict->SetNewFor("Font"); + CPVT_FontMap font_map(doc(), res_dict, def_font(), "Helvetica"); + + RetainPtr sys_font = font_map.GetPDFFont(1); + ByteString sys_alias = font_map.GetPDFFontAlias(1); + + if (sys_font) { + EXPECT_FALSE(sys_alias.IsEmpty()); + EXPECT_TRUE(font_list->KeyExist(sys_alias.AsStringView())); + + // Repeated calls return the cached system font and alias. + EXPECT_EQ(sys_font, font_map.GetPDFFont(1)); + EXPECT_EQ(sys_alias, font_map.GetPDFFontAlias(1)); + } else { + EXPECT_TRUE(sys_alias.IsEmpty()); + } +} From bb85c99f8d280196f374ff556357718a8a8411dd Mon Sep 17 00:00:00 2001 From: Tom Sepez Date: Tue, 10 Nov 2026 12:01:30 -0800 Subject: [PATCH 20/47] Add unit tests for core/fxcrt/css - cfx_cssdeclaration: Add tests for named color parsing (red, green, blue), string unquoting, standard property additions (color, font, text alignment, borders), and !important flag handling. - cfx_cssstyleselector: Add cfx_cssstyleselector_unittest.cpp testing default font size scaling, inline style computation, align strings, inherited property propagation, and user-agent stylesheet matching. Change-Id: Ib497f219a28eed7b1fa9ff7ca18e754895098ed3 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163591 Reviewed-by: Lei Zhang Commit-Queue: Tom Sepez --- core/fxcrt/css/BUILD.gn | 1 + .../fxcrt/css/cfx_cssdeclaration_unittest.cpp | 73 ++++++++++++++++ .../css/cfx_cssstyleselector_unittest.cpp | 87 +++++++++++++++++++ 3 files changed, 161 insertions(+) create mode 100644 core/fxcrt/css/cfx_cssstyleselector_unittest.cpp diff --git a/core/fxcrt/css/BUILD.gn b/core/fxcrt/css/BUILD.gn index c7939ce18..734b8436d 100644 --- a/core/fxcrt/css/BUILD.gn +++ b/core/fxcrt/css/BUILD.gn @@ -66,6 +66,7 @@ pdfium_unittest_source_set("unittests") { sources = [ "cfx_cssdata_unittest.cpp", "cfx_cssdeclaration_unittest.cpp", + "cfx_cssstyleselector_unittest.cpp", "cfx_cssstylesheet_unittest.cpp", "cfx_csssyntaxparser_unittest.cpp", "cfx_cssvaluelistparser_unittest.cpp", diff --git a/core/fxcrt/css/cfx_cssdeclaration_unittest.cpp b/core/fxcrt/css/cfx_cssdeclaration_unittest.cpp index 31f254245..c6b6cb455 100644 --- a/core/fxcrt/css/cfx_cssdeclaration_unittest.cpp +++ b/core/fxcrt/css/cfx_cssdeclaration_unittest.cpp @@ -61,6 +61,79 @@ TEST(CFXCSSDeclarationTest, RGBEncodingParsing) { EXPECT_EQ(0xFF80FF30u, maybe_color.value()); } +TEST(CFXCSSDeclarationTest, NamedColorParsing) { + std::optional maybe_color = + CFX_CSSDeclaration::ParseCSSColor(L"red"); + ASSERT_TRUE(maybe_color.has_value()); + EXPECT_EQ(0xFFFF0000u, maybe_color.value()); + + maybe_color = CFX_CSSDeclaration::ParseCSSColor(L"green"); + ASSERT_TRUE(maybe_color.has_value()); + EXPECT_EQ(0xFF008000u, maybe_color.value()); + + maybe_color = CFX_CSSDeclaration::ParseCSSColor(L"blue"); + ASSERT_TRUE(maybe_color.has_value()); + EXPECT_EQ(0xFF0000FFu, maybe_color.value()); + + EXPECT_FALSE(CFX_CSSDeclaration::ParseCSSColor(L"notacolor")); +} + +TEST(CFXCSSDeclarationTest, ParseCSSString) { + EXPECT_EQ(L"Double Quoted", + CFX_CSSDeclaration::ParseCSSString(L"\"Double Quoted\"")); + EXPECT_EQ(L"Single Quoted", + CFX_CSSDeclaration::ParseCSSString(L"'Single Quoted'")); + EXPECT_EQ(L"Unquoted", CFX_CSSDeclaration::ParseCSSString(L"Unquoted")); + EXPECT_FALSE(CFX_CSSDeclaration::ParseCSSString(L"\"\"").has_value()); + EXPECT_FALSE(CFX_CSSDeclaration::ParseCSSString(L"").has_value()); +} + +TEST(CFXCSSDeclarationTest, AddProperty) { + CFX_CSSDeclaration decl; + EXPECT_TRUE(decl.empty()); + + bool important = false; + decl.AddProperty(CFX_CSSData::GetPropertyByEnum(CFX_CSSProperty::Color), + L"red"); + EXPECT_TRUE(decl.GetProperty(CFX_CSSProperty::Color, &important)); + EXPECT_FALSE(important); + + important = false; + decl.AddProperty(CFX_CSSData::GetPropertyByEnum(CFX_CSSProperty::FontSize), + L"16pt !important"); + EXPECT_TRUE(decl.GetProperty(CFX_CSSProperty::FontSize, &important)); + EXPECT_TRUE(important); + + important = false; + decl.AddProperty(CFX_CSSData::GetPropertyByEnum(CFX_CSSProperty::FontStyle), + L"italic"); + EXPECT_TRUE(decl.GetProperty(CFX_CSSProperty::FontStyle, &important)); + EXPECT_FALSE(important); + + important = false; + decl.AddProperty(CFX_CSSData::GetPropertyByEnum(CFX_CSSProperty::FontWeight), + L"bold"); + EXPECT_TRUE(decl.GetProperty(CFX_CSSProperty::FontWeight, &important)); + EXPECT_FALSE(important); + + important = false; + decl.AddProperty(CFX_CSSData::GetPropertyByEnum(CFX_CSSProperty::TextAlign), + L"center"); + EXPECT_TRUE(decl.GetProperty(CFX_CSSProperty::TextAlign, &important)); + EXPECT_FALSE(important); + + decl.AddProperty(CFX_CSSData::GetPropertyByEnum(CFX_CSSProperty::Border), + L"1px"); + EXPECT_TRUE(decl.GetProperty(CFX_CSSProperty::BorderLeftWidth, &important)); + EXPECT_TRUE(decl.GetProperty(CFX_CSSProperty::BorderTopWidth, &important)); + EXPECT_TRUE(decl.GetProperty(CFX_CSSProperty::BorderRightWidth, &important)); + EXPECT_TRUE(decl.GetProperty(CFX_CSSProperty::BorderBottomWidth, &important)); + + decl.AddProperty(L"--custom", L"custom_value"); + EXPECT_FALSE(decl.empty()); + EXPECT_EQ(1, std::distance(decl.custom_begin(), decl.custom_end())); +} + TEST(CFXCSSDeclarationTest, CustomPropertiesInInlineStyle) { CFX_CSSStyleSelector selector; RetainPtr style = selector.CreateComputedStyle(nullptr); diff --git a/core/fxcrt/css/cfx_cssstyleselector_unittest.cpp b/core/fxcrt/css/cfx_cssstyleselector_unittest.cpp new file mode 100644 index 000000000..9a3d168db --- /dev/null +++ b/core/fxcrt/css/cfx_cssstyleselector_unittest.cpp @@ -0,0 +1,87 @@ +// Copyright 2026 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "core/fxcrt/css/cfx_cssstyleselector.h" + +#include +#include +#include + +#include "core/fxcrt/css/cfx_csscomputedstyle.h" +#include "core/fxcrt/css/cfx_cssdeclaration.h" +#include "core/fxcrt/css/cfx_cssstylerule.h" +#include "core/fxcrt/css/cfx_cssstylesheet.h" +#include "core/fxcrt/retain_ptr.h" +#include "core/fxcrt/widestring.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +TEST(CFXCSSStyleSelectorTest, DefaultFontSize) { + CFX_CSSStyleSelector selector; + selector.SetDefaultFontSize(18.0f); + RetainPtr style = selector.CreateComputedStyle(nullptr); + ASSERT_TRUE(style); + selector.ComputeStyle({}, L"font-size: medium", L"", style.Get()); + EXPECT_FLOAT_EQ(18.0f, style->GetFontSize()); +} + +TEST(CFXCSSStyleSelectorTest, ComputeStyleInline) { + CFX_CSSStyleSelector selector; + RetainPtr style = selector.CreateComputedStyle(nullptr); + ASSERT_TRUE(style); + selector.ComputeStyle( + {}, L"color: red; font-size: 20pt; text-align: right; font-style: italic", + L"", style.Get()); + + EXPECT_EQ(0xFFFF0000u, style->GetColor()); + EXPECT_EQ(CFX_CSSTextAlign::Right, style->GetTextAlign()); + EXPECT_EQ(CFX_CSSFontStyle::Italic, style->GetFontStyle()); +} + +TEST(CFXCSSStyleSelectorTest, ComputeStyleWithAlignString) { + CFX_CSSStyleSelector selector; + RetainPtr style = selector.CreateComputedStyle(nullptr); + ASSERT_TRUE(style); + selector.ComputeStyle({}, L"", L"center", style.Get()); + EXPECT_EQ(CFX_CSSTextAlign::Center, style->GetTextAlign()); + + selector.ComputeStyle({}, L"", L"justify", style.Get()); + EXPECT_EQ(CFX_CSSTextAlign::Justify, style->GetTextAlign()); +} + +TEST(CFXCSSStyleSelectorTest, ComputeStyleInheritance) { + CFX_CSSStyleSelector selector; + RetainPtr parent_style = + selector.CreateComputedStyle(nullptr); + ASSERT_TRUE(parent_style); + selector.ComputeStyle({}, L"color: #0000ff; font-weight: bold", L"", + parent_style.Get()); + + RetainPtr child_style = + selector.CreateComputedStyle(parent_style.Get()); + ASSERT_TRUE(child_style); + selector.ComputeStyle({}, L"", L"", child_style.Get()); + + // Inherited properties should match parent. + EXPECT_EQ(0xFF0000FFu, child_style->GetColor()); + EXPECT_EQ(700, child_style->GetFontWeight()); +} + +TEST(CFXCSSStyleSelectorTest, MatchDeclarationsWithUAStyleSheet) { + CFX_CSSStyleSelector selector; + auto sheet = std::make_unique(); + EXPECT_TRUE(sheet->LoadBuffer(L"p { color: blue; } h1 { font-size: 24pt; }")); + ASSERT_EQ(2u, sheet->CountRules()); + ASSERT_TRUE(sheet->GetRule(0)); + ASSERT_TRUE(sheet->GetRule(1)); + const CFX_CSSDeclaration* p_decl = sheet->GetRule(0)->GetDeclaration(); + const CFX_CSSDeclaration* h1_decl = sheet->GetRule(1)->GetDeclaration(); + + selector.SetUAStyleSheet(std::move(sheet)); + selector.UpdateStyleIndex(); + + EXPECT_THAT(selector.MatchDeclarations(L"p"), testing::ElementsAre(p_decl)); + EXPECT_THAT(selector.MatchDeclarations(L"h1"), testing::ElementsAre(h1_decl)); + EXPECT_THAT(selector.MatchDeclarations(L"unknown_tag"), testing::IsEmpty()); +} From 034c460a95d1b44ce3b6031f975586f6dbf453b3 Mon Sep 17 00:00:00 2001 From: Tom Sepez Date: Tue, 10 Nov 2026 13:47:24 -0800 Subject: [PATCH 21/47] Add embedder tests for page box mutators and clip path transform Exercise FPDFPage_SetBleedBox, FPDFPage_SetTrimBox, and FPDFPage_SetArtBox in FPDFTransformEmbedderTest, verifying that the bounding box values update on the live page and persist across saving and reloading. Also exercise FPDFPageObj_TransformClipPath in FPDFEditEmbedderTest, verifying that matrix scaling and translation correctly transform the path segments of a page object's clip path. Bug: 42270238 Change-Id: I01c25cdb08fd8f2f04d594d09cac9f5a827c9ad3 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163650 Commit-Queue: Tom Sepez Reviewed-by: Lei Zhang --- fpdfsdk/fpdf_edit_embeddertest.cpp | 31 +++++ fpdfsdk/fpdf_transformpage_embeddertest.cpp | 121 ++++++++++++++++++++ 2 files changed, 152 insertions(+) diff --git a/fpdfsdk/fpdf_edit_embeddertest.cpp b/fpdfsdk/fpdf_edit_embeddertest.cpp index bea12c8a6..6c0fe5006 100644 --- a/fpdfsdk/fpdf_edit_embeddertest.cpp +++ b/fpdfsdk/fpdf_edit_embeddertest.cpp @@ -37,6 +37,7 @@ #include "public/fpdf_annot.h" #include "public/fpdf_doc.h" #include "public/fpdf_edit.h" +#include "public/fpdf_transformpage.h" #include "public/fpdfview.h" #include "testing/embedder_test.h" #include "testing/embedder_test_constants.h" @@ -689,6 +690,36 @@ TEST_F(FPDFEditEmbedderTest, ClipPath) { EXPECT_EQ(35, y); EXPECT_EQ(FPDF_SEGMENT_LINETO, FPDFPathSegment_GetType(segment)); EXPECT_FALSE(FPDFPathSegment_GetClose(segment)); + + // Null object does not crash. + FPDFPageObj_TransformClipPath(nullptr, 2.0, 0.0, 0.0, 3.0, 100.0, 200.0); + + // Transform clip path: scale X by 2, scale Y by 3, translate (100, 200). + FPDFPageObj_TransformClipPath(triangle, 2.0, 0.0, 0.0, 3.0, 100.0, 200.0); + + segment = FPDFClipPath_GetPathSegment(clip_path, 0, 0); + ASSERT_TRUE(segment); + EXPECT_TRUE(FPDFPathSegment_GetPoint(segment, &x, &y)); + EXPECT_FLOAT_EQ(120.0f, x); + EXPECT_FLOAT_EQ(245.0f, y); + + segment = FPDFClipPath_GetPathSegment(clip_path, 0, 1); + ASSERT_TRUE(segment); + EXPECT_TRUE(FPDFPathSegment_GetPoint(segment, &x, &y)); + EXPECT_FLOAT_EQ(180.0f, x); + EXPECT_FLOAT_EQ(245.0f, y); + + segment = FPDFClipPath_GetPathSegment(clip_path, 0, 2); + ASSERT_TRUE(segment); + EXPECT_TRUE(FPDFPathSegment_GetPoint(segment, &x, &y)); + EXPECT_FLOAT_EQ(180.0f, x); + EXPECT_FLOAT_EQ(305.0f, y); + + segment = FPDFClipPath_GetPathSegment(clip_path, 0, 3); + ASSERT_TRUE(segment); + EXPECT_TRUE(FPDFPathSegment_GetPoint(segment, &x, &y)); + EXPECT_FLOAT_EQ(120.0f, x); + EXPECT_FLOAT_EQ(305.0f, y); } TEST_F(FPDFEditEmbedderTest, Bug1399) { diff --git a/fpdfsdk/fpdf_transformpage_embeddertest.cpp b/fpdfsdk/fpdf_transformpage_embeddertest.cpp index 2be3ea0bf..2d50aa46d 100644 --- a/fpdfsdk/fpdf_transformpage_embeddertest.cpp +++ b/fpdfsdk/fpdf_transformpage_embeddertest.cpp @@ -331,6 +331,127 @@ TEST_F(FPDFTransformEmbedderTest, SetMediaBox) { } } +TEST_F(FPDFTransformEmbedderTest, SetBleedBox) { + { + ASSERT_TRUE(OpenDocument("rectangles.pdf")); + ScopedPage page = LoadScopedPage(0); + ASSERT_TRUE(page); + + FS_RECTF bleedbox; + EXPECT_FALSE(FPDFPage_GetBleedBox(page.get(), &bleedbox.left, + &bleedbox.bottom, &bleedbox.right, + &bleedbox.top)); + + // Null page does not crash. + FPDFPage_SetBleedBox(nullptr, 15, 25, 120, 180); + + FPDFPage_SetBleedBox(page.get(), 15, 25, 120, 180); + EXPECT_TRUE(FPDFPage_GetBleedBox(page.get(), &bleedbox.left, + &bleedbox.bottom, &bleedbox.right, + &bleedbox.top)); + EXPECT_EQ(15, bleedbox.left); + EXPECT_EQ(25, bleedbox.bottom); + EXPECT_EQ(120, bleedbox.right); + EXPECT_EQ(180, bleedbox.top); + } + + { + EXPECT_TRUE(FPDF_SaveAsCopy(document(), this, 0)); + ScopedSavedDoc saved_document = OpenScopedSavedDocument(); + ASSERT_TRUE(saved_document); + ScopedSavedPage saved_page = LoadScopedSavedPage(0); + ASSERT_TRUE(saved_page); + + FS_RECTF bleedbox; + EXPECT_TRUE(FPDFPage_GetBleedBox(saved_page.get(), &bleedbox.left, + &bleedbox.bottom, &bleedbox.right, + &bleedbox.top)); + EXPECT_EQ(15, bleedbox.left); + EXPECT_EQ(25, bleedbox.bottom); + EXPECT_EQ(120, bleedbox.right); + EXPECT_EQ(180, bleedbox.top); + } +} + +TEST_F(FPDFTransformEmbedderTest, SetTrimBox) { + { + ASSERT_TRUE(OpenDocument("rectangles.pdf")); + ScopedPage page = LoadScopedPage(0); + ASSERT_TRUE(page); + + FS_RECTF trimbox; + EXPECT_FALSE(FPDFPage_GetTrimBox(page.get(), &trimbox.left, &trimbox.bottom, + &trimbox.right, &trimbox.top)); + + // Null page does not crash. + FPDFPage_SetTrimBox(nullptr, 20, 30, 110, 170); + + FPDFPage_SetTrimBox(page.get(), 20, 30, 110, 170); + EXPECT_TRUE(FPDFPage_GetTrimBox(page.get(), &trimbox.left, &trimbox.bottom, + &trimbox.right, &trimbox.top)); + EXPECT_EQ(20, trimbox.left); + EXPECT_EQ(30, trimbox.bottom); + EXPECT_EQ(110, trimbox.right); + EXPECT_EQ(170, trimbox.top); + } + + { + EXPECT_TRUE(FPDF_SaveAsCopy(document(), this, 0)); + ScopedSavedDoc saved_document = OpenScopedSavedDocument(); + ASSERT_TRUE(saved_document); + ScopedSavedPage saved_page = LoadScopedSavedPage(0); + ASSERT_TRUE(saved_page); + + FS_RECTF trimbox; + EXPECT_TRUE(FPDFPage_GetTrimBox(saved_page.get(), &trimbox.left, + &trimbox.bottom, &trimbox.right, + &trimbox.top)); + EXPECT_EQ(20, trimbox.left); + EXPECT_EQ(30, trimbox.bottom); + EXPECT_EQ(110, trimbox.right); + EXPECT_EQ(170, trimbox.top); + } +} + +TEST_F(FPDFTransformEmbedderTest, SetArtBox) { + { + ASSERT_TRUE(OpenDocument("rectangles.pdf")); + ScopedPage page = LoadScopedPage(0); + ASSERT_TRUE(page); + + FS_RECTF artbox; + EXPECT_FALSE(FPDFPage_GetArtBox(page.get(), &artbox.left, &artbox.bottom, + &artbox.right, &artbox.top)); + + // Null page does not crash. + FPDFPage_SetArtBox(nullptr, 25, 35, 100, 160); + + FPDFPage_SetArtBox(page.get(), 25, 35, 100, 160); + EXPECT_TRUE(FPDFPage_GetArtBox(page.get(), &artbox.left, &artbox.bottom, + &artbox.right, &artbox.top)); + EXPECT_EQ(25, artbox.left); + EXPECT_EQ(35, artbox.bottom); + EXPECT_EQ(100, artbox.right); + EXPECT_EQ(160, artbox.top); + } + + { + EXPECT_TRUE(FPDF_SaveAsCopy(document(), this, 0)); + ScopedSavedDoc saved_document = OpenScopedSavedDocument(); + ASSERT_TRUE(saved_document); + ScopedSavedPage saved_page = LoadScopedSavedPage(0); + ASSERT_TRUE(saved_page); + + FS_RECTF artbox; + EXPECT_TRUE(FPDFPage_GetArtBox(saved_page.get(), &artbox.left, + &artbox.bottom, &artbox.right, &artbox.top)); + EXPECT_EQ(25, artbox.left); + EXPECT_EQ(35, artbox.bottom); + EXPECT_EQ(100, artbox.right); + EXPECT_EQ(160, artbox.top); + } +} + TEST_F(FPDFTransformEmbedderTest, ClipPath) { ASSERT_TRUE(OpenDocument("hello_world.pdf")); From ebffd536696b34d044bbfb0868df3a87a04ad16b Mon Sep 17 00:00:00 2001 From: Lei Zhang Date: Tue, 10 Nov 2026 16:26:59 -0800 Subject: [PATCH 22/47] Add unit test for a bug in FlatePredictorScanlineDecoder::Rewind() Demonstrate FlatePredictorScanlineDecoder::GetScanline() produces different results after an implicit Rewind(). This CL is AI generated. Bug: 584197771 Change-Id: Ida0283f57273f8719272e7a3cf920c978d558601 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163931 Reviewed-by: Tom Sepez Commit-Queue: Lei Zhang --- core/fxcodec/flate/flatemodule_unittest.cpp | 29 +++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/core/fxcodec/flate/flatemodule_unittest.cpp b/core/fxcodec/flate/flatemodule_unittest.cpp index 261a6f891..e546c9e79 100644 --- a/core/fxcodec/flate/flatemodule_unittest.cpp +++ b/core/fxcodec/flate/flatemodule_unittest.cpp @@ -4,7 +4,12 @@ #include "core/fxcodec/flate/flatemodule.h" +#include + +#include + #include "core/fxcodec/data_and_bytes_consumed.h" +#include "core/fxcodec/scanlinedecoder.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/test_support.h" @@ -86,3 +91,27 @@ TEST(FlateModule, LZWDecode) { EXPECT_THAT(result.data, ElementsAreArray(kExpected)); EXPECT_EQ(5u, result.bytes_consumed); } + +TEST(FlateModule, CreateDecoderPngPredictorRewind) { + // 2x2 RGB image encoded with PNG Paeth filter (tag 4) on each row. + static constexpr uint8_t kRawInput[] = { + 4, 80, 140, 200, 0, 0, 0, // Row 0 + 4, 0, 0, 0, 0, 0, 0, // Row 1 + }; + static constexpr uint8_t kExpectedRow[] = {80, 140, 200, 80, 140, 200}; + // TODO(crbug.com/578639452): Rewinding should not change the data. + static constexpr uint8_t kWrongRow[] = {160, 24, 144, 160, 24, 144}; + + DataVector encoded = FlateModule::Encode(kRawInput); + std::unique_ptr decoder = FlateModule::CreateDecoder( + encoded, /*width=*/2, /*height=*/2, /*nComps=*/3, /*bpc=*/8, + /*predictor=*/15, /*Colors=*/3, /*BitsPerComponent=*/8, /*Columns=*/2); + ASSERT_TRUE(decoder); + + EXPECT_THAT(decoder->GetScanline(0), ElementsAreArray(kExpectedRow)); + EXPECT_THAT(decoder->GetScanline(1), ElementsAreArray(kExpectedRow)); + + // Reading scanline 0 again rewinds the decoder. + EXPECT_THAT(decoder->GetScanline(0), ElementsAreArray(kWrongRow)); + EXPECT_THAT(decoder->GetScanline(1), ElementsAreArray(kWrongRow)); +} From 0254d297c70278467cab08d1f0e15f6153e6f54a Mon Sep 17 00:00:00 2001 From: Lei Zhang Date: Tue, 10 Nov 2026 16:27:27 -0800 Subject: [PATCH 23/47] Properly reset state in FlatePredictorScanlineDecoder::Rewind() As suggested in the bug report, clear `last_line_` in FlatePredictorScanlineDecoder::Rewind(). Then update unit test expectations now that the bug has been fixed. Bug: 584197771 Change-Id: I7a597f3b341949d532b67f22728b32f95f1e6b7b Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163932 Commit-Queue: Lei Zhang Reviewed-by: Tom Sepez --- core/fxcodec/flate/flatemodule.cpp | 1 + core/fxcodec/flate/flatemodule_unittest.cpp | 6 ++---- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/core/fxcodec/flate/flatemodule.cpp b/core/fxcodec/flate/flatemodule.cpp index 43958d297..c30a78c87 100644 --- a/core/fxcodec/flate/flatemodule.cpp +++ b/core/fxcodec/flate/flatemodule.cpp @@ -500,6 +500,7 @@ bool FlatePredictorScanlineDecoder::Rewind() { } left_over_ = 0; + std::ranges::fill(last_line_.span(), 0); return true; } diff --git a/core/fxcodec/flate/flatemodule_unittest.cpp b/core/fxcodec/flate/flatemodule_unittest.cpp index e546c9e79..f608b4eaa 100644 --- a/core/fxcodec/flate/flatemodule_unittest.cpp +++ b/core/fxcodec/flate/flatemodule_unittest.cpp @@ -99,8 +99,6 @@ TEST(FlateModule, CreateDecoderPngPredictorRewind) { 4, 0, 0, 0, 0, 0, 0, // Row 1 }; static constexpr uint8_t kExpectedRow[] = {80, 140, 200, 80, 140, 200}; - // TODO(crbug.com/578639452): Rewinding should not change the data. - static constexpr uint8_t kWrongRow[] = {160, 24, 144, 160, 24, 144}; DataVector encoded = FlateModule::Encode(kRawInput); std::unique_ptr decoder = FlateModule::CreateDecoder( @@ -112,6 +110,6 @@ TEST(FlateModule, CreateDecoderPngPredictorRewind) { EXPECT_THAT(decoder->GetScanline(1), ElementsAreArray(kExpectedRow)); // Reading scanline 0 again rewinds the decoder. - EXPECT_THAT(decoder->GetScanline(0), ElementsAreArray(kWrongRow)); - EXPECT_THAT(decoder->GetScanline(1), ElementsAreArray(kWrongRow)); + EXPECT_THAT(decoder->GetScanline(0), ElementsAreArray(kExpectedRow)); + EXPECT_THAT(decoder->GetScanline(1), ElementsAreArray(kExpectedRow)); } From 7efd3f31d501e8112c3929e2c17a3499011a8f08 Mon Sep 17 00:00:00 2001 From: Tom Sepez Date: Tue, 10 Nov 2026 16:33:16 -0800 Subject: [PATCH 24/47] Add embedder tests for annotation subtype predicates Directly test FPDFAnnot_IsSupportedSubtype and FPDFAnnot_IsObjectSupportedSubtype against supported subtypes, unsupported subtypes, and boundary/invalid values. Change-Id: Ib586952907300e07dfd4b478cb8dcdbfd685b3d2 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163612 Reviewed-by: Lei Zhang Commit-Queue: Tom Sepez --- fpdfsdk/fpdf_annot_embeddertest.cpp | 64 +++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/fpdfsdk/fpdf_annot_embeddertest.cpp b/fpdfsdk/fpdf_annot_embeddertest.cpp index ca4d439c6..f05c44427 100644 --- a/fpdfsdk/fpdf_annot_embeddertest.cpp +++ b/fpdfsdk/fpdf_annot_embeddertest.cpp @@ -116,6 +116,70 @@ void VerifyUriActionInLink(FPDF_DOCUMENT doc, class FPDFAnnotEmbedderTest : public EmbedderTest {}; +TEST_F(FPDFAnnotEmbedderTest, IsSupportedSubtype) { + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_UNKNOWN)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_TEXT)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_LINK)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_FREETEXT)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_LINE)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_SQUARE)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_CIRCLE)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_HIGHLIGHT)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_UNDERLINE)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_SQUIGGLY)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_STRIKEOUT)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_STAMP)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_CARET)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_INK)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_POPUP)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_FILEATTACHMENT)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_SOUND)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_MOVIE)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_WIDGET)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_SCREEN)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_PRINTERMARK)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_TRAPNET)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_WATERMARK)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_THREED)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_RICHMEDIA)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_XFAWIDGET)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_REDACT)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(-1)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(999)); +} + +TEST_F(FPDFAnnotEmbedderTest, IsObjectSupportedSubtype) { + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_UNKNOWN)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_TEXT)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_LINK)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_FREETEXT)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_LINE)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_SQUARE)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_CIRCLE)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_HIGHLIGHT)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_UNDERLINE)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_SQUIGGLY)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_STRIKEOUT)); + EXPECT_TRUE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_STAMP)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_CARET)); + EXPECT_TRUE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_INK)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_POPUP)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_FILEATTACHMENT)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_SOUND)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_MOVIE)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_WIDGET)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_SCREEN)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_PRINTERMARK)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_TRAPNET)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_WATERMARK)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_THREED)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_RICHMEDIA)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_XFAWIDGET)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_REDACT)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(-1)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(999)); +} + TEST_F(FPDFAnnotEmbedderTest, SetAP) { ScopedFPDFDocument doc(FPDF_CreateNewDocument()); ASSERT_TRUE(doc); From e5e432d600d3335286acff720a3645187aaa585d Mon Sep 17 00:00:00 2001 From: Tom Sepez Date: Tue, 10 Nov 2026 16:35:06 -0800 Subject: [PATCH 25/47] Add JavaScript tests for app methods and field properties Add test cases in app_methods.in covering app.clearInterval, app.clearTimeOut, app.setInterval, and app.setTimeOut, verifying both valid calls and error handling for invalid argument counts and types. Add tests in field_properties.in for commitOnSelChange, currentValueIndices, editable, multipleSelection, numItems, required, and textFont across text fields, radio buttons, checkboxes, multi-select listboxes, and single-select listboxes. Change-Id: Ib96a36c99ebb9aaf9af7ac10453260ded1560e22 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163593 Reviewed-by: Lei Zhang Commit-Queue: Tom Sepez --- testing/resources/javascript/app_methods.in | 20 +++++++++++ .../javascript/app_methods_expected.txt | 18 ++++++++++ .../resources/javascript/field_properties.in | 36 ++++++++++++++----- .../javascript/field_properties_expected.txt | 31 ++++++++++++++++ 4 files changed, 97 insertions(+), 8 deletions(-) diff --git a/testing/resources/javascript/app_methods.in b/testing/resources/javascript/app_methods.in index 1c01e8473..8b208bfa2 100644 --- a/testing/resources/javascript/app_methods.in +++ b/testing/resources/javascript/app_methods.in @@ -54,6 +54,14 @@ try { expect("app.beep(1)", undefined); expectError("app.browseForDoc()"); + expectError("app.clearInterval()"); + expectError("app.clearInterval(1, 2)"); + expect("app.clearInterval(1)", undefined); + expect("app.clearInterval({})", undefined); + expectError("app.clearTimeOut()"); + expectError("app.clearTimeOut(1, 2)"); + expect("app.clearTimeOut(1)", undefined); + expect("app.clearTimeOut({})", undefined); expect("app.execDialog()", undefined); expectError("app.execMenuItem()"); expect("app.findComponent()", undefined); @@ -66,6 +74,18 @@ try { expect("app.openFDF()", undefined); expectError("app.popUpMenuEx()"); expectError("app.popUpMenu()"); + expectError("app.setInterval()"); + expectError("app.setInterval('')"); + expectError("app.setInterval('foo', 100, 200)"); + var testInterval = app.setInterval("42", 1000000); + expect("typeof testInterval", "object"); + expect("app.clearInterval(testInterval)", undefined); + expectError("app.setTimeOut()"); + expectError("app.setTimeOut('')"); + expectError("app.setTimeOut('foo', 100, 200)"); + var testTimeout = app.setTimeOut("42", 1000000); + expect("typeof testTimeout", "object"); + expect("app.clearTimeOut(testTimeout)", undefined); expect("app.mailMsg(true)", undefined); expect("app.mailMsg(false, 'user@example.com')", undefined); diff --git a/testing/resources/javascript/app_methods_expected.txt b/testing/resources/javascript/app_methods_expected.txt index 86fb3a94d..0d547f4b8 100644 --- a/testing/resources/javascript/app_methods_expected.txt +++ b/testing/resources/javascript/app_methods_expected.txt @@ -26,6 +26,14 @@ Alert: PASS: app.alert({'color': 'red', 'size': 42}) threw app.alert: Incorrect BEEP!!! 1 Alert: PASS: app.beep(1) = undefined Alert: FAIL: app.browseForDoc() = undefined, expected to throw +Alert: PASS: app.clearInterval() threw app.clearInterval: Incorrect number of parameters passed to function. +Alert: PASS: app.clearInterval(1, 2) threw app.clearInterval: Incorrect number of parameters passed to function. +Alert: PASS: app.clearInterval(1) = undefined +Alert: PASS: app.clearInterval({}) = undefined +Alert: PASS: app.clearTimeOut() threw app.clearTimeOut: Incorrect number of parameters passed to function. +Alert: PASS: app.clearTimeOut(1, 2) threw app.clearTimeOut: Incorrect number of parameters passed to function. +Alert: PASS: app.clearTimeOut(1) = undefined +Alert: PASS: app.clearTimeOut({}) = undefined Alert: PASS: app.execDialog() = undefined Alert: PASS: app.execMenuItem() threw app.execMenuItem: Operation not supported. Alert: PASS: app.findComponent() = undefined @@ -38,6 +46,16 @@ Alert: PASS: app.openDoc() threw app.openDoc: Operation not supported. Alert: PASS: app.openFDF() = undefined Alert: PASS: app.popUpMenuEx() threw app.popUpMenuEx: Operation not supported. Alert: PASS: app.popUpMenu() threw app.popUpMenu: Operation not supported. +Alert: PASS: app.setInterval() threw app.setInterval: Incorrect number of parameters passed to function. +Alert: PASS: app.setInterval('') threw app.setInterval: The input value is invalid. +Alert: PASS: app.setInterval('foo', 100, 200) threw app.setInterval: Incorrect number of parameters passed to function. +Alert: PASS: typeof testInterval = object +Alert: PASS: app.clearInterval(testInterval) = undefined +Alert: PASS: app.setTimeOut() threw app.setTimeOut: Incorrect number of parameters passed to function. +Alert: PASS: app.setTimeOut('') threw app.setTimeOut: The input value is invalid. +Alert: PASS: app.setTimeOut('foo', 100, 200) threw app.setTimeOut: Incorrect number of parameters passed to function. +Alert: PASS: typeof testTimeout = object +Alert: PASS: app.clearTimeOut(testTimeout) = undefined Mail Msg: 1, to=, cc=, bcc=, subject=, body= Alert: PASS: app.mailMsg(true) = undefined Mail Msg: 0, to=user@example.com, cc=, bcc=, subject=, body= diff --git a/testing/resources/javascript/field_properties.in b/testing/resources/javascript/field_properties.in index 5556e16d2..81e54d68f 100644 --- a/testing/resources/javascript/field_properties.in +++ b/testing/resources/javascript/field_properties.in @@ -14,6 +14,7 @@ function testProperties() { var badbutton = this.getField("MyField.MyBadPushButton"); var radio = this.getField("MyField.MyRadio"); var list = this.getField("MyField.MyMultiSelect"); + var single = this.getField("MyField.MySingleSelect"); var check = this.getField("MyField.MyCheckBox"); var file = this.getField("MyField.MyFile"); app.alert('Testing properties under delay'); @@ -28,6 +29,7 @@ function testProperties() { testRadioButtonPropertiesCase(radio); testCheckBoxPropertiesCase(check); testListBoxPropertiesCase(list); + testSingleSelectPropertiesCase(single); testFileSelectPropertiesCase(file); } catch (e) { app.alert("Unexpected error: " + e); @@ -44,35 +46,34 @@ function testFieldPropertiesCase(field) { function testTextPropertiesCase(field) { try { - // TODO(tsepez): devise tests and uncomment. testRIProperty(field, "alignment", "left", "center"); testRWProperty(field, "borderStyle", "solid", "inset"); testRIProperty(field, "calcOrderIndex", -1, 100); testRIProperty(field, "charLimit", 0, 100); testRIProperty(field, "comb", false, true); - // testRIProperty(field, "commitOnSelChange", false, true); - // testROProperty(field, "currentValueIndices", "clams"); + testUnreadableProperty(field, "commitOnSelChange"); + testUnreadableProperty(field, "currentValueIndices"); testXXProperty(field, "defaultStyle"); testRIProperty(field, "defaultValue", "grue", "clams"); testRIProperty(field, "doNotScroll", false, true); testRIProperty(field, "doNotSpellCheck", false, true); testRWProperty(field, "display", 2, 3); testROProperty(field, "doc", "[object global]"); - // testROProperty(field, "editable", "clams"); + testUnreadableProperty(field, "editable"); testRWProperty(field, "hidden", false, true); testRIProperty(field, "fileSelect", false, true); testRIProperty(field, "fillColor", "T", ["RGB", 0, 0, 0]); testRWProperty(field, "lineWidth", 1, 4); testRIProperty(field, "multiline", false, true); - // testROProperty(field, "multipleSelection", "clams"); + testUnreadableProperty(field, "multipleSelection"); testROProperty(field, "name", "MyField.MyText"); - // testROProperty(field, "numItems", "clams"); + testXXProperty(field, "numItems"); testROProperty(field, "page", 0); testRIProperty(field, "password", false, 42); testRWProperty(field, "print", true, false); testRWProperty(field, "readonly", false, true); testROProperty(field, "rect", [200,221,220,201]); - // testROProperty(field, "required", "clams"); + testRIProperty(field, "required", false, true); testRIProperty(field, "richText", false, true); testRIProperty(field, "richValue", undefined, "clams"); testRIProperty(field, "rotation", 0, 42); @@ -80,7 +81,7 @@ function testTextPropertiesCase(field) { testRIProperty(field, "strokeColor", "T", ["RGB", 0, 0, 0]); testRIProperty(field, "submitName", undefined, "clams"); testRIProperty(field, "textColor", "T", ["RGB", 0, 0, 0]); - // testROProperty(field, "textFont", "clams"); + testUnreadableProperty(field, "textFont"); testRIProperty(field, "textSize", 0, 32); testROProperty(field, "type", "text"); testRIProperty(field, "userName", ""); @@ -118,6 +119,7 @@ function testRadioButtonPropertiesCase(field) { try { testROProperty(field, "exportValues", "Yes"); testRIProperty(field, "radiosInUnison", false); + testRIProperty(field, "required", false, true); testRIProperty(field, "style", "circle"); testROProperty(field, "type", "radiobutton"); testRIProperty(field, "value", "Off"); @@ -130,6 +132,7 @@ function testRadioButtonPropertiesCase(field) { function testCheckBoxPropertiesCase(field) { try { testROProperty(field, "exportValues", "Yes"); + testRIProperty(field, "required", false, true); testRIProperty(field, "style", "check"); testROProperty(field, "type", "checkbox"); testRIProperty(field, "value", "Off"); @@ -142,6 +145,23 @@ function testCheckBoxPropertiesCase(field) { function testListBoxPropertiesCase(field) { try { testRWProperty(field, "currentValueIndices", 2, 1); + testROProperty(field, "numItems", 3); + testRIProperty(field, "multipleSelection", true, false); + testRIProperty(field, "commitOnSelChange", false, true); + testRIProperty(field, "required", false, true); + testUnreadableProperty(field, "editable"); + } catch (e) { + app.alert("Unexpected error: " + e); + } +} + +function testSingleSelectPropertiesCase(field) { + try { + testROProperty(field, "numItems", 3); + testRIProperty(field, "multipleSelection", false, true); + testRIProperty(field, "commitOnSelChange", false, true); + testRIProperty(field, "required", false, true); + testUnreadableProperty(field, "editable"); } catch (e) { app.alert("Unexpected error: " + e); } diff --git a/testing/resources/javascript/field_properties_expected.txt b/testing/resources/javascript/field_properties_expected.txt index 4b98bcf11..283b7e518 100644 --- a/testing/resources/javascript/field_properties_expected.txt +++ b/testing/resources/javascript/field_properties_expected.txt @@ -20,6 +20,8 @@ Alert: PASS: charLimit = 0 Alert: PASS: charLimit = 0 Alert: PASS: comb = false Alert: PASS: comb = false +Alert: PASS: commitOnSelChange threw Field.commitOnSelChange: Object is of the wrong type. +Alert: PASS: currentValueIndices threw Field.currentValueIndices: Object is of the wrong type. Alert: PASS: defaultStyle threw Field.defaultStyle: Operation not supported. Alert: PASS: defaultStyle threw Field.defaultStyle: Operation not supported. Alert: PASS: defaultValue = grue @@ -32,6 +34,7 @@ Alert: PASS: display = 2 Alert: PASS: display = 3 Alert: PASS: doc = [object global] Alert: PASS: doc threw Field.doc: Operation not supported. +Alert: PASS: editable threw Field.editable: Object is of the wrong type. Alert: PASS: hidden = false Alert: PASS: hidden = true Alert: PASS: fileSelect = false @@ -42,8 +45,11 @@ Alert: PASS: lineWidth = 1 Alert: PASS: lineWidth = 4 Alert: PASS: multiline = false Alert: PASS: multiline = false +Alert: PASS: multipleSelection threw Field.multipleSelection: Object is of the wrong type. Alert: PASS: name = MyField.MyText Alert: PASS: name threw Field.name: Operation not supported. +Alert: PASS: numItems threw Field.numItems: Object is of the wrong type. +Alert: PASS: numItems threw Field.numItems: Operation not supported. Alert: PASS: page = 0 Alert: PASS: page threw Field.page: Cannot assign to readonly property. Alert: PASS: password = false @@ -54,6 +60,8 @@ Alert: PASS: readonly = false Alert: PASS: readonly = true Alert: PASS: rect = 200,221,220,201 Alert: PASS: rect threw Field.rect: Incorrect parameter value. +Alert: PASS: required = false +Alert: PASS: required = false Alert: PASS: richText = false Alert: PASS: richText = false Alert: PASS: richValue = undefined @@ -68,6 +76,7 @@ Alert: PASS: submitName = undefined Alert: PASS: submitName = undefined Alert: PASS: textColor = T Alert: PASS: textColor = T +Alert: PASS: textFont threw Field.textFont: Object no longer exists. Alert: PASS: textSize = 0 Alert: PASS: textSize = 0 Alert: PASS: type = text @@ -100,6 +109,8 @@ Alert: PASS: exportValues = Yes Alert: PASS: exportValues threw Field.exportValues: Object no longer exists. Alert: PASS: radiosInUnison = false Alert: PASS: radiosInUnison = false +Alert: PASS: required = false +Alert: PASS: required = false Alert: PASS: style = circle Alert: PASS: style = circle Alert: PASS: type = radiobutton @@ -110,6 +121,8 @@ Alert: PASS: valueAsString = Off Alert: PASS: valueAsString threw Field.valueAsString: Operation not supported. Alert: PASS: exportValues = Yes Alert: PASS: exportValues threw Field.exportValues: Object no longer exists. +Alert: PASS: required = false +Alert: PASS: required = false Alert: PASS: style = check Alert: PASS: style = check Alert: PASS: type = checkbox @@ -120,5 +133,23 @@ Alert: PASS: valueAsString = Off Alert: PASS: valueAsString threw Field.valueAsString: Operation not supported. Alert: PASS: currentValueIndices = 2 Alert: PASS: currentValueIndices = 1 +Alert: PASS: numItems = 3 +Alert: PASS: numItems threw Field.numItems: Operation not supported. +Alert: PASS: multipleSelection = true +Alert: PASS: multipleSelection = true +Alert: PASS: commitOnSelChange = false +Alert: PASS: commitOnSelChange = false +Alert: PASS: required = false +Alert: PASS: required = false +Alert: PASS: editable threw Field.editable: Object is of the wrong type. +Alert: PASS: numItems = 3 +Alert: PASS: numItems threw Field.numItems: Operation not supported. +Alert: PASS: multipleSelection = false +Alert: PASS: multipleSelection = false +Alert: PASS: commitOnSelChange = false +Alert: PASS: commitOnSelChange = false +Alert: PASS: required = false +Alert: PASS: required = false +Alert: PASS: editable threw Field.editable: Object is of the wrong type. Alert: PASS: fileSelect = true Alert: PASS: fileSelect = true From 7758e6f3ca32e1b72303d781aa84bc2af681ef62 Mon Sep 17 00:00:00 2001 From: Tom Sepez Date: Tue, 10 Nov 2026 16:38:48 -0800 Subject: [PATCH 26/47] Add unit tests for CFX_Barcode methods and edge cases Add unit tests in cfx_barcode_unittest.cpp covering CFX_Barcode::GetType across all barcode formats, start and end delimiter character mutators, 1D versus 2D property configuration, error correction levels, module dimensions, text locations, EAN truncation on oversized contents, Code128C odd-length padding, and validation failure cases. Change-Id: I429d5e3faf18fa65f402e8f9c47b826ae8e03bff Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163613 Reviewed-by: Lei Zhang Commit-Queue: Tom Sepez --- fxbarcode/cfx_barcode_unittest.cpp | 179 +++++++++++++++++++++++++++++ 1 file changed, 179 insertions(+) diff --git a/fxbarcode/cfx_barcode_unittest.cpp b/fxbarcode/cfx_barcode_unittest.cpp index 626ed1356..53ccec178 100644 --- a/fxbarcode/cfx_barcode_unittest.cpp +++ b/fxbarcode/cfx_barcode_unittest.cpp @@ -251,3 +251,182 @@ TEST_F(BarcodeTest, QrCode) { #endif EXPECT_EQ(kExpectedChecksum, BitmapChecksum()); } + +TEST_F(BarcodeTest, GetType) { + Create(BC_TYPE::kCode39); + EXPECT_EQ(BC_TYPE::kCode39, barcode()->GetType()); + + Create(BC_TYPE::kCodabar); + EXPECT_EQ(BC_TYPE::kCodabar, barcode()->GetType()); + + Create(BC_TYPE::kCode128); + EXPECT_EQ(BC_TYPE::kCode128, barcode()->GetType()); + + Create(BC_TYPE::kCode128B); + EXPECT_EQ(BC_TYPE::kCode128, barcode()->GetType()); + + Create(BC_TYPE::kCode128C); + EXPECT_EQ(BC_TYPE::kCode128, barcode()->GetType()); + + Create(BC_TYPE::kEAN8); + EXPECT_EQ(BC_TYPE::kEAN8, barcode()->GetType()); + + Create(BC_TYPE::kUPCA); + EXPECT_EQ(BC_TYPE::kUPCA, barcode()->GetType()); + + Create(BC_TYPE::kEAN13); + EXPECT_EQ(BC_TYPE::kEAN13, barcode()->GetType()); + + Create(BC_TYPE::kQRCode); + EXPECT_EQ(BC_TYPE::kQRCode, barcode()->GetType()); + + Create(BC_TYPE::kPDF417); + EXPECT_EQ(BC_TYPE::kPDF417, barcode()->GetType()); + + Create(BC_TYPE::kDataMatrix); + EXPECT_EQ(BC_TYPE::kDataMatrix, barcode()->GetType()); +} + +TEST_F(BarcodeTest, SetStartEndChar) { + Create(BC_TYPE::kCodabar); + EXPECT_TRUE(barcode()->SetStartChar('A')); + EXPECT_TRUE(barcode()->SetStartChar('B')); + EXPECT_TRUE(barcode()->SetStartChar('C')); + EXPECT_TRUE(barcode()->SetStartChar('D')); + EXPECT_TRUE(barcode()->SetStartChar('E')); + EXPECT_TRUE(barcode()->SetStartChar('N')); + EXPECT_TRUE(barcode()->SetStartChar('T')); + EXPECT_TRUE(barcode()->SetStartChar('*')); + EXPECT_FALSE(barcode()->SetStartChar('X')); + EXPECT_FALSE(barcode()->SetStartChar('0')); + EXPECT_FALSE(barcode()->SetStartChar('\0')); + + EXPECT_TRUE(barcode()->SetEndChar('A')); + EXPECT_TRUE(barcode()->SetEndChar('B')); + EXPECT_TRUE(barcode()->SetEndChar('C')); + EXPECT_TRUE(barcode()->SetEndChar('D')); + EXPECT_TRUE(barcode()->SetEndChar('E')); + EXPECT_TRUE(barcode()->SetEndChar('N')); + EXPECT_TRUE(barcode()->SetEndChar('T')); + EXPECT_TRUE(barcode()->SetEndChar('*')); + EXPECT_FALSE(barcode()->SetEndChar('X')); + EXPECT_FALSE(barcode()->SetEndChar('0')); + EXPECT_FALSE(barcode()->SetEndChar('\0')); + + Create(BC_TYPE::kCode39); + EXPECT_FALSE(barcode()->SetStartChar('A')); + EXPECT_FALSE(barcode()->SetEndChar('A')); + + Create(BC_TYPE::kQRCode); + EXPECT_FALSE(barcode()->SetStartChar('A')); + EXPECT_FALSE(barcode()->SetEndChar('A')); +} + +TEST_F(BarcodeTest, OneDimVsTwoDimProperties) { + Create(BC_TYPE::kCode39); + EXPECT_TRUE(barcode()->SetPrintChecksum(true)); + EXPECT_TRUE(barcode()->SetDataLength(10)); + EXPECT_TRUE(barcode()->SetCalChecksum(true)); + EXPECT_TRUE(barcode()->SetFontSize(12.0f)); + EXPECT_TRUE(barcode()->SetFontColor(0xFF000000)); + EXPECT_TRUE(barcode()->SetWideNarrowRatio(2)); + EXPECT_TRUE(barcode()->SetWideNarrowRatio(3)); + EXPECT_FALSE(barcode()->SetWideNarrowRatio(1)); + EXPECT_FALSE(barcode()->SetWideNarrowRatio(4)); + + Create(BC_TYPE::kQRCode); + EXPECT_FALSE(barcode()->SetPrintChecksum(true)); + EXPECT_FALSE(barcode()->SetDataLength(10)); + EXPECT_FALSE(barcode()->SetCalChecksum(true)); + EXPECT_FALSE(barcode()->SetFontSize(12.0f)); + EXPECT_FALSE(barcode()->SetFontColor(0xFF000000)); + EXPECT_FALSE(barcode()->SetWideNarrowRatio(2)); + + Create(BC_TYPE::kPDF417); + EXPECT_FALSE(barcode()->SetPrintChecksum(true)); + EXPECT_FALSE(barcode()->SetDataLength(10)); + EXPECT_FALSE(barcode()->SetCalChecksum(true)); + EXPECT_FALSE(barcode()->SetFontSize(12.0f)); + EXPECT_FALSE(barcode()->SetFontColor(0xFF000000)); + EXPECT_FALSE(barcode()->SetWideNarrowRatio(2)); + + Create(BC_TYPE::kDataMatrix); + EXPECT_FALSE(barcode()->SetPrintChecksum(true)); + EXPECT_FALSE(barcode()->SetDataLength(10)); + EXPECT_FALSE(barcode()->SetCalChecksum(true)); + EXPECT_FALSE(barcode()->SetFontSize(12.0f)); + EXPECT_FALSE(barcode()->SetFontColor(0xFF000000)); + EXPECT_FALSE(barcode()->SetWideNarrowRatio(2)); +} + +TEST_F(BarcodeTest, ErrorCorrectionLevel) { + Create(BC_TYPE::kQRCode); + EXPECT_TRUE(barcode()->SetErrorCorrectionLevel(0)); + EXPECT_TRUE(barcode()->SetErrorCorrectionLevel(1)); + EXPECT_TRUE(barcode()->SetErrorCorrectionLevel(2)); + EXPECT_TRUE(barcode()->SetErrorCorrectionLevel(3)); + EXPECT_FALSE(barcode()->SetErrorCorrectionLevel(-1)); + EXPECT_FALSE(barcode()->SetErrorCorrectionLevel(4)); + + Create(BC_TYPE::kPDF417); + EXPECT_TRUE(barcode()->SetErrorCorrectionLevel(0)); + EXPECT_TRUE(barcode()->SetErrorCorrectionLevel(4)); + EXPECT_TRUE(barcode()->SetErrorCorrectionLevel(8)); + EXPECT_FALSE(barcode()->SetErrorCorrectionLevel(-1)); + EXPECT_FALSE(barcode()->SetErrorCorrectionLevel(9)); + + Create(BC_TYPE::kDataMatrix); + EXPECT_TRUE(barcode()->SetErrorCorrectionLevel(0)); + EXPECT_TRUE(barcode()->SetErrorCorrectionLevel(3)); + + Create(BC_TYPE::kCode39); + EXPECT_FALSE(barcode()->SetErrorCorrectionLevel(0)); +} + +TEST_F(BarcodeTest, ModuleDimensionsAndTextLocation) { + Create(BC_TYPE::kCode39); + EXPECT_TRUE(barcode()->SetModuleHeight(1)); + EXPECT_TRUE(barcode()->SetModuleHeight(5)); + EXPECT_TRUE(barcode()->SetModuleHeight(10)); + EXPECT_FALSE(barcode()->SetModuleHeight(0)); + EXPECT_FALSE(barcode()->SetModuleHeight(11)); + + EXPECT_TRUE(barcode()->SetModuleWidth(1)); + EXPECT_TRUE(barcode()->SetModuleWidth(5)); + EXPECT_TRUE(barcode()->SetModuleWidth(10)); + EXPECT_FALSE(barcode()->SetModuleWidth(0)); + EXPECT_FALSE(barcode()->SetModuleWidth(11)); + + barcode()->SetTextLocation(BC_TEXT_LOC::kNone); + barcode()->SetTextLocation(BC_TEXT_LOC::kAbove); + barcode()->SetTextLocation(BC_TEXT_LOC::kBelow); + barcode()->SetTextLocation(BC_TEXT_LOC::kAboveEmbed); + barcode()->SetTextLocation(BC_TEXT_LOC::kBelowEmbed); +} + +TEST_F(BarcodeTest, EanTruncation) { + Create(BC_TYPE::kEAN8); + EXPECT_TRUE(barcode()->Encode(L"1234567890")); + + Create(BC_TYPE::kEAN13); + EXPECT_TRUE(barcode()->Encode(L"1234567890123456")); + + Create(BC_TYPE::kUPCA); + EXPECT_TRUE(barcode()->Encode(L"1234567890123456")); +} + +TEST_F(BarcodeTest, Code128COddLengthPadded) { + Create(BC_TYPE::kCode128C); + EXPECT_TRUE(barcode()->Encode(L"123")); + RenderDevice(); +} + +TEST_F(BarcodeTest, ValidationFailures) { + Create(BC_TYPE::kCode128); + EXPECT_FALSE(barcode()->Encode(L"")); + EXPECT_FALSE(barcode()->Encode(L"\"")); + + Create(BC_TYPE::kDataMatrix); + WideString long_str(std::wstring(3117, L'1').c_str()); + EXPECT_FALSE(barcode()->Encode(long_str.AsStringView())); +} From a05cd1ce1e50ee23e1f9142faf7ba2bebbd1b584 Mon Sep 17 00:00:00 2001 From: Tom Sepez Date: Tue, 10 Nov 2026 16:43:11 -0800 Subject: [PATCH 27/47] Remove dead SetFontStyle from CBC_OneCode and CBC_OneDimWriter Remove SetFontStyle and the backing font_style_ member variable from CBC_OneCode and CBC_OneDimWriter. font_style_ was initialized to 0 and never read in any rendering or calculation, and SetFontStyle was never exposed on CFX_Barcode or called anywhere in PDFium. Change-Id: Ic5c35ba59cd346a9ffa4c84cf51922027eabbafc Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163670 Commit-Queue: Tom Sepez Reviewed-by: Lei Zhang --- fxbarcode/cbc_onecode.cpp | 4 ---- fxbarcode/cbc_onecode.h | 1 - fxbarcode/oned/BC_OneDimWriter.cpp | 4 ---- fxbarcode/oned/BC_OneDimWriter.h | 2 -- 4 files changed, 11 deletions(-) diff --git a/fxbarcode/cbc_onecode.cpp b/fxbarcode/cbc_onecode.cpp index f5e5ef0f6..b59a13c31 100644 --- a/fxbarcode/cbc_onecode.cpp +++ b/fxbarcode/cbc_onecode.cpp @@ -50,10 +50,6 @@ void CBC_OneCode::SetFontSize(float size) { GetOneDimWriter()->SetFontSize(size); } -void CBC_OneCode::SetFontStyle(int32_t style) { - GetOneDimWriter()->SetFontStyle(style); -} - void CBC_OneCode::SetFontColor(FX_ARGB color) { GetOneDimWriter()->SetFontColor(color); } diff --git a/fxbarcode/cbc_onecode.h b/fxbarcode/cbc_onecode.h index 1eb313ff5..1ddc48f94 100644 --- a/fxbarcode/cbc_onecode.h +++ b/fxbarcode/cbc_onecode.h @@ -27,7 +27,6 @@ class CBC_OneCode : public CBC_CodeBase { void SetCalChecksum(bool calc); bool SetFont(CFX_Font* cFont); void SetFontSize(float size); - void SetFontStyle(int32_t style); void SetFontColor(FX_ARGB color); private: diff --git a/fxbarcode/oned/BC_OneDimWriter.cpp b/fxbarcode/oned/BC_OneDimWriter.cpp index 3b59b1114..1f99886db 100644 --- a/fxbarcode/oned/BC_OneDimWriter.cpp +++ b/fxbarcode/oned/BC_OneDimWriter.cpp @@ -77,10 +77,6 @@ void CBC_OneDimWriter::SetFontSize(float size) { font_size_ = size; } -void CBC_OneDimWriter::SetFontStyle(int32_t style) { - font_style_ = style; -} - void CBC_OneDimWriter::SetFontColor(FX_ARGB color) { font_color_ = color; } diff --git a/fxbarcode/oned/BC_OneDimWriter.h b/fxbarcode/oned/BC_OneDimWriter.h index 7228005e9..509af9fc6 100644 --- a/fxbarcode/oned/BC_OneDimWriter.h +++ b/fxbarcode/oned/BC_OneDimWriter.h @@ -45,7 +45,6 @@ class CBC_OneDimWriter : public CBC_Writer { void SetPrintChecksum(bool checksum); void SetCalcChecksum(bool state); void SetFontSize(float size); - void SetFontStyle(int32_t style); void SetFontColor(FX_ARGB color); virtual DataVector Encode(const ByteString& contents) = 0; @@ -84,7 +83,6 @@ class CBC_OneDimWriter : public CBC_Writer { UnownedPtr font_; float font_size_ = 10.0f; - int32_t font_style_ = 0; uint32_t font_color_ = 0xff000000; BC_TEXT_LOC loc_text_loc_ = BC_TEXT_LOC::kBelowEmbed; From 2686a8c36c8fd51362a4c0e8c3af8875e6db9792 Mon Sep 17 00:00:00 2001 From: Tom Sepez Date: Wed, 11 Nov 2026 10:13:14 -0800 Subject: [PATCH 28/47] Revert "Support conservative stack scanning in standalone cppgc heap" This reverts commit d340036bb312602b9680b645fc9935c611462601. Reason for revert: Use after poison Failure Link: crbug.com/584686932 Original change's description: > Support conservative stack scanning in standalone cppgc heap > > Neccessary but vastly insufficient step for turning on heap per > document mode in PDFium. In doing so, pick up a few pointers > on the heap which could not hurt. > > Earlier versions of cppgc suffered from bugs when tracing partially- > constructed objects during stack scans, leading to the selection of > `kNoConservativeStackScan`. Modern cppgc safely handles in-construction > objects without invoking `Trace()` on uninitialized members. > > Change-Id: Ifb9259d36f892a5e185e74dd4969e8ea6fa7f0ef > Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163570 > Commit-Queue: Tom Sepez > Reviewed-by: Lei Zhang TBR=thestig@chromium.org,tsepez@chromium.org,pdfium-scoped@luci-project-accounts.iam.gserviceaccount.com,omerkatz@chromium.org No-Presubmit: true No-Tree-Checks: true No-Try: true Change-Id: I8e33170dc085b99c959599f657fef809f5f036e5 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/164070 Reviewed-by: Tom Sepez Auto-Submit: Tom Sepez Commit-Queue: Tom Sepez Reviewed-by: Lei Zhang --- fxjs/gc/heap.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/fxjs/gc/heap.cpp b/fxjs/gc/heap.cpp index ba3baa9d8..119e9cdf0 100644 --- a/fxjs/gc/heap.cpp +++ b/fxjs/gc/heap.cpp @@ -139,10 +139,10 @@ FXGCScopedHeap FXGC_CreateHeap(v8::Isolate* isolate) { std::make_shared(), cppgc::Heap::HeapOptions{ {}, - // Note that STL containers have backing stores that are "malloc'd" - // and scanning will *not* try to trace them. So this is not a - // sufficient defense while STL containers still exist on the stack. - cppgc::Heap::StackSupport::kSupportsConservativeStackScan, + // Do not enable conservative stack scanning. STL containers have + // backing stores that are "malloc'd" and therefore scanning will + // *not* try to trace them. + cppgc::Heap::StackSupport::kNoConservativeStackScan, cppgc::Heap::MarkingType::kAtomic, cppgc::Heap::SweepingType::kIncrementalAndConcurrent, {}}); From 833ce834d6f9680c931a689fcf3ad35dde9187d4 Mon Sep 17 00:00:00 2001 From: Lei Zhang Date: Wed, 11 Nov 2026 10:26:37 -0800 Subject: [PATCH 29/47] Ensure equal span sizes inside cfx_scanlinecompositor_hwy.cpp kernels Call `dest.first(src.size())` at the beginning of RunBgra2Bgra() and RunBgra2BgrxForceOpaque(). Although CompositeRowBgra2BgraSimd() and CompositeRowBgra2BgrxForceOpaqueSimd() already checked `dest` has a valid size compared to `src`, that relationship is lost across the Highway dispatch. Once the compiler can see the equal span sizes inside the kernels, the compiler can then eliminate the per-iteration `dest.subspan()` bounds check and extra size tracking in the SIMD and scalar tail loops. Change-Id: I9bae29e000b67d1c570e8ef727ce28a8206469a3 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/164050 Commit-Queue: Lei Zhang Reviewed-by: Tom Sepez --- core/fxge/dib/cfx_scanlinecompositor_hwy.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/fxge/dib/cfx_scanlinecompositor_hwy.cpp b/core/fxge/dib/cfx_scanlinecompositor_hwy.cpp index 59a2fcb64..1b1dd145c 100644 --- a/core/fxge/dib/cfx_scanlinecompositor_hwy.cpp +++ b/core/fxge/dib/cfx_scanlinecompositor_hwy.cpp @@ -69,6 +69,8 @@ inline void CompositePixelBgra2Bgra(const FX_BGRA_STRUCT& src, // Byte loads bitcast to u32 lanes -> no 4-byte scanline alignment needed. void RunBgra2Bgra(pdfium::span> src, pdfium::span> dest) { + // Make sure the compiler can see equal span sizes after the dispatch. + dest = dest.first(src.size()); #if HWY_TARGET != HWY_SCALAR const hn::ScalableTag d; const hn::ScalableTag d8; @@ -133,6 +135,8 @@ void RunBgra2Bgra(pdfium::span> src, // order required: src and dest both packed BGRA. void RunBgra2BgrxForceOpaque(pdfium::span> src, pdfium::span> dest) { + // Make sure the compiler can see equal span sizes after the dispatch. + dest = dest.first(src.size()); #if HWY_TARGET != HWY_SCALAR const hn::ScalableTag d; const hn::ScalableTag d8; From 89660bafdbdb649c3eac6c6aae259ede7429a10e Mon Sep 17 00:00:00 2001 From: Cristiano Nunes Date: Wed, 11 Nov 2026 10:30:04 -0800 Subject: [PATCH 30/47] Store annotations as indirect objects in /Annots FPDFPage_CreateAnnot appended the annotation dictionary directly into the page /Annots array. ISO 32000-1:2008 Table 30 requires each entry to be an indirect reference, so a direct dictionary has no object number and readers that only follow references never see it. Convert the new entry to an indirect object after it is appended, and add an embedder test that a saved highlight is stored only as a reference. Bug: 584383499 Change-Id: I13b5b2314b337d7cdc2d18d862d9e087751db267 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163990 Reviewed-by: Lei Zhang Reviewed-by: Tom Sepez Commit-Queue: Tom Sepez --- AUTHORS | 1 + fpdfsdk/fpdf_annot.cpp | 3 ++ fpdfsdk/fpdf_annot_embeddertest.cpp | 57 +++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+) diff --git a/AUTHORS b/AUTHORS index a7bfeb888..6f9cf07d7 100644 --- a/AUTHORS +++ b/AUTHORS @@ -20,6 +20,7 @@ Bill Denney Chenguang Shao Chery Cherian Claudio DeSouza +Cristiano Fraga G. Nunes Dan Ilan Deepak Mohan Dmitrii Chunikhin diff --git a/fpdfsdk/fpdf_annot.cpp b/fpdfsdk/fpdf_annot.cpp index fb5c862d3..6661ee9c9 100644 --- a/fpdfsdk/fpdf_annot.cpp +++ b/fpdfsdk/fpdf_annot.cpp @@ -419,6 +419,9 @@ FPDFPage_CreateAnnot(FPDF_PAGE page, FPDF_ANNOTATION_SUBTYPE subtype) { RetainPtr pAnnotList = pPage->GetOrCreateAnnotsArray(); pAnnotList->Append(dict); + // ISO 32000-1:2008 spec, table 30: /Annots entries are indirect references. + pAnnotList->ConvertToIndirectObjectAt(pAnnotList->size() - 1, + pPage->GetDocument()); // Caller takes ownership. return FPDFAnnotationFromCPDFAnnotContext(pNewAnnot.release()); diff --git a/fpdfsdk/fpdf_annot_embeddertest.cpp b/fpdfsdk/fpdf_annot_embeddertest.cpp index f05c44427..8ac1e7291 100644 --- a/fpdfsdk/fpdf_annot_embeddertest.cpp +++ b/fpdfsdk/fpdf_annot_embeddertest.cpp @@ -15,6 +15,7 @@ #include "build/build_config.h" #include "constants/annotation_common.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/fxcrt/compiler_specific.h" @@ -112,6 +113,25 @@ void VerifyUriActionInLink(FPDF_DOCUMENT doc, EXPECT_EQ(expected_uri, buffer.data()); } +// ISO 32000-1:2008 spec, table 30. +// Each /Annots entry is an indirect reference. +void ExpectHighlightAnnotsAreReferences(FPDF_PAGE page) { + CPDF_Page* cpdf_page = CPDFPageFromFPDFPage(page); + ASSERT_TRUE(cpdf_page); + RetainPtr annots = cpdf_page->GetAnnotsArray(); + ASSERT_TRUE(annots); + ASSERT_EQ(2u, annots->size()); + for (size_t i = 0; i < annots->size(); ++i) { + RetainPtr entry = annots->GetObjectAt(i); + ASSERT_TRUE(entry); + EXPECT_TRUE(entry->IsReference()); + RetainPtr dict = annots->GetDictAt(i); + ASSERT_TRUE(dict); + EXPECT_EQ("Highlight", + dict->GetByteStringFor(pdfium::annotation::kSubtype)); + } +} + } // namespace class FPDFAnnotEmbedderTest : public EmbedderTest {}; @@ -881,6 +901,43 @@ TEST_F(FPDFAnnotEmbedderTest, AddAndSaveUnderlineAnnotation) { } } +TEST_F(FPDFAnnotEmbedderTest, CreateAnnotSavesIndirectReference) { + // ISO 32000-1:2008 spec, table 30. + // The /Annots to hold indirect references. A direct dictionary has + // no object number, so readers that only follow references skip the + // annotation. + ASSERT_TRUE(OpenDocument("annotation_highlight_long_content.pdf")); + ScopedPage page = LoadScopedPage(0); + ASSERT_TRUE(page); + EXPECT_EQ(1, FPDFPage_GetAnnotCount(page.get())); + + { + ScopedFPDFAnnotation annot( + FPDFPage_CreateAnnot(page.get(), FPDF_ANNOT_HIGHLIGHT)); + ASSERT_TRUE(annot); + const FS_RECTF kRect = {10.0f, 40.0f, 80.0f, 60.0f}; + EXPECT_TRUE(FPDFAnnot_SetRect(annot.get(), &kRect)); + } + EXPECT_EQ(2, FPDFPage_GetAnnotCount(page.get())); + ExpectHighlightAnnotsAreReferences(page.get()); + + ASSERT_TRUE(FPDF_SaveAsCopy(document(), this, 0)); + + { + ScopedSavedDoc saved_doc = OpenScopedSavedDocument(); + ASSERT_TRUE(saved_doc); + ScopedSavedPage saved_page = LoadScopedSavedPage(0); + ASSERT_TRUE(saved_page); + EXPECT_EQ(2, FPDFPage_GetAnnotCount(saved_page.get())); + ExpectHighlightAnnotsAreReferences(saved_page.get()); + for (int index = 0; index < 2; ++index) { + ScopedFPDFAnnotation annot(FPDFPage_GetAnnot(saved_page.get(), index)); + ASSERT_TRUE(annot); + EXPECT_EQ(FPDF_ANNOT_HIGHLIGHT, FPDFAnnot_GetSubtype(annot.get())); + } + } +} + TEST_F(FPDFAnnotEmbedderTest, GetAndSetQuadPoints) { // Open a file with four annotations and load its first page. ASSERT_TRUE(OpenDocument("annotation_highlight_square_with_ap.pdf")); From 4a9b009526e2fa4fdb680ff9befad663f053c604 Mon Sep 17 00:00:00 2001 From: Lei Zhang Date: Wed, 11 Nov 2026 10:58:42 -0800 Subject: [PATCH 31/47] Use std::optional for a CXFA_TextLayout::LoaderContext field Avoid using -1 as a sentinel value for "unknown line count". This avoids the need to use checked_cast(). Change-Id: I4a624a6f32c1df7d306c8168f3fb9d480b232e4a Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/164010 Commit-Queue: Lei Zhang Reviewed-by: Andy Phan --- xfa/fxfa/cxfa_textlayout.cpp | 18 ++++++++---------- xfa/fxfa/cxfa_textlayout.h | 6 +++--- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/xfa/fxfa/cxfa_textlayout.cpp b/xfa/fxfa/cxfa_textlayout.cpp index e2bee081d..fb21b846a 100644 --- a/xfa/fxfa/cxfa_textlayout.cpp +++ b/xfa/fxfa/cxfa_textlayout.cpp @@ -505,7 +505,7 @@ float CXFA_TextLayout::Layout(const CFX_SizeF& size) { Unload(); break_ = CreateBreak(true); if (loader_) { - loader_->iTotalLines = -1; + loader_->total_lines.reset(); loader_->nCharIdx = 0; } @@ -524,7 +524,7 @@ bool CXFA_TextLayout::LayoutInternal(size_t szBlockIndex) { return false; } - loader_->iTotalLines = -1; + loader_->total_lines.reset(); lines_ = 0; float fLinePos = 0; CXFA_Node* pNode = nullptr; @@ -542,8 +542,7 @@ bool CXFA_TextLayout::LayoutInternal(size_t szBlockIndex) { loader_->nCharIdx = 0; if (!blocks_.empty()) { - loader_->iTotalLines = - pdfium::checked_cast(blocks_[szBlockIndex].szLength); + loader_->total_lines = blocks_[szBlockIndex].szLength; } Loader(szText.width, &fLinePos, true); if (blocks_.empty() && loader_->fStartLineOffset < 0.1f) { @@ -551,8 +550,7 @@ bool CXFA_TextLayout::LayoutInternal(size_t szBlockIndex) { } } else if (text_data_node_) { if (!blocks_.empty() && szBlockIndex < blocks_.size() - 1) { - loader_->iTotalLines = - pdfium::checked_cast(blocks_[szBlockIndex].szLength); + loader_->total_lines = blocks_[szBlockIndex].szLength; } break_->Reset(); if (rich_text_) { @@ -905,7 +903,7 @@ bool CXFA_TextLayout::LoadRichText(const CFX_XMLNode* pXMLNode, if (!IsEnd(bSavePieces)) { return true; } - if (loader_ && loader_->iTotalLines > -1) { + if (loader_ && loader_->total_lines.has_value()) { loader_->pXMLNode = pXMLNode; loader_->pParentStyle = pParentStyle; } @@ -959,7 +957,7 @@ bool CXFA_TextLayout::LoadRichText(const CFX_XMLNode* pXMLNode, return true; } - if (loader_ && loader_->iTotalLines > -1) { + if (loader_ && loader_->total_lines.has_value()) { loader_->pXMLNode = pXMLNode->GetNextSibling(); loader_->pParentStyle = pParentStyle; } @@ -1005,8 +1003,8 @@ bool CXFA_TextLayout::IsEnd(bool bSavePieces) { if (!bSavePieces) { return false; } - if (loader_ && loader_->iTotalLines > 0) { - return lines_ >= loader_->iTotalLines; + if (loader_ && loader_->total_lines.value_or(0) > 0) { + return lines_ >= loader_->total_lines; } return false; } diff --git a/xfa/fxfa/cxfa_textlayout.h b/xfa/fxfa/cxfa_textlayout.h index 97324a48f..a36fc0593 100644 --- a/xfa/fxfa/cxfa_textlayout.h +++ b/xfa/fxfa/cxfa_textlayout.h @@ -8,6 +8,7 @@ #define XFA_FXFA_CXFA_TEXTLAYOUT_H_ #include +#include #include #include "core/fxcrt/css/cfx_css.h" @@ -112,8 +113,7 @@ class CXFA_TextLayout final : public cppgc::GarbageCollected { float fLastPos = 0; float fStartLineOffset = 0; size_t nCharIdx = 0; - // TODO(thestig): Make this size_t? - int32_t iTotalLines = -1; + std::optional total_lines; UnownedPtr pXMLNode; RetainPtr pParentStyle; cppgc::Member pNode; @@ -177,7 +177,7 @@ class CXFA_TextLayout final : public cppgc::GarbageCollected { bool has_block_ = false; bool rich_text_ = false; - int32_t lines_ = 0; + size_t lines_ = 0; float max_width_ = 0; std::vector blocks_; cppgc::Member const doc_; From a724e52c527fc3b49197cf912e060eba03af962d Mon Sep 17 00:00:00 2001 From: Tom Sepez Date: Wed, 11 Nov 2026 11:34:31 -0800 Subject: [PATCH 32/47] Separate graph reference counting into tree_traversal_util No functional change, but makes updating algorithms in follow-on CLs easier to review. Collapsing a set of nested dictionaries or arrays into a single node for tracing is complex and should be separated from the tracing itself. - Introduce tree_traversal_util.h/.cpp with AdjacencyMap to perform pure graph analysis on node IDs independently of CPDF_Object structures. - PdfReferenceGraphBuilder in object_tree_traversal_util.cpp walks the PDF document to extract the reference graph and passes it to CalculateReferenceCounts(). - Retain the existing reference-counting algorithm using a BFS queue and seen_ref_objects. - Add unit tests in tree_traversal_util_unittest.cpp covering basic DAG traversal, forward edges, self-loops, and disconnected components. Change-Id: Ia4ee18e29310cfc88b4a843856c2366cad2fcce6 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163790 Reviewed-by: Lei Zhang Commit-Queue: Tom Sepez --- core/fpdfapi/parser/BUILD.gn | 3 + .../parser/object_tree_traversal_util.cpp | 105 +++++++----------- .../parser/object_tree_traversal_util.h | 13 +++ core/fpdfapi/parser/tree_traversal_util.cpp | 82 ++++++++++++++ core/fpdfapi/parser/tree_traversal_util.h | 30 +++++ .../parser/tree_traversal_util_unittest.cpp | 86 ++++++++++++++ 6 files changed, 254 insertions(+), 65 deletions(-) create mode 100644 core/fpdfapi/parser/tree_traversal_util.cpp create mode 100644 core/fpdfapi/parser/tree_traversal_util.h create mode 100644 core/fpdfapi/parser/tree_traversal_util_unittest.cpp diff --git a/core/fpdfapi/parser/BUILD.gn b/core/fpdfapi/parser/BUILD.gn index 3e38e5ec8..6064d2928 100644 --- a/core/fpdfapi/parser/BUILD.gn +++ b/core/fpdfapi/parser/BUILD.gn @@ -75,6 +75,8 @@ source_set("parser") { "fpdf_parser_utility.h", "object_tree_traversal_util.cpp", "object_tree_traversal_util.h", + "tree_traversal_util.cpp", + "tree_traversal_util.h", ] configs += [ "../../../:pdfium_strict_config" ] public_deps = [ @@ -136,6 +138,7 @@ pdfium_unittest_source_set("unittests") { "cpdf_syntax_parser_unittest.cpp", "fpdf_parser_decode_unittest.cpp", "fpdf_parser_utility_unittest.cpp", + "tree_traversal_util_unittest.cpp", ] deps = [ ":parser", diff --git a/core/fpdfapi/parser/object_tree_traversal_util.cpp b/core/fpdfapi/parser/object_tree_traversal_util.cpp index e2118603d..0932bbc93 100644 --- a/core/fpdfapi/parser/object_tree_traversal_util.cpp +++ b/core/fpdfapi/parser/object_tree_traversal_util.cpp @@ -17,15 +17,18 @@ #include "core/fpdfapi/parser/cpdf_document.h" #include "core/fpdfapi/parser/cpdf_reference.h" #include "core/fpdfapi/parser/cpdf_stream.h" +#include "core/fpdfapi/parser/tree_traversal_util.h" #include "core/fxcrt/check.h" #include "core/fxcrt/containers/contains.h" #include "core/fxcrt/unowned_ptr.h" namespace { -class ObjectTreeTraverser { +// Traverses the PDF object hierarchy in a document to extract an `AdjacencyMap` +// and root node IDs. +class PdfReferenceGraphBuilder { public: - explicit ObjectTreeTraverser(const CPDF_Document* document) + explicit PdfReferenceGraphBuilder(const CPDF_Document* document) : document_(document) { const CPDF_Parser* parser = document_->GetParser(); const CPDF_Dictionary* trailer = parser ? parser->GetTrailer() : nullptr; @@ -34,33 +37,35 @@ class ObjectTreeTraverser { parser->GetTrailerObjectNumber()); } } - ~ObjectTreeTraverser() = default; - void Traverse() { CalculateReferenceCounts(GetReferenceEntries()); } + PdfReferenceGraph Build() { + DrainObjectQueue(); - const std::map& referenced_objects() { - return referenced_objects_; + // Also traverse the catalog if it was not reached from the trailer + // (e.g. if the trailer's `/Root` was missing, null, or diverged). + const CPDF_Dictionary* catalog = document_->GetRoot(); + if (catalog && !pdfium::Contains(seen_objects_, catalog)) { + EnqueueRoot(pdfium::WrapRetain(catalog), catalog->GetObjNum()); + DrainObjectQueue(); + } + + return {std::move(roots_), std::move(adj_)}; } private: - struct ReferenceEntry { - uint32_t ref_object_number; - uint32_t referenced_object_number; - }; - void EnqueueRoot(RetainPtr root, uint32_t root_object_number) { if (!root || !seen_objects_.insert(root.Get()).second) { return; } if (root_object_number) { - referenced_objects_[root_object_number] = 1; + roots_.push_back(root_object_number); object_number_map_[root.Get()] = root_object_number; } object_queue_.push(std::move(root)); } - void DrainObjectQueue(std::vector* reference_entries) { + void DrainObjectQueue() { while (!object_queue_.empty()) { RetainPtr current_object = object_queue_.front(); object_queue_.pop(); @@ -97,8 +102,13 @@ class ObjectTreeTraverser { // Unlike the other object types, CPDF_Reference can point at nullptr. if (referenced_object) { CHECK(referenced_object_number); - reference_entries->push_back( - {ref_object_number, referenced_object_number}); + if (ref_object_number) { + if (referenced_object_number != ref_object_number) { + adj_[ref_object_number].push_back(referenced_object_number); + } + } else { + roots_.push_back(referenced_object_number); + } PushNewObject(ref_object, referenced_object); } break; @@ -120,45 +130,6 @@ class ObjectTreeTraverser { } } - std::vector GetReferenceEntries() { - std::vector reference_entries; - DrainObjectQueue(&reference_entries); - - // Also traverse the catalog if it was not reached from the trailer - // (e.g. if the trailer's `/Root` was missing, null, or diverged). - const CPDF_Dictionary* catalog = document_->GetRoot(); - if (catalog && !pdfium::Contains(seen_objects_, catalog)) { - EnqueueRoot(pdfium::WrapRetain(catalog), catalog->GetObjNum()); - DrainObjectQueue(&reference_entries); - } - return reference_entries; - } - - void CalculateReferenceCounts( - const std::vector& reference_entries) { - // Tracks PDF objects that referenced other PDF objects, identified by their - // object numbers. Never 0. - std::set seen_ref_objects; - - for (const ReferenceEntry& entry : reference_entries) { - // Make sure this is not a self-reference. - if (entry.referenced_object_number == entry.ref_object_number) { - continue; - } - - // Make sure this is not a circular reference. - if (pdfium::Contains(seen_ref_objects, entry.ref_object_number) && - pdfium::Contains(seen_ref_objects, entry.referenced_object_number)) { - continue; - } - - ++referenced_objects_[entry.referenced_object_number]; - if (entry.ref_object_number) { - seen_ref_objects.insert(entry.ref_object_number); - } - } - } - void PushNewObject(const CPDF_Object* parent_object, RetainPtr child_object) { CHECK(parent_object); @@ -187,6 +158,8 @@ class ObjectTreeTraverser { } UnownedPtr const document_; + std::vector roots_; + pdfium::AdjacencyMap adj_; // Queue of objects to traverse. // - Pointers in the queue are non-null. @@ -203,21 +176,22 @@ class ObjectTreeTraverser { // Tracks traversed objects to prevent duplicates from getting into // `object_queue_` and `object_number_map_`. std::set seen_objects_; - - // Tracks which PDF objects are referenced. - // Key: object number - // Value: number of times referenced - std::map referenced_objects_; }; } // namespace +PdfReferenceGraph BuildPdfReferenceGraphForTesting( + const CPDF_Document* document) { + return PdfReferenceGraphBuilder(document).Build(); +} + std::set GetObjectsWithReferences(const CPDF_Document* document) { - ObjectTreeTraverser traverser(document); - traverser.Traverse(); + PdfReferenceGraph graph = PdfReferenceGraphBuilder(document).Build(); + std::map counts = + pdfium::CalculateReferenceCounts(graph.roots, graph.adj); std::set results; - for (const auto& it : traverser.referenced_objects()) { + for (const auto& it : counts) { results.insert(it.first); } return results; @@ -225,11 +199,12 @@ std::set GetObjectsWithReferences(const CPDF_Document* document) { std::set GetObjectsWithMultipleReferences( const CPDF_Document* document) { - ObjectTreeTraverser traverser(document); - traverser.Traverse(); + PdfReferenceGraph graph = PdfReferenceGraphBuilder(document).Build(); + std::map counts = + pdfium::CalculateReferenceCounts(graph.roots, graph.adj); std::set results; - for (const auto& it : traverser.referenced_objects()) { + for (const auto& it : counts) { if (it.second > 1) { results.insert(it.first); } diff --git a/core/fpdfapi/parser/object_tree_traversal_util.h b/core/fpdfapi/parser/object_tree_traversal_util.h index f8f2ff956..444529f1b 100644 --- a/core/fpdfapi/parser/object_tree_traversal_util.h +++ b/core/fpdfapi/parser/object_tree_traversal_util.h @@ -8,9 +8,22 @@ #include #include +#include + +#include "core/fpdfapi/parser/tree_traversal_util.h" class CPDF_Document; +struct PdfReferenceGraph { + std::vector roots; + pdfium::AdjacencyMap adj; +}; + +// Traverses the PDF object hierarchy in `document` and returns the extracted +// reference graph without reference count analysis or cycle pruning. +PdfReferenceGraph BuildPdfReferenceGraphForTesting( + const CPDF_Document* document); + // Traverses `document` starting with its trailer, if it has one, and also from // the catalog if not reached from the trailer. The traversal avoids cycles. // Returns all the PDF objects (not CPDF_Objects) the traversal reached as a set diff --git a/core/fpdfapi/parser/tree_traversal_util.cpp b/core/fpdfapi/parser/tree_traversal_util.cpp new file mode 100644 index 000000000..9ec0c3065 --- /dev/null +++ b/core/fpdfapi/parser/tree_traversal_util.cpp @@ -0,0 +1,82 @@ +// Copyright 2026 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "core/fpdfapi/parser/tree_traversal_util.h" + +#include + +#include +#include +#include +#include + +#include "core/fxcrt/containers/contains.h" +#include "core/fxcrt/span.h" + +namespace pdfium { + +std::map CalculateReferenceCounts(pdfium::span roots, + const AdjacencyMap& adj) { + std::map ref_counts; + for (NodeId root : roots) { + ++ref_counts[root]; + } + + // Tracks nodes that have previously acted as the source of a reference edge. + std::set seen_ref_objects; + std::set queued_nodes; + std::queue queue; + + auto enqueue = [&](NodeId node) { + const bool inserted = queued_nodes.insert(node).second; + if (inserted) { + queue.push(node); + } + return inserted; + }; + + auto drain_queue = [&]() { + while (!queue.empty()) { + NodeId u = queue.front(); + queue.pop(); + + auto it = adj.find(u); + if (it == adj.end()) { + continue; + } + + for (NodeId v : it->second) { + // Make sure this is not a self-reference. + if (u == v) { + continue; + } + + // Make sure this is not a circular reference. + if (pdfium::Contains(seen_ref_objects, u) && + pdfium::Contains(seen_ref_objects, v)) { + continue; + } + + ++ref_counts[v]; + seen_ref_objects.insert(u); + enqueue(v); + } + } + }; + + for (NodeId root : roots) { + enqueue(root); + } + drain_queue(); + + for (const auto& it : adj) { + if (enqueue(it.first)) { + drain_queue(); + } + } + + return ref_counts; +} + +} // namespace pdfium diff --git a/core/fpdfapi/parser/tree_traversal_util.h b/core/fpdfapi/parser/tree_traversal_util.h new file mode 100644 index 000000000..f4b4237b1 --- /dev/null +++ b/core/fpdfapi/parser/tree_traversal_util.h @@ -0,0 +1,30 @@ +// Copyright 2026 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CORE_FPDFAPI_PARSER_TREE_TRAVERSAL_UTIL_H_ +#define CORE_FPDFAPI_PARSER_TREE_TRAVERSAL_UTIL_H_ + +#include + +#include +#include + +#include "core/fxcrt/data_vector.h" +#include "core/fxcrt/span.h" + +namespace pdfium { + +using NodeId = uint32_t; +using AdjacencyMap = std::map>; +using RefcountMap = std::map; + +// Given roots and an adjacency map of a directed graph, calculates reference +// counts for all reachable nodes while ignoring self-references and back-edges +// (cycles). Also traverses any remaining disconnected components in `adj`. +RefcountMap CalculateReferenceCounts(pdfium::span roots, + const AdjacencyMap& adjacenty_map); + +} // namespace pdfium + +#endif // CORE_FPDFAPI_PARSER_TREE_TRAVERSAL_UTIL_H_ diff --git a/core/fpdfapi/parser/tree_traversal_util_unittest.cpp b/core/fpdfapi/parser/tree_traversal_util_unittest.cpp new file mode 100644 index 000000000..7ba575a23 --- /dev/null +++ b/core/fpdfapi/parser/tree_traversal_util_unittest.cpp @@ -0,0 +1,86 @@ +// Copyright 2026 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "core/fpdfapi/parser/tree_traversal_util.h" + +#include + +#include +#include + +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using testing::ElementsAre; +using testing::Pair; + +namespace pdfium { + +TEST(TreeTraversalUtilTest, EmptyGraph) { + AdjacencyMap adj; + std::map counts = CalculateReferenceCounts({}, adj); + EXPECT_TRUE(counts.empty()); +} + +TEST(TreeTraversalUtilTest, SingleNodeRoot) { + AdjacencyMap adj; + std::map counts = CalculateReferenceCounts({1}, adj); + EXPECT_THAT(counts, ElementsAre(Pair(1, 1))); +} + +TEST(TreeTraversalUtilTest, SimpleTree) { + // 1 -> 2 + // 1 -> 3 + AdjacencyMap adj = {{1, {2, 3}}}; + std::map counts = CalculateReferenceCounts({1}, adj); + EXPECT_THAT(counts, ElementsAre(Pair(1, 1), Pair(2, 1), Pair(3, 1))); +} + +TEST(TreeTraversalUtilTest, DiamondDAGCrossEdge) { + // 1 -> 2, 3 + // 2 -> 4 + // 3 -> 4 + AdjacencyMap adj = {{1, {2, 3}}, {2, {4}}, {3, {4}}}; + std::map counts = CalculateReferenceCounts({1}, adj); + EXPECT_THAT(counts, + ElementsAre(Pair(1, 1), Pair(2, 1), Pair(3, 1), Pair(4, 2))); +} + +TEST(TreeTraversalUtilTest, SelfLoopIgnored) { + // 1 -> 2 -> 2 + AdjacencyMap adj = {{1, {2}}, {2, {2}}}; + std::map counts = CalculateReferenceCounts({1}, adj); + EXPECT_THAT(counts, ElementsAre(Pair(1, 1), Pair(2, 1))); +} + +TEST(TreeTraversalUtilTest, ForwardEdge) { + // 1 -> 2 -> 3 + // 1 -> 3 + AdjacencyMap adj = {{1, {2, 3}}, {2, {3}}}; + std::map counts = CalculateReferenceCounts({1}, adj); + EXPECT_THAT(counts, ElementsAre(Pair(1, 1), Pair(2, 1), Pair(3, 2))); +} + +TEST(TreeTraversalUtilTest, DeepLinearChainNoStackOverflow) { + // 1 -> 2 -> 3 -> ... -> 10000 + AdjacencyMap adj; + for (uint32_t i = 1; i < 10000; ++i) { + adj[i].push_back(i + 1); + } + std::map counts = CalculateReferenceCounts({1}, adj); + EXPECT_EQ(10000u, counts.size()); + EXPECT_EQ(1, counts.at(1)); + EXPECT_EQ(1, counts.at(5000)); + EXPECT_EQ(1, counts.at(10000)); +} + +TEST(TreeTraversalUtilTest, DisconnectedComponent) { + // Root 1 -> 2 + // Disconnected 3 -> 4 + AdjacencyMap adj = {{1, {2}}, {3, {4}}}; + std::map counts = CalculateReferenceCounts({1}, adj); + EXPECT_THAT(counts, ElementsAre(Pair(1, 1), Pair(2, 1), Pair(4, 1))); +} + +} // namespace pdfium From cc6e71c577560865aa221c0f34ee13c3316d7158 Mon Sep 17 00:00:00 2001 From: Lei Zhang Date: Wed, 11 Nov 2026 12:09:12 -0800 Subject: [PATCH 33/47] Update Highway build config Effectively apply the following Chromium CLs: - crrev.com/1501220 - Use current_cpu instead of target_cpu - crrev.com/1632679 - GN format Also remove an obsolete ppc64/s390x workaround, since the upstream Highway bug has been fixed. Change-Id: I5ae3be5a9afe393d77817ce461879fde407ec156 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/164030 Commit-Queue: Lei Zhang Reviewed-by: Andy Phan --- third_party/highway/BUILD.gn | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/third_party/highway/BUILD.gn b/third_party/highway/BUILD.gn index a975b0b41..091bd0ba5 100644 --- a/third_party/highway/BUILD.gn +++ b/third_party/highway/BUILD.gn @@ -6,24 +6,19 @@ config("libhwy_external_config") { include_dirs = [ "src" ] defines = [] - if (target_cpu == "x86") { + if (current_cpu == "x86") { # Highway automatically disables AVX2 and AVX3 targets when compiling in # 32-bit mode due to bugs in the generated code. However, when doing so it # prints a warning (#pragma message). This flag silences that warning by # explicitly disabling AVX2 and AVX3 targets. defines += [ "HWY_BROKEN_TARGETS=(HWY_AVX2|HWY_AVX3)" ] } - if (target_cpu == "arm64") { + if (current_cpu == "arm" || current_cpu == "arm64") { # There are Chrome targets that use HWY_ALIGN on absl::uint128. This breaks - # with SVE, since HWY_ALIGN == 8 for it and the minimal alignment requirement - # for absl::uint128 is 16. + # with SVE, since HWY_ALIGN == 8 for it and the minimal alignment + # requirement for absl::uint128 is 16. defines += [ "HWY_BROKEN_TARGETS=HWY_ALL_SVE" ] } - if (target_cpu == "ppc64" || target_cpu == "s390x") { - # Not using on ppc64/s390x: - # https://github.com/google/highway/issues/2406 - defines += [ "TOOLCHAIN_MISS_ASM_HWCAP_H" ] - } } source_set("libhwy") { From 99da130a26ad610843d041a509efd8ea68cc05b7 Mon Sep 17 00:00:00 2001 From: Tom Sepez Date: Wed, 11 Nov 2026 12:49:05 -0800 Subject: [PATCH 34/47] Fix nits in tree_traversal_util.h/.cpp. Remove stray header, fix typo, and make .cpp/.h file argument names agree with each other. Change-Id: I7f9a878876cdd94b094fb347bd95d626d6aafb27 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/164130 Commit-Queue: Tom Sepez Reviewed-by: Lei Zhang --- core/fpdfapi/parser/tree_traversal_util.cpp | 11 ++++++----- core/fpdfapi/parser/tree_traversal_util.h | 6 +++--- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/core/fpdfapi/parser/tree_traversal_util.cpp b/core/fpdfapi/parser/tree_traversal_util.cpp index 9ec0c3065..1ae1eb276 100644 --- a/core/fpdfapi/parser/tree_traversal_util.cpp +++ b/core/fpdfapi/parser/tree_traversal_util.cpp @@ -16,8 +16,9 @@ namespace pdfium { -std::map CalculateReferenceCounts(pdfium::span roots, - const AdjacencyMap& adj) { +std::map CalculateReferenceCounts( + pdfium::span roots, + const AdjacencyMap& adjacency_map) { std::map ref_counts; for (NodeId root : roots) { ++ref_counts[root]; @@ -41,8 +42,8 @@ std::map CalculateReferenceCounts(pdfium::span roots, NodeId u = queue.front(); queue.pop(); - auto it = adj.find(u); - if (it == adj.end()) { + auto it = adjacency_map.find(u); + if (it == adjacency_map.end()) { continue; } @@ -70,7 +71,7 @@ std::map CalculateReferenceCounts(pdfium::span roots, } drain_queue(); - for (const auto& it : adj) { + for (const auto& it : adjacency_map) { if (enqueue(it.first)) { drain_queue(); } diff --git a/core/fpdfapi/parser/tree_traversal_util.h b/core/fpdfapi/parser/tree_traversal_util.h index f4b4237b1..394a3c8e9 100644 --- a/core/fpdfapi/parser/tree_traversal_util.h +++ b/core/fpdfapi/parser/tree_traversal_util.h @@ -8,7 +8,6 @@ #include #include -#include #include "core/fxcrt/data_vector.h" #include "core/fxcrt/span.h" @@ -21,9 +20,10 @@ using RefcountMap = std::map; // Given roots and an adjacency map of a directed graph, calculates reference // counts for all reachable nodes while ignoring self-references and back-edges -// (cycles). Also traverses any remaining disconnected components in `adj`. +// (cycles). Also traverses any remaining disconnected components in +// `adjacency_map`. RefcountMap CalculateReferenceCounts(pdfium::span roots, - const AdjacencyMap& adjacenty_map); + const AdjacencyMap& adjacency_map); } // namespace pdfium From ddb2abb6fb9ced762512dc0501b8cf57800deba6 Mon Sep 17 00:00:00 2001 From: Jan Wytze Zuidema Date: Wed, 11 Nov 2026 16:04:53 -0800 Subject: [PATCH 35/47] Add an /ActualText test with RTL glyphs, numbers and punctuation Add actual_text_rtl_glyphs.in and FPDFTextEmbedderTest.ActualTextOnRtlGlyphsWithNumbersAndPunctuation. Unlike ActualTextRtl, its /ActualText spans mark RTL glyphs instead of Latin ones, which takes different code paths in CPDF_TextPage, and the /ActualText contains numbers and punctuation. The test documents how CPDF_TextPage extracts these lines today. Only the line without /ActualText comes out right, so mark the others with TODOs. Also add a TODO to ActualTextRtl, as /ActualText should not be mirrored. Bug: 525087036 Change-Id: I92dab436143b0d97c435c85d66afabe976239b89 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/162250 Commit-Queue: Andy Phan Reviewed-by: Andy Phan Reviewed-by: Lei Zhang --- fpdfsdk/fpdf_text_embeddertest.cpp | 40 ++++++ testing/resources/actual_text_rtl_glyphs.in | 125 +++++++++++++++++++ testing/resources/actual_text_rtl_glyphs.pdf | Bin 0 -> 6674 bytes 3 files changed, 165 insertions(+) create mode 100644 testing/resources/actual_text_rtl_glyphs.in create mode 100644 testing/resources/actual_text_rtl_glyphs.pdf diff --git a/fpdfsdk/fpdf_text_embeddertest.cpp b/fpdfsdk/fpdf_text_embeddertest.cpp index 470ecebb5..9deadd238 100644 --- a/fpdfsdk/fpdf_text_embeddertest.cpp +++ b/fpdfsdk/fpdf_text_embeddertest.cpp @@ -2524,6 +2524,8 @@ TEST_F(FPDFTextEmbedderTest, ActualTextRtl) { // Third line: 'M', 'i', 'r', 'r', 'o', 'r', 'e', 'd', ' ', // ם: + // TODO(crbug.com/525087036): Should be {0x05dd, '[', ')'}, since + // /ActualText should not be modified. 0x05dd, ']', '(', '\r', '\n', // Pure RTL case: // שלום (logical order): @@ -2577,6 +2579,44 @@ TEST_F(FPDFTextEmbedderTest, ActualTextRtl) { ElementsAreArray(kExpectedText)); } +// Like ActualTextRtl, but the /ActualText spans mark RTL glyphs instead of +// Latin ones, which takes different code paths in CPDF_TextPage, and the +// /ActualText also contains numbers and punctuation. +TEST_F(FPDFTextEmbedderTest, ActualTextOnRtlGlyphsWithNumbersAndPunctuation) { + ASSERT_TRUE(OpenDocument("actual_text_rtl_glyphs.pdf")); + ScopedPage page = LoadScopedPage(0); + ASSERT_TRUE(page); + + ScopedFPDFTextPage text_page(FPDFText_LoadPage(page.get())); + ASSERT_TRUE(text_page); + + static constexpr auto kExpectedText = std::to_array( + {// בין (literal text): + 0x05d1, 0x05d9, 0x05df, '\r', '\n', + // TODO(crbug.com/525087036): Should be {0x05d1, 0x05d9, 0x05df}. + 0x05df, 0x05d9, 0x05d1, '\r', '\n', + // TODO(crbug.com/525087036): Should be + // {0x05d1, '\'', 0x05d9, 0x05df, '.'}. + 0x05d1, '\'', 0x05df, 0x05d9, '.', '\r', '\n', + // TODO(crbug.com/525087036): Should be + // {0x05d1, 0x05d9, 0x05df, '1', '2', '3'}. + 0x05df, 0x05d9, 0x05d1, '3', '2', '1', '\r', '\n', + // TODO(crbug.com/525087036): Should be {'H', 'e', 'l', 'l', 'o', ' ', + // 'w', 'o', 'r', 'l', 'd', ' ', 0x05d1, 0x05d9, 0x05df, '.'}. + 'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', ' ', '.', 0x05df, + 0x05d9, 0x05d1, '\r', '\n', + // TODO(crbug.com/525087036): Should be + // {'1', '-', ' ', 0x05d1, 0x05d9, 0x05df}. + '-', '1', ' ', 0x05df, 0x05d9, 0x05d1, '\0'}); + static constexpr int kExpectedTextSize = std::size(kExpectedText); + + unsigned short buffer[128] = {}; + EXPECT_EQ(kExpectedTextSize, + FPDFText_GetText(text_page.get(), 0, std::size(buffer), buffer)); + EXPECT_THAT(pdfium::span(buffer).first(), + ElementsAreArray(kExpectedText)); +} + TEST_F(FPDFTextEmbedderTest, Arabic) { ASSERT_TRUE(OpenDocument("arabic.pdf")); ScopedPage page = LoadScopedPage(0); diff --git a/testing/resources/actual_text_rtl_glyphs.in b/testing/resources/actual_text_rtl_glyphs.in new file mode 100644 index 000000000..195fa449a --- /dev/null +++ b/testing/resources/actual_text_rtl_glyphs.in @@ -0,0 +1,125 @@ +{{header}} +{{object 1 0}} << + /Type /Catalog + /Pages 2 0 R +>> +endobj +{{object 2 0}} << + /Type /Pages + /Count 1 + /Kids [3 0 R] +>> +endobj +{{object 3 0}} << + /Type /Page + /Contents 4 0 R + /Parent 2 0 R + /MediaBox [0 0 200 400] + /Resources << + /Font << + /F1 5 0 R + /F2 6 0 R + >> + >> +>> +endobj +{{object 4 0}} << + {{streamlen}} +>> +stream +BT +/F2 12 Tf +% RTL glyphs without /ActualText. +20 350 Td +<010205> Tj +% RTL glyphs with /ActualText. +0 -50 Td +/Span << + /ActualText +>> BDC +<010205> Tj +EMC +% RTL glyphs with /ActualText containing neutral punctuation. +0 -50 Td +/Span << + /ActualText +>> BDC +<010205> Tj +EMC +% RTL glyphs with /ActualText containing digits. +0 -50 Td +/Span << + /ActualText +>> BDC +<010205> Tj +EMC +% Latin text followed by RTL glyphs with /ActualText. +0 -50 Td +/F1 12 Tf +(Hello world ) Tj +/F2 12 Tf +/Span << + /ActualText +>> BDC +<010205> Tj +EMC +% Numbered list item as RTL glyphs with /ActualText. +0 -50 Td +/Span << + /ActualText +>> BDC +<010205> Tj +EMC +ET +endstream +endobj +{{object 5 0}} << + /Type /Font + /Subtype /Type1 + /BaseFont /Helvetica +>> +endobj +{{object 6 0}} << + /Type /Font + /Subtype /TrueType + /BaseFont /BAAAAA+NotoSansHebrew-Regular + /FirstChar 0 + /FontDescriptor 7 0 R + /LastChar 5 + /ToUnicode 9 0 R + /Widths [600 294 235 645 397 542] +>> +endobj +{{object 7 0}} << + /Type /FontDescriptor + /Ascent 1069 + /CapHeight 869 + /Descent -293 + /Flags 4 + /FontBBox [-210 -252 716 869] + /FontFile2 8 0 R + /FontName /BAAAAA+NotoSansHebrew-Regular + /ItalicAngle 0 + /StemV 80 +>> +endobj +{{object 8 0}} << + /Filter [/ASCII85Decode /FlateDecode] + {{streamlen}} + /Length1 6721 +>> +stream +{{include hebrew_truetype_font.fragment}} +endstream +endobj +{{object 9 0}} << + {{streamlen}} +>> +stream +{{include hebrew_cmap.fragment}} +endstream +endobj +{{xref}} +{{trailer}} +{{startxref}} +%%EOF diff --git a/testing/resources/actual_text_rtl_glyphs.pdf b/testing/resources/actual_text_rtl_glyphs.pdf new file mode 100644 index 0000000000000000000000000000000000000000..ea4a5535de6cc1773a6d3f809d61859f834c5d2a GIT binary patch literal 6674 zcmbt(+19dHlJ+@Qf%7bbAkKmeiW4Xfh$F}#$|PcEWgqml^g&-?ufBjE-|x-(GPCNh zs$R`nuy%wIv7gvOfX~i|3|B#_1d#d9|NgK40T2)deeDi*Isgblt6u{HglIKV9pCyW zMAb50AQ~GjfnE-*f-r?L~$c zy+G`%&o2mJtoX(d%QHi_)q(#Pa1X~OC=7!b3?DzfOXKCg!)pxqE1Ouu`LXA>@DULZ z{|*br7sR1p{jYMI9tg&dpJ{#|{KPpmJS)0^L>>E>yrR%hU0|>RK2Z=9T$w-yT&|{| z<@_4lUf?fwbo1X42vOJQtvV~?FHsdhVX%h7;7SKNFao16-UC`B6+hTkx|vrMDJ+RhN(Yt2zwS zm+`ehp?KK-&4}!)`n%2d*_i)4R`@nP@je~=3^$-YS847?zNC7uk)eggFO{WXy&X0D zm~wXbis+jfg7B9ZLu8ECHME1s4?*I)BtTR3+Y0|!t^BoTUwz#Go4*-sZ9R&&`o10) zA+(8sXblJJ7!KB&1c+nk?`z&C=-*4{XTP65sMqyV>kzo!{D`y~j11elMPTEH;$!_W zsG!Z-7jj3n;!^q5jFT9AmBk8*#9I}`QIJ6DAJ4Di_!()=b_^73{09G{nyYSH@&D45M#c}}3)gp9 z#n9SU%0EN|tP?2myE;3(Z3Kg!$uF8yqEtQ;bnGUzuD*r(ac4lbIT^{?bd%tbj`gxe zyEJQ6B2A3Q@X@7$zEk2B(7SzVj44UpETrBB@ZQ7DJ?U}j^3t|5#YWTT!e_lx!^((T zxQ=0-!}BOw%qFj${^{8}-4*t6-B&A5-8tzGgv*xA$*Rer1w$P{$U+7>)*LHrVee?Q zh-RaG?A$R_-z`fTkxldb#Ry@>N5zee;_G88*~q=492s1oKR*zF4ymx zS=BN6k&B3`?IxA(=>!oBwvlyjT)fFuTg{SEM{&*!AU`iD*)eO?{h~gcR;s*I^6s56 zyFg0akzxAAsIjo&ec{@v9!_E!o35BXqq>_a)b3YAW_fDtwe+KrJ52{Djb(Gdd~J0{ zbp6qwa@C2a5!+kAa2Q%9u)_2bUHcd1AZcwo-J@7%y;bykDbe7z@0R6FME&6orCB@k ztTjoO-V+^#9RUNee2=~ByM1Fb%^6+S2_IHzpM@~lOCh;Dfd=&Ta+T-v5~RR=W|p-w z1B)WBK4BD^OuxSeO-~mOL>9S2EEh7n?Bm&+=*r?8U!c$Fna7N`ZeiMSvRoZH0_8xfim2rJHC;&u zZJhJUaDuQYB9Kj9 z+Uv?0F1XM&luyAXoh-{xa`2jY{r0leLdv$#Cjh;e^eWesH4UnoC?v*@YB8)>ViDhG z;hwsG3d2j!_s-4B^kzA6pQM-=rO=efnI_Lt3-Pp)&WzNO4Y%)1(8LV5rLLs|)t%3g zg0ih_sam5rr(w$H&7m{r?r#D1 ztX*RjjPvDotvTVvTJ~A(eZDW{(Pl2 zJa)a~?zK~6fOYy&55S~Ba4MQNt`a|{P%-S!A3{~KOsusXM@6r~!rSA-r6x`R*-twg zGPk|U?r7k&uU@lKQ75Fcx`!-TOg;LQy6*wyR=e9S)dtt0L~tChTS&Y(`l5q zM)zer>yG}cVz=QD>OrpA9ythiY7Meg*?ztgxBQYy4g*93CGP3`omjZ@Tg!V@0XU#Zv8 z#s0L%e=%mYBF`Jq^!nM8?{f?^+r8~bt=?+!T>{1S5FoOz$ zbnzK&K<=VFI$iKbzLi#&iU1?w#)WS3!Q8n_!z?m)5}1*8_c^iP!a3i=gz7M%;wKjE zX+rwAu$k)trR#xijU_g+djvZiSMu8@O)kbZqmy$j+DH?6dYKMFqO>54d@2LD=BkF`<&tV7b+v$B21{ zb%A+1Qr1ii1|3C|t|+qI)>7JAg!84QwN5EzZ3IaicSEsZ|AGU$5EV{~$6O1&n`sxC zu*5#I-sQRH+Al&&c=9!ErASp=%xh1LGqz4CVRV(~!g9G8k{`GkVzg{9+6J?%&Pqul zKyI-s=V==%ocBrOM%3#vlgm;}7^YoB8t5DI|khccP2{5-*>rRCRL8*Ji!S6pm|>cVdK{8W#Pw;e~m(dEW?!cKlGD z@ne6uv!c$AvHLcU2=7D5gVrQfk%x)wvRuBH0J=pEHKAY3ObM&pBUhJ%*)V2KN*shw z$VIy}nR80}`XRBR$q7a6XIqsEx#f@&dF3%>8_Uz~Hs0XE(dKyTd>8_@(5-JKhj*LK z^}1T$G&16CJ8e!7RhuvEo*&&)B_-GHcqKa{(4%W>xVRjHim%Z^WCvCCbTvEc`!2x^ z3u64AdkU12_ua6BogMp9x(|rUhV8tP7`3@4tG!_O@FDZrfRf$T5+~y~|KfN>*NA2~ ziL-Zs%XDu;?OvKP%8DbB8>h__1i+EromjaZwM21_$nFF`(Q)}>x)?6+D^y)37RL-{ z7gQk{OJ2XUo}oGDT-djQ3+$lr+j%@tqxh52_DXB_%rQgY*`C!4d%h{$X1vtxIGoDt z8;4WSI*$rt*nxA)W>$F*g>z5mI9jW|#|uZxFR%_yy$K9Gk52SH?S*Yv9%EWo!pQ>kQ^`i@!uDu<>rQmbn$iWm&%x09`j^v z=*h*>I(b&YYQ9wLA@>JIdFy6Rk*W2;s!^fku+41wJy<8=C&i9rt7?h7+I*)Q%W zI(VvG&CUfCZoe$;vg2E>)nlY4->!)4lsFu4jz&8B^E$0BT(?AvIKQxLrY9|iZrfiD zu?JpV$Ft1zTP_dL-Fm@nQ?nMdj!p+I*E%>hntZCttrH!RSFxSQcWSHtFyHfioGG{B z7jKE~A16MPw21`mL5 z&ZpCd#3qECD;6t7KZAllhZ}yZ??GEU}sxFtYV_@GajYgmBv9Bza6edqh)Z+TkY&Fd1B@gq) ze$$(H4}K?|u-g66EfuO|RelL_9=kqg^@+M_5u=%e1Ni2-ZCB}tNj&Cst!tDliFl@y z-s6^gI63Q*Lza(X?S7kP$83UAwzpMk&gYS3p-+yz0bIx`G~xD;?OU(8!l1(eoj$U5 zSVI;03C5()DY>>zTB z+5Jhv9uTbj#}^U)N9yat3H>BLzDbQ5QU4u>0nt3edv*kgp?{T(m};~=J^bdZLCvsi z4~Th0-M&WO(wFY)ssZrvm41E2qzmtve#~gcWVaPFfZ?xTo{BknqX0lcs2kyjz0I#_ zDVC*o5IBbW;fp>r4X7Jt9A~BmAI=B*@~ZH9{IebXT8UkL8hkN#F_PE;`2pp_-Mj+z zYJ{q188NX8_hQ~TW}0K>?@zzsKRh(^8WU_E3Ocs@!Af^v^hdkdi}kf1?U)_zz}Q!t zg+J|>6aUyFU$MWVe0uo|!*A%p>pT3M3Ve;#S56(O}`pyLZszYKr^K*gTPhCAGx&EX>YVjG$pLA$5UJrlNAxKQd{f({} zAEo@suJ(6)>*(M3;!War_+qv`=Jvwx!-1vm$0Xu!G@oSuyYb2O>(oLGqp$4iSp5GY JlVJr8_ Date: Wed, 11 Nov 2026 16:10:39 -0800 Subject: [PATCH 36/47] Use SetTextSkipNotify in CFWL_ComboBox programmatic updates Update CFWL_ComboBox::SetCurSel(), SetEditText(), and Layout() to call edit_->SetTextSkipNotify() rather than edit_->SetText(). Programmatic model-to-widget synchronization (via LoadWidget() and UpdateFWLData()) must not notify and dispatch TextWillChange/EditChanged events, which synchronously execute attacker-authored Change scripts during initial page layout or data binding updates. As with the hardening in CXFA_FFTextEdit::UpdateFWLData(), using the silent path prevents unintended script re-entrancy while preserving notifying behavior for user interactions. Update test replacing change event with an enter event since layout no longer dispatches change events. Remove unused preceding field to allow the initial tab keypress to focus the choiceList directly. Fixed: 575157680 Change-Id: I16f44ad616be3ce6c34058dfc546fddeaf9daf80 Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/163952 Commit-Queue: Tom Sepez Reviewed-by: Lei Zhang --- .../javascript/xfa_specific/bug_1109108.in | 16 +--------------- .../xfa_specific/bug_1109108_expected.txt | 1 + xfa/fwl/cfwl_combobox.cpp | 14 ++++++++++---- 3 files changed, 12 insertions(+), 19 deletions(-) diff --git a/testing/resources/javascript/xfa_specific/bug_1109108.in b/testing/resources/javascript/xfa_specific/bug_1109108.in index 550112e72..c51488b36 100644 --- a/testing/resources/javascript/xfa_specific/bug_1109108.in +++ b/testing/resources/javascript/xfa_specific/bug_1109108.in @@ -10,20 +10,6 @@ stream