Merge remote-tracking branch 'origin/main' into HEAD

This commit is contained in:
David Mann committed 2026-11-16 00:52:56 +01:00
commit 1d4c4e2d6b
5 files changed
+195 -34

No files matched your search

+7 -4
View File
@@ -5,6 +5,7 @@
//! unless `PHOTOCRAFT_REQUIRE_WINRES=1` (set by the release packaging script) turns it into a
//! build error.
/// Embeds the Windows resources and delay-loads the print-only system DLLs (#8272).
fn main() -> std::io::Result<()> {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=../../assets/app-icon/photocraft.ico");
@@ -12,12 +13,14 @@ fn main() -> std::io::Result<()> {
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return Ok(());
}
// Printing to PDF (winprint's `PdfCreateRenderer`) imports Windows.Data.Pdf.dll, which
// stripped Windows images (NTLite, some N/LTSC builds) lack. A load-time import stops the exe
// from starting at all ("windows.data.pdf.dll was not found", #5884), so load it on first use;
// the print command checks for it first and reports an error instead.
// Printing to PDF (winprint's `PdfCreateRenderer`) imports Windows.Data.Pdf.dll, and its
// printer options (the Print Ticket API) import prntvpt.dll; stripped Windows images (NTLite,
// some N/LTSC builds) lack them. A load-time import stops the exe from starting at all
// ("windows.data.pdf.dll was not found", #5884; "prntvpt.dll", #8272), so load them on first
// use; the print commands check for them first and report an error instead.
if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") {
println!("cargo:rustc-link-arg-bins=/DELAYLOAD:windows.data.pdf.dll");
println!("cargo:rustc-link-arg-bins=/DELAYLOAD:prntvpt.dll");
println!("cargo:rustc-link-arg-bins=delayimp.lib");
}
let mut res = winresource::WindowsResource::new();
+7 -4
View File
@@ -4,6 +4,7 @@
//! cross-compile from macOS or Linux still links, unless `PHOTOCRAFT_REQUIRE_WINRES=1` (set by the
//! release workflow) turns it into an error.
/// Embeds the Windows resources and delay-loads the print-only system DLLs (#5884, #8272).
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=../../assets/app-icon/photocraft.ico");
@@ -11,12 +12,14 @@ fn main() {
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
// Printing to PDF (winprint's `PdfCreateRenderer`) imports Windows.Data.Pdf.dll, which
// stripped Windows images (NTLite, some N/LTSC builds) lack. A load-time import stops the exe
// from starting at all ("windows.data.pdf.dll was not found", #5884), so load it on first use;
// the print command checks for it first and reports an error instead.
// Printing to PDF (winprint's `PdfCreateRenderer`) imports Windows.Data.Pdf.dll, and its
// printer options (the Print Ticket API) import prntvpt.dll; stripped Windows images (NTLite,
// some N/LTSC builds) lack them. A load-time import stops the exe from starting at all
// ("windows.data.pdf.dll was not found", #5884; "prntvpt.dll", #8272), so load them on first
// use; the print commands check for them first and report an error instead.
if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") {
println!("cargo:rustc-link-arg-bins=/DELAYLOAD:windows.data.pdf.dll");
println!("cargo:rustc-link-arg-bins=/DELAYLOAD:prntvpt.dll");
println!("cargo:rustc-link-arg-bins=delayimp.lib");
}
let mut res = winresource::WindowsResource::new();
@@ -0,0 +1,87 @@
//! Print-only Windows components must not be load-time imports of `photocraft.exe`: stripped
//! Windows images (NTLite, some N/LTSC builds) lack them, and a load-time import stops the app
//! from starting at all (#5884 Windows.Data.Pdf.dll, #8272 prntvpt.dll). `build.rs` delay-loads
//! them; this reads the built exe's PE import tables to prove it.
#![cfg(all(target_os = "windows", target_env = "msvc", target_pointer_width = "64",))]
/// Loaded on first use by the print commands, which check them first.
const PRINT_ONLY: [&str; 2] = ["windows.data.pdf.dll", "prntvpt.dll"];
/// The built exe names each print-only DLL in its delay-load table, never its import table.
#[test]
fn print_only_system_dlls_are_delay_loaded() {
let exe = std::fs::read(env!("CARGO_BIN_EXE_photocraft")).unwrap();
let pe = Pe::parse(&exe);
let imports = pe.dll_names(1, 20, 12);
let delayed = pe.dll_names(13, 32, 4);
assert!(imports.iter().any(|d| d == "kernel32.dll"), "the import table parses: {imports:?}");
for dll in PRINT_ONLY {
assert!(!imports.iter().any(|d| d == dll), "{dll} is a load-time import: {imports:?}");
assert!(delayed.iter().any(|d| d == dll), "{dll} is not delay-loaded: {delayed:?}");
}
}
/// Just enough of a PE32+ image to list the DLLs its import directories name.
struct Pe<'a> {
bytes: &'a [u8],
/// Virtual address, virtual size, file offset of each section.
sections: Vec<(u32, u32, u32)>,
/// Offset of the optional header's data directories.
directories: usize,
}
impl<'a> Pe<'a> {
/// Reads the PE headers and section table of a PE32+ image, panicking (a test) on any other.
fn parse(bytes: &'a [u8]) -> Self {
let pe = u32_at(bytes, 0x3c) as usize;
assert_eq!(&bytes[pe..pe + 4], b"PE\0\0");
let coff = pe + 4;
let sections = u16_at(bytes, coff + 2) as usize;
let optional = coff + 20;
let optional_size = u16_at(bytes, coff + 16) as usize;
assert_eq!(u16_at(bytes, optional), 0x20b, "a PE32+ image");
let table = optional + optional_size;
let sections = (0..sections)
.map(|i| {
let s = table + i * 40;
(u32_at(bytes, s + 12), u32_at(bytes, s + 8), u32_at(bytes, s + 20))
})
.collect();
Pe { bytes, sections, directories: optional + 112 }
}
/// The file offset of relative virtual address `rva`, through the section that holds it.
fn offset(&self, rva: u32) -> usize {
let &(va, _, raw) = self.sections.iter().find(|&&(va, size, _)| rva >= va && rva < va + size).unwrap();
(rva - va + raw) as usize
}
/// The DLL names of data directory `index`: an array of `entry`-byte descriptors, ended by an
/// all-zero one, with the name's RVA at `name_at`.
fn dll_names(&self, index: usize, entry: usize, name_at: usize) -> Vec<String> {
let rva = u32_at(self.bytes, self.directories + index * 8);
if rva == 0 {
return Vec::new();
}
let start = self.offset(rva);
(0..)
.map(|i| start + i * entry)
.take_while(|&d| self.bytes[d..d + entry].iter().any(|&b| b != 0))
.map(|d| {
let name = self.offset(u32_at(self.bytes, d + name_at));
let end = name + self.bytes[name..].iter().position(|&b| b == 0).unwrap();
String::from_utf8_lossy(&self.bytes[name..end]).to_ascii_lowercase()
})
.collect()
}
}
/// The little-endian `u16` at byte offset `at`.
fn u16_at(b: &[u8], at: usize) -> u16 {
u16::from_le_bytes([b[at], b[at + 1]])
}
/// The little-endian `u32` at byte offset `at`.
fn u32_at(b: &[u8], at: usize) -> u32 {
u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]])
}
+66 -14
View File
@@ -170,13 +170,27 @@ fn list_system_printers(s: &Session) -> Vec<craft_print::Printer> {
Some(source) => source(),
None => {
SYSTEM_LISTINGS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
craft_print::printers()
system_printers_now()
}
};
keep(&LAST_PRINTERS, s.printer_source.as_ref(), list.clone());
list
}
/// The system's printers. craft-print asks each Windows driver about two-sided printing through
/// prntvpt.dll; without it, list the spooler's printers through GDI instead (#8272). Like
/// `craft_print::printers`, a listing that fails is an empty list.
fn system_printers_now() -> Vec<craft_print::Printer> {
if require_print_tickets().is_ok() {
return craft_print::printers();
}
craft_print::rgb::printers()
.unwrap_or_default()
.into_iter()
.map(|p| craft_print::Printer { name: p.name, description: String::new(), default: p.default, two_sided: None })
.collect()
}
/// `file.printers`' stand-in: the session's outside the browser, and `None` in the browser, where
/// `file.printers` lists no printers.
fn stand_in_printers(source: Option<&PrinterSource>, browser: bool) -> Option<&PrinterSource> {
@@ -1067,6 +1081,8 @@ fn driver_printable(p: &Value) -> Option<Value> {
Some(json!([pg.printable.0, pg.printable.1, pg.printable.2, pg.printable.3]))
}
/// Lays out and renders the print page as a PDF for `cmd` and, when the params ask for it, sends
/// it to the printer through `spooler`; returns the job summary (paper, image rect, spooler).
fn render_and_spool(doc: &Document, p: &Value, cmd: &str, spooler: Option<&Spooler>) -> Result<Value> {
let fit = p.get("scaleToFit").and_then(Value::as_bool).unwrap_or(false);
let driver = (fit && native_route(p, spooler)).then(|| with_driver_printable(p));
@@ -1143,31 +1159,67 @@ fn render_and_spool(doc: &Document, p: &Value, cmd: &str, spooler: Option<&Spool
)
}
/// Windows prints a PDF through Windows.Data.Pdf.dll, which the apps delay-load (see their
/// `build.rs`) so a Windows image without it still starts. Calling into it when it cannot load
/// would abort the process, so check that it loads first (#5884).
/// Windows prints a PDF through Windows.Data.Pdf.dll and sets its options through the Print
/// Ticket API in prntvpt.dll, which the apps delay-load (see their `build.rs`) so a Windows image
/// without them still starts. Calling into one that cannot load would abort the process, so check
/// that both load first (#5884, #8272).
fn require_windows_pdf() -> Result<()> {
#[cfg(target_os = "windows")]
{
let root = std::env::var_os("SystemRoot").unwrap_or_else(|| std::ffi::OsString::from(r"C:\Windows"));
if !windows_pdf_loads(&windows_pdf_dll(std::path::Path::new(&root))) {
return Err(other(
"printing this page needs the Windows PDF component (Windows.Data.Pdf.dll), which is missing or cannot load. Save as PDF and print it from another app, or print an RGB image without page text or labels to print directly.",
));
}
require_windows_pdf_at(&system_root())?;
Ok(())
}
/// `craft-print` reads and sets Windows printer options through prntvpt.dll (the Print Ticket
/// API), which stripped Windows images can lack; the apps delay-load it (#8272).
fn require_print_tickets() -> Result<()> {
#[cfg(target_os = "windows")]
require_print_tickets_at(&system_root())?;
Ok(())
}
/// [`require_windows_pdf`] against the Windows directory `system_root` (tests pass a fixture).
#[cfg(target_os = "windows")]
fn require_windows_pdf_at(system_root: &std::path::Path) -> Result<()> {
if !dll_loads(&system_dll(system_root, WINDOWS_PDF_DLL)) {
return Err(other(
"printing this page needs the Windows PDF component (Windows.Data.Pdf.dll), which is missing or cannot load. Save as PDF and print it from another app, or print an RGB image without page text or labels to print directly.",
));
}
require_print_tickets_at(system_root)
}
/// [`require_print_tickets`] against the Windows directory `system_root` (tests pass a fixture).
#[cfg(target_os = "windows")]
fn require_print_tickets_at(system_root: &std::path::Path) -> Result<()> {
if !dll_loads(&system_dll(system_root, PRINT_TICKET_DLL)) {
return Err(other(
"printing this page needs the Windows Print Ticket component (prntvpt.dll), which is missing or cannot load. Save as PDF and print it from another app, or print an RGB image without page text or labels to print directly.",
));
}
Ok(())
}
#[cfg(target_os = "windows")]
fn windows_pdf_dll(system_root: &std::path::Path) -> std::path::PathBuf {
system_root.join("System32").join("Windows.Data.Pdf.dll")
const WINDOWS_PDF_DLL: &str = "Windows.Data.Pdf.dll";
#[cfg(target_os = "windows")]
const PRINT_TICKET_DLL: &str = "prntvpt.dll";
/// The running Windows directory (`%SystemRoot%`), `C:\Windows` if the variable is unset.
#[cfg(target_os = "windows")]
fn system_root() -> std::path::PathBuf {
std::env::var_os("SystemRoot").map_or_else(|| std::path::PathBuf::from(r"C:\Windows"), std::path::PathBuf::from)
}
/// Where the system DLL `name` lives under the Windows directory `system_root`.
#[cfg(target_os = "windows")]
fn system_dll(system_root: &std::path::Path, name: &str) -> std::path::PathBuf {
system_root.join("System32").join(name)
}
/// Loads the DLL rather than checking the file exists: one that is present but cannot load (a
/// dependency stripped too) would still abort at the delay-load stub.
#[cfg(target_os = "windows")]
fn windows_pdf_loads(dll: &std::path::Path) -> bool {
fn dll_loads(dll: &std::path::Path) -> bool {
dll.to_str().is_some_and(|p| winsafe::HINSTANCE::LoadLibrary(p).is_ok())
}
+28 -12
View File
@@ -1310,28 +1310,44 @@ mod cups {
}
}
/// #5884, #8272: a Windows image without a loadable Windows.Data.Pdf.dll or prntvpt.dll reports
/// an error instead of aborting at the delay-load stub. The checks run against a fixture
/// `System32`, so they don't depend on what the host has installed.
#[cfg(target_os = "windows")]
#[test]
fn windows_pdf_component_is_detected_by_loading_its_dll() {
// #5884: a Windows image without a loadable Windows.Data.Pdf.dll reports an error instead of
// aborting at the delay-load stub.
fn windows_print_components_are_detected_by_loading_their_dlls() {
let system_dll_loads = |name| dll_loads(&system_dll(&system_root(), name));
let dir = tempfile::tempdir().unwrap();
let dll = windows_pdf_dll(dir.path());
assert!(!windows_pdf_loads(&dll));
// Present but not loadable counts as missing.
std::fs::create_dir(dir.path().join("System32")).unwrap();
std::fs::write(&dll, b"MZ").unwrap();
assert!(!windows_pdf_loads(&dll));
let root = std::env::var_os("SystemRoot").unwrap();
// The real DLL may be missing or unloadable on a stripped image; the check follows the loader.
let system = windows_pdf_dll(std::path::Path::new(&root));
assert_eq!(require_windows_pdf().is_ok(), windows_pdf_loads(&system));
for name in [WINDOWS_PDF_DLL, PRINT_TICKET_DLL] {
let dll = system_dll(dir.path(), name);
assert!(!dll_loads(&dll), "{name}: missing");
// Present but not loadable counts as missing.
std::fs::write(&dll, b"MZ").unwrap();
assert!(!dll_loads(&dll), "{name}: not loadable");
}
// Both stubs fail to load, so both checks report the missing component.
assert!(require_print_tickets_at(dir.path()).is_err());
assert!(require_windows_pdf_at(dir.path()).is_err());
// With a loadable prntvpt.dll (the host's, copied in) only the PDF check still fails: it
// checks Windows.Data.Pdf.dll itself, not just the Print Ticket API.
let tickets = system_dll(dir.path(), PRINT_TICKET_DLL);
if system_dll_loads(PRINT_TICKET_DLL) && std::fs::copy(system_dll(&system_root(), PRINT_TICKET_DLL), &tickets).is_ok() {
assert_eq!(require_print_tickets_at(dir.path()).is_ok(), dll_loads(&tickets));
assert!(require_windows_pdf_at(dir.path()).is_err(), "Windows.Data.Pdf.dll is still a stub");
}
// The wrappers follow the loader on the real Windows directory (a stripped image may lack either).
let host_tickets = system_dll_loads(PRINT_TICKET_DLL);
assert_eq!(require_print_tickets().is_ok(), host_tickets);
assert_eq!(require_windows_pdf().is_ok(), system_dll_loads(WINDOWS_PDF_DLL) && host_tickets);
}
/// Off Windows there are no Windows print components to check, so both checks pass.
#[cfg(not(target_os = "windows"))]
#[test]
fn the_windows_pdf_check_is_a_no_op_elsewhere() {
assert!(require_windows_pdf().is_ok());
assert!(require_print_tickets().is_ok());
}
/// A 500 × 1000 pt document (72 ppi) on A3 (841.89 × 1190.55 pt): its height sets the fit.