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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
// 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 channel objects.

use crate::ok;
use crate::{
    size_to_u32_sat, usize_into_u32, AsHandleRef, Handle, HandleBased, HandleDisposition,
    HandleInfo, HandleOp, HandleRef, ObjectType, Peered, Rights, Status, Time,
};
use fuchsia_zircon_sys as sys;
use std::mem::{self, MaybeUninit};

impl HandleDisposition<'_> {
    const fn invalid<'a>() -> HandleDisposition<'a> {
        HandleDisposition {
            handle_op: HandleOp::Move(Handle::invalid()),
            object_type: ObjectType::NONE,
            rights: Rights::NONE,
            result: Status::OK,
        }
    }
}

/// An object representing a Zircon
/// [channel](https://fuchsia.dev/fuchsia-src/concepts/objects/channel.md).
///
/// As essentially a subtype of `Handle`, it can be freely interconverted.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[repr(transparent)]
pub struct Channel(Handle);
impl_handle_based!(Channel);
impl Peered for Channel {}

impl Channel {
    /// Create a channel, resulting in a pair of `Channel` objects representing both
    /// sides of the channel. Messages written into one may be read from the opposite.
    ///
    /// Wraps the
    /// [zx_channel_create](https://fuchsia.dev/fuchsia-src/reference/syscalls/channel_create.md)
    /// syscall.
    ///
    /// # Panics
    ///
    /// If the process' job policy denies channel creation or the kernel reports no memory
    /// available to create a new channel.
    pub fn create() -> (Self, Self) {
        unsafe {
            let mut handle0 = 0;
            let mut handle1 = 0;
            let opts = 0;
            ok(sys::zx_channel_create(opts, &mut handle0, &mut handle1)).expect(
                "channel creation always succeeds except with OOM or when job policy denies it",
            );
            (Self(Handle::from_raw(handle0)), Self(Handle::from_raw(handle1)))
        }
    }

    /// Read a message from a channel. Wraps the
    /// [zx_channel_read](https://fuchsia.dev/fuchsia-src/reference/syscalls/channel_read.md)
    /// syscall.
    ///
    /// If the slice lacks the capacity to hold the pending message,
    /// returns an `Err` with the number of bytes and number of handles needed.
    /// Otherwise returns an `Ok` with the result as usual.
    /// If both the outer and inner `Result`s are `Ok`, then the caller can
    /// assume that the `handles` array is initialized.
    ///
    /// Note that `read_slice` may call `read_raw` with some uninitialized
    /// elements because it resizes the input vector to its capacity
    /// without initializing all of the elements.
    pub fn read_raw(
        &self,
        bytes: &mut [u8],
        handles: &mut [MaybeUninit<Handle>],
    ) -> Result<(Result<(), Status>, usize, usize), (usize, usize)> {
        let opts = 0;
        unsafe {
            let raw_handle = self.raw_handle();
            let mut actual_bytes = 0;
            let mut actual_handles = 0;
            let status = ok(sys::zx_channel_read(
                raw_handle,
                opts,
                bytes.as_mut_ptr(),
                handles.as_mut_ptr() as *mut _,
                bytes.len() as u32,
                handles.len() as u32,
                &mut actual_bytes,
                &mut actual_handles,
            ));
            if status == Err(Status::BUFFER_TOO_SMALL) {
                Err((actual_bytes as usize, actual_handles as usize))
            } else {
                Ok((status, actual_bytes as usize, actual_handles as usize))
            }
        }
    }

    /// Read a message from a channel.
    ///
    /// Note that this method can cause internal reallocations in the `MessageBuf`
    /// if it is lacks capacity to hold the full message. If such reallocations
    /// are not desirable, use `read_raw` instead.
    pub fn read(&self, buf: &mut MessageBuf) -> Result<(), Status> {
        let (bytes, handles) = buf.split_mut();
        self.read_split(bytes, handles)
    }

    /// Read a message from a channel into a separate byte vector and handle vector.
    ///
    /// Note that this method can cause internal reallocations in the `Vec`s
    /// if they lacks capacity to hold the full message. If such reallocations
    /// are not desirable, use `read_raw` instead.
    pub fn read_split(&self, bytes: &mut Vec<u8>, handles: &mut Vec<Handle>) -> Result<(), Status> {
        loop {
            unsafe {
                bytes.set_len(bytes.capacity());
                handles.set_len(handles.capacity());
            }
            let handle_slice: &mut [Handle] = handles;
            match self.read_raw(bytes, unsafe { mem::transmute(handle_slice) }) {
                Ok((result, num_bytes, num_handles)) => {
                    unsafe {
                        bytes.set_len(num_bytes);
                        handles.set_len(num_handles);
                    }
                    return result;
                }
                Err((num_bytes, num_handles)) => {
                    ensure_capacity(bytes, num_bytes);
                    ensure_capacity(handles, num_handles);
                }
            }
        }
    }

