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,