summaryrefslogtreecommitdiffstats
path: root/third_party/rust/fuchsia-zircon/src/port.rs
blob: 6a9e8a8f7fbffa2caeb21a6e0f3a2b8ba2549568 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! Type-safe bindings for Zircon port objects.

use std::mem;

use {AsHandleRef, HandleBased, Handle, HandleRef, Signals, Status, Time};
use {sys, ok};

/// An object representing a Zircon
/// [port](https://fuchsia.googlesource.com/zircon/+/master/docs/objects/port.md).
///
/// As essentially a subtype of `Handle`, it can be freely interconverted.
#[derive(Debug, Eq, PartialEq)]
pub struct Port(Handle);
impl_handle_based!(Port);

/// A packet sent through a port. This is a type-safe wrapper for
/// [zx_port_packet_t](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/port_wait.md).
#[derive(PartialEq, Eq, Debug)]
pub struct Packet(sys::zx_port_packet_t);

/// The contents of a `Packet`.
#[derive(Debug, Copy, Clone)]
pub enum PacketContents {
    /// A user-generated packet.
    User(UserPacket),
    /// A one-shot signal packet generated via `object_wait_async`.
    SignalOne(SignalPacket),
    /// A repeating signal packet generated via `object_wait_async`.
    SignalRep(SignalPacket),

    #[doc(hidden)]
    __Nonexhaustive
}

/// Contents of a user packet (one sent by `port_queue`). This is a type-safe wrapper for
/// [zx_packet_user_t](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/port_wait.md).
#[derive(Debug, Copy, Clone)]
pub struct UserPacket(sys::zx_packet_user_t);

/// Contents of a signal packet (one generated by the kernel). This is a type-safe wrapper for
/// [zx_packet_signal_t](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/port_wait.md).
#[derive(Debug, Copy, Clone)]
pub struct SignalPacket(sys::zx_packet_signal_t);

impl Packet {
    /// Creates a new packet with `UserPacket` data.
    pub fn from_user_packet(key: u64, status: i32, user: UserPacket) -> Packet {
        Packet(
            sys::zx_port_packet_t {
                key: key,
                packet_type: sys::zx_packet_type_t::ZX_PKT_TYPE_USER,
                status: status,
                union: user.0,
            }
        )
    }

    /// The packet's key.
    pub fn key(&self) -> u64 {
        self.0.key
    }

    /// The packet's status.
    // TODO: should this type be wrapped?
    pub fn status(&self) -> i32 {
        self.0.status
    }

    /// The contents of the packet.
    pub fn contents(&self) -> PacketContents {
        if self.0.packet_type == sys::zx_packet_type_t::ZX_PKT_TYPE_USER {
            PacketContents::User(UserPacket(self.0.union))
        } else if self.0.packet_type == sys::zx_packet_type_t::ZX_PKT_TYPE_SIGNAL_ONE {
            PacketContents::SignalOne(SignalPacket(unsafe { mem::transmute_copy(&self.0.union) }))
        } else if self.0.packet_type == sys::zx_packet_type_t::ZX_PKT_TYPE_SIGNAL_REP {
            PacketContents::SignalRep(SignalPacket(unsafe { mem::transmute_copy(&self.0.union) }))
        } else {
            panic!("unexpected packet type");
        }
    }
}

impl UserPacket {
    pub fn from_u8_array(val: [u8; 32]) -> UserPacket {
        UserPacket(val)
    }

    pub fn as_u8_array(&self) -> &[u8; 32] {
        &self.0
    }

    pub fn as_mut_u8_array(&mut self) -> &mut [u8; 32] {
        &mut self.0
    }
}

impl SignalPacket {
    /// The signals used in the call to `object_wait_async`.
    pub fn trigger(&self) -> Signals {
        Signals::from_bits_truncate(self.0.trigger)
    }

    /// The observed signals.
    pub fn observed(&self) -> Signals {
        Signals::from_bits_truncate(self.0.observed)
    }

    /// A per object count of pending operations.
    pub fn count(&self) -> u64 {
        self.0.count
    }
}

impl Port {
    /// Create an IO port, allowing IO packets to be read and enqueued.
    ///
    /// Wraps the
    /// [zx_port_create](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/port_create.md)
    /// syscall.
    pub fn create() -> Result<Port, Status> {
        unsafe {
            let mut handle = 0;
            let opts = 0;
            let status = sys::zx_port_create(opts, &mut handle);
            ok(status)?;
            Ok(Handle::from_raw(handle).into())
        }
    }