    /// Read a message from a channel.
    /// Wraps the [zx_channel_read_etc](https://fuchsia.dev/fuchsia-src/reference/syscalls/channel_read_etc.md)
    /// syscall.
    ///
    /// This differs from `read_raw` in that it returns extended information on
    /// the handles.
    ///
    /// If the slice lacks the capacity to hold the pending message,
    /// returns an `Err` with the number of bytes and number of handles needed.
    /// Otherwise returns an `Ok` with the result as usual.
    /// If both the outer and inner `Result`s are `Ok`, then the caller can
    /// assume that the `handle_infos` array is initialized.
    ///
    /// Note that `read_etc_slice` may call `read_etc_raw` with some
    /// uninitialized elements because it resizes the input vector to its
    /// capacity without initializing all of the elements.
    pub fn read_etc_raw(
        &self,
        bytes: &mut [u8],
        handle_infos: &mut [MaybeUninit<HandleInfo>],
    ) -> Result<(Result<(), Status>, usize, usize), (usize, usize)> {
        let opts = 0;
        unsafe {
            let raw_handle = self.raw_handle();
            let mut zx_handle_infos: [MaybeUninit<sys::zx_handle_info_t>;
                sys::ZX_CHANNEL_MAX_MSG_HANDLES as usize] = MaybeUninit::uninit().assume_init();
            let mut actual_bytes = 0;
            let mut actual_handle_infos = 0;
            let status = ok(sys::zx_channel_read_etc(
                raw_handle,
                opts,
                bytes.as_mut_ptr(),
                zx_handle_infos.as_mut_ptr() as *mut sys::zx_handle_info_t,
                bytes.len() as u32,
                handle_infos.len() as u32,
                &mut actual_bytes,
                &mut actual_handle_infos,
            ));
            if status == Err(Status::BUFFER_TOO_SMALL) {
                Err((actual_bytes as usize, actual_handle_infos as usize))
            } else {
                Ok((
                    status.map(|()| {
                        for i in 0..actual_handle_infos as usize {
                            std::mem::swap(
                                &mut handle_infos[i],
                                &mut MaybeUninit::new(HandleInfo::from_raw(
                                    zx_handle_infos[i].assume_init(),
                                )),
                            );
                        }
                    }),
                    actual_bytes as usize,
                    actual_handle_infos as usize,
                ))
            }
        }
    }

    /// Read a message from a channel.
    ///
    /// This differs from `read` in that it returns extended information on
    /// the handles.
    ///
    /// Note that this method can cause internal reallocations in the `MessageBufEtc`
    /// if it is lacks capacity to hold the full message. If such reallocations
    /// are not desirable, use `read_etc_raw` instead.
    pub fn read_etc(&self, buf: &mut MessageBufEtc) -> Result<(), Status> {
        let (bytes, handles) = buf.split_mut();
        self.read_etc_split(bytes, handles)
    }

    /// Read a message from a channel into a separate byte vector and handle vector.
    ///
    /// This differs from `read_split` in that it returns extended information on
    /// the handles.
    ///
    /// Note that this method can cause internal reallocations in the `Vec`s
    /// if they lacks capacity to hold the full message. If such reallocations
    /// are not desirable, use `read_raw` instead.
    pub fn read_etc_split(
        &self,
        bytes: &mut Vec<u8>,
        handle_infos: &mut Vec<HandleInfo>,
    ) -> Result<(), Status> {
        loop {
            unsafe {
                bytes.set_len(bytes.capacity());
                handle_infos.set_len(handle_infos.capacity());
            }
            let handle_info_slice: &mut [HandleInfo] = handle_infos;
            match self.read_etc_raw(bytes, unsafe { std::mem::transmute(handle_info_slice) }) {
                Ok((result, num_bytes, num_handle_infos)) => {
                    unsafe {
                        bytes.set_len(num_bytes);
                        handle_infos.set_len(num_handle_infos);
                    }
                    return result;
                }
                Err((num_bytes, num_handle_infos)) => {
                    ensure_capacity(bytes, num_bytes);
                    ensure_capacity(handle_infos, num_handle_infos);
                }
            }
        }
    }

    /// Write a message to a channel. Wraps the
    /// [zx_channel_write](https://fuchsia.dev/fuchsia-src/reference/syscalls/channel_write.md)
    /// syscall.
    pub fn write(&self, bytes: &[u8], handles: &mut [Handle]) -> Result<(), Status> {
        let opts = 0;
        let n_bytes = usize_into_u32(bytes.len()).map_err(|_| Status::OUT_OF_RANGE)?;
        let n_handles = usize_into_u32(handles.len()).map_err(|_| Status::OUT_OF_RANGE)?;
        unsafe {
            let status = sys::zx_channel_write(
                self.raw_handle(),
                opts,
                bytes.as_ptr(),
                n_bytes,
                handles.as_ptr() as *const sys::zx_handle_t,
                n_handles,
            );
            // Handles are consumed by zx_channel_write so prevent the destructor from being called.
            for handle in handles {
                std::mem::forget(std::mem::replace(handle, Handle::invalid()));
            }
            ok(status)?;
            Ok(())
        }
    }

