Add DVT screenshot bindings

This commit is contained in:
Jackson Coxson
2025-10-21 08:47:07 -06:00
parent 779db7ecec
commit a7daac3a46
17 changed files with 326 additions and 17 deletions

View File

@@ -0,0 +1,116 @@
// Jackson Coxson
use std::ptr::null_mut;
use idevice::{ReadWrite, dvt::location_simulation::LocationSimulationClient};
use crate::{IdeviceFfiError, RUNTIME, dvt::remote_server::RemoteServerHandle, ffi_err};
/// Opaque handle to a ProcessControlClient
pub struct LocationSimulationHandle<'a>(pub LocationSimulationClient<'a, Box<dyn ReadWrite>>);
/// Creates a new ProcessControlClient from a RemoteServerClient
///
/// # Arguments
/// * [`server`] - The RemoteServerClient to use
/// * [`handle`] - Pointer to store the newly created ProcessControlClient handle
///
/// # Returns
/// An IdeviceFfiError on error, null on success
///
/// # Safety
/// `server` must be a valid pointer to a handle allocated by this library
/// `handle` must be a valid pointer to a location where the handle will be stored
#[unsafe(no_mangle)]
pub unsafe extern "C" fn location_simulation_new(
server: *mut RemoteServerHandle,
handle: *mut *mut LocationSimulationHandle<'static>,
) -> *mut IdeviceFfiError {
if server.is_null() || handle.is_null() {
return ffi_err!(IdeviceError::FfiInvalidArg);
}
let server = unsafe { &mut (*server).0 };
let res = RUNTIME.block_on(async move { LocationSimulationClient::new(server).await });
match res {
Ok(client) => {
let boxed = Box::new(LocationSimulationHandle(client));
unsafe { *handle = Box::into_raw(boxed) };
null_mut()
}
Err(e) => ffi_err!(e),
}
}
/// Frees a ProcessControlClient handle
///
/// # Arguments
/// * [`handle`] - The handle to free
///
/// # Safety
/// `handle` must be a valid pointer to a handle allocated by this library or NULL
#[unsafe(no_mangle)]
pub unsafe extern "C" fn location_simulation_free(handle: *mut LocationSimulationHandle<'static>) {
if !handle.is_null() {
let _ = unsafe { Box::from_raw(handle) };
}
}
/// Clears the location set
///
/// # Arguments
/// * [`handle`] - The LocationSimulation handle
///
/// # Returns
/// An IdeviceFfiError on error, null on success
///
/// # Safety
/// All pointers must be valid or NULL where appropriate
#[unsafe(no_mangle)]
pub unsafe extern "C" fn location_simulation_clear(
handle: *mut LocationSimulationHandle<'static>,
) -> *mut IdeviceFfiError {
if handle.is_null() {
return ffi_err!(IdeviceError::FfiInvalidArg);
}
let client = unsafe { &mut (*handle).0 };
let res = RUNTIME.block_on(async move { client.clear().await });
match res {
Ok(_) => null_mut(),
Err(e) => ffi_err!(e),
}
}
/// Sets the location
///
/// # Arguments
/// * [`handle`] - The LocationSimulation handle
/// * [`latitude`] - The latitude to set
/// * [`longitude`] - The longitude to set
///
/// # Returns
/// An IdeviceFfiError on error, null on success
///
/// # Safety
/// All pointers must be valid or NULL where appropriate
#[unsafe(no_mangle)]
pub unsafe extern "C" fn location_simulation_set(
handle: *mut LocationSimulationHandle<'static>,
latitude: f64,
longitude: f64,
) -> *mut IdeviceFfiError {
if handle.is_null() {
return ffi_err!(IdeviceError::FfiInvalidArg);
}
let client = unsafe { &mut (*handle).0 };
let res = RUNTIME.block_on(async move { client.set(latitude, longitude).await });
match res {
Ok(_) => null_mut(),
Err(e) => ffi_err!(e),
}
}

8
ffi/src/dvt/mod.rs Normal file
View File

@@ -0,0 +1,8 @@
// Jackson Coxson
#[cfg(feature = "location_simulation")]
pub mod location_simulation;
pub mod process_control;
pub mod remote_server;
pub mod screenshot;

View File

