Promote verified native PDF and box capacity support

This commit is contained in:
gloamxun committed 2026-11-19 14:39:39 +08:00
1 parent 3706afa483
commit 72ed779749
31 files changed
+1042 -78

No files matched your search

+11 -1
View File
@@ -167,12 +167,15 @@ pub struct Executor {
pdf_colors: crate::pdf_device::PdfColorStacks,
pdf_link_stack: Vec<pdf_links::ActiveLink>,
pdf_catalog_tokens: Vec<Token>,
pdf_info_tokens: Vec<Token>,
pdf_images: Vec<pdf_image::RegisteredImage>,
input_position: Option<(usize, usize)>,
paragraph: Option<super::paragraph::Builder>,
vertical: super::boxes::VerticalBuilder,
box_frames: Vec<boxes::BoxFrame>,
box_nodes_created: usize,
material_charge: usize,
mark_cells_created: usize,
diagnostic_bytes: usize,
after_assignment: Option<Token>,
after_group_tokens: usize,
@@ -291,12 +294,15 @@ impl Executor {
pdf_colors: Default::default(),
pdf_link_stack: Vec::new(),
pdf_catalog_tokens: Vec::new(),
pdf_info_tokens: Vec::new(),
pdf_images: Vec::new(),
input_position: None,
paragraph: None,
vertical: super::boxes::VerticalBuilder::default(),
box_frames: Vec::new(),
box_nodes_created: 0,
material_charge: 0,
mark_cells_created: 0,
diagnostic_bytes: 0,
after_assignment: None,
after_group_tokens: 0,
@@ -3107,7 +3113,7 @@ impl Executor {
result: Result<(), Error>,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if let Err(mut error) = result.and_then(|()| self.finish_pdf_catalog()) {
if let Err(mut error) = result.and_then(|()| self.finish_pdf_dictionaries()) {
if let Err(sink) = files.observe_error(&error) {
error
.message
@@ -3195,8 +3201,10 @@ impl Executor {
mut capture_boundary: impl FnMut(&Self, usize, &mut F),
) -> Result<(), Error> {
loop {
self.check_box_capacity(None)?;
capture_boundary(self, initial_depth, files);
self.process_native_pages(files)?;
self.check_box_capacity(None)?;
let Some(input) = self.expanded(files)? else {
break;
};
@@ -3530,6 +3538,7 @@ impl Executor {
self.scan_pdf_link(primitive, token.span, files)?;
}
Pdfcatalog => self.scan_pdf_catalog(files)?,
Pdfinfo => self.scan_pdf_info(files)?,
Pdfximage => self.scan_pdf_image(&token, false, files)?,
Pdfrefximage => self.reference_pdf_image(&token, files)?,
_ => {
@@ -3585,6 +3594,7 @@ impl Executor {
}
self.validate_pdf_final_state()?;
self.end_paragraph(files)?;
self.check_box_capacity(None)?;
if self.state.group_depth() != initial_depth {
return self.fail("unclosed native group at end of input");
}
@@ -257,10 +257,7 @@ impl Executor {
"improper native discretionary material: only glyphs, boxes, rules and kerns are allowed",
);
}
self.box_nodes_created = self.box_nodes_created.saturating_add(part.len());
if self.box_nodes_created > self.limits.tokens {
return self.fail("native discretionary node capacity exceeded");
}
self.charge_box_material(part.len(), "native discretionary node capacity exceeded")?;
disc.parts.push(part);
if disc.parts.len() < 3 {
return self.begin_discretionary_part(disc, files);
@@ -313,10 +310,18 @@ impl Executor {
}
}
pub(super) fn account_box(&mut self, b: &NativeBox) -> Result<(), Error> {
self.box_nodes_created = self.box_nodes_created.saturating_add(b.node_count());
if self.box_nodes_created > self.limits.tokens {
return self.fail("native box node capacity exceeded");
};
self.charge_box_material(b.node_count(), "native box node capacity exceeded")
}
pub(super) fn charge_box_material(
&mut self,
nodes: usize,
error: &'static str,
) -> Result<(), Error> {
self.box_nodes_created = self.box_nodes_created.saturating_add(nodes);
if nodes > self.limits.tokens {
return self.fail(error);
}
self.material_charge = self.material_charge.saturating_add(nodes);
Ok(())
}
pub(super) fn scan_box(
@@ -21,10 +21,14 @@ impl Executor {
0
};
let tokens = self.scan_expanded_group(files)?;
self.box_nodes_created = self.box_nodes_created.saturating_add(1 + tokens.len());
if self.box_nodes_created > self.limits.tokens {
// Mark payload has its own cumulative limit. A transferred box is not
// another allocation of the tokens stored in that box.
let cells = 1 + tokens.len();
self.mark_cells_created = self.mark_cells_created.saturating_add(cells);
if self.mark_cells_created > self.limits.tokens {
return self.fail("native mark token/node capacity exceeded");
}
self.charge_box_material(1, "native mark token/node capacity exceeded")?;
let mark = NativeMark {
class,
tokens: tokens.into(),
@@ -88,10 +88,7 @@ impl Executor {
return self.fail("native math family must be in 0..15");
};
self.optional_equals(files)?;
let t = self.expanded_non_space(files)?.token;
let Meaning::Font(font) = self.meaning(&t) else {
return self.fail("expected actual native font selector");
};
let font = self.font_identifier(files)?;
let size = match p {
Primitive::Textfont => 0,
Primitive::Scriptfont => 1,
@@ -229,6 +229,7 @@ impl Executor {
files: &mut impl SourceProvider,
) -> Result<(), Error> {
self.native_page_mut()?;
self.check_box_capacity(Some(&b))?;
let h_offset = i64::from(self.read_parameter(Parameter::Hoffset).width());
let v_offset = i64::from(self.read_parameter(Parameter::Voffset).width());
const MAX_DIMEN: i64 = 1_073_741_823;
@@ -135,21 +135,44 @@ impl Executor {
}
}
fn pdf_dictionary_enabled(
&mut self,
command: &str,
files: &mut impl SourceProvider,
) -> Result<bool, Error> {
let enabled = self.read_parameter(Parameter::Pdfoutput).width() > 0;
if !enabled {
let text = format!(
"pdfTeX warning (\\{command}): not allowed in DVI mode (\\pdfoutput <= 0); ignoring it"
);
files
.observe_message(&text)
.map_err(|error| self.error(error, self.current))?;
self.events.push(Event::Message {
text,
span: self.current,
});
}
Ok(enabled)
}
pub(super) fn scan_pdf_info(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
let enabled = self.pdf_dictionary_enabled("pdfinfo", files)?;
let tokens = self.scan_pdf_tokens(files)?;
if enabled {
if self.pdf_info_tokens.len().saturating_add(tokens.len()) > self.limits.tokens {
return self.fail("native PDF information token limit exceeded");
}
self.pdf_info_tokens.extend(tokens);
}
Ok(())
}
pub(super) fn scan_pdf_catalog(
&mut self,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let enabled = self.read_parameter(Parameter::Pdfoutput).width() > 0;
if !enabled {
let text = "pdfTeX warning (\\pdfcatalog): not allowed in DVI mode (\\pdfoutput <= 0); ignoring it";
files
.observe_message(text)
.map_err(|error| self.error(error, self.current))?;
self.events.push(Event::Message {
text: text.into(),
span: self.current,
});
}
let enabled = self.pdf_dictionary_enabled("pdfcatalog", files)?;
let tokens = self.scan_pdf_tokens(files)?;
if enabled {
if self.pdf_catalog_tokens.len().saturating_add(tokens.len()) > self.limits.tokens {
@@ -181,7 +204,7 @@ impl Executor {
Ok(())
}
pub(super) fn finish_pdf_catalog(&mut self) -> Result<(), Error> {
pub(super) fn finish_pdf_dictionaries(&mut self) -> Result<(), Error> {
if !self.pdf_catalog_tokens.is_empty() {
let tokens = std::mem::take(&mut self.pdf_catalog_tokens);
let bytes = self.pdf_token_bytes(&tokens)?;
@@ -191,6 +214,10 @@ impl Executor {
.entries
.extend(bytes);
}
if !self.pdf_info_tokens.is_empty() {
let tokens = std::mem::take(&mut self.pdf_info_tokens);
self.state.pdf_info = self.pdf_token_bytes(&tokens)?;
}
Ok(())
}
}
@@ -16,6 +16,11 @@ impl Executor {
match (command, self.pdf_images.last()) {
(Primitive::Pdflastximage, Some(image)) => image.image.id as i32,
(Primitive::Pdflastximagepages, Some(image)) => image.image.image.page_count as i32,
(Primitive::Pdflastximagecolordepth, Some(image)) => image
.image
.image
.jpeg_frame()
.map_or(0, |(_, precision)| i32::from(precision)),
_ => 0,
}
}
@@ -58,9 +63,7 @@ impl Executor {
return self.fail("native PDF image named destinations require PDF object support");
}
let page = if self.keyword("page", files)? {
let page = self.integer(files)?;
usize::try_from(page)
.map_err(|_| self.error("required page does not exist", token.span))?
self.integer(files)?
} else {
1
};
@@ -96,8 +99,29 @@ impl Executor {
token.span,
)
})?;
let image = PdfImage::read(source, page, page_box)
.and_then(|image| PdfImageUse::new(self.pdf_images.len() + 1, image, dimensions))
let image = if PdfImage::is_jpeg(&source) {
let resolution = self.read_parameter(Parameter::Pdfimageresolution).width();
let version = (
self.read_parameter(Parameter::Pdfmajorversion).width(),
self.read_parameter(Parameter::Pdfminorversion).width(),
);
let (image, warning) = PdfImage::read_jpeg(source, resolution, version)
.map_err(|error| self.error(error, token.span))?;
if let Some(warning) = warning {
files
.observe_diagnostic(
WriteDestination::TerminalAndLog,
&format!("pdfTeX warning: pdftex: {warning}\n"),
)
.map_err(|error| self.error(error, token.span))?;
}
image
} else {
let page = usize::try_from(page)
.map_err(|_| self.error("required page does not exist", token.span))?;
PdfImage::read(source, page, page_box).map_err(|error| self.error(error, token.span))?
};
let image = PdfImageUse::new(self.pdf_images.len() + 1, image, dimensions)
.map_err(|error| self.error(error, token.span))?;
let id = image.id;
self.pdf_images.push(RegisteredImage {
@@ -18,6 +18,23 @@ impl Executor {
pub(super) fn observe_resource_stacks(&mut self) {
self.stack_peaks.include(&self.stack_usage());
}
pub(super) fn check_box_capacity(&mut self, shipping: Option<&NativeBox>) -> Result<(), Error> {
if self.material_charge <= self.limits.tokens {
return Ok(());
}
// Packing can move existing lists or replace an old register. Recount
// actual owners at an execution boundary before rejecting the job.
let usage = self.resource_usage(shipping, None);
self.material_charge = usage
.active_material
.records()
.saturating_add(usage.retained_material.records());
if self.material_charge > self.limits.tokens {
return self.fail("native box node capacity exceeded");
}
Ok(())
}
fn resource_usage(
&self,
shipping: Option<&NativeBox>,
@@ -7,7 +7,7 @@ use std::{
path::Path,
};
const SCHEMA: u32 = 23;
const SCHEMA: u32 = 25;
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
#[derive(serde::Serialize, serde::Deserialize)]
+25 -8
View File
@@ -14,8 +14,8 @@ pub enum JobParameter {
Year,
}
/// One real host-local timestamp, captured at job start. Tests may inject an
/// explicit timestamp; absence is an error on access, never a fake zero date.
/// The TeX time registers and PDF creation timestamp captured at job start.
/// The host can supply a separate PDF date for reproducible builds.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct JobTime {
pub year: i32,
@@ -24,6 +24,8 @@ pub struct JobTime {
pub minutes: i32,
#[serde(default)]
pdf_clock: Option<(u8, i16)>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pdf_calendar: Option<(i32, i32, i32, i32)>,
}
impl JobTime {
pub fn new(year: i32, month: i32, day: i32, minutes: i32) -> Result<Self, &'static str> {
@@ -44,6 +46,7 @@ impl JobTime {
day,
minutes,
pdf_clock: None,
pdf_calendar: None,
})
}
/// Add the seconds and UTC offset supplied by the job host.
@@ -56,11 +59,28 @@ impl JobTime {
return Err("invalid host PDF creation timestamp");
}
self.pdf_clock = Some((seconds, offset_minutes));
self.pdf_calendar = None;
Ok(self)
}
/// Use the PDF timestamp from another host clock without changing TeX's registers.
pub fn with_pdf_date(mut self, source: Self) -> Self {
let calendar =
source
.pdf_calendar
.unwrap_or((source.year, source.month, source.day, source.minutes));
self.pdf_clock = source.pdf_clock;
self.pdf_calendar = (source.pdf_clock.is_some()
&& calendar != (self.year, self.month, self.day, self.minutes))
.then_some(calendar);
self
}
pub fn pdf_creation_date(self) -> Option<String> {
let (seconds, offset) = self.pdf_clock?;
let (year, month, day, minutes) =
self.pdf_calendar
.unwrap_or((self.year, self.month, self.day, self.minutes));
let zone = if offset == 0 {
"Z".to_owned()
} else {
@@ -69,12 +89,9 @@ impl JobTime {
format!("{sign}{:02}'{:02}'", offset / 60, offset % 60)
};
Some(format!(
"D:{:04}{:02}{:02}{:02}{:02}{seconds:02}{zone}",
self.year,
self.month,
self.day,
self.minutes / 60,
self.minutes % 60
"D:{year:04}{month:02}{day:02}{:02}{:02}{seconds:02}{zone}",
minutes / 60,
minutes % 60
))
}
@@ -12,7 +12,9 @@ pub enum Parameter {
Pdfcompresslevel,
Pdfdecimaldigits,
Pdfpkresolution,
Pdfimageresolution,
Pdfgentounicode,
Pdfinfoomitdate,
Tracingcommands,
Tracingrestores,
Tracingassigns,
@@ -124,7 +126,9 @@ impl Parameter {
Self::Pdfcompresslevel,
Self::Pdfdecimaldigits,
Self::Pdfpkresolution,
Self::Pdfimageresolution,
Self::Pdfgentounicode,
Self::Pdfinfoomitdate,
Self::Tracingcommands,
Self::Tracingrestores,
Self::Tracingassigns,
@@ -109,6 +109,7 @@ pub enum Primitive {
Pdfendlink,
Pdfdest,
Pdfcatalog,
Pdfinfo,
Pdfsetmatrix,
Pdfrestore,
Pdfglyphtounicode,
@@ -597,6 +598,7 @@ pub struct State {
pub(super) pdf_file_options: Option<crate::pdf_device::PdfFileOptions>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) pdf_catalog: Option<Box<crate::pdf_device::catalog::PdfCatalog>>,
pub(super) pdf_info: Vec<u8>,
pub(super) glyph_unicode: crate::pdf_unicode::GlyphUnicodeMap,
pub(super) hyphenation: super::hyphenation::HyphenationData,
}
@@ -638,6 +640,7 @@ impl Default for State {
output_mode_set: None,
pdf_file_options: None,
pdf_catalog: None,
pdf_info: Vec::new(),
glyph_unicode: crate::pdf_unicode::GlyphUnicodeMap::default(),
hyphenation: super::hyphenation::HyphenationData::default(),
};
@@ -859,6 +862,7 @@ impl Default for State {
("pdfendlink", Pdfendlink),
("pdfdest", Pdfdest),
("pdfcatalog", Pdfcatalog),
("pdfinfo", Pdfinfo),
("pdfsetmatrix", Pdfsetmatrix),
("pdfrestore", Pdfrestore),
("pdfglyphtounicode", Pdfglyphtounicode),
@@ -1245,6 +1249,7 @@ impl State {
self.output_mode_set = None;
self.pdf_file_options = None;
self.pdf_catalog = None;
self.pdf_info.clear();
self
}
pub fn is_initex(&self) -> bool {
@@ -1258,6 +1263,12 @@ impl State {
generate_unicode: self.parameter(Parameter::Pdfgentounicode).width(),
glyph_unicode: &self.glyph_unicode,
catalog: self.pdf_catalog.as_deref(),
info: crate::pdf_device::PdfInfo {
entries: &self.pdf_info,
date: (self.parameter(Parameter::Pdfinfoomitdate).width() == 0)
.then_some(self.pdf_creation_date.as_deref())
.flatten(),
},
}
}
/// Job-wide decoding choice; it is not a scoped TeX assignment.
@@ -112,6 +112,7 @@ pub struct ResourceUsage {
/// Runtime events excluding statistics reports themselves.
pub retained_events: usize,
pub retained_shipouts: usize,
/// Cumulative node visits charged by packing and copying operations, including transfers.
pub box_nodes_created: usize,
pub diagnostic_bytes_generated: usize,
pub stacks: StackUsage,
+55 -19
View File
@@ -850,13 +850,19 @@ fn page_content(
height: image_height,
image,
} => {
let [sx, sy] = if list.units == crate::render::DisplayUnits::TeX {
let [sx, sy] = if image.image.jpeg_frame().is_some()
&& list.units == crate::render::DisplayUnits::TeX
{
[
crate::pdf_device::print_sp(*width, 4),
crate::pdf_device::print_sp(*image_height, 4),
]
} else if list.units == crate::render::DisplayUnits::TeX {
let [natural_width, natural_height] = image.image.natural;
// pdfTeX out_image prints a six-decimal ratio of scaled
// dimensions, while translation follows pdfdecimaldigits.
let scale = |placed, natural| {
let (coefficient, _) =
crate::pdf_device::divide_scaled(placed, i64::from(natural), 6);
let (coefficient, _) = crate::pdf_device::divide_scaled(placed, natural, 6);
crate::pdf_device::print_decimal(coefficient, 6)
};
[
@@ -1007,6 +1013,36 @@ fn metadata_object(metadata: &PdfMetadata) -> Option<String> {
Some(format!("<< {} >>", fields.join(" ")))
}
fn native_information_dictionary(info: crate::pdf_device::PdfInfo<'_>) -> Vec<u8> {
// pdfTeX suppresses defaults based on the raw byte spelling anywhere in
// the expanded list. Preserve the supplied PDF syntax verbatim.
let supplied = |key: &[u8]| info.entries.windows(key.len()).any(|value| value == key);
let mut object = b"<<\n".to_vec();
if !supplied(b"/Producer") {
object.extend_from_slice(b"/Producer (texrra Route-D native)\n");
}
if !info.entries.is_empty() {
object.extend_from_slice(info.entries);
object.push(b'\n');
}
if !supplied(b"/Creator") {
object.extend_from_slice(b"/Creator (TeX)\n");
}
if let Some(date) = info.date {
for key in ["CreationDate", "ModDate"] {
let name = format!("/{key}");
if !supplied(name.as_bytes()) {
writeln!(&mut object, "{name} ({date})").unwrap();
}
}
}
if !supplied(b"/Trapped") {
object.extend_from_slice(b"/Trapped /False\n");
}
object.extend_from_slice(b">>");
object
}
/// Write several display lists as a multi-page PDF at the default page origin.
pub fn display_lists_to_pdf(pages: &[DisplayList], page_height: i64) -> Vec<u8> {
display_lists_to_pdf_with_origin(pages, page_height, PageOrigin::default())
@@ -2207,6 +2243,22 @@ fn write_pdf(
catalog.extend_from_slice(b" >>");
objects[0] = catalog;
if let Some(level) = final_compression {
let info = match unicode {
Some(options) => native_information_dictionary(options.info),
None => metadata_object(metadata)
.map(String::into_bytes)
.unwrap_or_else(|| b"<< /Producer (texrra Route-D native) >>".to_vec()),
};
objects.push(info);
let options = &pages[0]
.pdf
.as_ref()
.expect("validated native PDF options")
.file;
return objects::serialize(&objects, Some(objects.len()), options, level.max(0).min(9) as u8);
}
let info_ref = match metadata_object(metadata) {
Some(object) => {
objects.push(object.into_bytes());
@@ -2214,22 +2266,6 @@ fn write_pdf(
}
None => String::new(),
};
if let Some(level) = final_compression {
let info = if info_ref.is_empty() {
objects.push(b"<< /Producer (texrra Route-D native) >>".to_vec());
Some(objects.len())
} else {
Some(objects.len())
};
let options = &pages[0]
.pdf
.as_ref()
.expect("validated native PDF options")
.file;
return objects::serialize(&objects, info, options, level.max(0).min(9) as u8);
}
let mut pdf: Vec<u8> = b"%PDF-1.4\n".to_vec();
let mut offsets = Vec::new();
for (index, object) in objects.iter().enumerate() {
+6
View File
@@ -1,4 +1,10 @@
//! Actual PDF device state shared by execution, painting and serialization.
#[derive(Clone, Copy)]
pub struct PdfInfo<'a> {
pub entries: &'a [u8],
pub date: Option<&'a str>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct PdfFileOptions {
pub major: i32,
+102 -8
View File
@@ -1,4 +1,5 @@
//! Embedded PDF pages and the resource objects reachable from their content.
//! Native image XObjects and the resource objects reachable from their content.
mod jpeg;
use crate::resources::{LoadedResource, ResourceVersion};
use lopdf::{Dictionary, Document, Object, ObjectId};
use std::{
@@ -33,7 +34,7 @@ pub struct PdfImage {
pub version: ResourceVersion,
pub page: usize,
pub page_count: usize,
pub natural: [i32; 2],
pub natural: [i64; 2],
extent: [u64; 2],
objects: Vec<Vec<Part>>,
}
@@ -59,7 +60,9 @@ impl PdfImageUse {
image: PdfImage,
requested: [Option<i32>; 3],
) -> Result<Self, String> {
let [w, h] = image.natural.map(i64::from);
let [w, h] = image.natural;
let jpeg = image.jpeg_frame().map(|(size, _)| size.map(i64::from));
let [aspect_width, aspect_height] = jpeg.unwrap_or([w, h]);
let [width, height, depth] = requested.map(|value| value.map(i64::from));
let ratio = |value: i64, numerator: i64, denominator: i64| {
let product = value * numerator;
@@ -67,9 +70,12 @@ impl PdfImageUse {
};
let depth = depth.unwrap_or(0);
let (width, height) = match (width, height) {
(None, None) if jpeg.is_some() && requested[2].is_some() => {
(ratio(h, aspect_width, aspect_height), h - depth)
}
(None, None) => (w, h - depth),
(Some(width), None) => (width, ratio(width, h, w) - depth),
(None, Some(height)) => (ratio(height + depth, w, h), height),
(Some(width), None) => (width, ratio(width, aspect_height, aspect_width) - depth),
(None, Some(height)) => (ratio(height + depth, aspect_width, aspect_height), height),
(Some(width), Some(height)) => (width, height),
};
if [width, height, depth].iter().any(|v| v.abs() > 1073741823) {
@@ -93,6 +99,11 @@ impl PdfImageUse {
enum Part {
Bytes(Vec<u8>),
Ref(usize),
Jpeg {
size: [u16; 2],
precision: u8,
bytes: Vec<u8>,
},
}
pub(crate) fn real(value: f64) -> String {
@@ -101,6 +112,89 @@ pub(crate) fn real(value: f64) -> String {
}
impl PdfImage {
pub(crate) fn is_jpeg(resource: &LoadedResource) -> bool {
resource.data.starts_with(jpeg::SIGNATURE)
|| (!resource.data.starts_with(b"%PDF-")
&& resource.version.path.extension().is_some_and(|extension| {
extension.eq_ignore_ascii_case("jpg") || extension.eq_ignore_ascii_case("jpeg")
}))
}
pub(crate) fn read_jpeg(
resource: LoadedResource,
fallback_resolution: i32,
pdf_version: (i32, i32),
) -> Result<(Self, Option<&'static str>), String> {
let header = jpeg::read(&resource.data).map_err(|error| {
format!(
"could not parse JPEG image {}: {error}",
resource.version.path.display()
)
})?;
if header.progressive && pdf_version.0 == 1 && pdf_version.1 <= 2 {
return Err("cannot use progressive DCT with PDF-1.2".into());
}
let [width, height] = header.size;
let color = match header.components {
1 => "/DeviceGray",
3 => "/DeviceRGB",
4 => "/DeviceCMYK /Decode [1 0 1 0 1 0 1 0]",
_ => unreachable!("JPEG component count was checked"),
};
let mut density = header.density;
let warning = if density.iter().any(|&dpi| dpi > 65_535) {
Some("too large image resolution ignored")
} else if density != [0, 0] && density.contains(&0) {
Some("too small image resolution ignored")
} else {
None
};
if warning.is_some() || density == [0, 0] {
let default = fallback_resolution.clamp(0, 65_535) as u32;
density = [if default == 0 { 72 } else { default }; 2];
}
let natural = std::array::from_fn(|axis| {
// One hundred inches in TeX scaled points.
let numerator = 473_628_672_i64 * i64::from(header.size[axis]);
let denominator = 100 * i64::from(density[axis]);
(numerator + denominator / 2) / denominator
});
let dictionary = format!(
"/Type /XObject /Subtype /Image /Width {width} /Height {height} \
/ColorSpace {color} /BitsPerComponent {} /Filter /DCTDecode /Length {} >>\nstream\n",
header.precision,
resource.data.len()
);
Ok((
Self {
version: resource.version,
page: 1,
page_count: 1,
natural,
extent: [1.0_f64.to_bits(); 2],
objects: vec![vec![
Part::Bytes(dictionary.into_bytes()),
Part::Jpeg {
size: header.size,
precision: header.precision,
bytes: resource.data,
},
Part::Bytes(b"\nendstream".to_vec()),
]],
},
warning,
))
}
pub(crate) fn jpeg_frame(&self) -> Option<([u16; 2], u8)> {
self.objects.first()?.iter().find_map(|part| match part {
Part::Jpeg {
size, precision, ..
} => Some((*size, *precision)),
_ => None,
})
}
pub(crate) fn read(
resource: LoadedResource,
page: usize,
@@ -172,12 +266,12 @@ impl PdfImage {
),
_ => return Err("PDF image rotation must be a multiple of 90 degrees".into()),
};
let sp = |bp: f64| -> Result<i32, String> {
let sp = |bp: f64| -> Result<i64, String> {
let value = (bp * 65536.0 * 803.0 / 800.0).round();
if !(1.0..=1073741823.0).contains(&value) {
return Err("invalid image dimensions".into());
}
Ok(value as i32)
Ok(value as i64)
};
let natural = [sp(width)?, sp(height)?];
let mut contents = Vec::new();
@@ -243,7 +337,7 @@ impl PdfImage {
}
for part in parts {
match part {
Part::Bytes(bytes) => body.extend_from_slice(bytes),
Part::Bytes(bytes) | Part::Jpeg { bytes, .. } => body.extend_from_slice(bytes),
Part::Ref(id) => write!(body, "{} 0 R", base + id).unwrap(),
}
}
@@ -0,0 +1,150 @@
//! JPEG frame and density metadata. The encoded image stays in its original stream.
pub(super) const SIGNATURE: &[u8] = b"\xff\xd8";
pub(super) struct Header {
pub size: [u16; 2],
pub precision: u8,
pub components: u8,
pub density: [u32; 2],
pub progressive: bool,
}
pub(super) fn read(bytes: &[u8]) -> Result<Header, &'static str> {
let mut rest = bytes
.strip_prefix(SIGNATURE)
.ok_or("missing JPEG signature")?;
let mut density = [0, 0];
let mut first = true;
let truncated = "premature end of JPEG header";
loop {
rest = rest.strip_prefix(&[0xff]).ok_or("expected JPEG marker")?;
while let Some(following) = rest.strip_prefix(&[0xff]) {
rest = following;
}
let (&marker, remaining) = rest.split_first().ok_or(truncated)?;
rest = remaining;
match marker {
0xd9 | 0xda => return Err("JPEG has no frame header"),
0x01 | 0xd0..=0xd8 => {
first = false;
continue;
}
_ => {}
}
let length = usize::from(u16::from_be_bytes(
rest.get(..2)
.ok_or(truncated)?
.try_into()
.expect("two-byte JPEG length"),
));
let segment = rest.get(2..length).ok_or(truncated)?;
rest = &rest[length..];
match marker {
0xc0..=0xc3 => {
let &[precision, h0, h1, w0, w1, components, ref table @ ..] = segment else {
return Err(truncated);
};
if !matches!(components, 1 | 3 | 4) {
return Err("unsupported JPEG color space");
}
if table.len() != 3 * usize::from(components) {
return Err("invalid JPEG component table");
}
let size = [u16::from_be_bytes([w0, w1]), u16::from_be_bytes([h0, h1])];
if size.contains(&0) || precision == 0 {
return Err("invalid JPEG frame dimensions or precision");
}
return Ok(Header {
size,
precision,
components,
density,
progressive: marker == 0xc2,
});
}
0xc5..=0xc7 | 0xc9..=0xcb | 0xcd..=0xcf => {
return Err("unsupported JPEG compression");
}
0xe0 if first => {
if let Some(&[_, _, unit, x0, x1, y0, y1, ..]) = segment.strip_prefix(b"JFIF\0") {
let x = u32::from(u16::from_be_bytes([x0, x1]));
let y = u32::from(u16::from_be_bytes([y0, y1]));
density = match unit {
1 => [x, y],
2 => [x * 254 / 100, y * 254 / 100],
_ => [0, 0],
};
if density.contains(&0) {
density = [density[0].max(density[1]); 2];
}
}
}
0xe1 if first => {
if let Some(tiff) = segment.strip_prefix(b"Exif\0") {
let start = tiff
.iter()
.position(|&byte| byte != 0)
.unwrap_or(tiff.len());
density = exif_density(&tiff[start..]).unwrap_or([0, 0]);
}
}
_ => {}
}
first = false;
}
}
fn exif_density(tiff: &[u8]) -> Option<[u32; 2]> {
let little = match tiff.get(..2)? {
b"II" => true,
b"MM" => false,
_ => return None,
};
let short = |at: usize| {
let bytes = tiff.get(at..at.checked_add(2)?)?.try_into().ok()?;
Some(if little {
u16::from_le_bytes(bytes)
} else {
u16::from_be_bytes(bytes)
})
};
let long = |at: usize| {
let bytes = tiff.get(at..at.checked_add(4)?)?.try_into().ok()?;
Some(if little {
u32::from_le_bytes(bytes)
} else {
u32::from_be_bytes(bytes)
})
};
if short(2)? != 42 {
return None;
}
let start = usize::try_from(long(4)?).ok()?;
let entries = usize::from(short(start)?);
let start = start.checked_add(2)?;
let end = start.checked_add(12 * entries)?;
tiff.get(start..end)?;
let mut density = [72, 72];
let mut cm = false;
for at in (start..end).step_by(12) {
match (short(at)?, short(at + 2)?, long(at + 4)?) {
(tag @ (282 | 283), 5, 1) => {
let offset = usize::try_from(long(at + 8)?).ok()?;
let numerator = long(offset)?;
let denominator = long(offset.checked_add(4)?)?;
if denominator != 0 {
density[usize::from(tag == 283)] = numerator / denominator;
}
}
(296, 3, 1) => cm = short(at + 8)? == 3,
_ => {}
}
}
if cm {
density =
density.map(|value| u32::try_from(u64::from(value) * 254 / 100).unwrap_or(u32::MAX));
}
Some(density)
}
@@ -129,6 +129,7 @@ pub struct PdfFinalOptions<'a> {
pub generate_unicode: i32,
pub glyph_unicode: &'a GlyphUnicodeMap,
pub catalog: Option<&'a crate::pdf_device::catalog::PdfCatalog>,
pub info: crate::pdf_device::PdfInfo<'a>,
}
#[cfg(test)]
@@ -34,6 +34,101 @@ fn messages(e: &Execution) -> Vec<String> {
})
.collect()
}
#[test]
fn transferred_nodes_can_be_repacked_without_spending_the_live_box_capacity() {
// Match the captured INITEX shape of the CVPR box-capacity reproducer.
let material = r"\kern1sp".repeat(500);
let source = format!(
r"\catcode123=1 \catcode125=2
\setbox2=\vbox{{\hrule width2pt height2pt {material}}}
\def\repack{{\ifnum\count0<2050 \advance\count0 by1
\setbox2=\vbox{{\unvbox2}}\expandafter\repack\fi}}
\repack
\message{{REPACKED=\number\count0|BOX=\number\wd2,\number\ht2,\number\dp2}}
\shipout\box2 \end"
);
let execution = Executor::new(
State::initex().with_etex(),
Limits {
steps: 2_000_000,
..Limits::default()
},
)
.with_native_pages()
.run(
SourceFile {
name: "repack.tex".into(),
data: source.into_bytes(),
},
&mut NoFiles,
)
.unwrap();
assert_eq!(messages(&execution), ["REPACKED=2050|BOX=131072,131572,0"]);
let pages: Vec<_> = execution
.events
.iter()
.filter_map(|event| match event {
Event::Shipout(page) => Some(page),
_ => None,
})
.collect();
assert_eq!(pages.len(), 1);
assert_eq!(pages[0].box_node.node_count(), 502);
assert!(execution.state.box_register(2).is_none());
}
#[test]
fn box_capacity_checks_live_copies_retained_pages_and_single_boxes() {
let material = r"\kern1sp".repeat(40);
let run = |body: &str| {
Executor::new(
State::initex().with_etex(),
Limits {
tokens: 64,
..Limits::default()
},
)
.with_native_pages()
.run_detailed(
SourceFile {
name: "box-capacity.tex".into(),
data: format!(r"\catcode123=1 \catcode125=2 {body}\end").into_bytes(),
},
&mut NoFiles,
)
};
let over = [
(format!(r"\setbox0=\vbox{{{material}{material}}}"), 0),
(format!(r"\setbox0=\vbox{{{material}}}\setbox1=\copy0"), 0),
(
format!(r"\shipout\vbox{{{material}}}\shipout\vbox{{{material}}}"),
1,
),
];
for (body, retained) in over {
let failed = run(&body).unwrap_err();
assert!(
failed
.error
.message
.contains("native box node capacity exceeded"),
"{}",
failed.error
);
let published = failed
.evidence
.events
.iter()
.filter(|event| matches!(event, Event::Shipout(_)))
.count();
assert_eq!(published, retained);
}
let body = format!(r"\setbox0=\vbox{{{material}}}\setbox0=\vbox{{{material}}}");
let final_box = run(&body).unwrap().state.box_register(0).unwrap().clone();
assert_eq!(final_box.node_count(), 41);
}
#[test]
fn box_registers_scopes_moves_and_dimensions_preserve_native_contents() {
let e = run(
@@ -148,6 +148,72 @@ fn actual_font_slot_bitmaps_and_identifiers_match_real_initex() {
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn assigning_math_families_scans_actual_current_and_family_font_identifiers() {
let setup = r"\font\regular=cmr10 \font\small=cmr7 \let\current=\font \regular ";
let body = r"
\textfont0=\current \scriptfont1=\textfont0
{\small \textfont0=\font \global\scriptscriptfont2=\textfont0
\message{ASSIGNED-LOCAL=[\fontname\textfont0,\fontname\scriptfont1,\fontname\scriptscriptfont2]}}
\message{ASSIGNED-OUTER=[\fontname\font,\fontname\textfont0,\fontname\scriptfont1,\fontname\scriptscriptfont2]}
\textfont3=\scriptscriptfont2
\message{ASSIGNED-COPIED=[\fontname\textfont3]}
";
let native = execute(setup, body, &mut Host::default()).unwrap();
let observed = messages(&native);
assert_eq!(
observed,
[
"ASSIGNED-LOCAL=[cmr7,cmr10,cmr7]",
"ASSIGNED-OUTER=[cmr10,cmr10,cmr10,cmr7]",
"ASSIGNED-COPIED=[cmr7]",
]
);
assert!(native.reads.contains(&Dependency::TextFont));
assert!(
native
.reads
.contains(&Dependency::MathFamily { size: 0, family: 0 })
);
let work = directory("math-family-identifiers");
if let Some((status, _, log)) = reference(&work, setup, body) {
assert_eq!(status, 0, "{log}");
for message in &observed {
assert!(log.contains(message), "{message}\n{log}");
}
let xetex = Command::new("xetex")
.args([
"-ini",
"-etex",
"-interaction=nonstopmode",
"-halt-on-error",
"probe.tex",
])
.current_dir(&work)
.output();
match xetex {
Ok(run) => {
assert!(
run.status.success(),
"{}",
String::from_utf8_lossy(&run.stdout)
);
let log = fs::read_to_string(work.join("probe.log")).unwrap();
for message in &observed {
assert!(log.contains(message), "{message}\n{log}");
}
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
eprintln!("xetex absent: math family XeTeX oracle skipped");
}
Err(error) => panic!("{error}"),
}
}
let invalid = execute(setup, r"\textfont2=\relax", &mut Host::default()).unwrap_err();
assert!(invalid.message.contains("expected native font identifier"));
fs::remove_dir_all(work).unwrap();
}
#[test]
fn tracing_channels_fatal_errors_and_conversion_timing_match_real_initex() {
let dir = directory("diagnostics");
@@ -246,7 +246,7 @@ fn genuine_fraction_primitives_and_retained_boxes_survive_format_roundtrip() {
let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let payload: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
assert_eq!(payload["schema"], 23);
assert_eq!(payload["schema"], 25);
let state = State::initex().with_etex();
let loaded = FormatImage::decode(&bytes)
.unwrap()
@@ -27,7 +27,13 @@ fn run_native(source: &str) -> Result<Execution, Error> {
Executor::new(
State::initex()
.with_etex()
.with_input_profile(InputProfile::TeX8Bit),
.with_input_profile(InputProfile::TeX8Bit)
.with_job_time(
JobTime::new(2000, 1, 1, 0)
.unwrap()
.with_pdf_clock(0, 0)
.unwrap(),
),
Limits::default(),
)
.with_native_pages()
@@ -66,6 +72,9 @@ fn pair(body: &str) -> (Document, Document, Vec<String>) {
"-halt-on-error",
"catalog.tex",
])
.env("TZ", "UTC")
.env("SOURCE_DATE_EPOCH", "946684800")
.env("FORCE_SOURCE_DATE", "1")
.current_dir(&work)
.output()
.unwrap();
@@ -222,10 +231,11 @@ fn absent_targets_follow_reference_destination_and_xref_behavior() {
}
#[test]
fn format_images_retain_catalog_primitive_and_clear_job_catalog_data() {
let seed = format!("{SETUP}\\pdfcatalog{{/Lang (seed)}}\\dump\n");
fn format_images_retain_dictionary_primitives_and_clear_job_data() {
let seed = format!("{SETUP}\\pdfcatalog{{/Lang (seed)}}\\pdfinfo{{/Author (seed)}}\\dump\n");
let dump = run_native(&seed).unwrap();
assert!(dump.state.pdf_final_options().catalog.is_some());
assert!(!dump.state.pdf_final_options().info.entries.is_empty());
let image = FormatImage::from_dump(dump, Vec::new(), Vec::new())
.unwrap()
.encode()
@@ -244,7 +254,10 @@ fn format_images_retain_catalog_primitive_and_clear_job_catalog_data() {
.run(
SourceFile {
name: "document.tex".into(),
data: format!("\\pdfcatalog{{/PageLayout /SinglePage}}{PAGE}\\end").into_bytes(),
data: format!(
"\\pdfcatalog{{/PageLayout /SinglePage}}\\pdfinfo{{/Title (job)}}{PAGE}\\end"
)
.into_bytes(),
},
&mut RulesOnly,
)
@@ -256,6 +269,11 @@ fn format_images_retain_catalog_primitive_and_clear_job_catalog_data() {
catalog.get(b"PageLayout").unwrap().as_name().unwrap(),
b"SinglePage"
);
assert!(information(&doc).get(b"Author").is_err());
assert_eq!(
information(&doc).get(b"Title").unwrap().as_str().unwrap(),
b"job"
);
}
#[test]
@@ -330,3 +348,116 @@ fn rejects_duplicate_actions_and_freezes_file_options_only_for_an_action() {
));
assert!(native.catalog().unwrap().get(b"Lang").is_err());
}
fn information(pdf: &Document) -> &Dictionary {
get(pdf, &pdf.trailer, b"Info").as_dict().unwrap()
}
fn compare_pdf_information(body: &str, custom_producer: bool) -> (Document, Document) {
let (reference, native, _) = pair(body);
let without_engine_identity = |pdf: &Document| {
let mut values = information(pdf).clone();
values.remove(b"PTEX.Fullbanner");
if !custom_producer {
values.remove(b"Producer");
}
comparable_dictionary(&values)
};
assert_eq!(
without_engine_identity(&reference),
without_engine_identity(&native)
);
if !custom_producer {
assert_eq!(
information(&native)
.get(b"Producer")
.unwrap()
.as_str()
.unwrap(),
b"texrra Route-D native"
);
}
(reference, native)
}
#[test]
fn pdf_info_accumulates_expanded_tokens_and_preserves_pdf_bytes() {
let (_, native) = compare_pdf_information(
&format!(
r"\def\text{{first}}\begingroup
\pdfinfo{{/Title (\text) /Custom <FEFF4E2D> }}\endgroup
\def\text{{second}}\pdfinfo{{/Subject (\text) /Author (^^e9)}}{PAGE}"
),
false,
);
let info = information(&native);
assert_eq!(info.get(b"Title").unwrap().as_str().unwrap(), b"first");
assert_eq!(info.get(b"Subject").unwrap().as_str().unwrap(), b"second");
assert_eq!(info.get(b"Author").unwrap().as_str().unwrap(), b"\xe9");
assert_eq!(
info.get(b"Custom").unwrap().as_str().unwrap(),
b"\xfe\xff\x4e\x2d"
);
}
#[test]
fn pdf_info_default_keys_follow_literal_pdftex_detection_and_final_scope() {
compare_pdf_information(
&format!(
r"\pdfinfo{{/Producer (custom) /Creator (custom) /CreationDate (custom) /ModDate (custom) /Trapped /True}}{PAGE}"
),
true,
);
let (_, literal) = compare_pdf_information(
&format!(r"\pdfinfo{{/Title (contains /CreatorSuffix and /Trapped)}}{PAGE}"),
false,
);
for key in [b"Creator".as_slice(), b"Trapped"] {
assert!(information(&literal).get(key).is_err());
}
let (_, omitted) = compare_pdf_information(
&format!(r"{PAGE}\pdfinfoomitdate=-1 \pdfinfo{{/CreationDate (kept)}}"),
false,
);
assert!(information(&omitted).get(b"ModDate").is_err());
assert_eq!(
information(&omitted)
.get(b"CreationDate")
.unwrap()
.as_str()
.unwrap(),
b"kept"
);
let (_, scoped) = compare_pdf_information(
&format!(r"\begingroup\pdfinfoomitdate=7 {PAGE}\endgroup"),
false,
);
assert_eq!(
information(&scoped)
.get(b"ModDate")
.unwrap()
.as_str()
.unwrap(),
b"D:20000101000000Z"
);
}
#[test]
fn pdf_info_ignores_dvi_and_does_not_freeze_pdf_settings() {
let body = format!(r"\pdfoutput=0 \pdfinfo{{/Title (ignored)}}\pdfoutput=1 {PAGE}");
let (_, ignored) = compare_pdf_information(&body, false);
assert!(information(&ignored).get(b"Title").is_err());
let execution = run_native(&format!("{SETUP}{body}\\end")).unwrap();
assert!(execution.events.iter().any(|event| matches!(
event, texrra_tex_core::execution::Event::Message { text, .. }
if text.contains(r"\pdfinfo") && text.contains("DVI mode")
)));
let (reference, native) = compare_pdf_information(
&format!(
r"\pdfinfo{{/Title (object stream)}}\pdfminorversion=5\pdfobjcompresslevel=3\pdfcompresslevel=6 {PAGE}"
),
false,
);
assert_eq!(reference.version, "1.5");
assert_eq!(native.version, reference.version);
}
@@ -334,7 +334,7 @@ fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums()
let envelope: serde_json::Value = serde_json::from_slice(&encoded).unwrap();
let original: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
assert_eq!(original["schema"], 23);
assert_eq!(original["schema"], 25);
for (schema, expected) in [
(1, "incompatible native format"),
(2, "incompatible native format"),
@@ -358,7 +358,9 @@ fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums()
(20, "incompatible native format"),
(21, "incompatible native format"),
(22, "incompatible native format"),
(23, "glyph_unicode"),
(23, "incompatible native format"),
(24, "incompatible native format"),
(25, "glyph_unicode"),
] {
let mut payload = original.clone();
payload["schema"] = schema.into();
@@ -164,7 +164,7 @@ fn new_format_owns_vcenter_and_boxed_math_without_reinjecting_old_meanings() {
let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let payload: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
assert_eq!(payload["schema"], 23);
assert_eq!(payload["schema"], 25);
let executor = FormatImage::decode(&bytes)
.unwrap()
.new_job(