    /// Write a message to a channel. Wraps the
    /// [zx_channel_write_etc](https://fuchsia.dev/fuchsia-src/reference/syscalls/channel_write_etc.md)
    /// syscall.
    pub fn write_etc(
        &self,
        bytes: &[u8],
        handle_dispositions: &mut [HandleDisposition<'_>],
    ) -> Result<(), Status> {
        let opts = 0;
        let n_bytes = usize_into_u32(bytes.len()).map_err(|_| Status::OUT_OF_RANGE)?;
        let n_handle_dispositions =
            usize_into_u32(handle_dispositions.len()).map_err(|_| Status::OUT_OF_RANGE)?;
        if n_handle_dispositions > sys::ZX_CHANNEL_MAX_MSG_HANDLES {
            // don't let the kernel check this bound for us because we have a fixed size array below
            return Err(Status::OUT_OF_RANGE);
        }
        unsafe {
            let mut zx_handle_dispositions: [std::mem::MaybeUninit<sys::zx_handle_disposition_t>;
                sys::ZX_CHANNEL_MAX_MSG_HANDLES as usize] =
                std::mem::MaybeUninit::uninit().assume_init();
            for i in 0..n_handle_dispositions as usize {
                let handle_disposition =
                    std::mem::replace(&mut handle_dispositions[i], HandleDisposition::invalid());
                zx_handle_dispositions[i] =
                    std::mem::MaybeUninit::new(handle_disposition.into_raw());
            }
            let status = sys::zx_channel_write_etc(
                self.raw_handle(),
                opts,
                bytes.as_ptr(),
                n_bytes,
                zx_handle_dispositions.as_mut_ptr() as *mut sys::zx_handle_disposition_t,
                n_handle_dispositions,
            );
            ok(status)?;
            Ok(())
        }
    }

    /// Send a message consisting of the given bytes and handles to a channel and await a reply.
    ///
    /// The first four bytes of the written and read back messages are treated as a transaction ID
    /// of type `zx_txid_t`. The kernel generates a txid for the written message, replacing that
    /// part of the message as read from userspace. In other words, the first four bytes of
    /// `bytes` will be ignored, and the first four bytes of the response will contain a
    /// kernel-generated txid.
    ///
    /// Wraps the
    /// [zx_channel_call](https://fuchsia.dev/fuchsia-src/reference/syscalls/channel_call.md)
    /// syscall.
    ///
    /// Note that unlike [`read`][read], the caller must ensure that the MessageBuf has enough
    /// capacity for the bytes and handles which will be received, as replies which are too large
    /// are discarded.
    ///
    /// On failure returns the both the main and read status.
    ///
    /// [read]: struct.Channel.html#method.read
    pub fn call(
        &self,
        timeout: Time,
        bytes: &[u8],
        handles: &mut [Handle],
        buf: &mut MessageBuf,
    ) -> Result<(), Status> {
        let write_num_bytes = usize_into_u32(bytes.len()).map_err(|_| Status::OUT_OF_RANGE)?;
        let write_num_handles = usize_into_u32(handles.len()).map_err(|_| Status::OUT_OF_RANGE)?;
        buf.clear();
        let read_num_bytes: u32 = size_to_u32_sat(buf.bytes.capacity());
        let read_num_handles: u32 = size_to_u32_sat(buf.handles.capacity());
        let args = sys::zx_channel_call_args_t {
            wr_bytes: bytes.as_ptr(),
            wr_handles: handles.as_ptr() as *const sys::zx_handle_t,
            rd_bytes: buf.bytes.as_mut_ptr(),
            rd_handles: buf.handles.as_mut_ptr() as *mut _,
            wr_num_bytes: write_num_bytes,
            wr_num_handles: write_num_handles,
            rd_num_bytes: read_num_bytes,
            rd_num_handles: read_num_handles,
        };
        let mut actual_read_bytes: u32 = 0;
        let mut actual_read_handles: u32 = 0;
        let options = 0;
        let status = unsafe {
            Status::from_raw(sys::zx_channel_call(
                self.raw_handle(),
                options,
                timeout.into_nanos(),
                &args,
                &mut actual_read_bytes,
                &mut actual_read_handles,
            ))
        };
        unsafe {
            // Outgoing handles are consumed by zx_channel_call so prevent the destructor from being called.
            for handle in handles {
                std::mem::forget(std::mem::replace(handle, Handle::invalid()));
            }
            buf.bytes.set_len(actual_read_bytes as usize);
            buf.handles.set_len(actual_read_handles as usize);
        }
        if Status::OK == status {
            Ok(())
        } else {
            Err(status)
        }
    }

    /// Send a message consisting of the given bytes and handles to a channel and await a reply.
    ///
    /// The first four bytes of the written and read back messages are treated as a transaction ID
    /// of type `zx_txid_t`. The kernel generates a txid for the written message, replacing that
    /// part of the message as read from userspace. In other words, the first four bytes of
    /// `bytes` will be ignored, and the first four bytes of the response will contain a
    /// kernel-generated txid.
    ///
    /// This differs from `call`, in that it uses extended handle info.
    ///
    /// Wraps the
    /// [zx_channel_call_etc](https://fuchsia.dev/fuchsia-src/reference/syscalls/channel_call_etc.md)
    /// syscall.
    ///
    /// Note that unlike [`read_etc`][read_etc], the caller must ensure that the MessageBufEtc
    /// has enough capacity for the bytes and handles which will be received, as replies which are
    /// too large are discarded.
    ///
    /// On failure returns the both the main and read status.
    ///
    /// [read_etc]: struct.Channel.html#method.read_etc
    pub fn call_etc(
        &self,
        timeout: Time,
        bytes: &[u8],
        handle_dispositions: &mut [HandleDisposition<'_>],
        buf: &mut MessageBufEtc,
    ) -> Result<(), Status> {
        let write_num_bytes = usize_into_u32(bytes.len()).map_err(|_| Status::OUT_OF_RANGE)?;
        let write_num_handle_dispositions =
            usize_into_u32(handle_dispositions.len()).map_err(|_| Status::OUT_OF_RANGE)?;
        if write_num_handle_dispositions > sys::ZX_CHANNEL_MAX_MSG_HANDLES {
            // don't let the kernel check this bound for us because we have a fixed size array below
            return Err(Status::OUT_OF_RANGE);
        }
        let mut zx_handle_dispositions: [std::mem::MaybeUninit<sys::zx_handle_disposition_t>;
            sys::ZX_CHANNEL_MAX_MSG_HANDLES as usize] =
            [std::mem::MaybeUninit::uninit(); sys::ZX_CHANNEL_MAX_MSG_HANDLES as usize];
        for i in 0..write_num_handle_dispositions as usize {
            let handle_disposition =
                std::mem::replace(&mut handle_dispositions[i], HandleDisposition::invalid());
            zx_handle_dispositions[i].write(handle_disposition.into_raw());
        }
        buf.clear();
        let read_num_bytes: u32 = size_to_u32_sat(buf.bytes.capacity());
        let read_num_handle_infos: u32 = size_to_u32_sat(buf.handle_infos.capacity());
        let mut zx_handle_infos: [std::mem::MaybeUninit<sys::zx_handle_info_t>;
            sys::ZX_CHANNEL_MAX_MSG_HANDLES as usize] =
            unsafe { std::mem::MaybeUninit::uninit().assume_init() };
        let mut args = sys::zx_channel_call_etc_args_t {
            wr_bytes: bytes.as_ptr(),
            wr_handles: zx_handle_dispositions.as_mut_ptr() as *mut sys::zx_handle_disposition_t,
            rd_bytes: buf.bytes.as_mut_ptr(),
            rd_handles: zx_handle_infos.as_mut_ptr() as *mut sys::zx_handle_info_t,
            wr_num_bytes: write_num_bytes,
            wr_num_handles: write_num_handle_dispositions,
            rd_num_bytes: read_num_bytes,
            rd_num_handles: read_num_handle_infos,
        };
        let mut actual_read_bytes: u32 = 0;
        let mut actual_read_handle_infos: u32 = 0;
        let options = 0;
        let status = unsafe {
            Status::from_raw(sys::zx_channel_call_etc(
                self.raw_handle(),
                options,
                timeout.into_nanos(),
                &mut args,
                &mut actual_read_bytes,
                &mut actual_read_handle_infos,
            ))
        };
        unsafe {
            buf.ensure_capacity_handle_infos(actual_read_handle_infos as usize);
            for i in 0..actual_read_handle_infos as usize {
                buf.handle_infos.push(HandleInfo::from_raw(zx_handle_infos[i].assume_init()));
            }
            buf.bytes.set_len(actual_read_bytes as usize);
        }
        if Status::OK == status {
            Ok(())
        } else {
            Err(status)
        }
    }
}

#[test]
pub fn test_handle_repr() {
    assert_eq!(::std::mem::size_of::<sys::zx_handle_t>(), 4);
    assert_eq!(::std::mem::size_of::<Handle>(), 4);
    assert_eq!(::std::mem::align_of::<sys::zx_handle_t>(), ::std::mem::align_of::<Handle>());

    // This test asserts that repr(transparent) still works for Handle -> zx_handle_t

    let n: Vec<sys::zx_handle_t> = vec![0, 100, 2 << 32 - 1];
    let v: Vec<Handle> = n.iter().map(|h| unsafe { Handle::from_raw(*h) }).collect();

    for (handle, raw) in v.iter().zip(n.iter()) {
        unsafe {
            assert_eq!(
                *(handle as *const _ as *const [u8; 4]),
                *(raw as *const _ as *const [u8; 4])
            );
        }
    }

    for h in v.into_iter() {
        ::std::mem::forget(h);
    }
}

impl AsRef<Channel> for Channel {
    fn as_ref(&self) -> &Self {
        &self
    }
}

/// A buffer for _receiving_ messages from a channel.
///
/// A `MessageBuf` is essentially a byte buffer and a vector of
/// handles, but move semantics for "taking" handles requires special handling.
///
/// Note that for sending messages to a channel, the caller manages the buffers,
/// using a plain byte slice and `Vec<Handle>`.
#[derive(Debug, Default)]
pub struct MessageBuf {
    bytes: Vec<u8>,
    handles: Vec<Handle>,
}

impl MessageBuf {
    /// Create a new, empty, message buffer.
    pub fn new() -> Self {
        Default::default()
    }

    /// Create a new non-empty message buffer.
    pub fn new_with(v: Vec<u8>, h: Vec<Handle>) -> Self {
        Self { bytes: v, handles: h }
    }

    /// Splits apart the message buf into a vector of bytes and a vector of handles.
    pub fn split_mut(&mut self) -> (&mut Vec<u8>, &mut Vec<Handle>) {
        (&mut self.bytes, &mut self.handles)
    }

    /// Splits apart the message buf into a vector of bytes and a vector of handles.
    pub fn split(self) -> (Vec<u8>, Vec<Handle>) {
        (self.bytes, self.handles)
    }

    /// Ensure that the buffer has the capacity to hold at least `n_bytes` bytes.
    pub fn ensure_capacity_bytes(&mut self, n_bytes: usize) {
        ensure_capacity(&mut self.bytes, n_bytes);
    }

    /// Ensure that the buffer has the capacity to hold at least `n_handles` handles.
    pub fn ensure_capacity_handles(&mut self, n_handles: usize) {
        ensure_capacity(&mut self.handles, n_handles);
    }

    /// Ensure that at least n_bytes bytes are initialized (0 fill).
    pub fn ensure_initialized_bytes(&mut self, n_bytes: usize) {
        if n_bytes <= self.bytes.len() {
            return;
        }
        self.bytes.resize(n_bytes, 0);
    }

    /// Get a reference to the bytes of the message buffer, as a `&[u8]` slice.
    pub fn bytes(&self) -> &[u8] {
        self.bytes.as_slice()
    }

    /// The number of handles in the message buffer. Note this counts the number
    /// available when the message was received; `take_handle` does not affect
    /// the count.
    pub fn n_handles(&self) -> usize {
        self.handles.len()
    }

    /// Take the handle at the specified index from the message buffer. If the
    /// method is called again with the same index, it will return `None`, as
    /// will happen if the index exceeds the number of handles available.
    pub fn take_handle(&mut self, index: usize) -> Option<Handle> {
        self.handles.get_mut(index).and_then(|handle| {
            if handle.is_invalid() {
                None
            } else {
                Some(mem::replace(handle, Handle::invalid()))
            }
        })
    }

    /// Clear the bytes and handles contained in the buf. This will drop any
    /// contained handles, resulting in their resources being freed.
    pub fn clear(&mut self) {
        self.bytes.clear();
        self.handles.clear();
    }
}

/// A buffer for _receiving_ messages from a channel.
///
/// This differs from `MessageBuf` in that it holds `HandleInfo` with
/// extended handle information.
///
/// A `MessageBufEtc` is essentially a byte buffer and a vector of handle
/// infos, but move semantics for "taking" handles requires special handling.
///
/// Note that for sending messages to a channel, the caller manages the buffers,
/// using a plain byte slice and `Vec<HandleDisposition>`.
#[derive(Debug, Default)]
pub struct MessageBufEtc {
    bytes: Vec<u8>,
    handle_infos: Vec<HandleInfo>,
}

impl MessageBufEtc {
    /// Create a new, empty, message buffer.
    pub fn new() -> Self {
        Default::default()
    }

    /// Create a new non-empty message buffer.
    pub fn new_with(v: Vec<u8>, h: Vec<HandleInfo>) -> Self {
        Self { bytes: v, handle_infos: h }
    }

    /// Splits apart the message buf into a vector of bytes and a vector of handle infos.
    pub fn split_mut(&mut self) -> (&mut Vec<u8>, &mut Vec<HandleInfo>) {
        (&mut self.bytes, &mut self.handle_infos)
    }

    /// Splits apart the message buf into a vector of bytes and a vector of handle infos.
    pub fn split(self) -> (Vec<u8>, Vec<HandleInfo>) {
        (self.bytes, self.handle_infos)
    }

    /// Ensure that the buffer has the capacity to hold at least `n_bytes` bytes.
    pub fn ensure_capacity_bytes(&mut self, n_bytes: usize) {
        ensure_capacity(&mut self.bytes, n_bytes);
    }

    /// Ensure that the buffer has the capacity to hold at least `n_handles` handle infos.
    pub fn ensure_capacity_handle_infos(&mut self, n_handle_infos: usize) {
        ensure_capacity(&mut self.handle_infos, n_handle_infos);
    }

    /// Ensure that at least n_bytes bytes are initialized (0 fill).
    pub fn ensure_initialized_bytes(&mut self, n_bytes: usize) {
        if n_bytes <= self.bytes.len() {
            return;
        }
        self.bytes.resize(n_bytes, 0);
    }

    /// Get a reference to the bytes of the message buffer, as a `&[u8]` slice.
    pub fn bytes(&self) -> &[u8] {
        self.bytes.as_slice()
    }

    /// The number of handles in the message buffer. Note this counts the number
    /// available when the message was received; `take_handle` does not affect
    /// the count.
    pub fn n_handle_infos(&self) -> usize {
        self.handle_infos.len()
    }

    /// Take the handle at the specified index from the message buffer. If the
    /// method is called again with the same index, it will return `None`, as
    /// will happen if the index exceeds the number of handles available.
    pub fn take_handle_info(&mut self, index: usize) -> Option<HandleInfo> {
        self.handle_infos.get_mut(index).and_then(|handle_info| {
            if handle_info.handle.is_invalid() {
                None
            } else {
                Some(mem::replace(
                    handle_info,
                    HandleInfo {
                        handle: Handle::invalid(),
                        object_type: ObjectType::NONE,
                        rights: Rights::NONE,
                    },
                ))
            }
        })
    }

    /// Clear the bytes and handles contained in the buf. This will drop any
    /// contained handles, resulting in their resources being freed.
    pub fn clear(&mut self) {
        self.bytes.clear();
        self.handle_infos.clear();
    }
}

fn ensure_capacity<T>(vec: &mut Vec<T>, size: usize) {
    let len = vec.len();
    if size > len {
        vec.reserve(size - len);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{DurationNum, Port, Signals, Vmo};
    use std::thread;

    #[test]
    fn channel_basic() {
        let (p1, p2) = Channel::create();

        let mut empty = vec![];
        assert!(p1.write(b"hello", &mut empty).is_ok());

        let mut buf = MessageBuf::new();
        assert!(p2.read(&mut buf).is_ok());
        assert_eq!(buf.bytes(), b"hello");
    }

    #[test]
    fn channel_basic_etc() {
        let (p1, p2) = Channel::create();

        let mut empty = vec![];
        assert!(p1.write_etc(b"hello", &mut empty).is_ok());

        let mut buf = MessageBufEtc::new();
        assert!(p2.read_etc(&mut buf).is_ok());
        assert_eq!(buf.bytes(), b"hello");
    }

    #[test]
    fn channel_basic_etc_with_handle_move() {
        let (p1, p2) = Channel::create();

        let mut handles = vec![HandleDisposition {
            handle_op: HandleOp::Move(Port::create().into()),
            rights: Rights::TRANSFER,
            object_type: ObjectType::PORT,
            result: Status::OK,
        }];
        match p1.write_etc(b"", &mut handles) {
            Err(err) => {
                panic!("error: {}", err);
            }
            _ => {}
        }

        let mut buf = MessageBufEtc::new();
        assert!(p2.read_etc(&mut buf).is_ok());
        assert_eq!(buf.bytes(), b"");
        assert_eq!(buf.n_handle_infos(), 1);
        let out_handles = buf.handle_infos;
        assert_eq!(out_handles.len(), 1);
        assert_ne!(out_handles[0].handle, Handle::invalid());
        assert_eq!(out_handles[0].rights, Rights::TRANSFER);
        assert_eq!(out_handles[0].object_type, ObjectType::PORT);
    }

    #[test]
    fn channel_basic_etc_with_handle_duplicate() {
        let (p1, p2) = Channel::create();

        let port = Port::create();
        let mut handles = vec![HandleDisposition {
            handle_op: HandleOp::Duplicate(port.as_handle_ref()),
            rights: Rights::SAME_RIGHTS,
            object_type: ObjectType::NONE,
            result: Status::OK,
        }];
        p1.write_etc(b"", &mut handles).unwrap();

        let orig_port_info = port.basic_info().unwrap();
        let mut buf = MessageBufEtc::new();
        assert!(p2.read_etc(&mut buf).is_ok());
        assert_eq!(buf.bytes(), b"");
        assert_eq!(buf.n_handle_infos(), 1);
        let out_handles = buf.handle_infos;
        assert_eq!(out_handles.len(), 1);
        assert_ne!(out_handles[0].handle.raw_handle(), 0);
        assert_ne!(out_handles[0].handle.raw_handle(), port.raw_handle());
        assert_eq!(out_handles[0].rights, orig_port_info.rights);
        assert_eq!(out_handles[0].object_type, ObjectType::PORT);
    }

    #[test]
    fn channel_read_raw_too_small() {
        let (p1, p2) = Channel::create();

        let mut empty = vec![];
        assert!(p1.write(b"hello", &mut empty).is_ok());

        let result = p2.read_raw(&mut vec![], &mut vec![]);
        assert_eq!(result, Err((5, 0)));
    }

    #[test]
    fn channel_read_etc_raw_too_small() {
        let (p1, p2) = Channel::create();

        let mut empty = vec![];
        assert!(p1.write_etc(b"hello", &mut empty).is_ok());

        let result = p2.read_etc_raw(&mut vec![], &mut vec![]);
        assert_eq!(result, Err((5, 0)));
    }

    fn too_many_bytes() -> Vec<u8> {
        vec![b'A'; (sys::ZX_CHANNEL_MAX_MSG_BYTES + 1) as usize]
    }

    fn too_many_handles() -> Vec<Handle> {
        let mut handles = vec![];
        for _ in 0..sys::ZX_CHANNEL_MAX_MSG_HANDLES + 1 {
            handles.push(crate::Event::create().into());
        }
        handles
    }

    fn too_many_dispositions() -> Vec<HandleDisposition<'static>> {
        let mut handles = vec![];
        for _ in 0..sys::ZX_CHANNEL_MAX_MSG_HANDLES + 1 {
            handles.push(HandleDisposition {
                handle_op: HandleOp::Move(crate::Event::create().into()),
                object_type: ObjectType::EVENT,
                rights: Rights::TRANSFER,
                result: Status::OK,
            });
        }
        handles
    }

    #[test]
    fn channel_write_too_many_bytes() {
        Channel::create().0.write(&too_many_bytes(), &mut vec![]).unwrap_err();
    }

    #[test]
    fn channel_write_too_many_handles() {
        Channel::create().0.write(&vec![], &mut too_many_handles()[..]).unwrap_err();
    }

    #[test]
    fn channel_write_etc_too_many_bytes() {
        Channel::create().0.write_etc(&too_many_bytes(), &mut []).unwrap_err();
    }

    #[test]
    fn channel_write_etc_too_many_handles() {
        Channel::create().0.write_etc(&vec![], &mut too_many_dispositions()[..]).unwrap_err();
    }

    #[test]
    fn channel_call_too_many_bytes() {
        Channel::create()
            .0
            .call(Time::INFINITE, &too_many_bytes(), &mut vec![], &mut MessageBuf::new())
            .unwrap_err();
    }

    #[test]
    fn channel_call_too_many_handles() {
        Channel::create()
            .0
            .call(Time::INFINITE, &vec![], &mut too_many_handles()[..], &mut MessageBuf::new())
            .unwrap_err();
    }

    #[test]
    fn channel_call_etc_too_many_bytes() {
        Channel::create()
            .0
            .call_etc(Time::INFINITE, &too_many_bytes(), &mut vec![], &mut MessageBufEtc::new())
            .unwrap_err();
    }

    #[test]
    fn channel_call_etc_too_many_handles() {
        Channel::create()
            .0
            .call_etc(
                Time::INFINITE,
                &vec![],
                &mut too_many_dispositions()[..],
                &mut MessageBufEtc::new(),
            )
            .unwrap_err();
    }

    #[test]
    fn channel_send_handle() {
        let hello_length: usize = 5;

        // Create a pair of channels and a virtual memory object.
        let (p1, p2) = Channel::create();
        let vmo = Vmo::create(hello_length as u64).unwrap();

        // Duplicate VMO handle and send it down the channel.
        let duplicate_vmo_handle = vmo.duplicate_handle(Rights::SAME_RIGHTS).unwrap().into();
        let mut handles_to_send: Vec<Handle> = vec![duplicate_vmo_handle];
        assert!(p1.write(b"", &mut handles_to_send).is_ok());
        // The handle vector should only contain invalid handles.
        for handle in handles_to_send {
            assert!(handle.is_invalid());
        }

        // Read the handle from the receiving channel.
        let mut buf = MessageBuf::new();
        assert!(p2.read(&mut buf).is_ok());
        assert_eq!(buf.n_handles(), 1);
        // Take the handle from the buffer.
        let received_handle = buf.take_handle(0).unwrap();
        // Should not affect number of handles.
        assert_eq!(buf.n_handles(), 1);
        // Trying to take it again should fail.
        assert!(buf.take_handle(0).is_none());

        // Now to test that we got the right handle, try writing something to it...
        let received_vmo = Vmo::from(received_handle);
        assert!(received_vmo.write(b"hello", 0).is_ok());

        // ... and reading it back from the original VMO.
        let mut read_vec = vec![0; hello_length];
        assert!(vmo.read(&mut read_vec, 0).is_ok());
        assert_eq!(read_vec, b"hello");
    }

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

        // Create a pair of channels and a virtual memory object.
        let (p1, p2) = Channel::create();
        let vmo = Vmo::create(0 as u64).unwrap();

        // Duplicate VMO handle and send it along with the call.
        let duplicate_vmo_handle = vmo.duplicate_handle(Rights::SAME_RIGHTS).unwrap().into();
        let mut handles_to_send: Vec<Handle> = vec![duplicate_vmo_handle];
        let mut buf = MessageBuf::new();
        assert_eq!(
            p1.call(Time::after(ten_ms), b"0000call", &mut handles_to_send, &mut buf),
            Err(Status::TIMED_OUT)
        );
        // Despite not getting a response, the handles were sent so the handle slice
        // should only contain invalid handles.
        for handle in handles_to_send {
            assert!(handle.is_invalid());
        }

        // Should be able to read call even though it timed out waiting for a response.
        let mut buf = MessageBuf::new();
        assert!(p2.read(&mut buf).is_ok());
        assert_eq!(&buf.bytes()[4..], b"call");
        assert_eq!(buf.n_handles(), 1);
    }

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

        // Create a pair of channels and a virtual memory object.
        let (p1, p2) = Channel::create();

        // Duplicate VMO handle and send it along with the call.
        let mut empty: Vec<HandleDisposition<'_>> = vec![];
        let mut buf = MessageBufEtc::new();
        assert_eq!(
            p1.call_etc(Time::after(ten_ms), b"0000call", &mut empty, &mut buf),
            Err(Status::TIMED_OUT)
        );

        // Should be able to read call even though it timed out waiting for a response.
        let mut buf = MessageBuf::new();
        assert!(p2.read(&mut buf).is_ok());
        assert_eq!(&buf.bytes()[4..], b"call");
        assert_eq!(buf.n_handles(), 0);
    }