@@ -0,0 +1,208 @@
// Jackson Coxson
use std::{
ffi::{CStr, c_char},
ptr::null_mut,
};
use idevice::{ReadWrite, dvt::process_control::ProcessControlClient};
use plist::{Dictionary, Value};
use crate::{IdeviceFfiError, RUNTIME, dvt::remote_server::RemoteServerHandle, ffi_err};
/// Opaque handle to a ProcessControlClient
pub struct ProcessControlHandle<'a>(pub ProcessControlClient<'a, Box<dyn ReadWrite>>);
/// Creates a new ProcessControlClient from a RemoteServerClient
///
/// # Arguments
/// * [`server`] - The RemoteServerClient to use
/// * [`handle`] - Pointer to store the newly created ProcessControlClient handle
///
/// # Returns
/// An IdeviceFfiError on error, null on success
///
/// # Safety
/// `server` must be a valid pointer to a handle allocated by this library
/// `handle` must be a valid pointer to a location where the handle will be stored
#[unsafe(no_mangle)]
pub unsafe extern "C" fn process_control_new(
server: *mut RemoteServerHandle,
handle: *mut *mut ProcessControlHandle<'static>,
) -> *mut IdeviceFfiError {
if server.is_null() || handle.is_null() {
return ffi_err!(IdeviceError::FfiInvalidArg);
}
let server = unsafe { &mut (*server).0 };
let res = RUNTIME.block_on(async move { ProcessControlClient::new(server).await });
match res {
Ok(client) => {
let boxed = Box::new(ProcessControlHandle(client));
unsafe { *handle = Box::into_raw(boxed) };
null_mut()
}
Err(e) => ffi_err!(e),
}
}
/// Frees a ProcessControlClient handle
///
/// # Arguments
/// * [`handle`] - The handle to free
///
/// # Safety
/// `handle` must be a valid pointer to a handle allocated by this library or NULL
#[unsafe(no_mangle)]
pub unsafe extern "C" fn process_control_free(handle: *mut ProcessControlHandle<'static>) {
if !handle.is_null() {
let _ = unsafe { Box::from_raw(handle) };
}
}
/// Launches an application on the device
///
/// # Arguments
/// * [`handle`] - The ProcessControlClient handle
/// * [`bundle_id`] - The bundle identifier of the app to launch
/// * [`env_vars`] - NULL-terminated array of environment variables (format "KEY=VALUE")
/// * [`arguments`] - NULL-terminated array of arguments
/// * [`start_suspended`] - Whether to start the app suspended
/// * [`kill_existing`] - Whether to kill existing instances of the app
/// * [`pid`] - Pointer to store the process ID of the launched app
///
/// # Returns
/// An IdeviceFfiError on error, null on success
///
/// # Safety
/// All pointers must be valid or NULL where appropriate
#[unsafe(no_mangle)]
pub unsafe extern "C" fn process_control_launch_app(
handle: *mut ProcessControlHandle<'static>,
bundle_id: *const c_char,
env_vars: *const *const c_char,
env_vars_count: usize,
arguments: *const *const c_char,
arguments_count: usize,
start_suspended: bool,
kill_existing: bool,
pid: *mut u64,
) -> *mut IdeviceFfiError {
if handle.is_null() || bundle_id.is_null() || pid.is_null() {
return ffi_err!(IdeviceError::FfiInvalidArg);
}
let bundle_id = unsafe { CStr::from_ptr(bundle_id) };
let bundle_id = match bundle_id.to_str() {
Ok(s) => s.to_string(),
Err(_) => return ffi_err!(IdeviceError::FfiInvalidArg),
};
let mut env_dict = Dictionary::new();
if !env_vars.is_null() {
let env_vars_slice = unsafe { std::slice::from_raw_parts(env_vars, env_vars_count) };
for &env_var in env_vars_slice {
if !env_var.is_null() {
let env_var = unsafe { CStr::from_ptr(env_var) };
if let Ok(env_var) = env_var.to_str()
&& let Some((key, value)) = env_var.split_once('=')
{
env_dict.insert(key.to_string(), Value::String(value.to_string()));
}
}
}
}
let mut args_dict = Dictionary::new();
if !arguments.is_null() {
let args_slice = unsafe { std::slice::from_raw_parts(arguments, arguments_count) };
for (i, &arg) in args_slice.iter().enumerate() {
if !arg.is_null() {
let arg = unsafe { CStr::from_ptr(arg) };
if let Ok(arg) = arg.to_str() {
args_dict.insert(i.to_string(), Value::String(arg.to_string()));
}
}
}
}
let client = unsafe { &mut (*handle).0 };
let res = RUNTIME.block_on(async move {
client
.launch_app(
bundle_id,
Some(env_dict),
Some(args_dict),
start_suspended,
kill_existing,
)
.await
});
match res {
Ok(p) => {
unsafe { *pid = p };
null_mut()
}
Err(e) => ffi_err!(e),
}
}
/// Kills a running process
///
/// # Arguments
/// * [`handle`] - The ProcessControlClient handle
/// * [`pid`] - The process ID to kill
///
/// # Returns
/// An IdeviceFfiError on error, null on success
///
/// # Safety
/// `handle` must be a valid pointer to a handle allocated by this library
#[unsafe(no_mangle)]
pub unsafe extern "C" fn process_control_kill_app(
handle: *mut ProcessControlHandle<'static>,
pid: u64,
) -> *mut IdeviceFfiError {
if handle.is_null() {
return ffi_err!(IdeviceError::FfiInvalidArg);
}
let client = unsafe { &mut (*handle).0 };
let res = RUNTIME.block_on(async move { client.kill_app(pid).await });
match res {
Ok(_) => null_mut(),
Err(e) => ffi_err!(e),
}
}
/// Disables memory limits for a process
///
/// # Arguments
/// * [`handle`] - The ProcessControlClient handle
/// * [`pid`] - The process ID to modify
///
/// # Returns
/// An IdeviceFfiError on error, null on success
///
/// # Safety
/// `handle` must be a valid pointer to a handle allocated by this library
#[unsafe(no_mangle)]
pub unsafe extern "C" fn process_control_disable_memory_limit(
handle: *mut ProcessControlHandle<'static>,
pid: u64,
) -> *mut IdeviceFfiError {
if handle.is_null() {
return ffi_err!(IdeviceError::FfiInvalidArg);
}
let client = unsafe { &mut (*handle).0 };
let res = RUNTIME.block_on(async move { client.disable_memory_limit(pid).await });
match res {
Ok(_) => null_mut(),
Err(e) => ffi_err!(e),
}
}