    /// Attempt to queue a user packet to the IO port.
    ///
    /// Wraps the
    /// [zx_port_queue](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/port_queue.md)
    /// syscall.
    pub fn queue(&self, packet: &Packet) -> Result<(), Status> {
        let status = unsafe {
            sys::zx_port_queue(self.raw_handle(),
                &packet.0 as *const sys::zx_port_packet_t, 0)
        };
        ok(status)
    }

    /// Wait for a packet to arrive on a (V2) port.
    ///
    /// Wraps the
    /// [zx_port_wait](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/port_wait.md)
    /// syscall.
    pub fn wait(&self, deadline: Time) -> Result<Packet, Status> {
        let mut packet = Default::default();
        let status = unsafe {
            sys::zx_port_wait(self.raw_handle(), deadline.nanos(),
                &mut packet as *mut sys::zx_port_packet_t, 0)
        };
        ok(status)?;
        Ok(Packet(packet))
    }

    /// Cancel pending wait_async calls for an object with the given key.
    ///
    /// Wraps the
    /// [zx_port_cancel](https://fuchsia.googlesource.com/zircon/+/HEAD/docs/syscalls/port_cancel.md)
    /// syscall.
    pub fn cancel<H>(&self, source: &H, key: u64) -> Result<(), Status> where H: HandleBased {
        let status = unsafe {
            sys::zx_port_cancel(self.raw_handle(), source.raw_handle(), key)
        };
        ok(status)
    }
}

/// Options for wait_async.
#[repr(u32)]
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum WaitAsyncOpts {
    Once = sys::ZX_WAIT_ASYNC_ONCE,
    Repeating = sys::ZX_WAIT_ASYNC_REPEATING,
}

#[cfg(test)]
mod tests {
    use super::*;
    use {DurationNum, Event};

    #[test]
    fn port_basic() {
        let ten_ms = 10.millis();

        let port = Port::create().unwrap();

        // Waiting now should time out.
        assert_eq!(port.wait(ten_ms.after_now()), Err(Status::TIMED_OUT));

        // Send a valid packet.
        let packet = Packet::from_user_packet(
            42,
            123,
            UserPacket::from_u8_array([13; 32]),
        );
        assert!(port.queue(&packet).is_ok());

        // Waiting should succeed this time. We should get back the packet we sent.
        let read_packet = port.wait(ten_ms.after_now()).unwrap();
        assert_eq!(read_packet, packet);
    }

    #[test]
    fn wait_async_once() {
        let ten_ms = 10.millis();
        let key = 42;

        let port = Port::create().unwrap();
        let event = Event::create().unwrap();

        assert!(event.wait_async_handle(&port, key, Signals::USER_0 | Signals::USER_1,
            WaitAsyncOpts::Once).is_ok());

        // Waiting without setting any signal should time out.
        assert_eq!(port.wait(ten_ms.after_now()), Err(Status::TIMED_OUT));

        // If we set a signal, we should be able to wait for it.
        assert!(event.signal_handle(Signals::NONE, Signals::USER_0).is_ok());
        let read_packet = port.wait(ten_ms.after_now()).unwrap();
        assert_eq!(read_packet.key(), key);
        assert_eq!(read_packet.status(), 0);
        match read_packet.contents() {
            PacketContents::SignalOne(sig) => {
                assert_eq!(sig.trigger(), Signals::USER_0 | Signals::USER_1);
                assert_eq!(sig.observed(), Signals::USER_0);
                assert_eq!(sig.count(), 1);
            }
            _ => panic!("wrong packet type"),
        }

        // Shouldn't get any more packets.
        assert_eq!(port.wait(ten_ms.after_now()), Err(Status::TIMED_OUT));

        // Calling wait_async again should result in another packet.
        assert!(event.wait_async_handle(&port, key, Signals::USER_0, WaitAsyncOpts::Once).is_ok());
        let read_packet = port.wait(ten_ms.after_now()).unwrap();
        assert_eq!(read_packet.key(), key);
        assert_eq!(read_packet.status(), 0);
        match read_packet.contents() {
            PacketContents::SignalOne(sig) => {
                assert_eq!(sig.trigger(), Signals::USER_0);
                assert_eq!(sig.observed(), Signals::USER_0);
                assert_eq!(sig.count(), 1);
            }
            _ => panic!("wrong packet type"),
        }

        // Calling wait_async_handle then cancel, we should not get a packet as cancel will
        // remove it from  the queue.
        assert!(event.wait_async_handle(&port, key, Signals::USER_0, WaitAsyncOpts::Once).is_ok());
        assert!(port.cancel(&event, key).is_ok());
        assert_eq!(port.wait(ten_ms.after_now()), Err(Status::TIMED_OUT));

        // If the event is signalled after the cancel, we also shouldn't get a packet.
        assert!(event.signal_handle(Signals::USER_0, Signals::NONE).is_ok());  // clear signal
        assert!(event.wait_async_handle(&port, key, Signals::USER_0, WaitAsyncOpts::Once).is_ok());
        assert!(port.cancel(&event, key).is_ok());
        assert!(event.signal_handle(Signals::NONE, Signals::USER_0).is_ok());
        assert_eq!(port.wait(ten_ms.after_now()), Err(Status::TIMED_OUT));
    }

