mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 03:39:52 +00:00
Dispatch queued GDK callbacks through translated guest execution
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
This commit is contained in:
1 parent
b8fae106af
commit
fa2e89cc06
4 files changed
+173
-9
No files matched your search
@@ -195,11 +195,30 @@ fn trampoline_address(index: usize) -> u64 {
|
||||
IMPORT_TRAMPOLINE_BASE_VA + index as u64 * IMPORT_TRAMPOLINE_STRIDE
|
||||
}
|
||||
|
||||
const CALLBACK_RETURN: u64 = IMPORT_TRAMPOLINE_BASE_VA - IMPORT_TRAMPOLINE_STRIDE;
|
||||
const MAX_CALLBACK_DEPTH: usize = 32;
|
||||
|
||||
pub(crate) struct GuestCallback {
|
||||
pub(crate) entry: u64,
|
||||
pub(crate) context: u64,
|
||||
}
|
||||
|
||||
type CallbackDispatch = Box<
|
||||
dyn Fn(&Win64Args, &GuestMemory) -> Result<Option<GuestCallback>, ExitReason> + Send + Sync,
|
||||
>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct CallbackFrame {
|
||||
resume: u64,
|
||||
preserved: Nonvolatile,
|
||||
}
|
||||
|
||||
/// Registry for resolving and binding import symbols to guest trampoline VAs.
|
||||
pub struct ImportRegistry {
|
||||
// (lower-case module, name) -> service index. Symbol names keep their case.
|
||||
services: HashMap<(String, ImportName), usize>,
|
||||
handlers: Vec<ServiceDescriptor>,
|
||||
callback_dispatchers: HashMap<usize, CallbackDispatch>,
|
||||
dynamic_trampolines: DynamicTrampolines,
|
||||
trampoline_to_service: HashMap<u64, usize>, // Trampoline VA -> service_index
|
||||
}
|
||||
@@ -215,6 +234,7 @@ impl ImportRegistry {
|
||||
Self {
|
||||
services: HashMap::new(),
|
||||
handlers: Vec::new(),
|
||||
callback_dispatchers: HashMap::new(),
|
||||
trampoline_to_service: HashMap::new(),
|
||||
dynamic_trampolines: DynamicTrampolines::default(),
|
||||
}
|
||||
@@ -488,9 +508,29 @@ impl ImportRegistry {
|
||||
Ok(slots.len())
|
||||
}
|
||||
|
||||
pub(crate) fn register_callback_dispatch(
|
||||
&mut self,
|
||||
module: &str,
|
||||
symbol: &str,
|
||||
handler: impl Fn(&Win64Args, &GuestMemory) -> Result<Option<GuestCallback>, ExitReason>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
) {
|
||||
self.register_with_status(module, symbol, ServiceStatus::Partial, |_, _, _| {
|
||||
Err(ExitReason::IllegalInstruction(0xff))
|
||||
});
|
||||
let index = self
|
||||
.service_index(module, symbol)
|
||||
.expect("registered dispatcher");
|
||||
self.callback_dispatchers.insert(index, Box::new(handler));
|
||||
}
|
||||
|
||||
/// Check if target RIP matches a synthetic service trampoline.
|
||||
pub fn is_service_trampoline(&self, rip: u64) -> bool {
|
||||
self.trampoline_to_service.contains_key(&rip) || self.dynamic_trampolines.get(rip).is_some()
|
||||
rip == CALLBACK_RETURN
|
||||
|| self.trampoline_to_service.contains_key(&rip)
|
||||
|| self.dynamic_trampolines.get(rip).is_some()
|
||||
}
|
||||
|
||||
/// Dispatch a service call when guest RIP hits a service trampoline.
|
||||
@@ -500,6 +540,19 @@ impl ImportRegistry {
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
) -> Result<(), ExitReason> {
|
||||
if rip == CALLBACK_RETURN {
|
||||
let key = (cpu.gs_base, cpu.get(Register::Rsp));
|
||||
let frame = memory
|
||||
.callback_frames
|
||||
.remove(&key)
|
||||
.ok_or(ExitReason::IllegalInstruction(0xff))?;
|
||||
if Nonvolatile::of(cpu) != frame.preserved {
|
||||
return Err(ExitReason::ServiceAbiViolation);
|
||||
}
|
||||
cpu.set(Register::Rax, 1);
|
||||
cpu.rip = frame.resume;
|
||||
return Ok(());
|
||||
}
|
||||
let service_idx = self
|
||||
.trampoline_to_service
|
||||
.get(&rip)
|
||||
@@ -518,6 +571,39 @@ impl ImportRegistry {
|
||||
|
||||
let args = Win64Args::new(cpu);
|
||||
let preserved = Nonvolatile::of(cpu);
|
||||
if let Some(dispatcher) = self.callback_dispatchers.get(&service_idx) {
|
||||
let key = (cpu.gs_base, after);
|
||||
if memory.callback_frames.len() >= MAX_CALLBACK_DEPTH
|
||||
|| memory.callback_frames.contains_key(&key)
|
||||
{
|
||||
return Err(ExitReason::ServiceAbiViolation);
|
||||
}
|
||||
memory
|
||||
.check_write(rsp, 8)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
if let Some(callback) = dispatcher(&args, memory)? {
|
||||
memory
|
||||
.write_u64(rsp, CALLBACK_RETURN)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
let mut preserved = preserved;
|
||||
preserved.gpr[4] = after;
|
||||
memory.callback_frames.insert(
|
||||
key,
|
||||
CallbackFrame {
|
||||
resume: ret_addr,
|
||||
preserved,
|
||||
},
|
||||
);
|
||||
cpu.set(Register::Rcx, callback.context);
|
||||
cpu.set(Register::Rdx, 0);
|
||||
cpu.rip = callback.entry;
|
||||
return Ok(());
|
||||
}
|
||||
cpu.set(Register::Rax, 0);
|
||||
cpu.set(Register::Rsp, after);
|
||||
cpu.rip = ret_addr;
|
||||
return Ok(());
|
||||
}
|
||||
let value = (descriptor.handler)(&args, cpu, memory)?;
|
||||
if Nonvolatile::of(cpu) != preserved {
|
||||
return Err(ExitReason::ServiceAbiViolation);
|
||||
@@ -531,7 +617,7 @@ impl ImportRegistry {
|
||||
}
|
||||
|
||||
/// Registers a Win64 callee must preserve (Microsoft x64 calling convention).
|
||||
#[derive(PartialEq, Eq)]
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
struct Nonvolatile {
|
||||
gpr: [u64; 9],
|
||||
xmm: [u128; 10],
|
||||
|
||||
@@ -122,6 +122,8 @@ pub struct GuestMemory {
|
||||
private_heap_serial: u64,
|
||||
// Stable errno pointers indexed by the guest thread's TEB address.
|
||||
crt_errno: std::collections::BTreeMap<u64, u64>,
|
||||
pub(crate) callback_frames:
|
||||
std::collections::BTreeMap<(u64, u64), crate::imports::CallbackFrame>,
|
||||
}
|
||||
|
||||
impl GuestMemory {
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
|
||||
use super::ServicesState;
|
||||
use super::{ERROR_INVALID_HANDLE, ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED};
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{GuestCallback, ImportRegistry, ServiceStatus};
|
||||
use crate::memory::GuestMemory;
|
||||
use crate::runtime::HResult;
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
@@ -23,12 +24,6 @@ pub(super) struct QueueHandles {
|
||||
pending: BTreeMap<u64, VecDeque<GuestCallback>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct GuestCallback {
|
||||
entry: u64,
|
||||
context: u64,
|
||||
}
|
||||
|
||||
impl QueueHandles {
|
||||
fn open(
|
||||
&mut self,
|
||||
@@ -196,4 +191,27 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
)))
|
||||
},
|
||||
);
|
||||
let dispatch = Arc::clone(state);
|
||||
registry.register_callback_dispatch(MODULE, "XTaskQueueDispatch", move |args, memory| {
|
||||
if args.r8 as u32 != 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut queues = dispatch.gdk_queues.lock().expect("GDK queue handle table");
|
||||
let Some(&port) = queues
|
||||
.queues
|
||||
.get(&args.rcx)
|
||||
.and_then(|ports| ports.get(args.rdx as u32 as usize))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(pending) = queues.pending.get_mut(&port) else {
|
||||
return Ok(None);
|
||||
};
|
||||
if let Some(callback) = pending.front() {
|
||||
memory
|
||||
.fetch_instruction_byte(callback.entry)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
Ok(pending.pop_front())
|
||||
});
|
||||
}
|
||||
@@ -1121,6 +1121,64 @@ fn test_guest_crt_string_length_through_iat() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guest_gdk_dispatch_runs_callback_and_resumes_caller() {
|
||||
const IMAGE: u64 = 0x140000000;
|
||||
const MODULE: &str = "xgameruntime.dll";
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
let output = PROCESS_FIXTURE_STACK_TOP - 0x400;
|
||||
let created = call_service_fixture(&state, MODULE, "XTaskQueueCreate", &[0, 0, output]);
|
||||
let queue = created.image.memory.read_u64(output).unwrap();
|
||||
assert_ne!(queue, 0);
|
||||
let mut code = vec![0x48, 0x83, 0xec, 0x48];
|
||||
let set_args = |code: &mut Vec<u8>, values: &[u64]| {
|
||||
for (register, value) in [[0x48, 0xb9], [0x48, 0xba], [0x49, 0xb8], [0x49, 0xb9]]
|
||||
.into_iter()
|
||||
.zip(values)
|
||||
{
|
||||
code.extend_from_slice(®ister);
|
||||
code.extend_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
};
|
||||
code.extend_from_slice(&[0x48, 0xb8]);
|
||||
code.extend_from_slice(&output.to_le_bytes());
|
||||
code.extend_from_slice(&[0x48, 0xc7, 0x00, 0xff, 0xff, 0xff, 0xff]);
|
||||
set_args(&mut code, &[queue, 0, output, IMAGE + 0x1100]);
|
||||
append_import_call(&mut code, 0x2060);
|
||||
set_args(&mut code, &[queue, 0, 0]);
|
||||
append_import_call(&mut code, 0x21a0);
|
||||
code.extend_from_slice(&[0x48, 0x89, 0xc3]); // retain successful dispatch in RBX
|
||||
set_args(&mut code, &[queue, 0, 0]);
|
||||
append_import_call(&mut code, 0x21a0);
|
||||
code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x48, 0xf4]);
|
||||
code.resize(0x100, 0);
|
||||
// Store canceled, then clobber RAX to verify the dispatch return is restored.
|
||||
code.extend_from_slice(&[0x48, 0x89, 0x11, 0xb8, 99, 0, 0, 0, 0xc3]);
|
||||
let image = TestPeBuilder::new(IMAGE, 0x1000)
|
||||
.add_import(MODULE, "XTaskQueueSubmitCallback")
|
||||
.add_import(MODULE, "XTaskQueueDispatch")
|
||||
.code(&code)
|
||||
.build();
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, state);
|
||||
let result = run_synthetic_startup(
|
||||
&image,
|
||||
StartupLayout {
|
||||
image_base: IMAGE,
|
||||
stack_top: PROCESS_FIXTURE_STACK_TOP,
|
||||
tls_base: 0x300000000,
|
||||
},
|
||||
registry,
|
||||
100,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result.execution.exit_reason, ExitReason::Halt);
|
||||
let cpu = result.execution.final_state;
|
||||
assert_eq!(cpu.get(Register::Rbx), 1);
|
||||
assert_eq!(cpu.get(Register::Rax), 0);
|
||||
assert_eq!(result.image.memory.read_u64(output).unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guest_gdk_manual_queue_handles_have_independent_lifetimes() {
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
|
||||
Reference in new issue
Block a user