View File

@@ -0,0 +1,116 @@
// Jackson Coxson
use std::ptr::null_mut;
use crate::core_device_proxy::AdapterHandle;
use crate::rsd::RsdHandshakeHandle;
use crate::{IdeviceFfiError, RUNTIME, ReadWriteOpaque, ffi_err};
use idevice::dvt::remote_server::RemoteServerClient;
use idevice::{IdeviceError, ReadWrite, RsdService};
/// Opaque handle to a RemoteServerClient
pub struct RemoteServerHandle(pub RemoteServerClient<Box<dyn ReadWrite>>);
/// Creates a new RemoteServerClient from a ReadWrite connection
///
/// # Arguments
/// * [`socket`] - The connection to use for communication, an object that implements ReadWrite
/// * [`handle`] - Pointer to store the newly created RemoteServerClient handle
///
/// # Returns
/// An IdeviceFfiError on error, null on success
///
/// # Safety
/// `socket` must be a valid pointer to a handle allocated by this library. It is consumed and may
/// not be used again.
/// `handle` must be a valid pointer to a location where the handle will be stored
#[unsafe(no_mangle)]
pub unsafe extern "C" fn remote_server_new(
socket: *mut ReadWriteOpaque,
handle: *mut *mut RemoteServerHandle,
) -> *mut IdeviceFfiError {
if socket.is_null() {
return ffi_err!(IdeviceError::FfiInvalidArg);
}
let wrapper = unsafe { &mut *socket };
let res: Result<RemoteServerClient<Box<dyn ReadWrite>>, IdeviceError> =
match wrapper.inner.take() {
Some(stream) => RUNTIME.block_on(async move {
let mut client = RemoteServerClient::new(stream);
client.read_message(0).await?;
Ok(client)
}),
None => return ffi_err!(IdeviceError::FfiInvalidArg),
};
match res {
Ok(client) => {
let boxed = Box::new(RemoteServerHandle(client));
unsafe { *handle = Box::into_raw(boxed) };
null_mut()
}
Err(e) => ffi_err!(e),
}
}
/// Creates a new RemoteServerClient from a handshake and adapter
///
/// # Arguments
/// * [`provider`] - An adapter created by this library
/// * [`handshake`] - An RSD handshake from the same provider
///
/// # Returns
/// An IdeviceFfiError on error, null on success
///
/// # Safety
/// `provider` must be a valid pointer to a handle allocated by this library
/// `handshake` must be a valid pointer to a location where the handle will be stored
#[unsafe(no_mangle)]
pub unsafe extern "C" fn remote_server_connect_rsd(
provider: *mut AdapterHandle,
handshake: *mut RsdHandshakeHandle,
handle: *mut *mut RemoteServerHandle,
) -> *mut IdeviceFfiError {
if provider.is_null() || handshake.is_null() || handshake.is_null() {
return ffi_err!(IdeviceError::FfiInvalidArg);
}
let res: Result<RemoteServerClient<Box<dyn ReadWrite>>, IdeviceError> =
RUNTIME.block_on(async move {
let provider_ref = unsafe { &mut (*provider).0 };
let handshake_ref = unsafe { &mut (*handshake).0 };
// Connect using the reference
let mut rs_client =
RemoteServerClient::connect_rsd(provider_ref, handshake_ref).await?;
// TODO: remove this when we can read from the remote server, or rethink the Rust API
rs_client.read_message(0).await?;
Ok(rs_client)
});
match res {
Ok(d) => {
let boxed = Box::new(RemoteServerHandle(RemoteServerClient::new(Box::new(
d.into_inner(),
))));
unsafe { *handle = Box::into_raw(boxed) };
null_mut()
}
Err(e) => ffi_err!(e),
}
}
/// Frees a RemoteServerClient handle
///
/// # Arguments
/// * [`handle`] - The handle to free
///
/// # Safety
/// `handle` must be a valid pointer to a handle allocated by this library or NULL
#[unsafe(no_mangle)]
pub unsafe extern "C" fn remote_server_free(handle: *mut RemoteServerHandle) {
if !handle.is_null() {
let _ = unsafe { Box::from_raw(handle) };
}
}