    #[test]
    fn channel_call() {
        // Create a pair of channels
        let (p1, p2) = Channel::create();

        // create an mpsc channel for communicating the call data for later assertion
        let (tx, rx) = ::std::sync::mpsc::channel();

        // Start a new thread to respond to the call.
        thread::spawn(move || {
            let mut buf = MessageBuf::new();
            // if either the read or the write fail, this thread will panic,
            // resulting in tx being dropped, which will be noticed by the rx.
            p2.wait_handle(Signals::CHANNEL_READABLE, Time::after(1.seconds()))
                .expect("callee wait error");
            p2.read(&mut buf).expect("callee read error");

            let (bytes, handles) = buf.split_mut();
            tx.send(bytes.clone()).expect("callee mpsc send error");
            assert_eq!(handles.len(), 0);

            bytes.truncate(4); // Drop the received message, leaving only the txid
            bytes.extend_from_slice(b"response");

            p2.write(bytes, handles).expect("callee write error");
        });

        // Make the call.
        let mut buf = MessageBuf::new();
        buf.ensure_capacity_bytes(12);
        // NOTE(raggi): CQ has been seeing some long stalls from channel call,
        // and it's as yet unclear why. The timeout here has been made much
        // larger in order to avoid that, as the issues are not issues with this
        // crate's concerns. The timeout is here just to prevent the tests from
        // stalling forever if a developer makes a mistake locally in this
        // crate. Tests of Zircon behavior or virtualization behavior should be
        // covered elsewhere. See https://fxbug.dev/42106187.
        p1.call(Time::after(30.seconds()), b"txidcall", &mut vec![], &mut buf)
            .expect("channel call error");
        assert_eq!(&buf.bytes()[4..], b"response");
        assert_eq!(buf.n_handles(), 0);

        let sbuf = rx.recv().expect("mpsc channel recv error");
        assert_eq!(&sbuf[4..], b"call");
    }

