use crate::engine::TChar;
use std::ffi::{c_int, c_void};
use wim_format::ParseError;
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct ExtractProgress {
pub image: u32,
pub extract_flags: u32,
pub wimfile_name: *const TChar,
pub image_name: *const TChar,
pub target: *const TChar,
pub reserved: *const TChar,
pub total_bytes: u64,
pub completed_bytes: u64,
pub total_streams: u64,
pub completed_streams: u64,
pub part_number: u32,
pub total_parts: u32,
pub guid: [u8; 16],
pub current_file_count: u64,
pub end_file_count: u64,
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct VerifyImageProgress {
pub wimfile: *const TChar,
pub total_images: u32,
pub current_image: u32,
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct VerifyStreamsProgress {
pub wimfile: *const TChar,
pub total_streams: u64,
pub total_bytes: u64,
pub completed_streams: u64,
pub completed_bytes: u64,
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct WriteStreamsProgress {
pub total_bytes: u64,
pub total_streams: u64,
pub completed_bytes: u64,
pub completed_streams: u64,
pub num_threads: u32,
pub compression_type: i32,
pub total_parts: u32,
pub completed_parts: u32,
pub completed_compressed_bytes: u64,
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct IntegrityProgress {
pub total_bytes: u64,
pub completed_bytes: u64,
pub total_chunks: u32,
pub completed_chunks: u32,
pub chunk_size: u32,
pub filename: *const TChar,
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct SplitProgress {
pub total_bytes: u64,
pub completed_bytes: u64,
pub cur_part_number: u32,
pub total_parts: u32,
pub part_name: *mut TChar,
}
#[repr(C)]
#[derive(Clone, Copy)]
pub struct RenameProgress {
pub from: *const TChar,
pub to: *const TChar,
}
#[repr(C)]
#[derive(Clone, Copy)]
pub struct UnmountProgress {
pub mountpoint: *const TChar,
pub mounted_wim: *const TChar,
pub mounted_image: u32,
pub mount_flags: u32,
pub unmount_flags: u32,
}
#[repr(C)]
#[derive(Clone, Copy)]
pub struct DoneWithFileProgress {
pub path_to_file: *const TChar,
}
#[repr(C)]
#[derive(Clone, Copy)]
pub union ProgressInfo {
pub unmount: UnmountProgress,
pub done_with_file: DoneWithFileProgress,
#[cfg(any(unix, windows))]
pub handle_error: crate::engine::capture::HandleErrorProgress,
#[cfg(any(unix, windows))]
pub scan: crate::engine::capture::ScanProgress,
#[cfg(any(unix, windows))]
pub replace: crate::engine::capture::ReplaceProgress,
#[cfg(any(unix, windows))]
pub file_exclusion: crate::engine::capture::FileExclusionProgress,
pub update: crate::engine::update::UpdateProgress,
pub extract: ExtractProgress,
pub verify_image: VerifyImageProgress,
pub verify_streams: VerifyStreamsProgress,
pub write_streams: WriteStreamsProgress,
pub integrity: IntegrityProgress,
pub split: SplitProgress,
pub rename: RenameProgress,
pub storage: [u64; 14],
}
impl ProgressInfo {
pub const fn zeroed() -> Self {
Self { storage: [0; 14] }
}
}
pub type ProgressCallback = unsafe extern "C" fn(c_int, *mut ProgressInfo, *mut c_void) -> c_int;
#[derive(Clone, Copy, Debug)]
pub struct ProgressRegistration {
pub callback: Option<ProgressCallback>,
pub context: *mut c_void,
cancellation: Option<unsafe fn(*mut c_void) -> bool>,
}
impl Default for ProgressRegistration {
fn default() -> Self {
Self {
callback: None,
context: std::ptr::null_mut(),
cancellation: None,
}
}
}
impl ProgressRegistration {
pub fn new(callback: Option<ProgressCallback>, context: *mut c_void) -> Self {
Self {
callback,
context,
cancellation: None,
}
}
pub(crate) fn is_registered(self) -> bool {
self.callback.is_some() || self.cancellation.is_some()
}
pub(crate) unsafe fn cancellation<F: FnMut() -> bool>(callback: &mut F) -> Self {
unsafe fn invoke<F: FnMut() -> bool>(context: *mut c_void) -> bool {
let callback = unsafe { &mut *context.cast::<F>() };
std::panic::catch_unwind(std::panic::AssertUnwindSafe(callback)).unwrap_or(true)
}
Self {
callback: None,
context: std::ptr::from_mut(callback).cast(),
cancellation: Some(invoke::<F>),
}
}
pub unsafe fn call(self, event: c_int, info: *mut ProgressInfo) -> Result<(), ParseError> {
if let Some(cancelled) = self.cancellation {
return if unsafe { cancelled(self.context) } {
Err(ParseError::AbortedByProgress)
} else {
Ok(())
};
}
let Some(callback) = self.callback else {
return Ok(());
};
match unsafe { callback(event, info, self.context) } {
0 => Ok(()),
1 => Err(ParseError::AbortedByProgress),
_ => Err(ParseError::UnknownProgressStatus),
}
}
}
pub(crate) fn with_cancellation<T>(
handle: &mut crate::engine::handles::WimHandle,
cancelled: &mut impl FnMut() -> bool,
operation: impl FnOnce(&mut crate::engine::handles::WimHandle) -> T,
) -> T {
let registration = unsafe { ProgressRegistration::cancellation(cancelled) };
let old = handle.progress.replace(registration);
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| operation(handle)));
handle.progress.set(old);
match result {
Ok(result) => result,
Err(panic) => std::panic::resume_unwind(panic),
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wimlib_register_progress_function(
handle: *mut crate::engine::handles::WimHandle,
callback: Option<ProgressCallback>,
context: *mut c_void,
) {
if let Some(handle) = unsafe { handle.as_ref() } {
handle
.progress
.set(ProgressRegistration::new(callback, context));
}
}
pub(crate) fn filename_buffer(
path: Option<&std::path::Path>,
) -> Result<Option<Vec<TChar>>, ParseError> {
let Some(path) = path else {
return Ok(None);
};
let mut output = Vec::new();
#[cfg(not(windows))]
{
use std::os::unix::ffi::OsStrExt;
let bytes = path.as_os_str().as_bytes();
output
.try_reserve_exact(bytes.len() + 1)
.map_err(|_| ParseError::Nomem)?;
output.extend(bytes.iter().map(|&b| b as TChar));
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt;
let units = path.as_os_str().encode_wide();
output
.try_reserve_exact(units.clone().count() + 1)
.map_err(|_| ParseError::Nomem)?;
output.extend(units);
}
output.push(0);
Ok(Some(output))
}
pub fn next_progress(completed: u64, total: u64, next: u64) -> u64 {
if next < total {
completed
.saturating_add(total / 100)
.min(completed.saturating_add(1 << 30))
.min(total)
} else {
u64::MAX
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn selected_structures_match_original_64_bit_layout() {
assert_eq!(std::mem::size_of::<ProgressInfo>(), 112);
assert_eq!(std::mem::size_of::<ExtractProgress>(), 112);
assert_eq!(std::mem::offset_of!(ExtractProgress, total_bytes), 40);
assert_eq!(
std::mem::offset_of!(ExtractProgress, current_file_count),
96
);
assert_eq!(std::mem::align_of::<ProgressInfo>(), 8);
assert_eq!(std::mem::size_of::<VerifyImageProgress>(), 16);
assert_eq!(std::mem::size_of::<VerifyStreamsProgress>(), 40);
assert_eq!(std::mem::size_of::<WriteStreamsProgress>(), 56);
assert_eq!(std::mem::size_of::<IntegrityProgress>(), 40);
assert_eq!(std::mem::size_of::<SplitProgress>(), 32);
assert_eq!(std::mem::offset_of!(VerifyImageProgress, total_images), 8);
assert_eq!(
std::mem::offset_of!(VerifyStreamsProgress, completed_bytes),
32
);
}
unsafe extern "C" fn return_context_status(
_event: c_int,
_info: *mut ProgressInfo,
context: *mut c_void,
) -> c_int {
unsafe { *context.cast::<c_int>() }
}
#[test]
fn native_cancellation_restores_previous_registration_after_operation_panics() {
let mut handle =
crate::engine::handles::create_handle(wim_format::Compression::None).unwrap();
let mut status = 2;
let old = ProgressRegistration::new(
Some(return_context_status),
std::ptr::from_mut(&mut status).cast(),
);
handle.progress.set(old);
let mut calls = 0;
let mut cancelled = || {
calls += 1;
false
};
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
with_cancellation(&mut handle, &mut cancelled, |handle| {
let mut info = ProgressInfo::zeroed();
assert_eq!(unsafe { handle.progress.get().call(12, &mut info) }, Ok(()));
panic!("operation panic after a native cancellation checkpoint");
});
}));
assert!(result.is_err());
assert_eq!(calls, 1);
let mut info = ProgressInfo::zeroed();
assert_eq!(
unsafe { handle.progress.get().call(12, &mut info) },
Err(ParseError::UnknownProgressStatus)
);
handle.progress.set(Default::default());
}
#[test]
fn dispatcher_preserves_context_and_maps_every_callback_status() {
let mut info = ProgressInfo::zeroed();
for (mut status, expected) in [
(0, Ok(())),
(1, Err(ParseError::AbortedByProgress)),
(-1, Err(ParseError::UnknownProgressStatus)),
(2, Err(ParseError::UnknownProgressStatus)),
] {
let registration = ProgressRegistration::new(
Some(return_context_status),
(&mut status as *mut c_int).cast(),
);
assert_eq!(unsafe { registration.call(29, &mut info) }, expected);
}
}
#[test]
fn byte_progress_threshold_tracks_original_terminal_and_gib_rules() {
assert_eq!(next_progress(15, 63, 0), 15);
assert_eq!(next_progress(63, 63, 15), 63);
assert_eq!(next_progress(63, 63, 63), u64::MAX);
assert_eq!(next_progress(0, 0, 0), u64::MAX);
assert_eq!(next_progress(0, 1 << 40, 0), 1 << 30);
}
}