mirror of
https://github.com/storytold/craft-libs.git
synced 2026-12-01 02:36:54 +01:00
hayro-jbig2: the JBIG2 decoder applies the document's pixel limit
hayro-jbig2 held every bitmap to a fixed 2^28 pixels, and the bounds on decoding work, a dictionary's symbol pixels, halftone grid cells and retained segment words were derived from that figure. hayro-syntax's JBIG2 filter also refused a page over 2^28 pixels itself, so a document opened with a raised DecodeLimits::max_image_pixels still could not decode a larger JBIG2 page. - hayro_jbig2::Limits carries the per-bitmap pixel bound, and the other bounds follow it in their default proportions. - Image::new_embedded_with_limits opens and decodes an image within a caller's Limits. Image::new and Image::new_embedded keep the 2^28 default and the same decoding work. - The JBIG2 filter passes the document's max_image_pixels. - hayro-syntax's manifest takes hayro-jbig2 from ../hayro-jbig2, so its own tests build against the patched decoder. - SOURCE.json records the committed hash of each changed file, and of the hayro-syntax files whose recorded hash was out of date.
This commit is contained in:
1 parent
01a4aca8eb
commit
f3540bc051
17 files changed
+373
-146
No files matched your search
Vendored
+19
-3
@@ -109,8 +109,8 @@ the last filter of an image of known size may produce (1 GiB by default), and
|
||||
`with_max_image_pixels` sets the most pixels an image or mask may have for the interpreter to
|
||||
decode it (2^28 by default, at most 2^32), before and after its codec decodes it. With 64-bit
|
||||
pointers a caller may raise either one; elsewhere a raise is clamped to the default.
|
||||
The CCITT and JPEG 2000 decoders hold an image to the document's pixel limit; JBIG2 keeps
|
||||
its own 2^28. `image_size_ok` and `ccitt_size_ok` keep the 2^28 default. An 8-bit `DeviceRGB` image with the default or inverted `/Decode` and no transfer function keeps its decoded samples as its
|
||||
The CCITT, JBIG2 and JPEG 2000 decoders hold an image to the document's pixel limit.
|
||||
`image_size_ok` and `ccitt_size_ok` keep the 2^28 default. An 8-bit `DeviceRGB` image with the default or inverted `/Decode` and no transfer function keeps its decoded samples as its
|
||||
RGB data instead of copying them into a second buffer. Tests:
|
||||
`decode_limits_tests::image_limits_default_and_caller_figures` in hayro-syntax and
|
||||
`image_limits` in `crates/pdf/tests/interpretation.rs`.
|
||||
@@ -149,7 +149,7 @@ Hostile-input bounds (CodeRabbit findings):
|
||||
inserted, so a tiny stream cannot declare billions of entries.
|
||||
- Each object stream's `/N` header pairs are parsed once per document and cached beside its
|
||||
decoded data, instead of on every compressed-object lookup.
|
||||
- An embedded JBIG2 page over 2^28 pixels is refused before the output buffer is allocated,
|
||||
- An embedded JBIG2 page over the document's pixel limit (2^28 by default) is refused before the output buffer is allocated,
|
||||
and that buffer is reserved fallibly (`Bitmap::reinitialize` allocates before touching the
|
||||
existing bitmap, so a failed reservation leaves it intact). A `JBIG2Globals` stream with an image filter is
|
||||
ignored, so globals cannot recurse through further globals.
|
||||
@@ -464,6 +464,22 @@ refused-mask handling in `hayro-syntax` and `hayro-interpret` (0ed33990, 4aa732e
|
||||
the decoded-image cache of 558ffd7f (a performance change). Tests: those that came with the patches in
|
||||
`hayro-jbig2`, and PdfCraft's raster tests adapted in `hayro-jbig2/src/pdfcraft_tests.rs`.
|
||||
|
||||
A craft-libs patch, labeled `Craft patch` in `hayro-jbig2`, derives these bounds from one figure,
|
||||
`Limits::max_pixels` (2^28 by default): the pixels of one bitmap (the page, a region, a symbol),
|
||||
the decoding work of one image (4 × the pixels, 2^30 by default), a dictionary's symbol pixels,
|
||||
the cells of a halftone grid (an eighth of the pixels, 2^25 by default) and the words a page's
|
||||
segments may hold (two bitmaps of the pixels, 64 MiB by default). `Image::new_embedded_with_limits`
|
||||
opens and decodes an image within a caller's `Limits`; `Image::new` and `Image::new_embedded`
|
||||
keep the defaults. hayro-syntax's JBIG2 filter passes the document's
|
||||
`DecodeLimits::max_image_pixels`, and its manifest takes `hayro-jbig2` from `../hayro-jbig2`, so
|
||||
`cargo test --manifest-path vendor/hayro-syntax/Cargo.toml` builds against the patched decoder.
|
||||
Each side of a bitmap is still at most 65535. Tests:
|
||||
`bitmap::pdfcraft_limit_tests::the_pixel_bound_follows_the_limits`,
|
||||
`tests::the_page_and_its_regions_follow_the_limits` and
|
||||
`tests::a_page_past_the_bounds_is_refused_when_opened` in hayro-jbig2;
|
||||
`filter::jbig2::tests::the_pixel_limit_given_is_the_one_applied` and
|
||||
`decode_limits_tests::a_documents_pixel_limit_reaches_the_jbig2_decoder` in hayro-syntax.
|
||||
|
||||
## Craft review note: the one direct `unsafe`
|
||||
|
||||
`hayro-syntax/src/page.rs` holds the snapshot's only direct `unsafe` block: a
|
||||
|
||||
Vendored
+9
-9
@@ -62,25 +62,25 @@
|
||||
"path": "src/bitmap.rs",
|
||||
"source_sha256": "59ed83d8bac6c39e40270a9856ca3faee628de7d9efae1b01f714e140e2b6b7e",
|
||||
"source_git_blob": "35ed97561597d30a70fe819cf8cfbd3780538f75",
|
||||
"sha256": "f5fa055ed19f6113d517875479ed4d4d732e06a0010067883a4c38820d55ff97"
|
||||
"sha256": "b718d061b68ffae040014e989e4c8473bbc64ed1f87fa05514fe3c69d8a1620a"
|
||||
},
|
||||
{
|
||||
"path": "src/decode/generic.rs",
|
||||
"source_sha256": "6646417cbea6b4563f47f6fa01d521f4654d609aa86713d34b4474963d222f81",
|
||||
"source_git_blob": "a788163f237a37016948e390083aefae702c4898",
|
||||
"sha256": "6646417cbea6b4563f47f6fa01d521f4654d609aa86713d34b4474963d222f81"
|
||||
"sha256": "860c4fd167e07f5d3110dce85a2509cb03ccc78056ce1752b747b5f07b291f8b"
|
||||
},
|
||||
{
|
||||
"path": "src/decode/generic_refinement.rs",
|
||||
"source_sha256": "625075671e510e8ff1d7c3cade857792413c091d57a35561ad0591d7f04c2ea5",
|
||||
"source_git_blob": "a566b8de58c078dec874d5d1dea36c0f557f1a16",
|
||||
"sha256": "7a4e36aa8b371f532e33163aad59133f8afa946935570b2312d057cd2a8b3837"
|
||||
"sha256": "c72f950c3f4db874f1503efe417a1a4b79503b13ad456808882851e16f5d3b89"
|
||||
},
|
||||
{
|
||||
"path": "src/decode/halftone.rs",
|
||||
"source_sha256": "0e4a5ef92e194b4eba2367196e904786dd7d346cdf0ab291c72a77b5aee5873a",
|
||||
"source_git_blob": "eb5c1c21e8a7d1a99c497e83ea59547b7dd19a96",
|
||||
"sha256": "16454b87a0c23e42d09936ae88f85cc03b4ea0e9d00ee409e751b4c94906c9d9"
|
||||
"sha256": "6714617563ddecde25a7bb8c799b8b90f1353e765855673fe4b3f1374523f115"
|
||||
},
|
||||
{
|
||||
"path": "src/decode/mod.rs",
|
||||
@@ -92,19 +92,19 @@
|
||||
"path": "src/decode/pattern.rs",
|
||||
"source_sha256": "abdd326c08dee0488678d74915e6bb4138c9b0c07d44f24c3a5794ff640799ba",
|
||||
"source_git_blob": "2c15d70b8f9925638e41cec0eb1d73b91c1533f2",
|
||||
"sha256": "d0a431725919158734f047101d004001f2e58fc21af8f5e92ef03ae06041b9b1"
|
||||
"sha256": "a77fe7166eebac0556c904c8630104072ed5cc27291c8316f1cb0f27b868cd42"
|
||||
},
|
||||
{
|
||||
"path": "src/decode/symbol.rs",
|
||||
"source_sha256": "aa57e88cdc6fd1647d7996875c253a643fedfc4438d5137e326e00d17d0d29ee",
|
||||
"source_git_blob": "f1aa8a6639e53dd350057d8d078198d363daa918",
|
||||
"sha256": "793e9943183b5ef119aa281dc13e782083fdac16e9b4c598083af1a95209256f"
|
||||
"sha256": "122a4131a3bd37820e1d594179fb6026e6ce43d9b4c62f6bb428587a94b5c71d"
|
||||
},
|
||||
{
|
||||
"path": "src/decode/text.rs",
|
||||
"source_sha256": "01863cdcd48ab68b5230948d12212a815d293c7c9d5382a140772088bfb1c405",
|
||||
"source_git_blob": "bbc2ac55c7d7d5b8aebffbecfe93fda8b88526e8",
|
||||
"sha256": "1f75a55d76111980d667713f841aa38a1fc20918e5bdcfef08a3a36842e2ca10"
|
||||
"sha256": "83d87998b247e9c23b6225d0a0c05c84d06f7a1ceb8c6c5abfdb111c1529b026"
|
||||
},
|
||||
{
|
||||
"path": "src/error.rs",
|
||||
@@ -122,7 +122,7 @@
|
||||
"path": "src/gray_scale.rs",
|
||||
"source_sha256": "46f12893f4573610789015ba7036f6afb1d30b1454c0c674fc7ccdd9337d7487",
|
||||
"source_git_blob": "2836ec77a7c8d3970b13dd46f576778c64bfe2d9",
|
||||
"sha256": "f82a6760de85bab325cffa6c75a0fa4e1d55fb9c67617be0d0fa112f2dd6c15f"
|
||||
"sha256": "909276ecd9bbd6f7c489563f7cb795ac088de02dff21f6a8eebbd133d1a96984"
|
||||
},
|
||||
{
|
||||
"path": "src/huffman_table.rs",
|
||||
@@ -158,7 +158,7 @@
|
||||
"path": "src/lib.rs",
|
||||
"source_sha256": "22463230cc82543ee93791b642566a308f0f4eb14d3089b24dc2e7f06d0f784c",
|
||||
"source_git_blob": "ad77a6dd17920b2db66f6bb5a0f2cb8efaafd41a",
|
||||
"sha256": "ac97e81ca5ec61d5d40247b561d0c1b17d7ac80aa173ee1bde099eb90e52a82f"
|
||||
"sha256": "7b7c75bf1f0fed2b95670b2fe5af10b9ceba33c53e362bacdced85189a43633f"
|
||||
},
|
||||
{
|
||||
"path": "src/page_info.rs",
|
||||
|
||||
Vendored
+79
-15
@@ -16,9 +16,47 @@ pub(crate) const MAX_DIMENSION: u32 = u16::MAX as u32;
|
||||
|
||||
/// PdfCraft patch: the most pixels one bitmap may have (2^28, the renderer's
|
||||
/// `MAX_IMAGE_PIXELS`). Each side alone may be 65535, so a single region could be 4.3 billion
|
||||
/// pixels, decoded one by one.
|
||||
/// pixels, decoded one by one. Craft patch: this is the default of [`Limits::max_pixels`].
|
||||
pub(crate) const MAX_PIXELS: u64 = 1 << 28;
|
||||
|
||||
/// Craft patch: the bounds a stream is decoded within. The bound on the pixels of one bitmap, the
|
||||
/// decoding work ([`MAX_WORK`]), the symbol pixels of a dictionary, the halftone grid cells
|
||||
/// ([`MAX_GRID_CELLS`]) and the words a page's segments may hold all follow
|
||||
/// [`Limits::max_pixels`], in the proportions they have at its default of 2^28.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Limits {
|
||||
max_pixels: u64,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Self { max_pixels: MAX_PIXELS }
|
||||
}
|
||||
}
|
||||
|
||||
impl Limits {
|
||||
/// The limits for a caller that allows `max_pixels` pixels in one bitmap. Each side of a
|
||||
/// bitmap is still at most 65535.
|
||||
pub fn with_max_pixels(max_pixels: u64) -> Self {
|
||||
Self { max_pixels }
|
||||
}
|
||||
|
||||
/// The most pixels one bitmap (the page, a region, a symbol) may have.
|
||||
pub fn max_pixels(&self) -> u64 {
|
||||
self.max_pixels
|
||||
}
|
||||
|
||||
/// The decoding work one image may ask for (see [`MAX_WORK`]).
|
||||
pub(crate) fn work(&self) -> u64 {
|
||||
self.max_pixels.saturating_mul(MAX_WORK / MAX_PIXELS)
|
||||
}
|
||||
|
||||
/// The most cells a halftone grid may have (see [`MAX_GRID_CELLS`]).
|
||||
pub(crate) fn grid_cells(&self) -> u64 {
|
||||
self.max_pixels / (MAX_PIXELS / MAX_GRID_CELLS)
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch: the most cells a halftone grid may have, which still gives the largest page
|
||||
/// (see [`MAX_PIXELS`]) cells of 3 × 3, unrotated. Each cell takes a 4-byte value while the grid decodes, so
|
||||
/// the pixel bound alone let a 98-byte segment take 1 GiB; this one leaves 128 MiB.
|
||||
@@ -68,11 +106,12 @@ pub(crate) const BITMAP_WORDS: usize = size_of::<Bitmap>() / size_of::<Word>();
|
||||
/// PdfCraft patch: refuse a page past the bounds on a bitmap (see `MAX_PIXELS`). A stream is held
|
||||
/// to this when it is opened as well as when its page bitmap is sized: a caller sizes its own
|
||||
/// output from the page header in between, and a 743-byte PDF's Indexed image asked for 137 GB.
|
||||
pub(crate) fn check_page_size(width: u32, height: u32) -> Result<()> {
|
||||
/// Craft patch: at most `max_pixels` pixels (see [`Limits::max_pixels`]).
|
||||
pub(crate) fn check_page_size(width: u32, height: u32, max_pixels: u64) -> Result<()> {
|
||||
if width > MAX_DIMENSION || height > MAX_DIMENSION {
|
||||
return Err(OverflowError::BitmapLimit.into());
|
||||
}
|
||||
if u64::from(width) * u64::from(height) > MAX_PIXELS {
|
||||
if u64::from(width) * u64::from(height) > max_pixels {
|
||||
return Err(OverflowError::BitmapLimit.into());
|
||||
}
|
||||
Ok(())
|
||||
@@ -115,9 +154,10 @@ impl Bitmap {
|
||||
|
||||
/// Create a new bitmap filled with white pixels (false).
|
||||
///
|
||||
/// The bitmap is positioned at (0, 0).
|
||||
pub(crate) fn new(width: u32, height: u32) -> Result<Self> {
|
||||
Self::new_with(width, height, 0, 0, false)
|
||||
/// The bitmap is positioned at (0, 0). Craft patch: it has at most `max_pixels` pixels (see
|
||||
/// [`Limits::max_pixels`]).
|
||||
pub(crate) fn new(width: u32, height: u32, max_pixels: u64) -> Result<Self> {
|
||||
Self::new_with(width, height, 0, 0, false, max_pixels)
|
||||
}
|
||||
|
||||
/// Create a new bitmap with full configuration.
|
||||
@@ -127,12 +167,13 @@ impl Bitmap {
|
||||
x_location: u32,
|
||||
y_location: u32,
|
||||
default_pixel: bool,
|
||||
max_pixels: u64,
|
||||
) -> Result<Self> {
|
||||
if width > MAX_DIMENSION || height > MAX_DIMENSION {
|
||||
bail!(OverflowError::BitmapLimit);
|
||||
}
|
||||
// PdfCraft patch: see `MAX_PIXELS`.
|
||||
if u64::from(width) * u64::from(height) > MAX_PIXELS {
|
||||
if u64::from(width) * u64::from(height) > max_pixels {
|
||||
bail!(OverflowError::BitmapLimit);
|
||||
}
|
||||
|
||||
@@ -177,8 +218,9 @@ impl Bitmap {
|
||||
width: u32,
|
||||
height: u32,
|
||||
default_pixel: bool,
|
||||
max_pixels: u64,
|
||||
) -> Result<()> {
|
||||
check_page_size(width, height)?;
|
||||
check_page_size(width, height, max_pixels)?;
|
||||
|
||||
let stride = width.div_ceil(WORD_BITS);
|
||||
let default_word: Word = if default_pixel { !0 } else { 0 };
|
||||
@@ -324,9 +366,10 @@ impl Bitmap {
|
||||
/// the page buffer, restricted to the area of the page buffer specified by this segment's
|
||||
/// region segment information field" (7.4.7.4). Off this bitmap the area is 0, past its width
|
||||
/// too whatever the padding of its rows holds, and outside the area the refinement reads 0
|
||||
/// (6.3.5.2), where reading the page itself took in the pixels around the area.
|
||||
pub(crate) fn area(&self, x: u32, y: u32, width: u32, height: u32) -> Result<Self> {
|
||||
let mut area = Self::new_with(width, height, x, y, false)?;
|
||||
/// (6.3.5.2), where reading the page itself took in the pixels around the area. Craft patch:
|
||||
/// the area has at most `max_pixels` pixels.
|
||||
pub(crate) fn area(&self, x: u32, y: u32, width: u32, height: u32, max_pixels: u64) -> Result<Self> {
|
||||
let mut area = Self::new_with(width, height, x, y, false, max_pixels)?;
|
||||
for row in 0..height {
|
||||
let Some(from_row) = y.checked_add(row).filter(|r| *r < self.height) else {
|
||||
continue;
|
||||
@@ -368,24 +411,45 @@ mod pdfcraft_limit_tests {
|
||||
fn a_bitmap_past_its_bounds_is_refused_by_a_limit() {
|
||||
let limit = Err(DecodeError::Overflow(OverflowError::BitmapLimit));
|
||||
assert_eq!(
|
||||
Bitmap::new(MAX_DIMENSION + 1, 1).map(|_| ()),
|
||||
Bitmap::new(MAX_DIMENSION + 1, 1, MAX_PIXELS).map(|_| ()),
|
||||
limit,
|
||||
"a side"
|
||||
);
|
||||
assert_eq!(
|
||||
Bitmap::new(1, MAX_DIMENSION + 1).map(|_| ()),
|
||||
Bitmap::new(1, MAX_DIMENSION + 1, MAX_PIXELS).map(|_| ()),
|
||||
limit,
|
||||
"the other"
|
||||
);
|
||||
// 2^28 + 2^14 pixels, each side within its bound.
|
||||
assert_eq!(
|
||||
Bitmap::new(1 << 14, (1 << 14) + 1).map(|_| ()),
|
||||
Bitmap::new(1 << 14, (1 << 14) + 1, MAX_PIXELS).map(|_| ()),
|
||||
limit,
|
||||
"the pixels"
|
||||
);
|
||||
assert!(
|
||||
Bitmap::new(1 << 14, 1 << 14).is_ok(),
|
||||
Bitmap::new(1 << 14, 1 << 14, MAX_PIXELS).is_ok(),
|
||||
"2^28 pixels are within it"
|
||||
);
|
||||
}
|
||||
|
||||
/// Craft patch: the pixel bound is the caller's, and the bounds derived from it keep their
|
||||
/// proportions to it. A side is still at most 65535 whatever the limit.
|
||||
#[test]
|
||||
fn the_pixel_bound_follows_the_limits() {
|
||||
let limit = Err(DecodeError::Overflow(OverflowError::BitmapLimit));
|
||||
assert_eq!(Bitmap::new(8, 4, 31).map(|_| ()), limit);
|
||||
assert!(Bitmap::new(8, 4, 32).is_ok());
|
||||
assert_eq!(check_page_size(1 << 15, 1 << 14, MAX_PIXELS), limit);
|
||||
assert!(check_page_size(1 << 15, 1 << 14, 1 << 29).is_ok());
|
||||
assert_eq!(check_page_size(MAX_DIMENSION + 1, 1, u64::MAX), limit);
|
||||
|
||||
let default = Limits::default();
|
||||
assert_eq!(default.max_pixels(), MAX_PIXELS);
|
||||
assert_eq!(default.work(), MAX_WORK);
|
||||
assert_eq!(default.grid_cells(), MAX_GRID_CELLS);
|
||||
let raised = Limits::with_max_pixels(1 << 30);
|
||||
assert_eq!(raised.work(), 4 << 30);
|
||||
assert_eq!(raised.grid_cells(), 1 << 27);
|
||||
assert_eq!(Limits::with_max_pixels(u64::MAX).work(), u64::MAX);
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -9,10 +9,12 @@ use crate::bitmap::{Bitmap, WORD_BITS, WORD_SHIFT, Word};
|
||||
use crate::error::{ParseError, RegionError, Result, TemplateError, bail};
|
||||
use crate::reader::Reader;
|
||||
|
||||
/// Generic region decoding procedure (6.2).
|
||||
/// Generic region decoding procedure (6.2). Craft patch: the region has at most `max_pixels`
|
||||
/// pixels (see `Limits::max_pixels`).
|
||||
pub(crate) fn decode(
|
||||
header: &GenericRegionHeader<'_>,
|
||||
ctx: &mut ScratchBuffers,
|
||||
max_pixels: u64,
|
||||
) -> Result<RegionBitmap> {
|
||||
let mut bitmap = Bitmap::new_with(
|
||||
header.region_info.width,
|
||||
@@ -20,6 +22,7 @@ pub(crate) fn decode(
|
||||
header.region_info.x_location,
|
||||
header.region_info.y_location,
|
||||
false,
|
||||
max_pixels,
|
||||
)?;
|
||||
|
||||
decode_into(header, &mut bitmap, ctx)?;
|
||||
|
||||
+4
-1
@@ -13,11 +13,13 @@ use crate::decode::generic::ContextGatherer;
|
||||
use crate::error::{ParseError, RegionError, Result, bail};
|
||||
use crate::reader::Reader;
|
||||
|
||||
/// Generic refinement region decoding procedure (6.3).
|
||||
/// Generic refinement region decoding procedure (6.3). Craft patch: the region has at most
|
||||
/// `max_pixels` pixels (see `Limits::max_pixels`).
|
||||
pub(crate) fn decode(
|
||||
header: &GenericRefinementRegionHeader<'_>,
|
||||
reference: &Bitmap,
|
||||
ctx: &mut ScratchBuffers,
|
||||
max_pixels: u64,
|
||||
) -> Result<RegionBitmap> {
|
||||
let mut region = Bitmap::new_with(
|
||||
header.region_info.width,
|
||||
@@ -25,6 +27,7 @@ pub(crate) fn decode(
|
||||
header.region_info.x_location,
|
||||
header.region_info.y_location,
|
||||
false,
|
||||
max_pixels,
|
||||
)?;
|
||||
|
||||
decode_into(header, reference, &mut region, ctx)?;
|
||||
|
||||
+14
-7
@@ -7,16 +7,18 @@ use super::RegionBitmap;
|
||||
use super::pattern::PatternDictionary;
|
||||
use super::{CombinationOperator, RegionSegmentInfo, Template, parse_region_segment_info};
|
||||
use crate::ScratchBuffers;
|
||||
use crate::bitmap::{Bitmap, MAX_DIMENSION, WORD_BITS, copy_work, decode_work};
|
||||
use crate::bitmap::{Bitmap, Limits, MAX_DIMENSION, WORD_BITS, copy_work, decode_work};
|
||||
use crate::error::{OverflowError, ParseError, RegionError, Result, bail};
|
||||
use crate::gray_scale::{GrayScaleParams, decode_gray_scale_image};
|
||||
use crate::reader::Reader;
|
||||
|
||||
/// Decode a halftone region segment (7.4.5.2, 6.6).
|
||||
/// Decode a halftone region segment (7.4.5.2, 6.6). Craft patch: the region and its grid stay
|
||||
/// within `limits`.
|
||||
pub(crate) fn decode(
|
||||
header: &HalftoneRegionHeader<'_>,
|
||||
pattern_dict: &PatternDictionary,
|
||||
ctx: &mut ScratchBuffers,
|
||||
limits: Limits,
|
||||
) -> Result<RegionBitmap> {
|
||||
let region = &header.region_info;
|
||||
|
||||
@@ -26,9 +28,10 @@ pub(crate) fn decode(
|
||||
region.x_location,
|
||||
region.y_location,
|
||||
header.flags.initial_pixel_color,
|
||||
limits.max_pixels(),
|
||||
)?;
|
||||
|
||||
decode_into(header, pattern_dict, &mut htreg, ctx)?;
|
||||
decode_into(header, pattern_dict, &mut htreg, ctx, limits)?;
|
||||
|
||||
Ok(RegionBitmap {
|
||||
bitmap: htreg,
|
||||
@@ -41,6 +44,7 @@ pub(crate) fn decode_into(
|
||||
pattern_dict: &PatternDictionary,
|
||||
htreg: &mut Bitmap,
|
||||
ctx: &mut ScratchBuffers,
|
||||
limits: Limits,
|
||||
) -> Result<()> {
|
||||
let skip_bitmap = if header.flags.enable_skip {
|
||||
Some(compute_skip_bitmap(header, pattern_dict, htreg)?)
|
||||
@@ -59,6 +63,7 @@ pub(crate) fn decode_into(
|
||||
height: header.grid_position_and_size.height,
|
||||
template: header.flags.template,
|
||||
skip_mask: skip_bitmap.as_deref(),
|
||||
max_cells: limits.grid_cells(),
|
||||
};
|
||||
let gi = decode_gray_scale_image(header.data, &gs_params, ctx)?;
|
||||
|
||||
@@ -91,8 +96,9 @@ fn bits_per_pixel(patterns: &PatternDictionary) -> u32 {
|
||||
.map_or(1, |n| n + 1)
|
||||
}
|
||||
|
||||
/// Parse a halftone region segment header (7.4.5.1).
|
||||
pub(crate) fn parse<'a>(reader: &mut Reader<'a>) -> Result<HalftoneRegionHeader<'a>> {
|
||||
/// Parse a halftone region segment header (7.4.5.1). Craft patch: the grid has at most the cells
|
||||
/// of `limits`.
|
||||
pub(crate) fn parse<'a>(reader: &mut Reader<'a>, limits: Limits) -> Result<HalftoneRegionHeader<'a>> {
|
||||
let region_info = parse_region_segment_info(reader)?;
|
||||
let flags_byte = reader.read_byte().ok_or(ParseError::UnexpectedEof)?;
|
||||
let mmr = flags_byte & 0x01 != 0;
|
||||
@@ -115,8 +121,9 @@ pub(crate) fn parse<'a>(reader: &mut Reader<'a>) -> Result<HalftoneRegionHeader<
|
||||
if grid_width > MAX_DIMENSION || grid_height > MAX_DIMENSION {
|
||||
bail!(OverflowError::GridDimension);
|
||||
}
|
||||
// PdfCraft patch: the product is bounded too (see `bitmap::MAX_GRID_CELLS`).
|
||||
if u64::from(grid_width) * u64::from(grid_height) > crate::bitmap::MAX_GRID_CELLS {
|
||||
// PdfCraft patch: the product is bounded too (see `bitmap::MAX_GRID_CELLS`; Craft patch: the
|
||||
// bound of `limits`).
|
||||
if u64::from(grid_width) * u64::from(grid_height) > limits.grid_cells() {
|
||||
bail!(OverflowError::GridDimension);
|
||||
}
|
||||
|
||||
|
||||
+5
-3
@@ -12,11 +12,13 @@ use alloc::vec::Vec;
|
||||
/// of 32 rows take 2 MiB. A 48-byte dictionary of 65,535 such patterns asked for 539 MB.
|
||||
const MAX_SHIFTED_WORDS: u64 = 1 << 22;
|
||||
|
||||
/// Decode a pattern dictionary segment (7.4.4.2, 6.7).
|
||||
/// Decode a pattern dictionary segment (7.4.4.2, 6.7). Craft patch: its bitmaps have at most
|
||||
/// `max_pixels` pixels (see `Limits::max_pixels`).
|
||||
pub(crate) fn decode(
|
||||
header: &PatternDictionaryHeader<'_>,
|
||||
scratch: &mut ScratchBuffers,
|
||||
room: u64,
|
||||
max_pixels: u64,
|
||||
) -> Result<PatternDictionary> {
|
||||
let pattern_width = header.pattern_width as u32;
|
||||
let pattern_height = header.pattern_height as u32;
|
||||
@@ -32,7 +34,7 @@ pub(crate) fn decode(
|
||||
.checked_mul(pattern_width)
|
||||
.ok_or(OverflowError::BitmapDimension)?;
|
||||
|
||||
let mut collective_bitmap = Bitmap::new(collective_width, pattern_height)?;
|
||||
let mut collective_bitmap = Bitmap::new(collective_width, pattern_height, max_pixels)?;
|
||||
|
||||
// "2) Decode the collective bitmap using a generic region decoding procedure
|
||||
// as described in 6.2." (6.7.5)
|
||||
@@ -89,7 +91,7 @@ pub(crate) fn decode(
|
||||
// HDPW × GRAY through HDPW × (GRAY + 1) − 1 be denoted B_P. Set:
|
||||
// HDPATS[GRAY] = B_P" (6.7.5)"
|
||||
let start_x = gray * pattern_width;
|
||||
let mut pattern = Bitmap::new(pattern_width, pattern_height)?;
|
||||
let mut pattern = Bitmap::new(pattern_width, pattern_height, max_pixels)?;
|
||||
|
||||
let src_word_idx = start_x / WORD_BITS;
|
||||
let src_bit_offset = start_x % WORD_BITS;
|
||||
|
||||
+26
-21
@@ -24,15 +24,6 @@ use crate::reader::Reader;
|
||||
|
||||
const MAX_SYMBOLS: u32 = u16::MAX as u32;
|
||||
|
||||
/// PdfCraft patch: the most symbol pixels one dictionary may decode, as many as the largest page
|
||||
/// bitmap holds (2^28, `bitmap::MAX_PIXELS`). Symbols are decoded pixel by pixel, and up to 65535
|
||||
/// of them of up to 65535 × 65535 each kept a fuzzed file decoding for minutes; each symbol now
|
||||
/// pays for its pixels out of the stream's decoding work (`bitmap::MAX_WORK`), which bounds the
|
||||
/// time, and holds them in the retained bitmaps (`room`), which bounds the memory. The bound was
|
||||
/// 2^26, a quarter of this, which a real scan passes: the soft mask of a 14,642 × 8,879 drawing
|
||||
/// with one dictionary of 7,559 symbols (#6722) needed more, and was refused.
|
||||
const MAX_DICTIONARY_PIXELS: u64 = crate::bitmap::MAX_PIXELS;
|
||||
|
||||
/// PdfCraft patch: decoding steps that decode nothing, allowed beyond what a valid dictionary can
|
||||
/// need. A height class without a symbol and an export run of length 0 don't move their loops
|
||||
/// on, and past the end of its data the arithmetic decoder can decode them for ever: one changed
|
||||
@@ -51,6 +42,7 @@ pub(crate) fn decode(
|
||||
input_contexts: Option<&RetainedContexts>,
|
||||
room: u64,
|
||||
work_left: &mut u64,
|
||||
max_pixels: u64,
|
||||
) -> Result<SymbolDictionary> {
|
||||
let num_new_symbols = header.num_new_symbols;
|
||||
|
||||
@@ -64,6 +56,7 @@ pub(crate) fn decode(
|
||||
total_width: 0,
|
||||
height_class_height: 0,
|
||||
pixels: 0,
|
||||
max_pixels,
|
||||
new_words: 0,
|
||||
room,
|
||||
work_left,
|
||||
@@ -134,11 +127,11 @@ pub(crate) fn decode(
|
||||
.total_width
|
||||
.checked_add(symbol_width)
|
||||
.ok_or(OverflowError::BitmapDimension)?;
|
||||
// PdfCraft patch: see `MAX_DICTIONARY_PIXELS`.
|
||||
// PdfCraft patch: see `SymbolDecodeContext::max_pixels`.
|
||||
ctx.pixels = ctx
|
||||
.pixels
|
||||
.saturating_add(u64::from(symbol_width) * u64::from(ctx.height_class_height));
|
||||
if ctx.pixels > MAX_DICTIONARY_PIXELS {
|
||||
if ctx.pixels > ctx.max_pixels {
|
||||
bail!(OverflowError::BitmapLimit);
|
||||
}
|
||||
// PdfCraft patch: see `bitmap::INTEGER_WORK`. Its width, and a stream can hold thousands
|
||||
@@ -159,7 +152,7 @@ pub(crate) fn decode(
|
||||
(false, false) => {
|
||||
// Decode a single symbol using a simple generic decoding procedure,
|
||||
// described in 6.5.8.1.
|
||||
let mut region = Bitmap::new(symbol_width, ctx.height_class_height)?;
|
||||
let mut region = Bitmap::new(symbol_width, ctx.height_class_height, ctx.max_pixels)?;
|
||||
generic::decode_bitmap_arithmetic_coding(
|
||||
&mut region,
|
||||
&mut ctx.a_ctx.decoder,
|
||||
@@ -319,7 +312,7 @@ fn decode_refinement_bitmap(
|
||||
};
|
||||
|
||||
let reference_region = ctx.symbols.get(symbol_id).ok_or(SymbolError::OutOfRange)?;
|
||||
let mut region = Bitmap::new(symbol_width, ctx.height_class_height)?;
|
||||
let mut region = Bitmap::new(symbol_width, ctx.height_class_height, ctx.max_pixels)?;
|
||||
|
||||
if use_huffman {
|
||||
let bitmap_size = ctx
|
||||
@@ -462,8 +455,9 @@ fn decode_aggregation_bitmap(
|
||||
header.region_info.x_location,
|
||||
header.region_info.y_location,
|
||||
header.flags.default_pixel,
|
||||
ctx.max_pixels,
|
||||
)?;
|
||||
decode_with(decode_ctx, &all_symbols, &header, &mut bitmap, ctx.work_left)?;
|
||||
decode_with(decode_ctx, &all_symbols, &header, &mut bitmap, ctx.work_left, ctx.max_pixels)?;
|
||||
Ok(bitmap)
|
||||
}
|
||||
|
||||
@@ -512,8 +506,18 @@ struct SymbolDecodeContext<'a> {
|
||||
new_words: u64,
|
||||
/// PdfCraft patch: the decoding work the stream may still ask for (see `bitmap::MAX_WORK`).
|
||||
work_left: &'a mut u64,
|
||||
/// PdfCraft patch: symbol pixels decoded so far (see `MAX_DICTIONARY_PIXELS`).
|
||||
/// PdfCraft patch: symbol pixels decoded so far (see `max_pixels`).
|
||||
pixels: u64,
|
||||
/// PdfCraft patch: the most symbol pixels one dictionary may decode, as many as the largest
|
||||
/// page bitmap holds (2^28, `bitmap::MAX_PIXELS`). Symbols are decoded pixel by pixel, and up
|
||||
/// to 65535 of them of up to 65535 × 65535 each kept a fuzzed file decoding for minutes; each
|
||||
/// symbol now pays for its pixels out of the stream's decoding work (`bitmap::MAX_WORK`),
|
||||
/// which bounds the time, and holds them in the retained bitmaps (`room`), which bounds the
|
||||
/// memory. The bound was 2^26, a quarter of this, which a real scan passes: the soft mask of a
|
||||
/// 14,642 × 8,879 drawing with one dictionary of 7,559 symbols (#6722) needed more, and was
|
||||
/// refused. Craft patch: this is `Limits::max_pixels`, 2^28 by default, which also bounds each
|
||||
/// bitmap the dictionary makes.
|
||||
max_pixels: u64,
|
||||
}
|
||||
|
||||
impl SymbolDecodeContext<'_> {
|
||||
@@ -677,7 +681,7 @@ fn decode_height_class_collective_bitmap(ctx: &mut SymbolDecodeContext<'_>) -> R
|
||||
// each byte. Rows are padded to the byte boundary.
|
||||
let row_bytes = ctx.total_width.div_ceil(8);
|
||||
|
||||
let mut bitmap = Bitmap::new(ctx.total_width, ctx.height_class_height)?;
|
||||
let mut bitmap = Bitmap::new(ctx.total_width, ctx.height_class_height, ctx.max_pixels)?;
|
||||
for y in 0..ctx.height_class_height {
|
||||
for byte_x in 0..row_bytes {
|
||||
let byte = ctx
|
||||
@@ -703,7 +707,7 @@ fn decode_height_class_collective_bitmap(ctx: &mut SymbolDecodeContext<'_>) -> R
|
||||
.read_bytes(bitmap_size as usize)
|
||||
.ok_or(ParseError::UnexpectedEof)?;
|
||||
|
||||
let mut bitmap = Bitmap::new(ctx.total_width, ctx.height_class_height)?;
|
||||
let mut bitmap = Bitmap::new(ctx.total_width, ctx.height_class_height, ctx.max_pixels)?;
|
||||
decode_bitmap_mmr(&mut bitmap, bitmap_data)?;
|
||||
bitmap
|
||||
};
|
||||
@@ -713,7 +717,7 @@ fn decode_height_class_collective_bitmap(ctx: &mut SymbolDecodeContext<'_>) -> R
|
||||
let mut x_offset: u32 = 0;
|
||||
for symbol_idx in ctx.height_class_first_symbol..ctx.symbols_decoded_count {
|
||||
let symbol_width = ctx.symbol_widths[symbol_idx as usize];
|
||||
let mut symbol = Bitmap::new(symbol_width, ctx.height_class_height)?;
|
||||
let mut symbol = Bitmap::new(symbol_width, ctx.height_class_height, ctx.max_pixels)?;
|
||||
|
||||
for y in 0..ctx.height_class_height {
|
||||
let src_bit_offset = x_offset % WORD_BITS;
|
||||
@@ -944,12 +948,13 @@ mod tests {
|
||||
// Huffman coding, 1,000 exported and no new symbols; export runs of 0 and 1,000 (B.1).
|
||||
let data = [0x00, 0x01, 0, 0, 0x03, 0xE8, 0, 0, 0, 0, 0x06, 0x02, 0xD8];
|
||||
let header = parse(&mut Reader::new(&data)).unwrap();
|
||||
let symbol = Bitmap::new(32, 32).unwrap();
|
||||
let max = crate::bitmap::MAX_PIXELS;
|
||||
let symbol = Bitmap::new(32, 32, max).unwrap();
|
||||
let input = vec![&symbol; 1000];
|
||||
let tables = StandardHuffmanTables::new();
|
||||
let words = symbol.words() as u64 * 1000;
|
||||
let decoded = decode(&header, &input, &[], &tables, None, words, &mut u64::MAX.clone()).unwrap();
|
||||
let decoded = decode(&header, &input, &[], &tables, None, words, &mut u64::MAX.clone(), max).unwrap();
|
||||
assert_eq!(decoded.exported_symbols.len(), 1000);
|
||||
assert!(decode(&header, &input, &[], &tables, None, words - 1, &mut u64::MAX.clone()).is_err());
|
||||
assert!(decode(&header, &input, &[], &tables, None, words - 1, &mut u64::MAX.clone(), max).is_err());
|
||||
}
|
||||
}
|
||||
+14
-6
@@ -18,7 +18,8 @@ use crate::integer_decoder::IntegerDecoder;
|
||||
use crate::reader::Reader;
|
||||
use crate::symbol_id_decoder::SymbolIdDecoder;
|
||||
|
||||
/// Decode a text region segment (6.4).
|
||||
/// Decode a text region segment (6.4). Craft patch: the region and its refined instances have
|
||||
/// at most `max_pixels` pixels (see `Limits::max_pixels`).
|
||||
pub(crate) fn decode(
|
||||
header: &TextRegionHeader<'_>,
|
||||
symbols: &[&Bitmap],
|
||||
@@ -26,6 +27,7 @@ pub(crate) fn decode(
|
||||
standard_tables: &StandardHuffmanTables,
|
||||
scratch: &mut ScratchBuffers,
|
||||
work_left: &mut u64,
|
||||
max_pixels: u64,
|
||||
) -> Result<RegionBitmap> {
|
||||
let mut bitmap = Bitmap::new_with(
|
||||
header.region_info.width,
|
||||
@@ -33,6 +35,7 @@ pub(crate) fn decode(
|
||||
header.region_info.x_location,
|
||||
header.region_info.y_location,
|
||||
header.flags.default_pixel,
|
||||
max_pixels,
|
||||
)?;
|
||||
|
||||
decode_into(
|
||||
@@ -43,6 +46,7 @@ pub(crate) fn decode(
|
||||
&mut bitmap,
|
||||
scratch,
|
||||
work_left,
|
||||
max_pixels,
|
||||
)?;
|
||||
|
||||
Ok(RegionBitmap {
|
||||
@@ -59,12 +63,13 @@ pub(crate) fn decode_into(
|
||||
bitmap: &mut Bitmap,
|
||||
scratch: &mut ScratchBuffers,
|
||||
work_left: &mut u64,
|
||||
max_pixels: u64,
|
||||
) -> Result<()> {
|
||||
if header.flags.use_huffman {
|
||||
let mut reader = Reader::new(header.data);
|
||||
let ctx =
|
||||
DecodeContext::new_huffman(&mut reader, header, referred_tables, standard_tables)?;
|
||||
decode_with(ctx, symbols, header, bitmap, work_left)?;
|
||||
decode_with(ctx, symbols, header, bitmap, work_left, max_pixels)?;
|
||||
} else {
|
||||
let mut decoder = ArithmeticDecoder::new(header.data);
|
||||
|
||||
@@ -79,19 +84,21 @@ pub(crate) fn decode_into(
|
||||
.resize(num_gr_contexts, ArithmeticDecoderContext::default());
|
||||
|
||||
let ctx = DecodeContext::new_arithmetic(&mut decoder, &mut contexts, &mut scratch.contexts);
|
||||
decode_with(ctx, symbols, header, bitmap, work_left)?;
|
||||
decode_with(ctx, symbols, header, bitmap, work_left, max_pixels)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decode a text region segment with a decode context (6.4).
|
||||
/// Decode a text region segment with a decode context (6.4). Craft patch: a refined instance has
|
||||
/// at most `max_pixels` pixels.
|
||||
pub(crate) fn decode_with(
|
||||
mut ctx: DecodeContext<'_, '_>,
|
||||
symbols: &[&Bitmap],
|
||||
header: &TextRegionHeader<'_>,
|
||||
region: &mut Bitmap,
|
||||
work_left: &mut u64,
|
||||
max_pixels: u64,
|
||||
) -> Result<()> {
|
||||
let strip_size = header.strip_size();
|
||||
|
||||
@@ -151,7 +158,7 @@ pub(crate) fn decode_with(
|
||||
let symbol_id = ctx.read_symbol_id()?;
|
||||
|
||||
let symbol_bitmap =
|
||||
decode_symbol_instance_bitmap(&mut ctx, symbols, header, symbol_id, work_left)?;
|
||||
decode_symbol_instance_bitmap(&mut ctx, symbols, header, symbol_id, work_left, max_pixels)?;
|
||||
|
||||
let symbol_bitmap_ref: &Bitmap = match &symbol_bitmap {
|
||||
SymbolBitmap::Reference(idx) => symbols.get(*idx).ok_or(SymbolError::OutOfRange)?,
|
||||
@@ -544,6 +551,7 @@ fn decode_symbol_instance_bitmap(
|
||||
header: &TextRegionHeader<'_>,
|
||||
symbol_id: usize,
|
||||
work_left: &mut u64,
|
||||
max_pixels: u64,
|
||||
) -> Result<SymbolBitmap> {
|
||||
if !header.flags.use_refinement || ctx.read_refinement_flag()? == 0 {
|
||||
return Ok(SymbolBitmap::Reference(symbol_id));
|
||||
@@ -580,7 +588,7 @@ fn decode_symbol_instance_bitmap(
|
||||
let work = decode_work(refined_width, refined_height).saturating_add(4 * INTEGER_WORK);
|
||||
*work_left = work_left.checked_sub(work).ok_or(OverflowError::DecodingWork)?;
|
||||
|
||||
let mut refined_bitmap = Bitmap::new(refined_width, refined_height)?;
|
||||
let mut refined_bitmap = Bitmap::new(refined_width, refined_height, max_pixels)?;
|
||||
|
||||
ctx.decode_refinement_bitmap(
|
||||
&mut refined_bitmap,
|
||||
|
||||
Vendored
+13
-7
@@ -27,6 +27,8 @@ pub(crate) struct GrayScaleParams<'a> {
|
||||
/// `GSKIP` - A mask indicating which values should be skipped.
|
||||
/// None if `GSUSESKIP` = 0.
|
||||
pub(crate) skip_mask: Option<&'a [u32]>,
|
||||
/// Craft patch: the most values the image may have (`Limits::grid_cells`).
|
||||
pub(crate) max_cells: u64,
|
||||
}
|
||||
|
||||
/// The gray-scale image decoding procedure (Annex C, C.5).
|
||||
@@ -59,7 +61,7 @@ fn decode_mmr(data: &[u8], params: &GrayScaleParams<'_>) -> Result<Vec<u32>> {
|
||||
let stride = width.div_ceil(WORD_BITS);
|
||||
|
||||
let mut offset = 0;
|
||||
decode_bitplanes(width, height, stride, bits_per_pixel, |_, bitplane| {
|
||||
decode_bitplanes(width, height, stride, bits_per_pixel, params.max_cells, |_, bitplane| {
|
||||
// Table C.4: "GBW = GSW, GBH = GSH"
|
||||
offset += decode_bitmap_mmr(bitplane, &data[offset..])?;
|
||||
|
||||
@@ -83,8 +85,9 @@ fn decode_arithmetic(
|
||||
if width > MAX_DIMENSION || height > MAX_DIMENSION {
|
||||
bail!(OverflowError::BitmapLimit);
|
||||
}
|
||||
// PdfCraft patch: the product is bounded too (see `bitmap::MAX_GRID_CELLS`).
|
||||
if u64::from(width) * u64::from(height) > crate::bitmap::MAX_GRID_CELLS {
|
||||
// PdfCraft patch: the product is bounded too (see `bitmap::MAX_GRID_CELLS`; Craft patch: the
|
||||
// bound of the image's limits).
|
||||
if u64::from(width) * u64::from(height) > params.max_cells {
|
||||
bail!(OverflowError::BitmapLimit);
|
||||
}
|
||||
|
||||
@@ -130,7 +133,7 @@ fn decode_arithmetic(
|
||||
|
||||
macro_rules! gs_decode_loop {
|
||||
($gather:expr) => {
|
||||
decode_bitplanes(width, height, stride, bits_per_pixel, |_, bitplane| {
|
||||
decode_bitplanes(width, height, stride, bits_per_pixel, params.max_cells, |_, bitplane| {
|
||||
// Table C.4: "GBW = GSW, GBH = GSH, TPGDON = 0"
|
||||
let mut gatherer = ContextGatherer::new(template, &at_pixels);
|
||||
|
||||
@@ -176,22 +179,24 @@ fn decode_arithmetic(
|
||||
/// The bitplane decoding and gray value computation procedure (C.5).
|
||||
///
|
||||
/// The closure `decode_next` is called for each bitplane, receiving the bitplane
|
||||
/// index (`GSBPP`-1 down to 0) and a zeroed bitmap to decode into.
|
||||
/// index (`GSBPP`-1 down to 0) and a zeroed bitmap to decode into. Craft patch: the image has at
|
||||
/// most `max_cells` values, checked before any of them is allocated.
|
||||
fn decode_bitplanes<F>(
|
||||
width: u32,
|
||||
height: u32,
|
||||
stride: u32,
|
||||
bits_per_pixel: u32,
|
||||
max_cells: u64,
|
||||
mut decode_next: F,
|
||||
) -> Result<Vec<u32>>
|
||||
where
|
||||
F: FnMut(u32, &mut Bitmap) -> Result<()>,
|
||||
{
|
||||
let mut bitplane = Bitmap::new(width, height, max_cells)?;
|
||||
|
||||
let size = width as usize * height as usize;
|
||||
// `GSVALS` - The decoded gray-scale image array.
|
||||
let mut values = vec![0_u32; size];
|
||||
|
||||
let mut bitplane = Bitmap::new(width, height)?;
|
||||
let mut prev_plane = vec![0; bitplane.data.len()];
|
||||
|
||||
simd::dispatch!(Level::new(), simd => {
|
||||
@@ -308,6 +313,7 @@ mod pdfcraft_limit_tests {
|
||||
height,
|
||||
template: Template::Template0,
|
||||
skip_mask: None,
|
||||
max_cells: crate::bitmap::MAX_GRID_CELLS,
|
||||
};
|
||||
decode_gray_scale_image(&[], ¶ms, &mut ScratchBuffers::default()).map(|_| ())
|
||||
};
|
||||
|
||||
Vendored
+114
-43
@@ -72,6 +72,7 @@ mod symbol_id_decoder;
|
||||
#[cfg(test)]
|
||||
mod pdfcraft_tests;
|
||||
|
||||
pub use bitmap::Limits;
|
||||
use error::bail;
|
||||
pub use error::{
|
||||
DecodeError, FormatError, HuffmanError, OverflowError, ParseError, RegionError, Result,
|
||||
@@ -108,6 +109,8 @@ pub struct Image<'a> {
|
||||
height: u32,
|
||||
/// The height determined from `EndOfStripe` segments, if applicable.
|
||||
height_from_stripes: Option<u32>,
|
||||
/// Craft patch: the bounds the image is opened and decoded within.
|
||||
limits: Limits,
|
||||
}
|
||||
|
||||
impl<'a> Image<'a> {
|
||||
@@ -117,7 +120,7 @@ impl<'a> Image<'a> {
|
||||
/// as defined in Annex D.1 and D.2.
|
||||
pub fn new(data: &'a [u8]) -> Result<Self> {
|
||||
let file = parse_file(data)?;
|
||||
Self::from_segments(file.segments)
|
||||
Self::from_segments(file.segments, Limits::default())
|
||||
}
|
||||
|
||||
/// Parse an embedded JBIG2 image with optional global segments.
|
||||
@@ -127,6 +130,12 @@ impl<'a> Image<'a> {
|
||||
/// is read past it, in the organization it declares, as Acrobat and PDFBox
|
||||
/// draw such streams; its segments still count together with the globals'.
|
||||
pub fn new_embedded(data: &'a [u8], globals: Option<&'a [u8]>) -> Result<Self> {
|
||||
Self::new_embedded_with_limits(data, globals, Limits::default())
|
||||
}
|
||||
|
||||
/// Craft patch: [`Image::new_embedded`] within `limits` instead of the defaults. The page is
|
||||
/// checked against them when it is opened, and the image decodes within them.
|
||||
pub fn new_embedded_with_limits(data: &'a [u8], globals: Option<&'a [u8]>, limits: Limits) -> Result<Self> {
|
||||
let mut segments = Vec::new();
|
||||
let mut count = SegmentCount::default();
|
||||
if let Some(globals_data) = globals {
|
||||
@@ -149,10 +158,10 @@ impl<'a> Image<'a> {
|
||||
|
||||
segments.sort_by_key(|seg| seg.header.segment_number);
|
||||
|
||||
Self::from_segments(segments)
|
||||
Self::from_segments(segments, limits)
|
||||
}
|
||||
|
||||
fn from_segments(segments: Vec<segment::Segment<'a>>) -> Result<Self> {
|
||||
fn from_segments(segments: Vec<segment::Segment<'a>>, limits: Limits) -> Result<Self> {
|
||||
// Pre-scan for stripe height from EndOfStripe segments.
|
||||
let height_from_stripes = segments
|
||||
.iter()
|
||||
@@ -181,13 +190,14 @@ impl<'a> Image<'a> {
|
||||
if page_info.width == 0 || height == 0 {
|
||||
bail!(FormatError::EmptyPage);
|
||||
}
|
||||
bitmap::check_page_size(page_info.width, height)?;
|
||||
bitmap::check_page_size(page_info.width, height, limits.max_pixels())?;
|
||||
|
||||
Ok(Self {
|
||||
segments,
|
||||
width: page_info.width,
|
||||
height,
|
||||
height_from_stripes,
|
||||
limits,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -213,8 +223,8 @@ impl<'a> Image<'a> {
|
||||
/// This is useful in case you want to convert multiple JBIG2 images,
|
||||
/// as it allows `hayro-jbig2` to reuse allocations during decoding.
|
||||
pub fn decode_with<D: Decoder>(&self, decoder: &mut D, ctx: &mut DecoderContext) -> Result<()> {
|
||||
let mut work_left = bitmap::MAX_WORK;
|
||||
decode_segments(&self.segments, self.height_from_stripes, ctx, &mut work_left)?;
|
||||
let mut work_left = self.limits.work();
|
||||
decode_segments(&self.segments, self.height_from_stripes, ctx, &mut work_left, self.limits)?;
|
||||
emit_bitmap(&ctx.page_bitmap, decoder);
|
||||
|
||||
Ok(())
|
||||
@@ -224,21 +234,22 @@ impl<'a> Image<'a> {
|
||||
/// across a run of images. An image spends what it took, failing or not, starting with its
|
||||
/// page's pixels, which whoever asked for them will go through, and its segments, so images
|
||||
/// that decode nothing add up too. On top of that, it takes at most [`bitmap::MAX_WORK`]
|
||||
/// whatever `work` says. One that `work` can't pay for spends all of it, so a run ends rather
|
||||
/// than trying every image it has left. Reading the stream comes before this and is charged
|
||||
/// by [`charge_reading`].
|
||||
/// (Craft patch: the work of the image's [`Limits`]) whatever `work` says. One that `work`
|
||||
/// can't pay for spends all of it, so a run ends rather than trying every image it has left.
|
||||
/// Reading the stream comes before this and is charged by [`charge_reading`].
|
||||
pub fn decode_within<D: Decoder>(&self, decoder: &mut D, work: &mut u64) -> Result<()> {
|
||||
let start = bitmap::decode_work(self.width, self.height).saturating_add(self.segments.len() as u64);
|
||||
if charge_work(work, start).is_err() {
|
||||
*work = 0;
|
||||
bail!(OverflowError::DecodingWork);
|
||||
}
|
||||
let allowed = bitmap::MAX_WORK.min(*work);
|
||||
let most = self.limits.work();
|
||||
let allowed = most.min(*work);
|
||||
let mut left = allowed;
|
||||
let mut ctx = DecoderContext::default();
|
||||
let decoded = decode_segments(&self.segments, self.height_from_stripes, &mut ctx, &mut left);
|
||||
let decoded = decode_segments(&self.segments, self.height_from_stripes, &mut ctx, &mut left, self.limits);
|
||||
let refused = decoded == Err(OverflowError::DecodingWork.into());
|
||||
*work = if refused && allowed < bitmap::MAX_WORK { 0 } else { *work - (allowed - left) };
|
||||
*work = if refused && allowed < most { 0 } else { *work - (allowed - left) };
|
||||
decoded?;
|
||||
emit_bitmap(&ctx.page_bitmap, &mut *decoder);
|
||||
|
||||
@@ -334,8 +345,8 @@ fn region_work(region: &decode::RegionSegmentInfo) -> u64 {
|
||||
/// PdfCraft patch: the page restricted to a refinement's area, its reference when it refers to no
|
||||
/// other region (7.4.7.4). Copying it a word at a time costs less than the region's own decoding,
|
||||
/// already charged, and it is held, as large as the region, only while the region decodes.
|
||||
fn page_area(page: &Bitmap, region: &decode::RegionSegmentInfo) -> Result<Bitmap> {
|
||||
page.area(region.x_location, region.y_location, region.width, region.height)
|
||||
fn page_area(page: &Bitmap, region: &decode::RegionSegmentInfo, max_pixels: u64) -> Result<Bitmap> {
|
||||
page.area(region.x_location, region.y_location, region.width, region.height, max_pixels)
|
||||
}
|
||||
|
||||
fn decode_segments(
|
||||
@@ -343,7 +354,9 @@ fn decode_segments(
|
||||
height_from_stripes: Option<u32>,
|
||||
decoder_ctx: &mut DecoderContext,
|
||||
work_left: &mut u64,
|
||||
limits: Limits,
|
||||
) -> Result<()> {
|
||||
let max_pixels = limits.max_pixels();
|
||||
// Find and parse page information segment first.
|
||||
if let Some(page_info) = segments
|
||||
.iter()
|
||||
@@ -355,6 +368,7 @@ fn decode_segments(
|
||||
height_from_stripes,
|
||||
&mut decoder_ctx.page_state,
|
||||
&mut decoder_ctx.page_bitmap,
|
||||
limits,
|
||||
)?;
|
||||
} else {
|
||||
bail!(FormatError::MissingPageInfo);
|
||||
@@ -380,7 +394,7 @@ fn decode_segments(
|
||||
if page_state.can_decode_directly(page_bitmap, &header.region_info, false) {
|
||||
generic::decode_into(&header, page_bitmap, scratch_buffers)?;
|
||||
} else {
|
||||
let region = generic::decode(&header, scratch_buffers)?;
|
||||
let region = generic::decode(&header, scratch_buffers, max_pixels)?;
|
||||
page_bitmap.combine_region(®ion.bitmap, region.combination_operator);
|
||||
}
|
||||
page_state.page_pristine = false;
|
||||
@@ -389,13 +403,13 @@ fn decode_segments(
|
||||
// Intermediate segments cannot have unknown length.
|
||||
let header = generic::parse(&mut reader, false)?;
|
||||
charge_work(work_left, region_work(&header.region_info))?;
|
||||
let region = generic::decode(&header, scratch_buffers)?;
|
||||
let region = generic::decode(&header, scratch_buffers, max_pixels)?;
|
||||
page_state.store_region(seg.header.segment_number, region.bitmap)?;
|
||||
}
|
||||
SegmentType::PatternDictionary => {
|
||||
let header = pattern::parse(&mut reader)?;
|
||||
charge_work(work_left, header.work())?;
|
||||
let dictionary = pattern::decode(&header, scratch_buffers, page_state.retained_room())?;
|
||||
let dictionary = pattern::decode(&header, scratch_buffers, page_state.retained_room(), max_pixels)?;
|
||||
page_state.store_pattern_dictionary(seg.header.segment_number, dictionary)?;
|
||||
}
|
||||
SegmentType::SymbolDictionary => {
|
||||
@@ -431,6 +445,7 @@ fn decode_segments(
|
||||
retained_contexts,
|
||||
page_state.retained_room(),
|
||||
work_left,
|
||||
max_pixels,
|
||||
)?;
|
||||
page_state.store_symbol_dictionary(seg.header.segment_number, dictionary)?;
|
||||
}
|
||||
@@ -470,6 +485,7 @@ fn decode_segments(
|
||||
page_bitmap,
|
||||
scratch_buffers,
|
||||
work_left,
|
||||
max_pixels,
|
||||
)?;
|
||||
} else {
|
||||
let region = text::decode(
|
||||
@@ -479,6 +495,7 @@ fn decode_segments(
|
||||
&page_state.standard_tables,
|
||||
scratch_buffers,
|
||||
work_left,
|
||||
max_pixels,
|
||||
)?;
|
||||
page_bitmap.combine_region(®ion.bitmap, region.combination_operator);
|
||||
}
|
||||
@@ -511,6 +528,7 @@ fn decode_segments(
|
||||
&page_state.standard_tables,
|
||||
scratch_buffers,
|
||||
work_left,
|
||||
max_pixels,
|
||||
)?;
|
||||
page_state.store_region(seg.header.segment_number, region.bitmap)?;
|
||||
}
|
||||
@@ -522,7 +540,7 @@ fn decode_segments(
|
||||
.and_then(|&num| page_state.get_pattern_dictionary(num))
|
||||
.ok_or(SegmentError::MissingPatternDictionary)?;
|
||||
|
||||
let header = halftone::parse(&mut reader)?;
|
||||
let header = halftone::parse(&mut reader, limits)?;
|
||||
charge_work(work_left, halftone::work(&header, pattern_dict))?;
|
||||
|
||||
if page_state.can_decode_directly(
|
||||
@@ -530,9 +548,9 @@ fn decode_segments(
|
||||
&header.region_info,
|
||||
header.flags.initial_pixel_color,
|
||||
) {
|
||||
halftone::decode_into(&header, pattern_dict, page_bitmap, scratch_buffers)?;
|
||||
halftone::decode_into(&header, pattern_dict, page_bitmap, scratch_buffers, limits)?;
|
||||
} else {
|
||||
let region = halftone::decode(&header, pattern_dict, scratch_buffers)?;
|
||||
let region = halftone::decode(&header, pattern_dict, scratch_buffers, limits)?;
|
||||
page_bitmap.combine_region(®ion.bitmap, region.combination_operator);
|
||||
}
|
||||
page_state.page_pristine = false;
|
||||
@@ -545,9 +563,9 @@ fn decode_segments(
|
||||
.and_then(|&num| page_state.get_pattern_dictionary(num))
|
||||
.ok_or(SegmentError::MissingPatternDictionary)?;
|
||||
|
||||
let header = halftone::parse(&mut reader)?;
|
||||
let header = halftone::parse(&mut reader, limits)?;
|
||||
charge_work(work_left, halftone::work(&header, pattern_dict))?;
|
||||
let region = halftone::decode(&header, pattern_dict, scratch_buffers)?;
|
||||
let region = halftone::decode(&header, pattern_dict, scratch_buffers, limits)?;
|
||||
page_state.store_region(seg.header.segment_number, region.bitmap)?;
|
||||
}
|
||||
SegmentType::IntermediateGenericRefinementRegion => {
|
||||
@@ -565,11 +583,11 @@ fn decode_segments(
|
||||
let reference = match referred_segment {
|
||||
Some(region) => region,
|
||||
None => {
|
||||
area = page_area(page_bitmap, &header.region_info)?;
|
||||
area = page_area(page_bitmap, &header.region_info, max_pixels)?;
|
||||
&area
|
||||
}
|
||||
};
|
||||
let region = generic_refinement::decode(&header, reference, scratch_buffers)?;
|
||||
let region = generic_refinement::decode(&header, reference, scratch_buffers, max_pixels)?;
|
||||
page_state.store_region(seg.header.segment_number, region.bitmap)?;
|
||||
}
|
||||
SegmentType::ImmediateGenericRefinementRegion
|
||||
@@ -603,11 +621,11 @@ fn decode_segments(
|
||||
let reference = match referred_segment {
|
||||
Some(region) => region,
|
||||
None => {
|
||||
area = page_area(page_bitmap, &header.region_info)?;
|
||||
area = page_area(page_bitmap, &header.region_info, max_pixels)?;
|
||||
&area
|
||||
}
|
||||
};
|
||||
let region = generic_refinement::decode(&header, reference, scratch_buffers)?;
|
||||
let region = generic_refinement::decode(&header, reference, scratch_buffers, max_pixels)?;
|
||||
page_bitmap.combine_region(®ion.bitmap, region.combination_operator);
|
||||
}
|
||||
page_state.page_pristine = false;
|
||||
@@ -638,9 +656,16 @@ const ENTRY_WORDS: u64 = 32;
|
||||
/// bound on all of them a stream of a few dozen bytes a segment held 33 MB each (a 16,384-sample
|
||||
/// square region of typical rows), and a few kilobytes could exhaust memory. A segment being
|
||||
/// decoded takes more for a while, within its own bounds: the page bitmap isn't counted, nor is
|
||||
/// what a region or a grid uses until it is stored or freed.
|
||||
const MAX_RETAINED_WORDS: u64 =
|
||||
2 * (bitmap::MAX_PIXELS / bitmap::WORD_BITS as u64 + bitmap::BITMAP_WORDS as u64 + ENTRY_WORDS);
|
||||
/// what a region or a grid uses until it is stored or freed. Craft patch: the bitmaps have
|
||||
/// `max_pixels` pixels each (see [`Limits::max_pixels`]), so the 64 MiB is the bound at the
|
||||
/// default [`Limits`].
|
||||
const fn max_retained_words(max_pixels: u64) -> u64 {
|
||||
(max_pixels / bitmap::WORD_BITS as u64 + bitmap::BITMAP_WORDS as u64 + ENTRY_WORDS).saturating_mul(2)
|
||||
}
|
||||
|
||||
/// Craft patch: [`max_retained_words`] at the default [`Limits`].
|
||||
#[cfg(test)]
|
||||
const MAX_RETAINED_WORDS: u64 = max_retained_words(bitmap::MAX_PIXELS);
|
||||
|
||||
/// PdfCraft patch: the most symbols one segment may refer to, 2^20, far beyond the 65,535 a
|
||||
/// dictionary may export. References may repeat, so each names the same symbols again: without
|
||||
@@ -664,14 +689,17 @@ pub(crate) struct PageState {
|
||||
/// "Tables – see 7.4.13." (type 53)
|
||||
pub(crate) huffman_tables: Vec<(u32, HuffmanTable)>,
|
||||
/// PdfCraft patch: the words the regions, dictionaries and tables above hold, at most
|
||||
/// [`MAX_RETAINED_WORDS`].
|
||||
/// [`max_retained_words`] of the page's limits.
|
||||
pub(crate) retained_words: u64,
|
||||
/// Craft patch: the limits the page decodes within, which set the bound on `retained_words`.
|
||||
pub(crate) limits: Limits,
|
||||
/// Standard Huffman tables (`TABLE_A` through `TABLE_O`).
|
||||
pub(crate) standard_tables: StandardHuffmanTables,
|
||||
}
|
||||
|
||||
impl PageState {
|
||||
fn reset(&mut self, page_info: PageInformation) {
|
||||
fn reset(&mut self, page_info: PageInformation, limits: Limits) {
|
||||
self.limits = limits;
|
||||
self.page_info = page_info;
|
||||
self.page_pristine = true;
|
||||
self.referred_segments.clear();
|
||||
@@ -718,14 +746,14 @@ impl PageState {
|
||||
|
||||
/// PdfCraft patch: the words the page may still hold for later segments.
|
||||
fn retained_room(&self) -> u64 {
|
||||
MAX_RETAINED_WORDS.saturating_sub(self.retained_words)
|
||||
max_retained_words(self.limits.max_pixels()).saturating_sub(self.retained_words)
|
||||
}
|
||||
|
||||
/// PdfCraft patch: count a stored item holding `words` for later segments, refusing past
|
||||
/// [`MAX_RETAINED_WORDS`].
|
||||
/// [`max_retained_words`] of the page's limits.
|
||||
fn retain(&mut self, words: usize) -> Result<()> {
|
||||
self.retained_words = self.retained_words.saturating_add(words as u64).saturating_add(ENTRY_WORDS);
|
||||
if self.retained_words > MAX_RETAINED_WORDS {
|
||||
if self.retained_words > max_retained_words(self.limits.max_pixels()) {
|
||||
bail!(OverflowError::RetainedBitmaps);
|
||||
}
|
||||
Ok(())
|
||||
@@ -811,6 +839,7 @@ fn init_page(
|
||||
height_from_stripes: Option<u32>,
|
||||
page: &mut PageState,
|
||||
bitmap: &mut Bitmap,
|
||||
limits: Limits,
|
||||
) -> Result<()> {
|
||||
let page_info = parse_page_information(reader)?;
|
||||
|
||||
@@ -826,9 +855,9 @@ fn init_page(
|
||||
// "Bit 2: Page default pixel value. This bit contains the initial value
|
||||
// for every pixel in the page, before any region segments are decoded
|
||||
// or drawn." (7.4.8.5)
|
||||
bitmap.reinitialize(page_info.width, height, page_info.flags.default_pixel != 0)?;
|
||||
bitmap.reinitialize(page_info.width, height, page_info.flags.default_pixel != 0, limits.max_pixels())?;
|
||||
|
||||
page.reset(page_info);
|
||||
page.reset(page_info, limits);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -852,6 +881,43 @@ mod tests {
|
||||
assert!(Image::new_embedded(&stream(16385, 16384), None).is_err());
|
||||
assert!(Image::new_embedded(&stream(65536, 1), None).is_err(), "too wide, though few pixels");
|
||||
assert!(Image::new_embedded(&stream(1 << 20, 1 << 20), None).is_err());
|
||||
// Craft patch: within a raised limit, a page past 2^28 pixels opens.
|
||||
let raised = Limits::with_max_pixels(1 << 29);
|
||||
assert!(Image::new_embedded_with_limits(&stream(32768, 16384), None, Limits::default()).is_err());
|
||||
assert!(Image::new_embedded_with_limits(&stream(32768, 16384), None, raised).is_ok());
|
||||
assert!(Image::new_embedded_with_limits(&stream(65536, 1), None, raised).is_err(), "a side is still at most 65535");
|
||||
}
|
||||
|
||||
/// Craft patch: the page and its regions follow the image's limits. A 9 × 8 generic region on an
|
||||
/// 8 × 8 page is decoded into a bitmap of its own, which a limit of 64 pixels refuses and one of
|
||||
/// 72 allows; the page alone opens within 64 and not within 63.
|
||||
#[test]
|
||||
fn the_page_and_its_regions_follow_the_limits() {
|
||||
let mut region: Vec<u8> = [9u32, 8, 0, 0].iter().flat_map(|v| v.to_be_bytes()).collect();
|
||||
region.push(OR);
|
||||
region.extend_from_slice(GENERIC);
|
||||
region.extend_from_slice(&[0x5a; 16]);
|
||||
let stream = [page_of_8(), segment(1, 38, &[], ®ion)].concat();
|
||||
struct Count(u32);
|
||||
impl Decoder for Count {
|
||||
fn push_pixel(&mut self, _: bool) {
|
||||
self.0 += 1;
|
||||
}
|
||||
fn push_pixel_chunk(&mut self, _: bool, chunks: u32) {
|
||||
self.0 += 8 * chunks;
|
||||
}
|
||||
fn next_line(&mut self) {}
|
||||
}
|
||||
let decoded = |max_pixels: u64| {
|
||||
let mut count = Count(0);
|
||||
Image::new_embedded_with_limits(&stream, None, Limits::with_max_pixels(max_pixels))
|
||||
.and_then(|image| image.decode(&mut count))
|
||||
.map(|()| count.0)
|
||||
};
|
||||
assert_eq!(decoded(1 << 28), Ok(64));
|
||||
assert_eq!(decoded(72), Ok(64));
|
||||
assert_eq!(decoded(64), Err(OverflowError::BitmapLimit.into()));
|
||||
assert_eq!(decoded(63), Err(OverflowError::BitmapLimit.into()));
|
||||
}
|
||||
|
||||
/// Segment `number` of `kind` on page 1, referring to `refers_to`.
|
||||
@@ -1027,9 +1093,9 @@ mod tests {
|
||||
/// that padding (patch 13), so the page's words are set to all 1s, padding included.
|
||||
#[test]
|
||||
fn a_page_area_is_the_page_inside_it_and_0_outside() {
|
||||
let mut page = Bitmap::new_with(40, 3, 0, 0, true).unwrap();
|
||||
let mut page = Bitmap::new_with(40, 3, 0, 0, true, bitmap::MAX_PIXELS).unwrap();
|
||||
page.data.fill(!0);
|
||||
let area = |x, y, width, height| page.area(x, y, width, height).unwrap().data;
|
||||
let area = |x, y, width, height| page.area(x, y, width, height, bitmap::MAX_PIXELS).unwrap().data;
|
||||
assert_eq!(area(30, 1, 20, 3), [0xFFC0_0000, 0xFFC0_0000, 0], "10 columns and 2 rows of the page");
|
||||
assert_eq!(area(0, 0, 33, 1), [!0, 0x8000_0000], "the whole of a word, and none of the area's padding");
|
||||
assert_eq!(area(36, 0, 8, 1), [0xF000_0000], "4 columns, and none of the page's padding");
|
||||
@@ -1107,6 +1173,10 @@ mod tests {
|
||||
assert_eq!(page.retained_room(), MAX_RETAINED_WORDS - 1000 - ENTRY_WORDS);
|
||||
page.retained_words = MAX_RETAINED_WORDS;
|
||||
assert_eq!(page.retained_room(), 0);
|
||||
// Craft patch: the bound follows the page's limits.
|
||||
page.limits = Limits::with_max_pixels(1 << 30);
|
||||
assert_eq!(page.retained_room(), max_retained_words(1 << 30) - MAX_RETAINED_WORDS);
|
||||
assert!(max_retained_words(1 << 30) > 4 * ((1 << 28) / 32));
|
||||
}
|
||||
|
||||
/// Pixels past a bitmap's edge are 0 (6.3.5.2), and a refinement reads its reference a word at
|
||||
@@ -1114,11 +1184,12 @@ mod tests {
|
||||
/// the next image.
|
||||
#[test]
|
||||
fn a_bitmap_of_1s_has_nothing_past_its_width() {
|
||||
assert_eq!(Bitmap::new_with(33, 2, 0, 0, true).unwrap().data, [!0, 1 << 31, !0, 1 << 31]);
|
||||
let mut page = Bitmap::new_with(40, 1, 0, 0, false).unwrap();
|
||||
page.reinitialize(7, 2, true).unwrap();
|
||||
let max = bitmap::MAX_PIXELS;
|
||||
assert_eq!(Bitmap::new_with(33, 2, 0, 0, true, max).unwrap().data, [!0, 1 << 31, !0, 1 << 31]);
|
||||
let mut page = Bitmap::new_with(40, 1, 0, 0, false, max).unwrap();
|
||||
page.reinitialize(7, 2, true, max).unwrap();
|
||||
assert_eq!(page.data, [0xFE00_0000, 0xFE00_0000]);
|
||||
assert_eq!(Bitmap::new_with(64, 1, 0, 0, true).unwrap().data, [!0, !0], "words filled whole");
|
||||
assert!(Bitmap::new_with(0, 3, 0, 0, true).unwrap().data.is_empty(), "no width");
|
||||
assert_eq!(Bitmap::new_with(64, 1, 0, 0, true, max).unwrap().data, [!0, !0], "words filled whole");
|
||||
assert!(Bitmap::new_with(0, 3, 0, 0, true, max).unwrap().data.is_empty(), "no width");
|
||||
}
|
||||
}
|
||||
-2
@@ -135,8 +135,6 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69374b3668dd45aeb3d3145cda68f2c7b4f223aaa2511e67d076f1c7d741388d"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
|
||||
Vendored
+1
@@ -78,6 +78,7 @@ default-features = false
|
||||
|
||||
[dependencies.hayro-jbig2]
|
||||
version = "=0.3.0"
|
||||
path = "../hayro-jbig2"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
|
||||
Vendored
+11
-11
@@ -8,13 +8,13 @@
|
||||
"path": "Cargo.lock",
|
||||
"source_sha256": "d73da432072780b3d1fc725da68ad174c75f1720d0ed903521f664bfc16c70a8",
|
||||
"source_git_blob": "ebc07dfff7b53f62a5ff422c19a779ab61c106cc",
|
||||
"sha256": "6106b3f3ad57258826fa72d2eaebfd2f66a37fccdc67507c348e603f71db088d"
|
||||
"sha256": "b6be8e801ccdc250aff6adc5cc20b53cdc9ff3dd2206328f9317db16c1b95a3f"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.toml",
|
||||
"source_sha256": "2520802133a82f9bfca9be7fe4a384af1bce05ada198fd9d637d99d877625333",
|
||||
"source_git_blob": "cc34e45f8745780a781c2bb2328fa79669998abf",
|
||||
"sha256": "86349f42b6632812f9ea23eddf56075698dfabbee6c31a04bf1d96431a5cb810"
|
||||
"sha256": "7052735bc69a132035bd293edbef425b376c92f0ef351c752ccffc314a494db4"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.toml.orig",
|
||||
@@ -146,7 +146,7 @@
|
||||
"path": "src/filter/ccitt.rs",
|
||||
"source_sha256": "45d7eb89934d28cff97a00c7b264010bccfd14f3d511e1307ad50a9fef3b53c8",
|
||||
"source_git_blob": "685d680d2fbadce608a9bd3ca925c2ccc6c5d641",
|
||||
"sha256": "67d17a339639eb0fef4cc6c745b579c6ba9ae3f2f67fd3bacb1bf1389aa5ffab"
|
||||
"sha256": "950d40c731b70999fa334fa5a3a7a83525a3cf9434849936531cb57f7d94a439"
|
||||
},
|
||||
{
|
||||
"path": "src/filter/dct.rs",
|
||||
@@ -158,13 +158,13 @@
|
||||
"path": "src/filter/jbig2.rs",
|
||||
"source_sha256": "0ac3c16e02cb13f2d5fe401edd35949320662906c3906cb39fe743acd5e32b09",
|
||||
"source_git_blob": "d87253f536e6b8ac18323f1f06164b516ad775df",
|
||||
"sha256": "294de5b38201a095c0dcde97ddbba2563d33874deede190b31869d3bcb110fd1"
|
||||
"sha256": "d48329e237ea5a6497fc492d4f2c41ecfeab94d85a70b53047897ffc8bb90b37"
|
||||
},
|
||||
{
|
||||
"path": "src/filter/jpx.rs",
|
||||
"source_sha256": "c9f068629c9cbe79af6793c3c125df4631ca1455691cb1335b44ff43cb1b4056",
|
||||
"source_git_blob": "74efd8b31e2b2935ff2bbceda2c1ffd36ea9c20d",
|
||||
"sha256": "81213936de6d1c6b63bea041a1f88a71753e3b4238a08d9bbc7dbdfaca0970a0"
|
||||
"sha256": "6f84cbceb7345a06a022d09518c4431be05c93d5cba3232dd51442605b433e92"
|
||||
},
|
||||
{
|
||||
"path": "src/filter/lzw_flate.rs",
|
||||
@@ -176,7 +176,7 @@
|
||||
"path": "src/filter/mod.rs",
|
||||
"source_sha256": "0af7145ab16b15b7a60c4b57efecb9bd5fd0cfdc9bb5f9388abb695386e63e49",
|
||||
"source_git_blob": "06bda29487d62c25dc39c1ee109091cb17e3867f",
|
||||
"sha256": "74127a32b9ac86e33f41ac10f9a51a95849caca9211b0f7ee7eb535f5a59d063"
|
||||
"sha256": "1673572232ffe5eab3a4b3a232a412d81f480dc80b1e3846c637404ba71a0a6e"
|
||||
},
|
||||
{
|
||||
"path": "src/filter/run_length.rs",
|
||||
@@ -278,7 +278,7 @@
|
||||
"path": "src/object/stream.rs",
|
||||
"source_sha256": "f5229eb2f52c9918830027c93112e042a9e97d34b5fec72f97dcc7de8c5410ac",
|
||||
"source_git_blob": "a80f0730cba317ed3771cee61d6a7ab18de296d7",
|
||||
"sha256": "ce9b81f31963cd0474aba253d7c9937f78cd3a1034b6811ccf4cbdf68c3769b6"
|
||||
"sha256": "21485a80db301098b04a93b0e6d8fbc00bd96c937bc1475c0d42545471cb03df"
|
||||
},
|
||||
{
|
||||
"path": "src/object/string.rs",
|
||||
@@ -302,13 +302,13 @@
|
||||
"path": "src/pdf.rs",
|
||||
"source_sha256": "b6938cd27757a20dca83b49db46d73ab32a0ca2a474a0c4517d1d82b71a1be1c",
|
||||
"source_git_blob": "c196cb14acc1bfd4dd572d7fedd8345b40e44873",
|
||||
"sha256": "e3c2b63122a7e6a6266aed7b3c58c7983e95595797dc1ab95500717ffff28dc9"
|
||||
"sha256": "4a7cb5d406e56690c0efe21bb55fad05f46b41f8ff1c2c089f6a79dbb9c75430"
|
||||
},
|
||||
{
|
||||
"path": "src/reader.rs",
|
||||
"source_sha256": "f2f10a5cddecd70dae36304f432d052f4d7fdf5113dc4473a06de502375c4f2e",
|
||||
"source_git_blob": "818f767f7b982bbe759f9c81dc91f0ddce335d25",
|
||||
"sha256": "a5ff6b8a90d3db6672b886558b1a1c13730eabbff4105233bcac637ac5324bfe"
|
||||
"sha256": "9730728810ca2a37026805f66d6ffd83484338733eb4ad8990591ee4357c72f7"
|
||||
},
|
||||
{
|
||||
"path": "src/sync.rs",
|
||||
@@ -338,13 +338,13 @@
|
||||
"path": "src/xref.rs",
|
||||
"source_sha256": "51ffeeb7d4ac035bae2cd5ba9288c180088ae06cdcefe2b29dfeda560a793aa0",
|
||||
"source_git_blob": "20e33a410489d42e438a3f2b87d70c7bb8d66eae",
|
||||
"sha256": "920adb9a303f92f3fed721242e5d0976d36ebc2a3e16ef55e19e254a0d16d564"
|
||||
"sha256": "0dae903df0a0c9cb3c7d9c327135df99ccd95c11ba85dcde6589989116dbc4d6"
|
||||
},
|
||||
{
|
||||
"path": "src/decode_limits_tests.rs",
|
||||
"source_sha256": null,
|
||||
"source_git_blob": null,
|
||||
"sha256": "0c486b89709267199242934da6568ac20aa3eb5f3269bd227bace3940aecb09e"
|
||||
"sha256": "b5edd289fea150edc9525ba086e228e3568163b4f7c16469b3117353f3fdb75f"
|
||||
},
|
||||
{
|
||||
"path": "src/cancel.rs",
|
||||
|
||||
+25
@@ -230,6 +230,31 @@ fn a_documents_pixel_limit_reaches_the_ccitt_decoder() {
|
||||
assert_eq!(decoded(DecodeLimits::default().with_max_image_pixels(31)), None);
|
||||
}
|
||||
|
||||
/// A document's pixel limit reaches the JBIG2 decoder: an embedded 8 × 4 page decodes with the
|
||||
/// default limit and with one of 32 pixels, and is refused with one of 31.
|
||||
#[cfg(feature = "images")]
|
||||
#[test]
|
||||
fn a_documents_pixel_limit_reaches_the_jbig2_decoder() {
|
||||
// A page information segment of 8 × 4 and nothing else: a blank page.
|
||||
let mut page = Vec::from([0, 0, 0, 0, 48, 0, 1, 0, 0, 0, 19, 0, 0, 0, 8, 0, 0, 0, 4]);
|
||||
page.extend_from_slice(&[0; 11]);
|
||||
let (mut out, mut offsets) = base();
|
||||
let mut image = format!("<< /Length {} /Filter /JBIG2Decode >>\nstream\n", page.len()).into_bytes();
|
||||
image.extend_from_slice(&page);
|
||||
image.extend_from_slice(b"\nendstream");
|
||||
object(&mut out, &mut offsets, 4, &image);
|
||||
table(&mut out, &offsets, "");
|
||||
let params = ImageDecodeParams { width: 8, height: 4, ..Default::default() };
|
||||
let decoded = |limits: DecodeLimits| {
|
||||
let pdf = Pdf::new_with_limits(out.clone(), limits).unwrap();
|
||||
let stream = pdf.xref().get::<Stream<'_>>(ObjectIdentifier::new(4, 0)).unwrap();
|
||||
stream.decoded_image(¶ms).map(|r| r.data.len()).ok()
|
||||
};
|
||||
assert_eq!(decoded(DecodeLimits::default()), Some(32));
|
||||
assert_eq!(decoded(DecodeLimits::default().with_max_image_pixels(32)), Some(32));
|
||||
assert_eq!(decoded(DecodeLimits::default().with_max_image_pixels(31)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_stream_limit_applies_after_successful_root_xref() {
|
||||
let (bytes, _, _) = object_stream_pdf(false);
|
||||
|
||||
+33
-15
@@ -8,12 +8,6 @@ use alloc::borrow::Cow;
|
||||
use alloc::vec::Vec;
|
||||
use core::iter;
|
||||
|
||||
/// PdfCraft patch: most pixels an embedded JBIG2 page may decode to, matching the renderer's
|
||||
/// `MAX_IMAGE_PIXELS` and `hayro_jbig2`'s region limit. The page header's own dimensions are
|
||||
/// checked here, before any output is allocated: the image dictionary's smaller ones say nothing
|
||||
/// about them.
|
||||
const MAX_PIXELS: u64 = 1 << 28;
|
||||
|
||||
/// Decode JBIG2 data from a PDF stream.
|
||||
///
|
||||
/// The `params` dictionary may contain a `JBIG2Globals` entry pointing to
|
||||
@@ -21,11 +15,18 @@ const MAX_PIXELS: u64 = 1 << 28;
|
||||
///
|
||||
/// PdfCraft patch: `limit` is the most bytes the page may decode to (see `filter::decode_limit`),
|
||||
/// checked against the page header's dimensions before any output is allocated.
|
||||
///
|
||||
/// PdfCraft patch: `max_pixels` is the most pixels the page may decode to (the document's
|
||||
/// [`DecodeLimits::max_image_pixels`](crate::DecodeLimits::max_image_pixels), 2^28 by default),
|
||||
/// checked against the page header's own dimensions before any output is allocated: the image
|
||||
/// dictionary's smaller ones say nothing about them. `hayro_jbig2` decodes the page within the
|
||||
/// same pixel limit, and its other bounds follow it (`hayro_jbig2::Limits`).
|
||||
pub(crate) fn decode(
|
||||
data: &[u8],
|
||||
params: &Dict<'_>,
|
||||
image_params: &ImageDecodeParams,
|
||||
limit: usize,
|
||||
max_pixels: u64,
|
||||
) -> Option<FilterResult<'static>> {
|
||||
// PdfCraft patch: globals are plain segment data. A globals stream filtered as an image
|
||||
// could name further globals of its own, recursing once per stream in the chain.
|
||||
@@ -41,9 +42,10 @@ pub(crate) fn decode(
|
||||
})
|
||||
.and_then(|g| g.decoded().ok());
|
||||
|
||||
let image = hayro_jbig2::Image::new_embedded(data, globals.as_deref()).ok()?;
|
||||
let limits = hayro_jbig2::Limits::with_max_pixels(max_pixels);
|
||||
let image = hayro_jbig2::Image::new_embedded_with_limits(data, globals.as_deref(), limits).ok()?;
|
||||
|
||||
if u64::from(image.width()) * u64::from(image.height()) > MAX_PIXELS {
|
||||
if u64::from(image.width()) * u64::from(image.height()) > max_pixels {
|
||||
warn!("embedded JBIG2 page is too large");
|
||||
|
||||
return None;
|
||||
@@ -52,7 +54,7 @@ pub(crate) fn decode(
|
||||
// PdfCraft patch: the page's bit-packed size (also what `hayro_jbig2` holds for the page
|
||||
// bitmap) and the size of the output built below. An image of known size has a limit in its
|
||||
// dictionary's 1-bit pixels, so its packed size is checked, and the 8-bit output it is widened
|
||||
// to stays within `MAX_PIXELS`. A stream decoded without image dimensions, such as an output
|
||||
// to stays within `max_pixels`. A stream decoded without image dimensions, such as an output
|
||||
// intent's ICC profile, gets back every byte built, so the output itself must fit.
|
||||
let packed_len = (image.width() as usize).div_ceil(8).checked_mul(image.height() as usize)?;
|
||||
let luma_len = (image.width() as usize).checked_mul(image.height() as usize)?;
|
||||
@@ -172,10 +174,26 @@ mod tests {
|
||||
let data = page_information(65_535, 65_535);
|
||||
for is_indexed in [false, true] {
|
||||
let params = ImageDecodeParams { is_indexed, bpc: Some(1), num_components: Some(1), target_dimension: None, width: 1, height: 1 };
|
||||
assert!(decode(&data, &Dict::empty(), ¶ms, usize::MAX).is_none());
|
||||
assert!(decode(&data, &Dict::empty(), ¶ms, usize::MAX, DEFAULT_PIXELS).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULT_PIXELS: u64 = crate::filter::MAX_IMAGE_PIXELS;
|
||||
|
||||
/// The page's 4,096 pixels are decoded with a pixel limit of 4,096 and refused with one of
|
||||
/// 4,095, and a page past the default opens with the limit raised.
|
||||
#[test]
|
||||
fn the_pixel_limit_given_is_the_one_applied() {
|
||||
let data = page_information(64, 64);
|
||||
let sized = ImageDecodeParams { is_indexed: true, bpc: Some(1), num_components: Some(1), target_dimension: None, width: 64, height: 64 };
|
||||
let decoded = |max_pixels| decode(&data, &Dict::empty(), &sized, 1 << 20, max_pixels).map(|r| r.data.len());
|
||||
assert_eq!(decoded(4096), Some(64 / 8 * 64));
|
||||
assert_eq!(decoded(4095), None);
|
||||
let large = page_information(32_768, 16_384);
|
||||
assert!(hayro_jbig2::Image::new_embedded_with_limits(&large, None, hayro_jbig2::Limits::with_max_pixels(DEFAULT_PIXELS)).is_err());
|
||||
assert!(hayro_jbig2::Image::new_embedded_with_limits(&large, None, hayro_jbig2::Limits::with_max_pixels(1 << 29)).is_ok());
|
||||
}
|
||||
|
||||
/// PdfCraft patch: a page within the pixel cap but past the caller's limit is refused before
|
||||
/// its output is allocated. Without image dimensions (an ICC profile decoded with a 16 MiB
|
||||
/// limit) the 8-bit output must fit; an image of known size is measured in 1-bit pixels.
|
||||
@@ -183,19 +201,19 @@ mod tests {
|
||||
fn a_page_past_the_limit_is_refused() {
|
||||
let data = page_information(16_384, 16_384);
|
||||
let untyped = ImageDecodeParams::default();
|
||||
assert!(decode(&data, &Dict::empty(), &untyped, 16 << 20).is_none());
|
||||
assert!(decode(&data, &Dict::empty(), &untyped, 16 << 20, DEFAULT_PIXELS).is_none());
|
||||
let sized = ImageDecodeParams { is_indexed: false, bpc: Some(1), num_components: Some(1), target_dimension: None, width: 16_384, height: 16_384 };
|
||||
assert!(decode(&data, &Dict::empty(), &sized, (16_384 / 8 * 16_384) - 1).is_none());
|
||||
assert!(decode(&data, &Dict::empty(), &sized, (16_384 / 8 * 16_384) - 1, DEFAULT_PIXELS).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_within_the_limit_decodes() {
|
||||
let data = page_information(64, 64);
|
||||
let untyped = ImageDecodeParams::default();
|
||||
let out = decode(&data, &Dict::empty(), &untyped, 64 * 64).expect("64 x 64 page");
|
||||
let out = decode(&data, &Dict::empty(), &untyped, 64 * 64, DEFAULT_PIXELS).expect("64 x 64 page");
|
||||
assert_eq!(out.data.len(), 64 * 64);
|
||||
assert!(decode(&data, &Dict::empty(), &untyped, 64 * 64 - 1).is_none());
|
||||
assert!(decode(&data, &Dict::empty(), &untyped, 64 * 64 - 1, DEFAULT_PIXELS).is_none());
|
||||
let sized = ImageDecodeParams { is_indexed: false, bpc: Some(1), num_components: Some(1), target_dimension: None, width: 64, height: 64 };
|
||||
assert_eq!(decode(&data, &Dict::empty(), &sized, 2 * 64 / 8 * 64).expect("sized page").data.len(), 64 * 64);
|
||||
assert_eq!(decode(&data, &Dict::empty(), &sized, 2 * 64 / 8 * 64, DEFAULT_PIXELS).expect("sized page").data.len(), 64 * 64);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -87,7 +87,7 @@ impl Filter {
|
||||
}
|
||||
|
||||
/// PdfCraft patch: `limit` is the most bytes the filter may produce (see `decode_limit`), and
|
||||
/// `max_pixels` the most pixels a CCITT or JPEG 2000 image may decode to (the document's
|
||||
/// `max_pixels` the most pixels a CCITT, JBIG2 or JPEG 2000 image may decode to (the document's
|
||||
/// [`DecodeLimits::max_image_pixels`](crate::DecodeLimits::max_image_pixels)).
|
||||
pub(crate) fn apply(
|
||||
&self,
|
||||
@@ -120,7 +120,7 @@ impl Filter {
|
||||
#[cfg(feature = "images")]
|
||||
Self::CcittFaxDecode => ccitt::decode(data, params, image_params, limit, max_pixels).ok_or(DecodeFailure::ImageDecode),
|
||||
#[cfg(feature = "images")]
|
||||
Self::Jbig2Decode => jbig2::decode(data, params, image_params, limit).ok_or(DecodeFailure::ImageDecode),
|
||||
Self::Jbig2Decode => jbig2::decode(data, params, image_params, limit, max_pixels).ok_or(DecodeFailure::ImageDecode),
|
||||
#[cfg(feature = "images")]
|
||||
Self::JpxDecode => jpx::decode(data, image_params, limit, max_pixels).ok_or(DecodeFailure::ImageDecode),
|
||||
#[cfg(not(feature = "images"))]
|
||||
|
||||
Reference in new issue
Block a user