    #[test]
    fn channel_call_etc() {
        // Create a pair of channels
        let (p1, p2) = Channel::create();

        // create an mpsc channel for communicating the call data for later assertion
        let (tx, rx) = ::std::sync::mpsc::channel();

        // Start a new thread to respond to the call.
        thread::spawn(move || {
            let mut buf = MessageBuf::new();
            // if either the read or the write fail, this thread will panic,
            // resulting in tx being dropped, which will be noticed by the rx.
            p2.wait_handle(Signals::CHANNEL_READABLE, Time::after(1.seconds()))
                .expect("callee wait error");
            p2.read(&mut buf).expect("callee read error");

            let (bytes, handles) = buf.split_mut();
            tx.send(bytes.clone()).expect("callee mpsc send error");
            assert_eq!(handles.len(), 1);

            bytes.truncate(4); // Drop the received message, leaving only the txid
            bytes.extend_from_slice(b"response");

            p2.write(bytes, handles).expect("callee write error");
        });

        // Make the call.
        let mut buf = MessageBufEtc::new();
        buf.ensure_capacity_bytes(12);
        buf.ensure_capacity_handle_infos(1);
        let mut handle_dispositions = [HandleDisposition {
            handle_op: HandleOp::Move(Port::create().into()),
            object_type: ObjectType::PORT,
            rights: Rights::TRANSFER,
            result: Status::OK,
        }];
        // NOTE(raggi): CQ has been seeing some long stalls from channel call,
        // and it's as yet unclear why. The timeout here has been made much
        // larger in order to avoid that, as the issues are not issues with this
        // crate's concerns. The timeout is here just to prevent the tests from
        // stalling forever if a developer makes a mistake locally in this
        // crate. Tests of Zircon behavior or virtualization behavior should be
        // covered elsewhere. See https://fxbug.dev/42106187.
        p1.call_etc(Time::after(30.seconds()), b"txidcall", &mut handle_dispositions, &mut buf)
            .expect("channel call error");
        assert_eq!(&buf.bytes()[4..], b"response");
        assert_eq!(buf.n_handle_infos(), 1);
        assert_ne!(buf.handle_infos[0].handle.raw_handle(), 0);
        assert_eq!(buf.handle_infos[0].object_type, ObjectType::PORT);
        assert_eq!(buf.handle_infos[0].rights, Rights::TRANSFER);

        let sbuf = rx.recv().expect("mpsc channel recv error");
        assert_eq!(&sbuf[4..], b"call");
    }
}