Apply XeLaTeX CMaps to document text and embedded fonts

This commit is contained in:
gloamxun committed 2026-11-28 21:40:17 +08:00
1 parent af6466cd98
commit 7d460e0fa1
20 files changed
+747 -65

No files matched your search

@@ -0,0 +1,306 @@
//! Character-code maps read from actual CMap resources.
use std::{collections::BTreeMap, sync::Arc};
use super::xdv_object::{split_string, trim_pdf};
use crate::{
execution::SourceProvider,
resources::{ResourceKind, ResourceVersion},
};
const MAX_CMAP_DEPTH: usize = 16;
const MAX_CMAP_BYTES: usize = 16 * 1024 * 1024;
#[derive(Debug)]
pub(crate) struct CMap {
codespaces: [Vec<[u32; 2]>; 4],
mappings: [BTreeMap<u32, Mapping>; 4],
inherited: Option<Arc<CMap>>,
pub(crate) resources: Vec<ResourceVersion>,
}
#[derive(Debug)]
struct Mapping {
last: u32,
destination: Destination,
}
#[derive(Debug)]
enum Destination {
Sequential(Vec<u8>),
Explicit(Vec<Vec<u8>>),
}
impl CMap {
pub(crate) fn load(
name: &str,
from: &str,
files: &mut impl SourceProvider,
) -> Result<Self, String> {
Self::load_inner(name, from, files, &mut Vec::new())
}
fn load_inner(
name: &str,
from: &str,
files: &mut impl SourceProvider,
stack: &mut Vec<ResourceVersion>,
) -> Result<Self, String> {
let resource = files
.optional_font_file(ResourceKind::CMap, name, from)?
.ok_or_else(|| format!("CMap {name} was not found"))?;
let resource = crate::native_font::verify_resource(resource, ResourceKind::CMap, name)?;
if stack.len() == MAX_CMAP_DEPTH || stack.iter().any(|v| v.path == resource.version.path) {
return Err(format!("invalid CMap inheritance for {name}"));
}
if resource.data.len() > MAX_CMAP_BYTES {
return Err(format!("CMap {name} exceeds the input limit"));
}
stack.push(resource.version.clone());
let (mut map, base) =
Self::parse(&resource.data).map_err(|error| format!("{name}: {error}"))?;
map.resources.push(resource.version.clone());
if let Some(base) = base {
let inherited = Self::load_inner(
&base,
&resource.version.path.to_string_lossy(),
files,
stack,
)?;
map.resources.extend(inherited.resources.iter().cloned());
map.inherited = Some(Arc::new(inherited));
}
stack.pop();
if map.codespaces.iter().all(Vec::is_empty) && map.inherited.is_none() {
return Err(format!("CMap {name} has no code space"));
}
Ok(map)
}
fn parse(data: &[u8]) -> Result<(Self, Option<String>), String> {
let mut lexer = Lexer(data);
let mut map = Self {
codespaces: Default::default(),
mappings: Default::default(),
inherited: None,
resources: Vec::new(),
};
let mut previous = &[][..];
let mut inherits = None;
let mut ended = false;
while let Some(token) = lexer.next()? {
let end = match token {
b"begincodespacerange" => b"endcodespacerange".as_slice(),
b"beginbfchar" => b"endbfchar",
b"beginbfrange" => b"endbfrange",
b"usecmap" => {
let name = previous
.strip_prefix(b"/")
.filter(|name| !name.is_empty())
.ok_or("missing CMap base name")?;
if inherits.is_some() {
return Err("more than one CMap base".into());
}
inherits = Some(
std::str::from_utf8(name)
.map_err(|_| "invalid CMap base name")?
.into(),
);
previous = token;
continue;
}
b"endcmap" => {
ended = true;
break;
}
_ => {
previous = token;
continue;
}
};
let count = std::str::from_utf8(previous)
.ok()
.and_then(|n| n.parse::<usize>().ok())
.filter(|&n| n <= data.len())
.ok_or("invalid CMap block count")?;
for _ in 0..count {
let (width, first) = read_code(lexer.required()?)?;
let last = if token == b"beginbfchar" {
first
} else {
let (end_width, last) = read_code(lexer.required()?)?;
if width != end_width || last < first {
return Err("invalid CMap source range".into());
}
last
};
if token == b"begincodespacerange" {
map.codespaces[width - 1].push([first, last]);
continue;
}
let value = lexer.required()?;
let destination = if value == b"[" && token == b"beginbfrange" {
let len = u64::from(last) - u64::from(first) + 1;
if len > data.len() as u64 {
return Err("invalid CMap array range".into());
}
let values = (0..len)
.map(|_| read_hex(lexer.required()?))
.collect::<Result<_, _>>()?;
if lexer.required()? != b"]" {
return Err("invalid CMap range array".into());
}
Destination::Explicit(values)
} else {
Destination::Sequential(read_hex(value)?)
};
map.mappings[width - 1].insert(first, Mapping { last, destination });
}
if lexer.required()? != end {
return Err("incorrect CMap block length".into());
}
previous = &[];
}
if !ended {
return Err("missing CMap end marker".into());
}
Ok((map, inherits))
}
fn lookup(&self, width: usize, code: u32) -> Option<Vec<u8>> {
if let Some((&first, mapping)) = self.mappings[width - 1].range(..=code).next_back()
&& code <= mapping.last
{
let offset = code - first;
return match &mapping.destination {
Destination::Explicit(values) => values.get(offset as usize).cloned(),
Destination::Sequential(value) => {
let mut carry = u64::from(offset);
let mut bytes = value.clone();
for byte in bytes.iter_mut().rev() {
if carry == 0 {
break;
}
carry += u64::from(*byte);
*byte = carry as u8;
carry >>= 8;
}
(carry == 0).then_some(bytes)
}
};
}
self.inherited.as_ref()?.lookup(width, code)
}
fn in_codespace(&self, width: usize, code: u32) -> bool {
self.codespaces[width - 1]
.iter()
.any(|&[lo, hi]| (lo..=hi).contains(&code))
|| self
.inherited
.as_ref()
.is_some_and(|base| base.in_codespace(width, code))
}
pub(crate) fn to_utf16(&self, mut input: &[u8]) -> Result<Vec<u8>, String> {
let mut output = Vec::with_capacity(2 + input.len());
output.extend_from_slice(&[0xfe, 0xff]);
while !input.is_empty() {
let mut code = 0;
let mut consumed = 1;
let mut decoded = None;
for (index, &byte) in input.iter().take(4).enumerate() {
code = (code << 8) | u32::from(byte);
let width = index + 1;
if self.in_codespace(width, code) {
consumed = width;
decoded = self.lookup(width, code);
break;
}
}
let bytes = decoded.as_deref().unwrap_or(&[0xff, 0xfd]);
if output.len().saturating_add(bytes.len()) > MAX_CMAP_BYTES {
return Err("CMap output exceeds the text limit".into());
}
output.extend_from_slice(bytes);
input = &input[consumed..];
}
Ok(output)
}
pub(crate) fn simple_unicode(&self) -> BTreeMap<u8, String> {
(0..=255)
.filter_map(|slot| {
let bytes = self.lookup(1, u32::from(slot))?;
if bytes.is_empty() || bytes.len() % 2 != 0 {
return None;
}
let units: Vec<_> = bytes
.chunks_exact(2)
.map(|pair| u16::from_be_bytes([pair[0], pair[1]]))
.collect();
Some((slot, String::from_utf16(&units).ok()?))
})
.collect()
}
}
fn read_hex(token: &[u8]) -> Result<Vec<u8>, String> {
let digits = token
.strip_prefix(b"<")
.and_then(|s| s.strip_suffix(b">"))
.ok_or("expected a CMap hexadecimal string")?;
let nibbles = digits
.iter()
.filter(|b| !b.is_ascii_whitespace())
.map(|&b| {
char::from(b)
.to_digit(16)
.map(|n| n as u8)
.ok_or("invalid CMap hexadecimal digit")
})
.collect::<Result<Vec<_>, _>>()?;
Ok(nibbles
.chunks(2)
.map(|pair| (pair[0] << 4) | pair.get(1).copied().unwrap_or(0))
.collect())
}
fn read_code(token: &[u8]) -> Result<(usize, u32), String> {
let code = read_hex(token)?;
if !(1..=4).contains(&code.len()) {
return Err("invalid CMap code length".into());
}
Ok((
code.len(),
code.iter().fold(0, |n, &b| (n << 8) | u32::from(b)),
))
}
struct Lexer<'a>(&'a [u8]);
impl<'a> Lexer<'a> {
fn required(&mut self) -> Result<&'a [u8], String> {
self.next()?.ok_or_else(|| "unexpected end of CMap".into())
}
fn next(&mut self) -> Result<Option<&'a [u8]>, String> {
let input = trim_pdf(self.0);
let token = match input {
[] => return Ok(None),
[b'<', b'<', ..] | [b'>', b'>', ..] => &input[..2],
[b'<' | b'(', ..] => split_string(input)?.0,
[b'[' | b']' | b'{' | b'}' | b')' | b'>', ..] => &input[..1],
_ => {
let end = input
.iter()
.enumerate()
.skip(1)
.find(|(_, b)| b.is_ascii_whitespace() || b"[]{}()<>/%".contains(b))
.map_or(input.len(), |(i, _)| i);
&input[..end]
}
};
self.0 = &input[token.len()..];
Ok(Some(token))
}
}
@@ -3,7 +3,7 @@ use std::{collections::BTreeMap, sync::Arc};
use lopdf::Object;
use super::xdv_navigation::read_fields;
use super::{xdv_document::TextEncoding, xdv_navigation::read_fields};
use super::xdv_object::{
Dictionary, Position, References, atom, encode_device_value, output_with_destination, target_name, trim_pdf,
};
@@ -153,6 +153,7 @@ impl Page<'_> {
transform: Affine,
position: Position,
order: Order,
text: &TextEncoding,
) -> Result<Vec<String>, String> {
match command {
Command::Begin => {
@@ -162,7 +163,7 @@ impl Page<'_> {
.into(),
]);
}
let (fields, warnings) = read_fields(operands, position)?;
let (fields, warnings) = read_fields(operands, position, text)?;
self.state.active = Some(Active {
fields: Arc::new(fields),
depth: self.depth,
@@ -192,7 +193,7 @@ impl Page<'_> {
self.expand(bounds);
return Ok(Vec::new());
}
let (fields, warnings) = read_fields(&operands[dictionary..], position)?;
let (fields, warnings) = read_fields(&operands[dictionary..], position, text)?;
self.annotations.push(Annotation {
order,
fields: Arc::new(fields),
@@ -1,9 +1,14 @@
//! Document dictionary specials executed in XDV page order.
use lopdf::{Object, StringFormat};
use std::{collections::{BTreeMap, BTreeSet}, sync::Arc};
use crate::execution::SourceProvider;
use super::{
PdfInfo,
cmap::CMap,
page_resources::{encode_value, parse_entries, parse_value},
xdv_object::{Position, References, atom, output_dictionary, trim_pdf},
xdv_navigation::read_fields,
};
const TEXT_KEYS: &[&[u8]] = &[
@@ -31,19 +36,102 @@ const INFO_STRING_KEYS: &[&[u8]] = &[
b"ModDate",
];
#[derive(Clone, Default)]
pub(crate) struct TextEncoding {
map: Option<Arc<CMap>>,
extra_keys: Arc<BTreeSet<Vec<u8>>>,
pub(super) tainted_literals: bool,
}
impl TextEncoding {
pub(crate) fn apply(
&mut self, operands: &[u8], from: &str, files: &mut impl SourceProvider,
) -> Vec<String> {
self.map = None;
self.tainted_literals = false;
let (name, rest) = atom(operands);
let Ok(name) = std::str::from_utf8(name) else {
return vec![warning("Invalid ToUnicode mapping name.")];
};
if name.is_empty() {
return vec![warning("Missing CMap name for pdf:tounicode.")];
}
match CMap::load(name, from, files) {
Ok(map) => {
self.tainted_literals = ["RKSJ", "B5", "GBK", "KSC"].iter().any(|tag| name.contains(tag));
self.map = Some(Arc::new(map));
}
Err(error) => return vec![warning(&format!("Failed to load ToUnicode mapping: {name} ({error})"))],
}
let mut warnings = Vec::new();
if !trim_pdf(rest).is_empty() {
match parse_value(rest) {
Ok(Object::Array(keys)) => {
for key in keys {
if let Object::Name(key) = key {
Arc::make_mut(&mut self.extra_keys).insert(key);
} else {
warnings.push(warning("Invalid argument specified in pdf:tounicode special."));
}
}
}
_ => warnings.push(warning("Invalid argument specified in pdf:tounicode special.")),
}
}
warnings
}
pub(super) fn normalize(&self, key: &[u8], bytes: &mut Vec<u8>, warnings: &mut Vec<String>) -> bool {
if (!TEXT_KEYS.contains(&key) && !self.extra_keys.contains(key)) || bytes.starts_with(&[0xfe, 0xff]) {
return false;
}
let result = if let Some(map) = &self.map {
map.to_utf16(bytes).ok()
} else if bytes.is_ascii() {
return false;
} else {
std::str::from_utf8(bytes).ok().map(|text| [0xfe, 0xff]
.into_iter().chain(text.encode_utf16().flat_map(u16::to_be_bytes)).collect())
};
if let Some(result) = result {
*bytes = result;
true
} else {
warnings.push(warning(&format!(
"Input string conversion (to UTF16BE) failed for {}...", String::from_utf8_lossy(key),
)));
false
}
}
}
fn warning(message: &str) -> String {
format!("xdvipdfmx: warning: {message}\n")
}
pub(crate) fn merge_docinfo(
current: &[u8],
special: &[u8],
text: &TextEncoding,
) -> Result<(Vec<u8>, Vec<String>), String> {
let Object::Dictionary(additions) = parse_value(special)? else {
return Err("pdf:docinfo requires a PDF dictionary".into());
let (additions, warnings) = if text.tainted_literals {
let position = Position { page: 0, coordinates: [0, 0], height: 0, magnification: 1000 };
let (fields, warnings) = read_fields(special, position, text)?;
let refs = References { pages: &[], named: &BTreeMap::new() };
(output_dictionary(&fields, &refs)?, warnings)
} else {
let Object::Dictionary(mut additions) = parse_value(special)? else {
return Err("pdf:docinfo requires a PDF dictionary".into());
};
let mut warnings = Vec::new();
for (key, value) in additions.iter_mut() {
convert_text(key, value, text, &mut warnings)?;
}
(additions, warnings)
};
let mut document = parse_entries(current)?;
let mut warnings = Vec::new();
for (key, value) in &additions {
let mut value = value.clone();
convert_text(key, &mut value, &mut warnings)?;
document.set(key.clone(), value);
document.set(key.clone(), value.clone());
}
let encoded = encode_value(Object::Dictionary(document))?;
@@ -55,21 +143,23 @@ pub(crate) fn merge_docinfo(
Ok((entries.to_vec(), warnings))
}
fn convert_text(key: &[u8], value: &mut Object, warnings: &mut Vec<String>) -> Result<(), String> {
fn convert_text(
key: &[u8], value: &mut Object, text: &TextEncoding, warnings: &mut Vec<String>,
) -> Result<(), String> {
match value {
Object::String(bytes, format) => {
if normalize_text(key, bytes, warnings) {
if text.normalize(key, bytes, warnings) {
*format = StringFormat::Hexadecimal;
}
}
Object::Array(values) => {
for value in values {
convert_text(key, value, warnings)?;
convert_text(key, value, text, warnings)?;
}
}
Object::Dictionary(entries) => {
for (key, value) in entries.iter_mut() {
convert_text(key, value, warnings)?;
convert_text(key, value, text, warnings)?;
}
}
Object::Reference(_) => {
@@ -80,25 +170,6 @@ fn convert_text(key: &[u8], value: &mut Object, warnings: &mut Vec<String>) -> R
Ok(())
}
pub(super) fn normalize_text(key: &[u8], bytes: &mut Vec<u8>, warnings: &mut Vec<String>) -> bool {
if !TEXT_KEYS.contains(&key) || bytes.starts_with(&[0xfe, 0xff]) || bytes.is_ascii() {
return false;
}
if let Ok(text) = std::str::from_utf8(bytes) {
*bytes = [0xfe, 0xff]
.into_iter()
.chain(text.encode_utf16().flat_map(u16::to_be_bytes))
.collect();
true
} else {
warnings.push(format!(
"xdvipdfmx: warning: Input string conversion (to UTF16BE) failed for {}...\n",
String::from_utf8_lossy(key),
));
false
}
}
pub(crate) fn information_dictionary(
info: PdfInfo<'_>,
diagnostics: &mut Vec<String>,
@@ -5,9 +5,9 @@ use lopdf::Object;
use serde::{Deserialize, Serialize};
use super::page_resources::parse_value;
use super::xdv_annotation::Order;
use super::{xdv_annotation::Order, xdv_document::TextEncoding};
use super::xdv_object::{
Dictionary, Position, References, Value, atom, dictionary, encode_device_value, output_dictionary,
Dictionary, Position, References, Value, atom, dictionary, dictionary_with_text, encode_device_value, output_dictionary,
output_with_destination, target_name, trim_pdf,
};
@@ -57,9 +57,10 @@ impl Navigation {
&mut self,
bytes: &[u8],
position: Position,
text: &TextEncoding,
limit: usize,
) -> Result<Vec<String>, String> {
let (mut additions, warnings) = read_fields(bytes, position)?;
let (mut additions, warnings) = read_fields(bytes, position, text)?;
if let (Some(Value::Dictionary(old)), Some(Value::Dictionary(new))) = (
self.catalog.get_mut(b"ViewerPreferences".as_slice()),
additions.get_mut(b"ViewerPreferences".as_slice()),
@@ -77,6 +78,7 @@ impl Navigation {
bytes: &[u8],
position: Position,
order: Order,
text: &TextEncoding,
limit: usize,
) -> Result<Vec<String>, String> {
let (force_open, rest) = match trim_pdf(bytes) {
@@ -97,7 +99,7 @@ impl Navigation {
if depth > 256 || depth as usize > previous_depth + 1 {
return Err("XDV outline jumps more than one level or exceeds depth limit".into());
}
let (fields, warnings) = read_fields(rest, position)?;
let (fields, warnings) = read_fields(rest, position, text)?;
self.add_payload(bytes.len(), limit)?;
self.lowest_level = Some(lowest);
self.outlines.push(Outline {
@@ -356,11 +358,12 @@ struct OutlineLinks {
pub(super) fn read_fields(
bytes: &[u8],
position: Position,
text: &TextEncoding,
) -> Result<(Dictionary, Vec<String>), String> {
let mut fields = dictionary(bytes, position)?;
let mut fields = dictionary_with_text(bytes, position, text.tainted_literals)?;
let mut warnings = Vec::new();
for (key, value) in &mut fields {
value.normalize_text(key, &mut warnings);
value.normalize_text(key, text, &mut warnings);
}
Ok((fields, warnings))
}
@@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, io::Write as _};
use super::page_resources::{encode_value, parse_name, parse_value};
use super::{magnify, print_sp};
use super::{magnify, print_sp, xdv_document::TextEncoding};
pub(super) fn trim_pdf(mut bytes: &[u8]) -> &[u8] {
loop {
@@ -152,9 +152,19 @@ impl Position {
}
pub(super) fn dictionary(input: &[u8], position: Position) -> Result<Dictionary, String> {
let Value::Dictionary(dictionary) = parse_object(input, position)? else {
dictionary_with_text(input, position, false)
}
pub(super) fn dictionary_with_text(
input: &[u8], position: Position, tainted: bool,
) -> Result<Dictionary, String> {
let mut parser = Parser { rest: input, position, tainted };
let Value::Dictionary(dictionary) = parser.value(0)? else {
return Err("expected an XDV PDF dictionary".into());
};
if !trim_pdf(parser.rest).is_empty() {
return Err("unexpected material after XDV PDF object".into());
}
Ok(dictionary)
}
@@ -167,7 +177,7 @@ pub(super) fn parse_object(bytes: &[u8], position: Position) -> Result<Value, St
}
pub(super) fn parse_object_prefix(bytes: &[u8], position: Position) -> Result<(Value, &[u8]), String> {
let mut parser = Parser { rest: bytes, position };
let mut parser = Parser { rest: bytes, position, tainted: false };
let value = parser.value(0)?;
Ok((value, trim_pdf(parser.rest)))
}
@@ -175,6 +185,7 @@ pub(super) fn parse_object_prefix(bytes: &[u8], position: Position) -> Result<(V
struct Parser<'a> {
rest: &'a [u8],
position: Position,
tainted: bool,
}
impl Parser<'_> {
@@ -217,6 +228,11 @@ impl Parser<'_> {
self.rest = rest;
return self.position.reference(token);
}
if self.tainted && self.rest.starts_with(b"(") {
let (value, rest) = tainted_literal(self.rest)?;
self.rest = rest;
return Ok(Value::String(value));
}
let (token, rest) = match self.rest.first() {
Some(b'(' | b'<') => split_string(self.rest)?,
Some(_) => atom(self.rest),
@@ -235,6 +251,61 @@ impl Parser<'_> {
}
}
fn tainted_literal(input: &[u8]) -> Result<(Vec<u8>, &[u8]), String> {
let mut rest = &input[1..];
let mut output = Vec::new();
let mut depth = 0;
while let Some((&byte, tail)) = rest.split_first() {
rest = tail;
if byte == b')' && depth == 0 {
return Ok((output, rest));
}
if byte >= 0x80 && let Some((&second, tail)) = rest.split_first() {
output.extend_from_slice(&[byte, second]);
rest = tail;
continue;
}
match byte {
b'(' => { depth += 1; output.push(byte); }
b')' => { depth -= 1; output.push(byte); }
b'\r' | b'\n' => {
if byte == b'\r' {
rest = rest.strip_prefix(b"\n").unwrap_or(rest);
}
output.push(b'\n');
}
b'\\' => {
let (&escaped, tail) = rest.split_first().ok_or("unfinished PDF string escape")?;
rest = tail;
match escaped {
b'\r' | b'\n' => {
if escaped == b'\r' {
rest = rest.strip_prefix(b"\n").unwrap_or(rest);
}
}
b'n' => output.push(b'\n'),
b'r' => output.push(b'\r'),
b't' => output.push(b'\t'),
b'b' => output.push(8),
b'f' => output.push(12),
b'0'..=b'7' => {
let mut code = escaped - b'0';
for _ in 0..2 {
let Some((&digit @ b'0'..=b'7', tail)) = rest.split_first() else { break };
rest = tail;
code = code.wrapping_mul(8) + (digit - b'0');
}
output.push(code);
}
_ => output.push(escaped),
}
}
_ => output.push(byte),
}
}
Err("unterminated PDF literal string".into())
}
pub(crate) struct References<'a> {
pub(crate) pages: &'a [usize],
pub(crate) named: &'a BTreeMap<Vec<u8>, u32>,
@@ -305,19 +376,21 @@ impl Value {
}
}
pub(super) fn normalize_text(&mut self, key: &[u8], warnings: &mut Vec<String>) {
pub(super) fn normalize_text(
&mut self, key: &[u8], text: &TextEncoding, warnings: &mut Vec<String>,
) {
match self {
Self::String(bytes) => {
super::xdv_document::normalize_text(key, bytes, warnings);
text.normalize(key, bytes, warnings);
}
Self::Array(values) => {
for value in values {
value.normalize_text(key, warnings);
value.normalize_text(key, text, warnings);
}
}
Self::Dictionary(values) => {
for (key, value) in values {
value.normalize_text(key, warnings);
value.normalize_text(key, text, warnings);
}
}
_ => {}