xasync.rs 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599
  1. //! XTaskQueue and XAsync: the runtime's callback queues and async-call
  2. //! blocks, served as the task-queue provider's object from `QueryApiImpl`.
  3. //!
  4. //! As documented for the public API: a queue has a work port and a
  5. //! completion port, each dispatched manually (the title calls dispatch),
  6. //! on a thread pool, serialised on one thread, or immediately on the
  7. //! submitting thread. A null queue handle means the process queue. An
  8. //! async block's system area holds its status and result size, so both
  9. //! stay readable after our state for the call is gone.
  10. #![allow(non_snake_case)]
  11. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  12. use std::collections::{BTreeMap, HashMap, VecDeque};
  13. use std::ffi::c_void;
  14. use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
  15. use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard};
  16. use std::time::Duration;
  17. use super::xgameruntime::{Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing};
  18. /// The task-queue provider; it is also the interface id titles ask for.
  19. pub const PROVIDER: Guid = Guid {
  20. data1: 0x073b_7dcb,
  21. data2: 0x1fcf,
  22. data3: 0x4030,
  23. data4: [0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28],
  24. };
  25. pub const E_PENDING: HRESULT = 0x8000_000A_u32 as i32;
  26. pub const E_ABORT: HRESULT = 0x8000_4004_u32 as i32;
  27. pub const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32;
  28. pub const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32;
  29. pub const E_NOT_SUFFICIENT_BUFFER: HRESULT = 0x8007_007A_u32 as i32;
  30. pub const E_ILLEGAL_METHOD_CALL: HRESULT = 0x8000_000E_u32 as i32;
  31. const WORK: u32 = 0;
  32. const COMPLETION: u32 = 1;
  33. const INFINITE: u32 = u32::MAX;
  34. type Callback = extern "system" fn(*mut c_void, bool);
  35. type MonitorCallback = extern "system" fn(*mut c_void, *const Queue, u32);
  36. type TerminatedCallback = extern "system" fn(*mut c_void);
  37. type CompletionRoutine = extern "system" fn(*mut AsyncBlock);
  38. type Provider = extern "system" fn(u32, *const ProviderData) -> HRESULT;
  39. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  40. enum Mode {
  41. Manual,
  42. ThreadPool,
  43. Serialized,
  44. Immediate,
  45. }
  46. impl Mode {
  47. fn from_raw(mode: u32) -> Option<Mode> {
  48. [
  49. Mode::Manual,
  50. Mode::ThreadPool,
  51. Mode::Serialized,
  52. Mode::Immediate,
  53. ]
  54. .get(mode as usize)
  55. .copied()
  56. }
  57. }
  58. /// A title callback and its context (addresses, so tasks can cross threads).
  59. #[derive(Clone, Copy)]
  60. struct Task {
  61. context: usize,
  62. callback: usize,
  63. }
  64. impl Task {
  65. fn new(context: *mut c_void, callback: Callback) -> Task {
  66. Task {
  67. context: context as usize,
  68. callback: callback as usize,
  69. }
  70. }
  71. fn run(self, canceled: bool) {
  72. // SAFETY: built from a `Callback` in `new`.
  73. let callback: Callback = unsafe { std::mem::transmute(self.callback) };
  74. callback(self.context as *mut c_void, canceled);
  75. }
  76. }
  77. struct Port {
  78. mode: Mode,
  79. tasks: Mutex<VecDeque<Task>>,
  80. ready: Condvar,
  81. }
  82. impl Port {
  83. fn new(mode: Mode) -> Arc<Port> {
  84. let port = Arc::new(Port {
  85. mode,
  86. tasks: Mutex::default(),
  87. ready: Condvar::new(),
  88. });
  89. if mode == Mode::Serialized {
  90. // The worker ends once it holds the last reference (every queue
  91. // using the port is closed) and nothing is left to run.
  92. let worker = port.clone();
  93. std::thread::spawn(move || {
  94. loop {
  95. match worker.take(1000, || false) {
  96. Some(task) => task.run(false),
  97. None if Arc::strong_count(&worker) == 1 => break,
  98. None => {}
  99. }
  100. }
  101. });
  102. }
  103. port
  104. }
  105. fn submit(&self, task: Task) {
  106. match self.mode {
  107. Mode::Immediate => task.run(false),
  108. Mode::ThreadPool => POOL.submit(task),
  109. Mode::Manual | Mode::Serialized => {
  110. lock(&self.tasks).push_back(task);
  111. self.ready.notify_one();
  112. }
  113. }
  114. }
  115. /// The next queued task, waiting up to `timeout_ms`, or until `ended`
  116. /// (checked whenever the port is woken) says no task will come.
  117. fn take(&self, timeout_ms: u32, ended: impl Fn() -> bool) -> Option<Task> {
  118. let waiting = |t: &mut VecDeque<Task>| t.is_empty() && !ended();
  119. let tasks = lock(&self.tasks);
  120. let mut tasks = if timeout_ms == INFINITE {
  121. self.ready
  122. .wait_while(tasks, waiting)
  123. .unwrap_or_else(|e| e.into_inner())
  124. } else {
  125. let timeout = Duration::from_millis(timeout_ms.into());
  126. self.ready
  127. .wait_timeout_while(tasks, timeout, waiting)
  128. .unwrap_or_else(|e| e.into_inner())
  129. .0
  130. };
  131. tasks.pop_front()
  132. }
  133. }
  134. /// The thread pool behind thread-pool ports: idle workers are reused, and a
  135. /// new one starts whenever more tasks wait than workers idle, so a callback
  136. /// that blocks on another never starves it. Workers stay for reuse.
  137. struct Pool {
  138. /// Queued tasks and the number of idle workers.
  139. state: Mutex<(VecDeque<Task>, usize)>,
  140. ready: Condvar,
  141. }
  142. static POOL: Pool = Pool {
  143. state: Mutex::new((VecDeque::new(), 0)),
  144. ready: Condvar::new(),
  145. };
  146. impl Pool {
  147. fn submit(&'static self, task: Task) {
  148. let mut state = lock(&self.state);
  149. state.0.push_back(task);
  150. if state.0.len() > state.1 {
  151. std::thread::spawn(move || self.work());
  152. } else {
  153. self.ready.notify_one();
  154. }
  155. }
  156. fn work(&self) {
  157. let mut state = lock(&self.state);
  158. loop {
  159. while state.0.is_empty() {
  160. state.1 += 1;
  161. state = self.ready.wait(state).unwrap_or_else(|e| e.into_inner());
  162. state.1 -= 1;
  163. }
  164. let task = state.0.pop_front();
  165. drop(state);
  166. if let Some(task) = task {
  167. task.run(false);
  168. }
  169. state = lock(&self.state);
  170. }
  171. }
  172. }
  173. /// A queue handle is `Arc::into_raw` of this; duplicating and closing a
  174. /// handle add and drop a reference.
  175. pub struct Queue {
  176. ports: [Arc<Port>; 2],
  177. monitors: Mutex<Vec<(u64, usize, usize)>>,
  178. terminated: AtomicBool,
  179. /// Delayed callbacks still waiting out their delay, in submission
  180. /// order: terminating the queue cancels them with the queued ones.
  181. delayed: Mutex<BTreeMap<u64, Task>>,
  182. }
  183. impl Queue {
  184. fn new(ports: [Arc<Port>; 2]) -> Arc<Queue> {
  185. Arc::new(Queue {
  186. ports,
  187. monitors: Mutex::default(),
  188. terminated: AtomicBool::new(false),
  189. delayed: Mutex::default(),
  190. })
  191. }
  192. fn submit(self: &Arc<Self>, port: u32, delay_ms: u32, task: Task) -> HRESULT {
  193. static NEXT_DELAYED: AtomicU64 = AtomicU64::new(0);
  194. if port > COMPLETION {
  195. return E_INVALIDARG;
  196. }
  197. if self.terminated.load(Ordering::Acquire) {
  198. return E_ABORT;
  199. }
  200. if delay_ms == 0 {
  201. self.deliver(port, task);
  202. return S_OK;
  203. }
  204. let id = NEXT_DELAYED.fetch_add(1, Ordering::Relaxed);
  205. {
  206. // Checked again under the lock termination drains: the callback
  207. // is either canceled with the others or refused.
  208. let mut delayed = lock(&self.delayed);
  209. if self.terminated.load(Ordering::Acquire) {
  210. return E_ABORT;
  211. }
  212. delayed.insert(id, task);
  213. }
  214. let queue = self.clone();
  215. std::thread::spawn(move || {
  216. std::thread::sleep(Duration::from_millis(delay_ms.into()));
  217. // Gone if the queue was terminated meanwhile, which canceled it.
  218. let task = lock(&queue.delayed).remove(&id);
  219. if let Some(task) = task {
  220. queue.deliver(port, task);
  221. }
  222. });
  223. S_OK
  224. }
  225. fn deliver(self: &Arc<Self>, port: u32, task: Task) {
  226. self.ports[port as usize].submit(task);
  227. // Copied out: a monitor may unregister itself.
  228. let monitors = lock(&self.monitors).clone();
  229. for (_, context, callback) in monitors {
  230. // SAFETY: stored from a `MonitorCallback` in `register_monitor`.
  231. let callback: MonitorCallback = unsafe { std::mem::transmute(callback) };
  232. callback(context as *mut c_void, Arc::as_ptr(self), port);
  233. }
  234. }
  235. }
  236. fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
  237. m.lock().unwrap_or_else(|e| e.into_inner())
  238. }
  239. /// The process queue: `None` until first used (then a thread-pool queue),
  240. /// `Some(None)` once the title clears it.
  241. static PROCESS_QUEUE: Mutex<Option<Option<Arc<Queue>>>> = Mutex::new(None);
  242. fn process_queue() -> Option<Arc<Queue>> {
  243. lock(&PROCESS_QUEUE)
  244. .get_or_insert_with(|| {
  245. Some(Queue::new([
  246. Port::new(Mode::ThreadPool),
  247. Port::new(Mode::ThreadPool),
  248. ]))
  249. })
  250. .clone()
  251. }
  252. /// A new reference to the queue behind `handle` (null: the process queue).
  253. fn queue(handle: *const Queue) -> Option<Arc<Queue>> {
  254. if handle.is_null() {
  255. return process_queue();
  256. }
  257. // SAFETY: a handle we returned, which the title has not closed.
  258. unsafe {
  259. Arc::increment_strong_count(handle);
  260. Some(Arc::from_raw(handle))
  261. }
  262. }
  263. pub fn XTaskQueueCreate(work: u32, completion: u32, out: *mut *const Queue) -> HRESULT {
  264. let (Some(work), Some(completion)) = (Mode::from_raw(work), Mode::from_raw(completion)) else {
  265. return E_INVALIDARG;
  266. };
  267. if out.is_null() {
  268. return E_INVALIDARG;
  269. }
  270. let queue = Queue::new([Port::new(work), Port::new(completion)]);
  271. // SAFETY: checked non-null; the title passes room for a handle.
  272. unsafe { out.write(Arc::into_raw(queue)) };
  273. S_OK
  274. }
  275. /// A port handle points at the port, which its queue keeps alive.
  276. pub fn XTaskQueueGetPort(handle: *const Queue, port: u32, out: *mut *const c_void) -> HRESULT {
  277. let Some(queue) = queue(handle) else {
  278. return E_INVALIDARG;
  279. };
  280. if port > COMPLETION || out.is_null() {
  281. return E_INVALIDARG;
  282. }
  283. // SAFETY: checked non-null.
  284. unsafe { out.write(Arc::as_ptr(&queue.ports[port as usize]).cast()) };
  285. S_OK
  286. }
  287. pub fn XTaskQueueCreateComposite(
  288. work: *const c_void,
  289. completion: *const c_void,
  290. out: *mut *const Queue,
  291. ) -> HRESULT {
  292. if work.is_null() || completion.is_null() || out.is_null() {
  293. return E_INVALIDARG;
  294. }
  295. let port = |p: *const c_void| {
  296. // SAFETY: a port handle from `XTaskQueueGetPort`, whose queue is open.
  297. unsafe {
  298. Arc::increment_strong_count(p.cast::<Port>());
  299. Arc::from_raw(p.cast::<Port>())
  300. }
  301. };
  302. let queue = Queue::new([port(work), port(completion)]);
  303. // SAFETY: checked non-null.
  304. unsafe { out.write(Arc::into_raw(queue)) };
  305. S_OK
  306. }
  307. pub fn XTaskQueueDuplicateHandle(handle: *const Queue, out: *mut *const Queue) -> HRESULT {
  308. match queue(handle) {
  309. Some(queue) if !out.is_null() => {
  310. // SAFETY: checked non-null.
  311. unsafe { out.write(Arc::into_raw(queue)) };
  312. S_OK
  313. }
  314. _ => E_INVALIDARG,
  315. }
  316. }
  317. pub fn XTaskQueueCloseHandle(handle: *const Queue) {
  318. if !handle.is_null() {
  319. // SAFETY: a handle we returned; this drops its reference.
  320. unsafe { Arc::decrement_strong_count(handle) };
  321. }
  322. }
  323. /// Runs one queued callback of a manual port; false if none came in time,
  324. /// or none can come: the queue was terminated (which ends a wait under way,
  325. /// as a dispatcher thread's loop expects).
  326. pub fn XTaskQueueDispatch(handle: *const Queue, port: u32, timeout_ms: u32) -> bool {
  327. let Some(queue) = queue(handle) else {
  328. return false;
  329. };
  330. let Some(port) = queue.ports.get(port as usize) else {
  331. return false;
  332. };
  333. if port.mode != Mode::Manual {
  334. return false;
  335. }
  336. match port.take(timeout_ms, || queue.terminated.load(Ordering::Acquire)) {
  337. Some(task) => {
  338. task.run(false);
  339. true
  340. }
  341. None => false,
  342. }
  343. }
  344. pub fn XTaskQueueSubmitDelayedCallback(
  345. handle: *const Queue,
  346. port: u32,
  347. delay_ms: u32,
  348. context: *mut c_void,
  349. callback: Option<Callback>,
  350. ) -> HRESULT {
  351. match (queue(handle), callback) {
  352. (Some(queue), Some(callback)) => queue.submit(port, delay_ms, Task::new(context, callback)),
  353. _ => E_INVALIDARG,
  354. }
  355. }
  356. /// Cancels what is still queued or waiting out a delay (callbacks see
  357. /// `canceled`), refuses new work, then calls `callback`.
  358. pub fn XTaskQueueTerminate(
  359. handle: *const Queue,
  360. _wait: bool,
  361. context: *mut c_void,
  362. callback: Option<TerminatedCallback>,
  363. ) -> HRESULT {
  364. let Some(queue) = queue(handle) else {
  365. return E_INVALIDARG;
  366. };
  367. queue.terminated.store(true, Ordering::Release);
  368. for port in &queue.ports {
  369. let pending: Vec<Task> = lock(&port.tasks).drain(..).collect();
  370. // Dispatches waiting on this queue end: nothing more will come.
  371. // (Those of other queues on the port see theirs is open and wait
  372. // on.) After the lock above, so none misses both flag and wake.
  373. port.ready.notify_all();
  374. for task in pending {
  375. task.run(true);
  376. }
  377. }
  378. let delayed = std::mem::take(&mut *lock(&queue.delayed));
  379. for task in delayed.into_values() {
  380. task.run(true);
  381. }
  382. if let Some(callback) = callback {
  383. callback(context);
  384. }
  385. S_OK
  386. }
  387. static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1);
  388. pub fn XTaskQueueRegisterMonitor(
  389. handle: *const Queue,
  390. context: *mut c_void,
  391. callback: Option<MonitorCallback>,
  392. token: *mut u64,
  393. ) -> HRESULT {
  394. let (Some(queue), Some(callback)) = (queue(handle), callback) else {
  395. return E_INVALIDARG;
  396. };
  397. if token.is_null() {
  398. return E_INVALIDARG;
  399. }
  400. let id = NEXT_TOKEN.fetch_add(1, Ordering::Relaxed);
  401. lock(&queue.monitors).push((id, context as usize, callback as usize));
  402. // SAFETY: checked non-null.
  403. unsafe { token.write(id) };
  404. S_OK
  405. }
  406. pub fn XTaskQueueUnregisterMonitor(handle: *const Queue, token: u64) {
  407. if let Some(queue) = queue(handle) {
  408. lock(&queue.monitors).retain(|m| m.0 != token);
  409. }
  410. }
  411. /// A new handle to the process queue, if there is one.
  412. pub fn XTaskQueueGetCurrentProcessTaskQueue(out: *mut *const Queue) -> bool {
  413. let found = process_queue();
  414. if !out.is_null() {
  415. // SAFETY: checked non-null.
  416. unsafe { out.write(found.clone().map_or(std::ptr::null(), Arc::into_raw)) };
  417. }
  418. found.is_some()
  419. }
  420. pub fn XTaskQueueSetCurrentProcessTaskQueue(handle: *const Queue) {
  421. let new = if handle.is_null() {
  422. None
  423. } else {
  424. queue(handle)
  425. };
  426. *lock(&PROCESS_QUEUE) = Some(new);
  427. }
  428. /// An async block: what the title fills in, then the system area.
  429. #[repr(C)]
  430. pub struct AsyncBlock {
  431. pub queue: *const Queue,
  432. pub context: *mut c_void,
  433. pub callback: Option<CompletionRoutine>,
  434. /// Ours: [unused, status, result size, unused].
  435. pub internal: [usize; 4],
  436. }
  437. #[repr(C)]
  438. pub struct ProviderData {
  439. pub block: *mut AsyncBlock,
  440. pub buffer_size: usize,
  441. pub buffer: *mut c_void,
  442. pub context: *mut c_void,
  443. }
  444. const OP_BEGIN: u32 = 0;
  445. const OP_DO_WORK: u32 = 1;
  446. const OP_GET_RESULT: u32 = 2;
  447. const OP_CANCEL: u32 = 3;
  448. const OP_CLEANUP: u32 = 4;
  449. /// One call in flight, until its result is taken or it fails.
  450. struct Call {
  451. provider: Provider,
  452. context: usize,
  453. identity: usize,
  454. done: Mutex<bool>,
  455. finished: Condvar,
  456. }
  457. impl Call {
  458. fn provider(
  459. &self,
  460. op: u32,
  461. block: *mut AsyncBlock,
  462. size: usize,
  463. buffer: *mut c_void,
  464. ) -> HRESULT {
  465. let data = ProviderData {
  466. block,
  467. buffer_size: size,
  468. buffer,
  469. context: self.context as *mut c_void,
  470. };
  471. (self.provider)(op, &data)
  472. }
  473. }
  474. /// Calls by block address.
  475. static CALLS: LazyLock<Mutex<HashMap<usize, Arc<Call>>>> = LazyLock::new(Default::default);
  476. fn call(block: *mut AsyncBlock) -> Option<Arc<Call>> {
  477. lock(&CALLS).get(&(block as usize)).cloned()
  478. }
  479. /// Whether `call` is still the call in flight on `block`: once it is over,
  480. /// the title may begin another call on the same block.
  481. fn is_current(call: &Arc<Call>, block: *mut AsyncBlock) -> bool {
  482. lock(&CALLS)
  483. .get(&(block as usize))
  484. .is_some_and(|current| Arc::ptr_eq(current, call))
  485. }
  486. /// The block's status and result-size words.
  487. fn words(block: *mut AsyncBlock) -> (&'static AtomicUsize, &'static AtomicUsize) {
  488. // SAFETY: the title's block outlives the call; its system area is ours.
  489. unsafe {
  490. let internal = std::ptr::addr_of_mut!((*block).internal).cast::<AtomicUsize>();
  491. (&*internal.add(1), &*internal.add(2))
  492. }
  493. }
  494. fn status(block: *mut AsyncBlock) -> HRESULT {
  495. words(block).0.load(Ordering::Acquire) as u32 as i32
  496. }
  497. /// Whether the block's system area is all zero, as in a block not yet used.
  498. fn zeroed(block: *mut AsyncBlock) -> bool {
  499. // SAFETY: the title's block, whose system area is ours to read.
  500. unsafe { std::ptr::addr_of!((*block).internal).read_volatile() == [0; 4] }
  501. }
  502. fn release(block: *mut AsyncBlock) {
  503. // Unlocked before the provider runs: it may call back into us.
  504. let removed = lock(&CALLS).remove(&(block as usize));
  505. if let Some(call) = removed {
  506. call.provider(OP_CLEANUP, block, 0, std::ptr::null_mut());
  507. }
  508. }
  509. pub fn XAsyncBegin(
  510. block: *mut AsyncBlock,
  511. context: *mut c_void,
  512. identity: *const c_void,
  513. _identity_name: *const u8,
  514. provider: Option<Provider>,
  515. ) -> HRESULT {
  516. let Some(provider) = provider else {
  517. return E_INVALIDARG;
  518. };
  519. if block.is_null() {
  520. return E_INVALIDARG;
  521. }
  522. if let Some(left) = call(block) {
  523. // Calls are filed by block address, and one that succeeded stays
  524. // filed until its result is taken. A title that never takes it and
  525. // frees the block may get the same address for its next one, which
  526. // it zeroes as every new block must be; the block of a result left
  527. // behind never reads zero (it holds the result's size). So this is
  528. // a new block, and the call left behind ends here. A call in flight
  529. // keeps its address, and a block still holding a result is in use.
  530. let over = *lock(&left.done);
  531. if !(over && zeroed(block)) {
  532. return E_INVALIDARG;
  533. }
  534. release(block);
  535. }
  536. let (status, size) = words(block);
  537. status.store(E_PENDING as u32 as usize, Ordering::Release);
  538. size.store(0, Ordering::Release);
  539. let call = Arc::new(Call {
  540. provider,
  541. context: context as usize,
  542. identity: identity as usize,
  543. done: Mutex::new(false),
  544. finished: Condvar::new(),
  545. });
  546. lock(&CALLS).insert(block as usize, call.clone());
  547. // A failed begin fails the call, so the completion routine still runs.
  548. let hr = call.provider(OP_BEGIN, block, 0, std::ptr::null_mut());
  549. if hr < 0 {
  550. complete_call(&call, block, hr, 0);
  551. }
  552. S_OK
  553. }
  554. /// Queues the provider's `DoWork` on the block's work port. The work
  555. /// belongs to the call that scheduled it: when it runs, that call may be
  556. /// over and the block may hold another.
  557. pub fn XAsyncSchedule(block: *mut AsyncBlock, delay_ms: u32) -> HRESULT {
  558. struct Work {
  559. call: Arc<Call>,
  560. block: *mut AsyncBlock,
  561. }
  562. extern "system" fn work(context: *mut c_void, canceled: bool) {
  563. // SAFETY: boxed in `XAsyncSchedule`; a task runs once.
  564. let Work { call, block } = *unsafe { Box::from_raw(context.cast::<Work>()) };
  565. if !is_current(&call, block) {
  566. return;
  567. }
  568. let hr = if canceled {
  569. E_ABORT
  570. } else {
  571. call.provider(OP_DO_WORK, block, 0, std::ptr::null_mut())
  572. };
  573. complete_call(&call, block, hr, 0);
  574. }
  575. if block.is_null() {
  576. return E_INVALIDARG;
  577. }
  578. let Some(call) = call(block) else {
  579. return E_INVALIDARG;
  580. };
  581. // SAFETY: a block in flight is valid.
  582. let handle = unsafe { (*block).queue };
  583. let Some(queue) = queue(handle) else {
  584. return E_INVALIDARG;
  585. };
  586. let context = Box::into_raw(Box::new(Work { call, block }));
  587. let hr = queue.submit(WORK, delay_ms, Task::new(context.cast(), work));
  588. if hr < 0 {
  589. // Refused, so the task never runs.
  590. // SAFETY: still ours.
  591. drop(unsafe { Box::from_raw(context) });
  592. }
  593. hr
  594. }
  595. /// Records the result (the first one wins), wakes waiters and queues the
  596. /// completion routine on the block's completion port.
  597. pub fn XAsyncComplete(block: *mut AsyncBlock, result: HRESULT, required_size: usize) {
  598. if let Some(call) = call(block) {
  599. complete_call(&call, block, result, required_size);
  600. }
  601. }
  602. /// [`XAsyncComplete`] for `call`, which is or was in flight on `block`. Our
  603. /// own completions name the call they belong to, not the block: if the
  604. /// provider already completed it, the title may have begun another call on
  605. /// the block, which a second complete by block would end.
  606. fn complete_call(call: &Call, block: *mut AsyncBlock, result: HRESULT, required_size: usize) {
  607. extern "system" fn complete(block: *mut c_void, _canceled: bool) {
  608. let block = block.cast::<AsyncBlock>();
  609. // SAFETY: read before the status was published; see below.
  610. if let Some(routine) = unsafe { (*block).callback } {
  611. routine(block);
  612. }
  613. }
  614. if result == E_PENDING {
  615. return;
  616. }
  617. let mut done = lock(&call.done);
  618. if *done {
  619. return;
  620. }
  621. // Read before publishing: once the status is set, the title may free
  622. // the block.
  623. // SAFETY: a block in flight is valid.
  624. let (handle, routine) = unsafe { ((*block).queue, (*block).callback) };
  625. let (status, size) = words(block);
  626. if result < 0 || required_size == 0 {
  627. release(block);
  628. }
  629. size.store(required_size, Ordering::Release);
  630. status.store(result as u32 as usize, Ordering::Release);
  631. *done = true;
  632. call.finished.notify_all();
  633. drop(done);
  634. if routine.is_some() {
  635. let task = Task::new(block.cast(), complete);
  636. match queue(handle) {
  637. Some(queue) if queue.submit(COMPLETION, 0, task) == S_OK => {}
  638. _ => task.run(true),
  639. }
  640. }
  641. }
  642. pub fn XAsyncGetStatus(block: *mut AsyncBlock, wait: bool) -> HRESULT {
  643. if block.is_null() {
  644. return E_INVALIDARG;
  645. }
  646. if wait && let Some(call) = call(block) {
  647. let done = lock(&call.done);
  648. drop(call.finished.wait_while(done, |d| !*d));
  649. }
  650. status(block)
  651. }
  652. pub fn XAsyncGetResultSize(block: *mut AsyncBlock, out: *mut usize) -> HRESULT {
  653. if block.is_null() || out.is_null() {
  654. return E_INVALIDARG;
  655. }
  656. let hr = status(block);
  657. // Any nonnegative completion carries a result, not just S_OK: S_FALSE
  658. // is a success code too and a provider may return data with it.
  659. if hr >= 0 {
  660. // SAFETY: checked non-null.
  661. unsafe { out.write(words(block).1.load(Ordering::Acquire)) };
  662. }
  663. hr
  664. }
  665. /// Asks the provider to cancel; the call fails with `E_ABORT` unless the
  666. /// provider completed it first.
  667. pub fn XAsyncCancel(block: *mut AsyncBlock) {
  668. if let Some(call) = call(block) {
  669. call.provider(OP_CANCEL, block, 0, std::ptr::null_mut());
  670. complete_call(&call, block, E_ABORT, 0);
  671. }
  672. }
  673. /// Has the provider write the result into `buffer`, then ends the call.
  674. pub fn XAsyncGetResult(
  675. block: *mut AsyncBlock,
  676. identity: *const c_void,
  677. buffer_size: usize,
  678. buffer: *mut c_void,
  679. used: *mut usize,
  680. ) -> HRESULT {
  681. if block.is_null() {
  682. return E_INVALIDARG;
  683. }
  684. let hr = status(block);
  685. let size = words(block).1.load(Ordering::Acquire);
  686. if hr < 0 || size == 0 {
  687. if hr >= 0 && !used.is_null() {
  688. // SAFETY: checked non-null.
  689. unsafe { used.write(0) };
  690. }
  691. return hr;
  692. }
  693. let Some(call) = call(block) else {
  694. return E_ILLEGAL_METHOD_CALL;
  695. };
  696. if call.identity != identity as usize {
  697. return E_INVALIDARG;
  698. }
  699. if buffer_size < size || buffer.is_null() {
  700. return E_NOT_SUFFICIENT_BUFFER;
  701. }
  702. let hr = call.provider(OP_GET_RESULT, block, buffer_size, buffer);
  703. if !used.is_null() {
  704. // SAFETY: checked non-null.
  705. unsafe { used.write(size) };
  706. }
  707. release(block);
  708. hr
  709. }
  710. /// Starts a call on `block` that is already over: it completes with `hr`
  711. /// and no result data, through the block's completion port as usual.
  712. pub fn finished(block: *mut AsyncBlock, identity: *const c_void, hr: HRESULT) -> HRESULT {
  713. finished_with(
  714. block,
  715. identity,
  716. if hr < 0 { Err(hr) } else { Ok(Vec::new()) },
  717. )
  718. }
  719. /// Like [`finished`], with the bytes `XAsyncGetResult` hands out for
  720. /// `identity` (an error has none).
  721. pub fn finished_with(
  722. block: *mut AsyncBlock,
  723. identity: *const c_void,
  724. result: Result<Vec<u8>, HRESULT>,
  725. ) -> HRESULT {
  726. type Data = Result<Vec<u8>, HRESULT>;
  727. extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT {
  728. // SAFETY: the runtime passes valid provider data; the context is the
  729. // boxed result until cleanup frees it.
  730. let data = unsafe { &*data };
  731. let result = data.context.cast::<Data>();
  732. match op {
  733. // SAFETY: boxed in `finished_with`; nothing runs after cleanup.
  734. OP_CLEANUP => drop(unsafe { Box::from_raw(result) }),
  735. OP_BEGIN => {
  736. // SAFETY: as above. Copied out: completing may clean up.
  737. let (hr, len) = match unsafe { &*result } {
  738. Ok(bytes) => (S_OK, bytes.len()),
  739. Err(hr) => (*hr, 0),
  740. };
  741. XAsyncComplete(data.block, hr, len);
  742. }
  743. // SAFETY: as above; the runtime checked the buffer's size.
  744. OP_GET_RESULT => unsafe {
  745. if let Ok(bytes) = &*result {
  746. data.buffer
  747. .cast::<u8>()
  748. .copy_from(bytes.as_ptr(), bytes.len());
  749. }
  750. },
  751. _ => {}
  752. }
  753. S_OK
  754. }
  755. let context = Box::into_raw(Box::new(result));
  756. let hr = XAsyncBegin(
  757. block,
  758. context.cast(),
  759. identity,
  760. std::ptr::null(),
  761. Some(provider),
  762. );
  763. if hr < 0 {
  764. // Refused before the call existed, so no cleanup will come.
  765. // SAFETY: still ours.
  766. drop(unsafe { Box::from_raw(context) });
  767. }
  768. hr
  769. }
  770. /// Like [`finished_with`], but the result comes from `work`, run on a
  771. /// thread of ours; the call stays pending until it returns (a dialog, say).
  772. pub fn pending_with(
  773. block: *mut AsyncBlock,
  774. identity: *const c_void,
  775. work: impl FnOnce() -> Result<Vec<u8>, HRESULT> + Send + 'static,
  776. ) -> HRESULT {
  777. type Data = Mutex<(Option<Box<dyn FnOnce() -> Result<Vec<u8>, HRESULT> + Send>>, Vec<u8>)>;
  778. extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT {
  779. // SAFETY: the runtime passes valid provider data; the context is the
  780. // boxed state until cleanup frees it.
  781. let data = unsafe { &*data };
  782. let state = data.context.cast::<Data>();
  783. match op {
  784. // SAFETY: boxed in `pending_with`; nothing runs after cleanup.
  785. OP_CLEANUP => drop(unsafe { Box::from_raw(state) }),
  786. OP_BEGIN => {
  787. // SAFETY: as above; cleanup waits for completion.
  788. let work = unsafe { &*state }.lock().unwrap_or_else(|e| e.into_inner()).0.take();
  789. let (block, state) = (data.block as usize, state as usize);
  790. std::thread::spawn(move || {
  791. let result = work.map_or(Err(E_ABORT), |work| work());
  792. let (hr, len) = match &result {
  793. Ok(bytes) => (S_OK, bytes.len()),
  794. Err(hr) => (*hr, 0),
  795. };
  796. if let Ok(bytes) = result {
  797. // SAFETY: the call is pending, so its state lives.
  798. let state = unsafe { &*(state as *const Data) };
  799. state.lock().unwrap_or_else(|e| e.into_inner()).1 = bytes;
  800. }
  801. XAsyncComplete(block as *mut AsyncBlock, hr, len);
  802. });
  803. }
  804. // SAFETY: as above; the runtime checked the buffer's size.
  805. OP_GET_RESULT => unsafe {
  806. let state = (*state).lock().unwrap_or_else(|e| e.into_inner());
  807. data.buffer
  808. .cast::<u8>()
  809. .copy_from(state.1.as_ptr(), state.1.len());
  810. },
  811. _ => {}
  812. }
  813. S_OK
  814. }
  815. let state: Box<Data> = Box::new(Mutex::new((Some(Box::new(work)), Vec::new())));
  816. let context = Box::into_raw(state);
  817. let hr = XAsyncBegin(block, context.cast(), identity, std::ptr::null(), Some(provider));
  818. if hr < 0 {
  819. // SAFETY: refused before the call existed; still ours.
  820. drop(unsafe { Box::from_raw(context) });
  821. }
  822. hr
  823. }
  824. /// The result of a call begun with [`finished_with`] for `identity`, as a
  825. /// `T` written through `out`.
  826. pub fn result<T>(block: *mut AsyncBlock, identity: *const c_void, out: *mut T) -> HRESULT {
  827. XAsyncGetResult(
  828. block,
  829. identity,
  830. size_of::<T>(),
  831. out.cast(),
  832. std::ptr::null_mut(),
  833. )
  834. }
  835. /// The bytes of a value, for [`finished_with`].
  836. pub fn bytes<T: Copy>(value: T) -> Vec<u8> {
  837. // SAFETY: a `Copy` value is plain data; padding bytes are never read.
  838. unsafe { std::slice::from_raw_parts((&raw const value).cast::<u8>(), size_of::<T>()) }.to_vec()
  839. }
  840. type Work = extern "system" fn(*mut AsyncBlock) -> HRESULT;
  841. /// Runs `work` on the block's work port as an async call of its own; its
  842. /// return value is the call's result.
  843. pub fn XAsyncRun(block: *mut AsyncBlock, work: Option<Work>) -> HRESULT {
  844. extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT {
  845. // SAFETY: the runtime passes valid provider data.
  846. let data = unsafe { &*data };
  847. match op {
  848. OP_BEGIN => XAsyncSchedule(data.block, 0),
  849. OP_DO_WORK => {
  850. // SAFETY: the context is the `Work` given to `XAsyncRun`.
  851. let work = unsafe { std::mem::transmute::<*mut c_void, Work>(data.context) };
  852. work(data.block)
  853. }
  854. _ => S_OK,
  855. }
  856. }
  857. let Some(work) = work else {
  858. return E_INVALIDARG;
  859. };
  860. let identity = XAsyncRun as *const c_void;
  861. XAsyncBegin(
  862. block,
  863. work as *mut c_void,
  864. identity,
  865. std::ptr::null(),
  866. Some(provider),
  867. )
  868. }
  869. // The object `QueryApiImpl` returns. Each method takes the object first,
  870. // then the API's arguments; slot offsets as titles call them.
  871. pub static OBJECT: Object = Object::new("task queue", &VTABLE);
  872. /// Its interface id is the provider's.
  873. pub const INTERFACES: &[Interface] = &[(PROVIDER, PROVIDER, &OBJECT)];
  874. type This = *const Object;
  875. extern "system" fn m_get_status(_: This, b: *mut AsyncBlock, wait: u8) -> HRESULT {
  876. XAsyncGetStatus(b, wait != 0)
  877. }
  878. extern "system" fn m_get_result_size(_: This, b: *mut AsyncBlock, out: *mut usize) -> HRESULT {
  879. XAsyncGetResultSize(b, out)
  880. }
  881. extern "system" fn m_cancel(_: This, b: *mut AsyncBlock) {
  882. XAsyncCancel(b)
  883. }
  884. extern "system" fn m_run(_: This, b: *mut AsyncBlock, work: Option<Work>) -> HRESULT {
  885. XAsyncRun(b, work)
  886. }
  887. extern "system" fn m_begin(
  888. _: This,
  889. b: *mut AsyncBlock,
  890. context: *mut c_void,
  891. identity: *const c_void,
  892. name: *const u8,
  893. provider: Option<Provider>,
  894. ) -> HRESULT {
  895. XAsyncBegin(b, context, identity, name, provider)
  896. }
  897. extern "system" fn m_schedule(_: This, b: *mut AsyncBlock, delay: u32) -> HRESULT {
  898. XAsyncSchedule(b, delay)
  899. }
  900. extern "system" fn m_complete(_: This, b: *mut AsyncBlock, hr: HRESULT, size: usize) {
  901. XAsyncComplete(b, hr, size)
  902. }
  903. extern "system" fn m_get_result(
  904. _: This,
  905. b: *mut AsyncBlock,
  906. identity: *const c_void,
  907. size: usize,
  908. buffer: *mut c_void,
  909. used: *mut usize,
  910. ) -> HRESULT {
  911. XAsyncGetResult(b, identity, size, buffer, used)
  912. }
  913. extern "system" fn m_create(
  914. _: This,
  915. work: u32,
  916. completion: u32,
  917. out: *mut *const Queue,
  918. ) -> HRESULT {
  919. XTaskQueueCreate(work, completion, out)
  920. }
  921. extern "system" fn m_create_composite(
  922. _: This,
  923. work: *const c_void,
  924. completion: *const c_void,
  925. out: *mut *const Queue,
  926. ) -> HRESULT {
  927. XTaskQueueCreateComposite(work, completion, out)
  928. }
  929. extern "system" fn m_get_port(
  930. _: This,
  931. q: *const Queue,
  932. port: u32,
  933. out: *mut *const c_void,
  934. ) -> HRESULT {
  935. XTaskQueueGetPort(q, port, out)
  936. }
  937. extern "system" fn m_duplicate(_: This, q: *const Queue, out: *mut *const Queue) -> HRESULT {
  938. XTaskQueueDuplicateHandle(q, out)
  939. }
  940. extern "system" fn m_dispatch(_: This, q: *const Queue, port: u32, timeout: u32) -> bool {
  941. XTaskQueueDispatch(q, port, timeout)
  942. }
  943. extern "system" fn m_close(_: This, q: *const Queue) {
  944. XTaskQueueCloseHandle(q)
  945. }
  946. extern "system" fn m_submit(
  947. _: This,
  948. q: *const Queue,
  949. port: u32,
  950. context: *mut c_void,
  951. callback: Option<Callback>,
  952. ) -> HRESULT {
  953. XTaskQueueSubmitDelayedCallback(q, port, 0, context, callback)
  954. }
  955. extern "system" fn m_submit_delayed(
  956. _: This,
  957. q: *const Queue,
  958. port: u32,
  959. delay: u32,
  960. context: *mut c_void,
  961. callback: Option<Callback>,
  962. ) -> HRESULT {
  963. XTaskQueueSubmitDelayedCallback(q, port, delay, context, callback)
  964. }
  965. extern "system" fn m_terminate(
  966. _: This,
  967. q: *const Queue,
  968. wait: u8,
  969. context: *mut c_void,
  970. callback: Option<TerminatedCallback>,
  971. ) -> HRESULT {
  972. XTaskQueueTerminate(q, wait != 0, context, callback)
  973. }
  974. extern "system" fn m_register_monitor(
  975. _: This,
  976. q: *const Queue,
  977. context: *mut c_void,
  978. callback: Option<MonitorCallback>,
  979. token: *mut u64,
  980. ) -> HRESULT {
  981. XTaskQueueRegisterMonitor(q, context, callback, token)
  982. }
  983. extern "system" fn m_unregister_monitor(_: This, q: *const Queue, token: u64) {
  984. XTaskQueueUnregisterMonitor(q, token)
  985. }
  986. extern "system" fn m_get_process_queue(_: This, out: *mut *const Queue) -> bool {
  987. XTaskQueueGetCurrentProcessTaskQueue(out)
  988. }
  989. extern "system" fn m_set_process_queue(_: This, q: *const Queue) {
  990. XTaskQueueSetCurrentProcessTaskQueue(q)
  991. }
  992. /// The runtime's debug check that the caller is not a time-critical thread,
  993. /// which every runtime call in a title makes first.
  994. extern "system" fn m_check_thread(_: This) {}
  995. static VTABLE: Methods<31> = Methods([
  996. missing::<0> as *const (), // 0x00 QueryInterface
  997. add_ref as *const (), // 0x08 AddRef
  998. add_ref as *const (), // 0x10 Release: the object is static
  999. m_get_status as *const (), // 0x18
  1000. m_get_result_size as *const (), // 0x20
  1001. m_cancel as *const (), // 0x28
  1002. m_run as *const (), // 0x30
  1003. m_begin as *const (), // 0x38
  1004. missing::<8> as *const (), // 0x40
  1005. m_schedule as *const (), // 0x48
  1006. m_complete as *const (), // 0x50
  1007. m_get_result as *const (), // 0x58
  1008. m_create as *const (), // 0x60
  1009. m_create_composite as *const (), // 0x68
  1010. m_get_port as *const (), // 0x70
  1011. m_duplicate as *const (), // 0x78
  1012. m_dispatch as *const (), // 0x80
  1013. m_close as *const (), // 0x88
  1014. m_submit as *const (), // 0x90
  1015. m_submit_delayed as *const (), // 0x98
  1016. missing::<20> as *const (), // 0xa0 register a wait handle
  1017. missing::<21> as *const (), // 0xa8 unregister it
  1018. m_terminate as *const (), // 0xb0
  1019. m_register_monitor as *const (), // 0xb8
  1020. m_unregister_monitor as *const (), // 0xc0
  1021. m_get_process_queue as *const (), // 0xc8
  1022. m_set_process_queue as *const (), // 0xd0
  1023. missing::<27> as *const (), // 0xd8 thread time-sensitivity
  1024. missing::<28> as *const (), // 0xe0
  1025. m_check_thread as *const (), // 0xe8
  1026. missing::<30> as *const (), // 0xf0
  1027. ]);
  1028. #[cfg(test)]
  1029. mod tests {
  1030. use super::*;
  1031. use std::sync::atomic::AtomicU32;
  1032. fn slot<F: Copy>(offset: usize) -> F {
  1033. crate::modules::xgameruntime::method(&OBJECT, offset)
  1034. }
  1035. static RAN: AtomicU32 = AtomicU32::new(0);
  1036. extern "system" fn count(context: *mut c_void, canceled: bool) {
  1037. RAN.fetch_add(
  1038. if canceled { 100 } else { context as u32 },
  1039. Ordering::SeqCst,
  1040. );
  1041. }
  1042. #[test]
  1043. fn manual_ports_run_callbacks_when_dispatched() {
  1044. type Create = extern "system" fn(This, u32, u32, *mut *const Queue) -> HRESULT;
  1045. type Submit = extern "system" fn(This, *const Queue, u32, *mut c_void, Callback) -> HRESULT;
  1046. type Dispatch = extern "system" fn(This, *const Queue, u32, u32) -> bool;
  1047. type Close = extern "system" fn(This, *const Queue);
  1048. let this: This = &OBJECT;
  1049. let mut q = std::ptr::null();
  1050. assert_eq!(slot::<Create>(0x60)(this, 0, 0, &mut q), S_OK);
  1051. assert_eq!(
  1052. slot::<Submit>(0x90)(this, q, COMPLETION, 5 as *mut c_void, count),
  1053. S_OK
  1054. );
  1055. assert_eq!(RAN.load(Ordering::SeqCst), 0, "manual: nothing runs yet");
  1056. assert!(
  1057. !slot::<Dispatch>(0x80)(this, q, WORK, 0),
  1058. "work port is empty"
  1059. );
  1060. assert!(slot::<Dispatch>(0x80)(this, q, COMPLETION, 0));
  1061. assert_eq!(RAN.load(Ordering::SeqCst), 5);
  1062. assert!(!slot::<Dispatch>(0x80)(this, q, COMPLETION, 0));
  1063. slot::<Close>(0x88)(this, q);
  1064. }
  1065. /// A provider that schedules its work and returns a u64 result.
  1066. extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT {
  1067. // SAFETY: the runtime passes valid provider data.
  1068. let data = unsafe { &*data };
  1069. match op {
  1070. OP_BEGIN => XAsyncSchedule(data.block, 0),
  1071. OP_DO_WORK => {
  1072. XAsyncComplete(data.block, S_OK, 8);
  1073. S_OK
  1074. }
  1075. OP_GET_RESULT => {
  1076. // SAFETY: at least 8 bytes, checked by the runtime.
  1077. unsafe { data.buffer.cast::<u64>().write(data.context as u64) };
  1078. S_OK
  1079. }
  1080. _ => S_OK,
  1081. }
  1082. }
  1083. static COMPLETED: AtomicU32 = AtomicU32::new(0);
  1084. extern "system" fn completed(_: *mut AsyncBlock) {
  1085. COMPLETED.fetch_add(1, Ordering::SeqCst);
  1086. }
  1087. /// A title that never takes a call's result and frees its block: the
  1088. /// next block allocated at that address (zeroed, as a new block must
  1089. /// be) begins a call like any other.
  1090. #[test]
  1091. fn a_new_block_where_a_result_was_left_begins_a_call() {
  1092. static CLEANED: AtomicU32 = AtomicU32::new(0);
  1093. /// Completes at once with one byte to fetch; counts its cleanups.
  1094. extern "system" fn left(op: u32, data: *const ProviderData) -> HRESULT {
  1095. match op {
  1096. // SAFETY: the runtime passes valid provider data.
  1097. OP_BEGIN => XAsyncComplete(unsafe { (*data).block }, S_OK, 1),
  1098. OP_CLEANUP => drop(CLEANED.fetch_add(1, Ordering::SeqCst)),
  1099. _ => {}
  1100. }
  1101. S_OK
  1102. }
  1103. /// Never completes by itself.
  1104. extern "system" fn idle(_: u32, _: *const ProviderData) -> HRESULT {
  1105. S_OK
  1106. }
  1107. let fresh = || AsyncBlock {
  1108. queue: std::ptr::null(),
  1109. context: std::ptr::null_mut(),
  1110. callback: None,
  1111. internal: [0; 4],
  1112. };
  1113. let (none, identity) = (std::ptr::null_mut(), 0x1e as *const c_void);
  1114. let begin = |block: &mut AsyncBlock, provider: Provider| {
  1115. XAsyncBegin(block, none, identity, std::ptr::null(), Some(provider))
  1116. };
  1117. let mut block = fresh();
  1118. assert_eq!(begin(&mut block, left), S_OK);
  1119. assert_eq!(XAsyncGetStatus(&mut block, false), S_OK);
  1120. // The block as the call left it is still that call's.
  1121. assert_eq!(begin(&mut block, left), E_INVALIDARG);
  1122. assert_eq!(CLEANED.load(Ordering::SeqCst), 0);
  1123. // Freed with its result never taken, and a new block in its place.
  1124. block = fresh();
  1125. assert_eq!(finished_with(&mut block, identity, Ok(vec![9])), S_OK);
  1126. assert_eq!(CLEANED.load(Ordering::SeqCst), 1, "the call left behind");
  1127. let mut value = 0u8;
  1128. assert_eq!(result(&mut block, identity, &mut value), S_OK);
  1129. assert_eq!(value, 9);
  1130. assert!(call(&mut block).is_none());
  1131. // A call still in flight keeps its address, whatever the block holds.
  1132. let mut block = fresh();
  1133. assert_eq!(begin(&mut block, idle), S_OK);
  1134. block = fresh();
  1135. assert_eq!(begin(&mut block, left), E_INVALIDARG);
  1136. XAsyncComplete(&mut block, E_ABORT, 0);
  1137. assert!(call(&mut block).is_none());
  1138. }
  1139. #[test]
  1140. fn async_calls_complete_and_return_results() {
  1141. let mut q = std::ptr::null();
  1142. // Work on a thread pool, completion dispatched by hand.
  1143. assert_eq!(XTaskQueueCreate(1, 0, &mut q), S_OK);
  1144. let mut block = AsyncBlock {
  1145. queue: q,
  1146. context: std::ptr::null_mut(),
  1147. callback: Some(completed),
  1148. internal: [0; 4],
  1149. };
  1150. let identity = 0x1d as *const c_void;
  1151. assert_eq!(
  1152. XAsyncBegin(
  1153. &mut block,
  1154. 42 as *mut c_void,
  1155. identity,
  1156. std::ptr::null(),
  1157. Some(provider)
  1158. ),
  1159. S_OK
  1160. );
  1161. assert_eq!(XAsyncGetStatus(&mut block, true), S_OK);
  1162. let mut size = 0;
  1163. assert_eq!(XAsyncGetResultSize(&mut block, &mut size), S_OK);
  1164. assert_eq!(size, 8);
  1165. assert_eq!(COMPLETED.load(Ordering::SeqCst), 0, "completion is manual");
  1166. assert!(XTaskQueueDispatch(q, COMPLETION, INFINITE));
  1167. assert_eq!(COMPLETED.load(Ordering::SeqCst), 1);
  1168. let mut value = 0u64;
  1169. let mut small = 0u32;
  1170. let out = (&mut small as *mut u32).cast();
  1171. assert_eq!(
  1172. XAsyncGetResult(&mut block, identity, 4, out, std::ptr::null_mut()),
  1173. E_NOT_SUFFICIENT_BUFFER
  1174. );
  1175. let out = (&mut value as *mut u64).cast();
  1176. let mut used = 0;
  1177. assert_eq!(
  1178. XAsyncGetResult(&mut block, identity, 8, out, &mut used),
  1179. S_OK
  1180. );
  1181. assert_eq!((value, used), (42, 8));
  1182. assert!(call(&mut block).is_none(), "the call ends with its result");
  1183. XTaskQueueCloseHandle(q);
  1184. }
  1185. /// What a test sees of a block that a title reuses: its completion
  1186. /// routine begins the next call on the same block.
  1187. #[derive(Default)]
  1188. struct Reuse {
  1189. completions: AtomicU32,
  1190. next_begun: AtomicBool,
  1191. next_worked: AtomicBool,
  1192. }
  1193. /// A block whose completion routine is [`begin_next`].
  1194. fn reused_block(queue: *const Queue, reuse: &Reuse) -> AsyncBlock {
  1195. AsyncBlock {
  1196. queue,
  1197. context: std::ptr::from_ref(reuse).cast_mut().cast(),
  1198. callback: Some(begin_next),
  1199. internal: [0; 4],
  1200. }
  1201. }
  1202. /// Begins a call without an identity.
  1203. fn begin(block: *mut AsyncBlock, context: *mut c_void, provider: Provider) -> HRESULT {
  1204. let none = std::ptr::null();
  1205. XAsyncBegin(block, context, none, none.cast(), Some(provider))
  1206. }
  1207. /// Begins the next call on the block the first time a call completes,
  1208. /// as a title that keeps one block for repeated calls does.
  1209. extern "system" fn begin_next(block: *mut AsyncBlock) {
  1210. // SAFETY: the block is from `reused_block`, its `Reuse` still alive.
  1211. let context = unsafe { (*block).context };
  1212. // SAFETY: as above.
  1213. let reuse = unsafe { &*context.cast::<Reuse>() };
  1214. if reuse.completions.fetch_add(1, Ordering::SeqCst) == 0 {
  1215. let hr = begin(block, context, next_call);
  1216. reuse.next_begun.store(hr == S_OK, Ordering::SeqCst);
  1217. }
  1218. }
  1219. /// The next call's provider: it never ends on its own, and notes being
  1220. /// asked to work.
  1221. extern "system" fn next_call(op: u32, data: *const ProviderData) -> HRESULT {
  1222. // SAFETY: the runtime passes valid provider data; its context is
  1223. // the test's `Reuse`.
  1224. let reuse = unsafe { &*(*data).context.cast::<Reuse>() };
  1225. if op == OP_DO_WORK {
  1226. reuse.next_worked.store(true, Ordering::SeqCst);
  1227. return E_PENDING;
  1228. }
  1229. S_OK
  1230. }
  1231. /// A provider that ends its call itself, in `DoWork` and on cancel, then
  1232. /// returns `S_OK`, as providers do.
  1233. extern "system" fn ends_itself(op: u32, data: *const ProviderData) -> HRESULT {
  1234. // SAFETY: the runtime passes valid provider data.
  1235. let block = unsafe { (*data).block };
  1236. match op {
  1237. OP_DO_WORK => XAsyncComplete(block, S_OK, 0),
  1238. OP_CANCEL => XAsyncComplete(block, E_ABORT, 0),
  1239. _ => {}
  1240. }
  1241. S_OK
  1242. }
  1243. #[test]
  1244. fn a_finished_calls_work_result_leaves_the_next_call_alone() {
  1245. let mut q = std::ptr::null();
  1246. // Work dispatched by hand; completion routines run where the call
  1247. // completes, inside the provider's `DoWork`.
  1248. assert_eq!(XTaskQueueCreate(0, 3, &mut q), S_OK);
  1249. let reuse = Reuse::default();
  1250. let mut block = reused_block(q, &reuse);
  1251. assert_eq!(begin(&mut block, std::ptr::null_mut(), ends_itself), S_OK);
  1252. assert_eq!(XAsyncSchedule(&mut block, 0), S_OK);
  1253. assert!(XTaskQueueDispatch(q, WORK, 0));
  1254. assert!(reuse.next_begun.load(Ordering::SeqCst));
  1255. assert_eq!(XAsyncGetStatus(&mut block, false), E_PENDING);
  1256. assert_eq!(reuse.completions.load(Ordering::SeqCst), 1);
  1257. XAsyncCancel(&mut block);
  1258. assert_eq!(XAsyncGetStatus(&mut block, false), E_ABORT);
  1259. XTaskQueueCloseHandle(q);
  1260. }
  1261. #[test]
  1262. fn a_canceled_call_leaves_the_next_call_alone() {
  1263. let mut q = std::ptr::null();
  1264. assert_eq!(XTaskQueueCreate(0, 3, &mut q), S_OK);
  1265. let reuse = Reuse::default();
  1266. let mut block = reused_block(q, &reuse);
  1267. assert_eq!(begin(&mut block, std::ptr::null_mut(), ends_itself), S_OK);
  1268. assert_eq!(XAsyncSchedule(&mut block, 0), S_OK);
  1269. // The provider ends the call on cancel, before its work has run.
  1270. XAsyncCancel(&mut block);
  1271. assert!(reuse.next_begun.load(Ordering::SeqCst));
  1272. assert_eq!(XAsyncGetStatus(&mut block, false), E_PENDING);
  1273. // The canceled call's work is still queued; it runs nothing now.
  1274. assert!(XTaskQueueDispatch(q, WORK, 0));
  1275. assert!(!reuse.next_worked.load(Ordering::SeqCst));
  1276. assert_eq!(XAsyncGetStatus(&mut block, false), E_PENDING);
  1277. assert_eq!(reuse.completions.load(Ordering::SeqCst), 1);
  1278. XAsyncCancel(&mut block);
  1279. assert_eq!(XAsyncGetStatus(&mut block, false), E_ABORT);
  1280. XTaskQueueCloseHandle(q);
  1281. }
  1282. #[test]
  1283. fn a_nonnegative_completion_still_returns_its_payload() {
  1284. const S_FALSE: HRESULT = 1;
  1285. extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT {
  1286. // SAFETY: the runtime passes valid provider data.
  1287. let data = unsafe { &*data };
  1288. match op {
  1289. OP_BEGIN => XAsyncSchedule(data.block, 0),
  1290. OP_DO_WORK => {
  1291. XAsyncComplete(data.block, S_FALSE, 8);
  1292. S_OK
  1293. }
  1294. OP_GET_RESULT => {
  1295. // SAFETY: the caller checked eight bytes.
  1296. unsafe { data.buffer.cast::<u64>().write(0x1234) };
  1297. S_OK
  1298. }
  1299. _ => S_OK,
  1300. }
  1301. }
  1302. let mut q = std::ptr::null();
  1303. assert_eq!(XTaskQueueCreate(0, 0, &mut q), S_OK);
  1304. let mut block = AsyncBlock {
  1305. queue: q,
  1306. context: std::ptr::null_mut(),
  1307. callback: None,
  1308. internal: [0; 4],
  1309. };
  1310. let identity = 0x77 as *const c_void;
  1311. assert_eq!(
  1312. XAsyncBegin(&mut block, std::ptr::null_mut(), identity, std::ptr::null(), Some(provider)),
  1313. S_OK
  1314. );
  1315. assert!(XTaskQueueDispatch(q, WORK, 0));
  1316. assert_eq!(XAsyncGetStatus(&mut block, false), S_FALSE);
  1317. let mut size = 0;
  1318. assert_eq!(XAsyncGetResultSize(&mut block, &mut size), S_FALSE);
  1319. assert_eq!(size, 8);
  1320. let mut value = 0u64;
  1321. let mut used = 0;
  1322. assert_eq!(
  1323. XAsyncGetResult(&mut block, identity, 8, (&mut value as *mut u64).cast(), &mut used),
  1324. S_OK
  1325. );
  1326. assert_eq!((value, used), (0x1234, 8));
  1327. assert!(call(&raw mut block).is_none(), "the call ends with its result");
  1328. XTaskQueueCloseHandle(q);
  1329. }
  1330. #[test]
  1331. fn run_returns_the_work_result() {
  1332. extern "system" fn work(_: *mut AsyncBlock) -> HRESULT {
  1333. E_ABORT
  1334. }
  1335. let mut block = AsyncBlock {
  1336. queue: std::ptr::null(),
  1337. context: std::ptr::null_mut(),
  1338. callback: None,
  1339. internal: [0; 4],
  1340. };
  1341. assert_eq!(
  1342. slot::<extern "system" fn(This, *mut AsyncBlock, Option<Work>) -> HRESULT>(0x30)(
  1343. &OBJECT,
  1344. &mut block,
  1345. Some(work)
  1346. ),
  1347. S_OK
  1348. );
  1349. assert_eq!(XAsyncGetStatus(&mut block, true), E_ABORT);
  1350. }
  1351. #[test]
  1352. fn pool_callbacks_may_wait_for_each_other() {
  1353. static SECOND: AtomicBool = AtomicBool::new(false);
  1354. static FIRST: AtomicBool = AtomicBool::new(false);
  1355. extern "system" fn waits(_: *mut c_void, _: bool) {
  1356. let start = std::time::Instant::now();
  1357. while !SECOND.load(Ordering::SeqCst) && start.elapsed().as_secs() < 5 {
  1358. std::thread::yield_now();
  1359. }
  1360. FIRST.store(SECOND.load(Ordering::SeqCst), Ordering::SeqCst);
  1361. }
  1362. extern "system" fn releases(_: *mut c_void, _: bool) {
  1363. SECOND.store(true, Ordering::SeqCst);
  1364. }
  1365. let mut q = std::ptr::null();
  1366. assert_eq!(XTaskQueueCreate(1, 1, &mut q), S_OK);
  1367. let none = std::ptr::null_mut();
  1368. assert_eq!(
  1369. XTaskQueueSubmitDelayedCallback(q, WORK, 0, none, Some(waits)),
  1370. S_OK
  1371. );
  1372. assert_eq!(
  1373. XTaskQueueSubmitDelayedCallback(q, WORK, 0, none, Some(releases)),
  1374. S_OK
  1375. );
  1376. let start = std::time::Instant::now();
  1377. while !FIRST.load(Ordering::SeqCst) && start.elapsed().as_secs() < 10 {
  1378. std::thread::sleep(Duration::from_millis(1));
  1379. }
  1380. assert!(FIRST.load(Ordering::SeqCst));
  1381. XTaskQueueCloseHandle(q);
  1382. }
  1383. /// A dispatcher thread's loop, `while (XTaskQueueDispatch(queue, port,
  1384. /// INFINITE));`, ends when its queue is terminated: nothing can be
  1385. /// submitted to it any more, so nothing else would ever wake it.
  1386. #[test]
  1387. fn terminate_ends_a_waiting_dispatch() {
  1388. static RAN: AtomicU32 = AtomicU32::new(0);
  1389. extern "system" fn ran(_: *mut c_void, _: bool) {
  1390. RAN.fetch_add(1, Ordering::SeqCst);
  1391. }
  1392. /// Dispatches `queue`'s work until a dispatch returns false, then
  1393. /// says so.
  1394. fn dispatcher(queue: *const Queue) -> std::sync::mpsc::Receiver<()> {
  1395. let (done, ended) = std::sync::mpsc::channel();
  1396. let queue = queue as usize;
  1397. std::thread::spawn(move || {
  1398. while XTaskQueueDispatch(queue as *const Queue, WORK, INFINITE) {}
  1399. let _ = done.send(());
  1400. });
  1401. ended
  1402. }
  1403. let run_one = |queue, total| {
  1404. let none = std::ptr::null_mut();
  1405. assert_eq!(
  1406. XTaskQueueSubmitDelayedCallback(queue, WORK, 0, none, Some(ran)),
  1407. S_OK
  1408. );
  1409. for _ in 0..500 {
  1410. if RAN.load(Ordering::SeqCst) == total {
  1411. return;
  1412. }
  1413. std::thread::sleep(Duration::from_millis(10));
  1414. }
  1415. panic!("callback {total} did not run");
  1416. };
  1417. let (long, short) = (Duration::from_secs(5), Duration::from_millis(200));
  1418. let none = std::ptr::null_mut();
  1419. // Two queues on the same manual ports.
  1420. let (mut a, mut b) = (std::ptr::null(), std::ptr::null());
  1421. assert_eq!(XTaskQueueCreate(0, 0, &mut a), S_OK);
  1422. let (mut work, mut completion) = (std::ptr::null(), std::ptr::null());
  1423. assert_eq!(XTaskQueueGetPort(a, WORK, &mut work), S_OK);
  1424. assert_eq!(XTaskQueueGetPort(a, COMPLETION, &mut completion), S_OK);
  1425. assert_eq!(XTaskQueueCreateComposite(work, completion, &mut b), S_OK);
  1426. let ended = dispatcher(a);
  1427. run_one(a, 1);
  1428. // The other queue's end is not this one's: the wait goes on and
  1429. // still runs what comes in.
  1430. assert_eq!(XTaskQueueTerminate(b, false, none, None), S_OK);
  1431. assert!(
  1432. ended.recv_timeout(short).is_err(),
  1433. "ended with another queue"
  1434. );
  1435. run_one(a, 2);
  1436. // Its own queue's end is.
  1437. assert_eq!(XTaskQueueTerminate(a, false, none, None), S_OK);
  1438. assert!(
  1439. ended.recv_timeout(long).is_ok(),
  1440. "still waiting on a terminated queue"
  1441. );
  1442. // And a dispatch that starts after the end returns at once.
  1443. assert!(!XTaskQueueDispatch(a, WORK, INFINITE));
  1444. XTaskQueueCloseHandle(a);
  1445. XTaskQueueCloseHandle(b);
  1446. }
  1447. #[test]
  1448. fn terminate_cancels_what_is_queued() {
  1449. static TERMINATED: AtomicBool = AtomicBool::new(false);
  1450. extern "system" fn terminated(_: *mut c_void) {
  1451. TERMINATED.store(true, Ordering::SeqCst);
  1452. }
  1453. extern "system" fn note(context: *mut c_void, canceled: bool) {
  1454. // SAFETY: the test passes a pointer to its flag.
  1455. unsafe { *context.cast::<bool>() = canceled };
  1456. }
  1457. let mut q = std::ptr::null();
  1458. assert_eq!(XTaskQueueCreate(0, 0, &mut q), S_OK);
  1459. let mut canceled = false;
  1460. let flag = (&mut canceled as *mut bool).cast();
  1461. assert_eq!(
  1462. XTaskQueueSubmitDelayedCallback(q, WORK, 0, flag, Some(note)),
  1463. S_OK
  1464. );
  1465. assert_eq!(
  1466. XTaskQueueTerminate(q, true, std::ptr::null_mut(), Some(terminated)),
  1467. S_OK
  1468. );
  1469. assert!(canceled && TERMINATED.load(Ordering::SeqCst));
  1470. assert_eq!(
  1471. XTaskQueueSubmitDelayedCallback(q, WORK, 0, flag, Some(note)),
  1472. E_ABORT
  1473. );
  1474. XTaskQueueCloseHandle(q);
  1475. }
  1476. #[test]
  1477. fn terminate_cancels_delayed_callbacks() {
  1478. static EVENTS: Mutex<Vec<&str>> = Mutex::new(Vec::new());
  1479. extern "system" fn delayed(_: *mut c_void, canceled: bool) {
  1480. lock(&EVENTS).push(if canceled { "canceled" } else { "ran" });
  1481. }
  1482. extern "system" fn terminated(_: *mut c_void) {
  1483. lock(&EVENTS).push("terminated");
  1484. }
  1485. let mut q = std::ptr::null();
  1486. assert_eq!(XTaskQueueCreate(1, 1, &mut q), S_OK);
  1487. let none = std::ptr::null_mut();
  1488. let hr = XTaskQueueSubmitDelayedCallback(q, WORK, 50, none, Some(delayed));
  1489. assert_eq!(hr, S_OK);
  1490. assert_eq!(XTaskQueueTerminate(q, true, none, Some(terminated)), S_OK);
  1491. assert_eq!(*lock(&EVENTS), ["canceled", "terminated"]);
  1492. // Its delay passes without it running.
  1493. std::thread::sleep(Duration::from_millis(200));
  1494. assert_eq!(*lock(&EVENTS), ["canceled", "terminated"]);
  1495. XTaskQueueCloseHandle(q);
  1496. }
  1497. }