113
ffi/src/dvt/screenshot.rs Normal file
View File

@@ -0,0 +1,113 @@
// Jackson Coxson
use std::ptr::null_mut;
use idevice::{ReadWrite, dvt::screenshot::ScreenshotClient};
use crate::{IdeviceFfiError, RUNTIME, dvt::remote_server::RemoteServerHandle, ffi_err};
/// An opaque FFI handle for a [`ScreenshotClient`].
///
/// This type wraps a [`ScreenshotClient`] that communicates with
/// a connected device to capture screenshots through the DVT (Device Virtualization Toolkit) service.
pub struct ScreenshotClientHandle<'a>(pub ScreenshotClient<'a, Box<dyn ReadWrite>>);
/// Creates a new [`ScreenshotClient`] associated with a given [`RemoteServerHandle`].
///
/// # Arguments
/// * `server` - A pointer to a valid [`RemoteServerHandle`], previously created by this library.
/// * `handle` - A pointer to a location where the newly created [`ScreenshotClientHandle`] will be stored.
///
/// # Returns
/// * `null_mut()` on success.
/// * A pointer to an [`IdeviceFfiError`] on failure.
///
/// # Safety
/// - `server` must be a non-null pointer to a valid remote server handle allocated by this library.
/// - `handle` must be a non-null pointer to a writable memory location where the handle will be stored.
/// - The returned handle must later be freed using [`screenshot_client_free`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn screenshot_client_new(
server: *mut RemoteServerHandle,
handle: *mut *mut ScreenshotClientHandle<'static>,
) -> *mut IdeviceFfiError {
if server.is_null() || handle.is_null() {
return ffi_err!(IdeviceError::FfiInvalidArg);
}
let server = unsafe { &mut (*server).0 };
let res = RUNTIME.block_on(async move { ScreenshotClient::new(server).await });
match res {
Ok(client) => {
let boxed = Box::new(ScreenshotClientHandle(client));
unsafe { *handle = Box::into_raw(boxed) };
null_mut()
}
Err(e) => ffi_err!(e),
}
}
/// Frees a [`ScreenshotClientHandle`].
///
/// This releases all memory associated with the handle.
/// After calling this function, the handle pointer must not be used again.
///
/// # Arguments
/// * `handle` - Pointer to a [`ScreenshotClientHandle`] previously returned by [`screenshot_client_new`].
///
/// # Safety
/// - `handle` must either be `NULL` or a valid pointer created by this library.
/// - Double-freeing or using the handle after freeing causes undefined behavior.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn screenshot_client_free(handle: *mut ScreenshotClientHandle<'static>) {
if !handle.is_null() {
let _ = unsafe { Box::from_raw(handle) };
}
}
/// Captures a screenshot from the connected device.
///
/// On success, this function writes a pointer to the PNG-encoded screenshot data and its length
/// into the provided output arguments. The caller is responsible for freeing this data using
/// `idevice_data_free`.
///
/// # Arguments
/// * `handle` - A pointer to a valid [`ScreenshotClientHandle`].
/// * `data` - Output pointer where the screenshot buffer pointer will be written.
/// * `len` - Output pointer where the buffer length (in bytes) will be written.
///
/// # Returns
/// * `null_mut()` on success.
/// * A pointer to an [`IdeviceFfiError`] on failure.
///
/// # Safety
/// - `handle` must be a valid pointer to a [`ScreenshotClientHandle`].
/// - `data` and `len` must be valid writable pointers.
/// - The data returned through `*data` must be freed by the caller with `idevice_data_free`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn screenshot_client_clear(
handle: *mut ScreenshotClientHandle<'static>,
data: *mut *mut u8,
len: *mut usize,
) -> *mut IdeviceFfiError {
if handle.is_null() || data.is_null() || len.is_null() {
return ffi_err!(IdeviceError::FfiInvalidArg);
}
let client = unsafe { &mut (*handle).0 };
let res = RUNTIME.block_on(async move { client.take_screenshot().await });
match res {
Ok(r) => {
let mut r = r.into_boxed_slice();
unsafe {
*data = r.as_mut_ptr();
*len = r.len();
}
std::mem::forget(r); // Prevent Rust from freeing the buffer
null_mut()
}
Err(e) => ffi_err!(e),
}
}