Decode XeTeX input files and streams with original byte spans

This commit is contained in:
gloamxun committed 2026-11-21 17:10:46 +08:00
1 parent 22e3ba993d
commit d11ac0cba1
18 files changed
+1040 -109

No files matched your search

@@ -0,0 +1,192 @@
//! The ICU converter used by XeTeX for non-built-in encoding names.
use super::{Character, utf16_character};
use libloading::Library;
use std::{
ffi::{CString, c_char, c_void},
sync::OnceLock,
};
type Open = unsafe extern "C" fn(*const c_char, *mut i32) -> *mut c_void;
type Close = unsafe extern "C" fn(*mut c_void);
type ToUnicode = unsafe extern "C" fn(
*mut c_void,
*mut *mut u16,
*const u16,
*mut *const c_char,
*const c_char,
*mut i32,
i8,
*mut i32,
);
struct Icu {
open: Open,
close: Close,
to_unicode: ToUnicode,
_library: Library,
}
fn library() -> Result<&'static Icu, String> {
static ICU: OnceLock<Option<Icu>> = OnceLock::new();
ICU.get_or_init(load)
.as_ref()
.ok_or_else(|| "XeTeX legacy input encodings require an ICU4C runtime".into())
}
fn load() -> Option<Icu> {
#[cfg(target_os = "windows")]
let unversioned = ["icu.dll", "icuuc.dll"];
#[cfg(target_os = "macos")]
let unversioned = ["libicucore.dylib", "libicuuc.dylib"];
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
let unversioned = ["libicuuc.so"];
let versions = (50..=100).rev();
// Only the platform loader's library search path is used, never the input
// directory or the encoding name supplied by a document.
for name in unversioned
.into_iter()
.map(str::to_owned)
.chain(versions.clone().map(|v| {
if cfg!(target_os = "windows") {
format!("icuuc{v}.dll")
} else if cfg!(target_os = "macos") {
format!("libicuuc.{v}.dylib")
} else {
format!("libicuuc.so.{v}")
}
}))
{
#[cfg(target_os = "windows")]
let loaded = unsafe {
// LOAD_LIBRARY_SEARCH_DEFAULT_DIRS excludes a document's cwd.
libloading::os::windows::Library::load_with_flags(name, 0x0000_1000).map(Library::from)
};
#[cfg(not(target_os = "windows"))]
let loaded = unsafe { Library::new(name) };
let Ok(lib) = loaded else { continue };
for suffix in
std::iter::once(String::new()).chain(versions.clone().map(|v| format!("_{v}")))
{
// ICU4C ships these declarations as stable C ABI. All three must
// come from this same library and use the same export suffix.
let symbols = unsafe {
(
lib.get::<Open>(format!("ucnv_open{suffix}").as_bytes()),
lib.get::<Close>(format!("ucnv_close{suffix}").as_bytes()),
lib.get::<ToUnicode>(format!("ucnv_toUnicode{suffix}").as_bytes()),
)
};
if let (Ok(open), Ok(close), Ok(to_unicode)) = symbols {
return Some(Icu {
open: *open,
close: *close,
to_unicode: *to_unicode,
_library: lib,
});
}
}
}
None
}
struct Converter {
icu: &'static Icu,
value: *mut c_void,
}
impl Converter {
fn new(name: &str) -> Result<Option<Self>, String> {
let Ok(name) = CString::new(name) else {
return Ok(None);
};
let icu = library()?;
let mut status = 0;
// name has a C terminator and only lives for this call.
let value = unsafe { (icu.open)(name.as_ptr(), &mut status) };
Ok((!value.is_null()).then(|| Self { icu, value }))
}
}
impl Drop for Converter {
fn drop(&mut self) {
// Each converter belongs to a single line conversion.
unsafe { (self.icu.close)(self.value) };
}
}
pub(super) fn recognizes(name: &str) -> Result<bool, String> {
Converter::new(name).map(|converter| converter.is_some())
}
pub(super) fn decode(name: &str, data: &[u8], base: usize) -> Result<Vec<Character>, String> {
if data.is_empty() {
return Ok(Vec::new());
}
let mut capacity = data.len().saturating_add(4);
let (units, offsets) = loop {
if capacity > i32::MAX as usize {
return Err("XeTeX legacy input line is too long".into());
}
let converter = Converter::new(name)?
.ok_or_else(|| format!("ICU converter for {name} is unavailable"))?;
let mut units = vec![0u16; capacity];
let mut offsets = vec![0; capacity];
let target = units.as_mut_ptr();
let source = data.as_ptr().cast::<c_char>();
let (mut end, mut read, mut status) = (target, source, 0);
// Both limits point one past allocated buffers. ICU writes one offset
// per UTF-16 unit and advances end and read within those buffers.
let count = unsafe {
(converter.icu.to_unicode)(
converter.value,
&mut end,
target.add(capacity),
&mut read,
source.add(data.len()),
offsets.as_mut_ptr(),
1,
&mut status,
);
end.offset_from(target) as usize
};
if status == 15 {
// U_BUFFER_OVERFLOW_ERROR
capacity *= 2;
continue;
}
if status > 0 {
return Err(format!(
"Unicode conversion failed (ICU error code = {status})"
));
}
units.truncate(count);
offsets.truncate(count);
break (units, offsets);
};
let mut chars = Vec::new();
let mut index = 0;
let mut start = 0;
let mut next_distinct = 0;
while index < units.len() {
let (value, width) = utf16_character(units[index], units.get(index + 1).copied());
if let Ok(offset) = usize::try_from(offsets[index]) {
start = offset.min(data.len());
}
next_distinct = next_distinct.max(index + width);
while next_distinct < offsets.len()
&& !usize::try_from(offsets[next_distinct]).is_ok_and(|offset| offset > start)
{
next_distinct += 1;
}
let end = offsets
.get(next_distinct)
.map_or(data.len(), |&offset| (offset as usize).min(data.len()));
chars.push(Character {
value,
start: base + start,
end: base + end,
});
index += width;
}
Ok(chars)
}