1use fidl::HandleBased;
6use fuchsia_sync::{Condvar, Mutex};
7use std::cell::UnsafeCell;
8use std::collections::hash_map::Entry;
9use std::collections::{HashMap, VecDeque};
10use std::marker::PhantomData;
11use std::mem::ManuallyDrop;
12use std::ops::Deref;
13use std::sync::{Arc, OnceLock, Weak};
14
15#[cfg(not(target_os = "fuchsia"))]
16use fuchsia_async::emulated_handle::zx_handle_t;
17#[cfg(target_os = "fuchsia")]
18use zx::sys::zx_handle_t;
19
20pub struct TempClonable<T: HandleBased>(ManuallyDrop<T>);
27
28impl<T: HandleBased> TempClonable<T> {
29 pub fn new(handle: T) -> Self {
31 Self(ManuallyDrop::new(handle))
32 }
33}
34
35impl<T: HandleBased> Deref for TempClonable<T> {
36 type Target = T;
37
38 fn deref(&self) -> &T {
39 &self.0
40 }
41}
42
43impl<T: HandleBased> TempClonable<T> {
44 pub fn temp_clone(&self) -> TempClone<T> {
50 assert!(!self.is_invalid_handle());
51 let mut clones = clones().lock();
52 let raw_handle = self.0.raw_handle();
53 TempClone {
54 handle: match clones.entry(raw_handle) {
55 Entry::Occupied(mut o) => {
56 if let Some(clone) = o.get().upgrade() {
57 clone
58 } else {
59 let clone =
63 Arc::new(TempHandle { raw_handle, tombstone: UnsafeCell::new(false) });
64 *o.get_mut() = Arc::downgrade(&clone);
65 clone
66 }
67 }
68 Entry::Vacant(v) => {
69 let clone =
70 Arc::new(TempHandle { raw_handle, tombstone: UnsafeCell::new(false) });
71 v.insert(Arc::downgrade(&clone));
72 clone
73 }
74 },
75 marker: PhantomData,
76 }
77 }
78}
79
80impl<T: HandleBased> Drop for TempClonable<T> {
81 fn drop(&mut self) {
82 if let Some(handle) = clones().lock().remove(&self.0.raw_handle()).and_then(|c| c.upgrade())
83 {
84 unsafe { *handle.tombstone.get() = true };
91 return;
92 }
93
94 unsafe { ManuallyDrop::drop(&mut self.0) }
97 }
98}
99
100type Clones = Mutex<HashMap<zx_handle_t, Weak<TempHandle>>>;
101
102fn clones() -> &'static Clones {
104 static CLONES: OnceLock<Clones> = OnceLock::new();
105 CLONES.get_or_init(|| Mutex::new(HashMap::new()))
106}
107
108pub struct TempClone<T> {
109 handle: Arc<TempHandle>,
110 marker: PhantomData<T>,
111}
112
113impl<T> Deref for TempClone<T> {
114 type Target = T;
115
116 fn deref(&self) -> &T {
117 unsafe { std::mem::transmute::<&zx_handle_t, &T>(&self.handle.raw_handle) }
119 }
120}
121
122struct TempHandle {
123 raw_handle: zx_handle_t,
124 tombstone: UnsafeCell<bool>,
125}
126
127unsafe impl Send for TempHandle {}
128unsafe impl Sync for TempHandle {}
129
130impl Drop for TempHandle {
131 fn drop(&mut self) {
132 if *self.tombstone.get_mut() {
133 unsafe { fidl::Handle::from_raw(self.raw_handle) };
136 } else {
137 if let Entry::Occupied(o) = clones().lock().entry(self.raw_handle) {
138 if std::ptr::eq(o.get().as_ptr(), self) {
141 o.remove_entry();
142 }
143 }
144 }
145 }
146}
147
148pub async fn unblock<T: 'static + Send>(f: impl FnOnce() -> T + Send + 'static) -> T {
152 const NUM_THREADS: u8 = 2;
153
154 struct State {
155 queue: Mutex<VecDeque<Box<dyn FnOnce() + Send + 'static>>>,
156 cvar: Condvar,
157 }
158
159 static STATE: OnceLock<State> = OnceLock::new();
160
161 let mut start_threads = false;
162 let state = STATE.get_or_init(|| {
163 start_threads = true;
164 State { queue: Mutex::new(VecDeque::new()), cvar: Condvar::new() }
165 });
166
167 if start_threads {
168 for _ in 0..NUM_THREADS {
169 std::thread::spawn(|| loop {
170 let item = {
171 let mut queue = state.queue.lock();
172 loop {
173 if let Some(item) = queue.pop_front() {
174 break item;
175 }
176 state.cvar.wait(&mut queue);
177 }
178 };
179 item();
180 });
181 }
182 }
183
184 let (tx, rx) = futures::channel::oneshot::channel();
185 state.queue.lock().push_back(Box::new(move || {
186 let _ = tx.send(f());
187 }));
188 state.cvar.notify_one();
189
190 rx.await.unwrap()
191}
192
193#[cfg(target_os = "fuchsia")]
194#[cfg(test)]
195mod tests {
196 use super::{clones, TempClonable};
197
198 use std::sync::Arc;
199
200 #[test]
201 fn test_temp_clone() {
202 let parent_vmo = zx::Vmo::create(100).expect("create failed");
203
204 {
205 let temp_clone = {
206 let vmo = TempClonable::new(
207 parent_vmo
208 .create_child(zx::VmoChildOptions::REFERENCE, 0, 0)
209 .expect("create_child failed"),
210 );
211
212 vmo.write(b"foo", 0).expect("write failed");
213 {
214 let temp_clone2 = vmo.temp_clone();
216 assert_eq!(&temp_clone2.read_to_vec(0, 3).expect("read_to_vec failed"), b"foo");
217 }
218
219 assert_eq!(&vmo.read_to_vec(0, 3).expect("read_to_vec failed"), b"foo");
221
222 let vmo2 = TempClonable::new(
225 parent_vmo
226 .create_child(zx::VmoChildOptions::REFERENCE, 0, 0)
227 .expect("create_child failed"),
228 );
229 vmo2.temp_clone();
231
232 let _clone1 = vmo.temp_clone();
234
235 vmo.temp_clone()
237 };
238
239 assert_eq!(&temp_clone.read_to_vec(0, 3).expect("read_to_vec failed"), b"foo");
242 }
243
244 assert_eq!(parent_vmo.info().expect("info failed").num_children, 0);
246 assert!(clones().lock().is_empty());
247 }
248
249 #[test]
250 fn test_race() {
251 let parent_vmo = zx::Vmo::create(100).expect("create failed");
252
253 {
254 let vmo = Arc::new(TempClonable::new(
255 parent_vmo
256 .create_child(zx::VmoChildOptions::REFERENCE, 0, 0)
257 .expect("create_child failed"),
258 ));
259 vmo.write(b"foo", 0).expect("write failed");
260
261 let vmo_clone = vmo.clone();
262
263 let t1 = std::thread::spawn(move || {
264 for _ in 0..1000 {
265 assert_eq!(
266 &vmo.temp_clone().read_to_vec(0, 3).expect("read_to_vec failed"),
267 b"foo"
268 );
269 }
270 });
271
272 let t2 = std::thread::spawn(move || {
273 for _ in 0..1000 {
274 assert_eq!(
275 &vmo_clone.temp_clone().read_to_vec(0, 3).expect("read_to_vec failed"),
276 b"foo"
277 );
278 }
279 });
280
281 let _ = t1.join();
282 let _ = t2.join();
283 }
284
285 assert_eq!(parent_vmo.info().expect("info failed").num_children, 0);
287 assert!(clones().lock().is_empty());
288 }
289}