    #[test]
    fn wait_async_repeating() {
        let ten_ms = 10.millis();
        let key = 42;

        let port = Port::create().unwrap();
        let event = Event::create().unwrap();

        assert!(event.wait_async_handle(&port, key, Signals::USER_0 | Signals::USER_1,
            WaitAsyncOpts::Repeating).is_ok());

        // Waiting without setting any signal should time out.
        assert_eq!(port.wait(ten_ms.after_now()), Err(Status::TIMED_OUT));

        // If we set a signal, we should be able to wait for it.
        assert!(event.signal_handle(Signals::NONE, Signals::USER_0).is_ok());
        let read_packet = port.wait(ten_ms.after_now()).unwrap();
        assert_eq!(read_packet.key(), key);
        assert_eq!(read_packet.status(), 0);
        match read_packet.contents() {
            PacketContents::SignalRep(sig) => {
                assert_eq!(sig.trigger(), Signals::USER_0 | Signals::USER_1);
                assert_eq!(sig.observed(), Signals::USER_0);
                assert_eq!(sig.count(), 1);
            }
            _ => panic!("wrong packet type"),
        }

        // Should not get any more packets, as ZX_WAIT_ASYNC_REPEATING is edge triggered rather than
        // level triggered.
        assert_eq!(port.wait(ten_ms.after_now()), Err(Status::TIMED_OUT));

        // If we clear and resignal, we should get the same packet again,
        // even though we didn't call event.wait_async again.
        assert!(event.signal_handle(Signals::USER_0, Signals::NONE).is_ok());  // clear signal
        assert!(event.signal_handle(Signals::NONE, Signals::USER_0).is_ok());
        let read_packet = port.wait(ten_ms.after_now()).unwrap();
        assert_eq!(read_packet.key(), key);
        assert_eq!(read_packet.status(), 0);
        match read_packet.contents() {
            PacketContents::SignalRep(sig) => {
                assert_eq!(sig.trigger(), Signals::USER_0 | Signals::USER_1);
                assert_eq!(sig.observed(), Signals::USER_0);
                assert_eq!(sig.count(), 1);
            }
            _ => panic!("wrong packet type"),
        }

        // Cancelling the wait should stop us getting packets...
        assert!(port.cancel(&event, key).is_ok());
        assert_eq!(port.wait(ten_ms.after_now()), Err(Status::TIMED_OUT));
        // ... even if we clear and resignal
        assert!(event.signal_handle(Signals::USER_0, Signals::NONE).is_ok());  // clear signal
        assert!(event.signal_handle(Signals::NONE, Signals::USER_0).is_ok());
        assert_eq!(port.wait(ten_ms.after_now()), Err(Status::TIMED_OUT));

        // Calling wait_async again should result in another packet.
        assert!(event.wait_async_handle(
            &port, key, Signals::USER_0, WaitAsyncOpts::Repeating).is_ok());
        let read_packet = port.wait(ten_ms.after_now()).unwrap();
        assert_eq!(read_packet.key(), key);
        assert_eq!(read_packet.status(), 0);
        match read_packet.contents() {
            PacketContents::SignalRep(sig) => {
                assert_eq!(sig.trigger(), Signals::USER_0);
                assert_eq!(sig.observed(), Signals::USER_0);
                assert_eq!(sig.count(), 1);
            }
            _ => panic!("wrong packet type"),
        }

        // Closing the handle should stop us getting packets.
        drop(event);
        assert_eq!(port.wait(ten_ms.after_now()), Err(Status::TIMED_OUT));
    }
}