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
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
// Copyright 2021 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.

use crate::zxio::{
    zxio_dirent_iterator_next, zxio_dirent_iterator_t, ZXIO_NODE_PROTOCOL_CONNECTOR,
    ZXIO_NODE_PROTOCOL_DIRECTORY, ZXIO_NODE_PROTOCOL_FILE, ZXIO_NODE_PROTOCOL_SYMLINK,
};
use bitflags::bitflags;
use bstr::BString;
use fidl::{encoding::const_assert_eq, endpoints::ServerEnd};
use fidl_fuchsia_io as fio;
use fuchsia_zircon::{self as zx, AsHandleRef as _, HandleBased as _};
use std::{
    ffi::CStr,
    marker::PhantomData,
    mem::{size_of, size_of_val},
    num::TryFromIntError,
    os::raw::{c_char, c_int, c_uint, c_void},
    pin::Pin,
};
use zerocopy::{AsBytes, FromBytes};
use zxio::{
    msghdr, sockaddr, sockaddr_storage, socklen_t, zx_handle_t, zx_status_t, zxio_object_type_t,
    zxio_seek_origin_t, zxio_storage_t, ZXIO_SHUTDOWN_OPTIONS_READ, ZXIO_SHUTDOWN_OPTIONS_WRITE,
};

pub mod zxio;

pub use zxio::{
    zxio_dirent_t, zxio_fsverity_descriptor, zxio_fsverity_descriptor_t,
    zxio_node_attr_zxio_node_attr_has_t as zxio_node_attr_has_t, zxio_node_attributes_t,
    zxio_signals_t,
};

// The inner mod is required because bitflags cannot pass the attribute through to the single
// variant, and attributes cannot be applied to macro invocations.
mod inner_signals {
    // Part of the code for the NONE case that's produced by the macro triggers the lint, but as a
    // whole, the produced code is still correct.
    #![allow(clippy::bad_bit_mask)] // TODO(b/303500202) Remove once addressed in bitflags.
    use super::{bitflags, zxio_signals_t};

    bitflags! {
        // These values should match the values in sdk/lib/zxio/include/lib/zxio/types.h
        #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
        pub struct ZxioSignals : zxio_signals_t {
            const NONE            =      0;
            const READABLE        = 1 << 0;
            const WRITABLE        = 1 << 1;
            const READ_DISABLED   = 1 << 2;
            const WRITE_DISABLED  = 1 << 3;
            const READ_THRESHOLD  = 1 << 4;
            const WRITE_THRESHOLD = 1 << 5;
            const OUT_OF_BAND     = 1 << 6;
            const ERROR           = 1 << 7;
            const PEER_CLOSED     = 1 << 8;
        }
    }
}

pub use inner_signals::ZxioSignals;

bitflags! {
    /// The flags for shutting down sockets.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct ZxioShutdownFlags: u32 {
        /// Further transmissions will be disallowed.
        const WRITE = 1 << 0;

        /// Further receptions will be disallowed.
        const READ = 1 << 1;
    }
}

const_assert_eq!(ZxioShutdownFlags::WRITE.bits(), ZXIO_SHUTDOWN_OPTIONS_WRITE);
const_assert_eq!(ZxioShutdownFlags::READ.bits(), ZXIO_SHUTDOWN_OPTIONS_READ);

pub enum SeekOrigin {
    Start,
    Current,
    End,
}

impl From<SeekOrigin> for zxio_seek_origin_t {
    fn from(origin: SeekOrigin) -> Self {
        match origin {
            SeekOrigin::Start => zxio::ZXIO_SEEK_ORIGIN_START,
            SeekOrigin::Current => zxio::ZXIO_SEEK_ORIGIN_CURRENT,
            SeekOrigin::End => zxio::ZXIO_SEEK_ORIGIN_END,
        }
    }
}

// TODO: We need a more comprehensive error strategy.
// Our dependencies create elaborate error objects, but Starnix would prefer
// this library produce zx::Status errors for easier conversion to Errno.

#[derive(Default, Debug)]
pub struct ZxioDirent {
    pub protocols: Option<zxio::zxio_node_protocols_t>,
    pub abilities: Option<zxio::zxio_abilities_t>,
    pub id: Option<zxio::zxio_id_t>,
    pub name: BString,
}

pub struct DirentIterator<'a> {
    iterator: Box<zxio_dirent_iterator_t>,

    // zxio_dirent_iterator_t holds pointers to the underlying directory, so we must keep it alive
    // until we've destroyed it.
    _directory: PhantomData<&'a Zxio>,

    /// Whether the iterator has reached the end of dir entries.
    /// This is necessary because the zxio API returns only once the error code
    /// indicating the iterator has reached the end, where subsequent calls may
    /// return other error codes.
    finished: bool,
}

impl DirentIterator<'_> {
    /// Rewind the iterator to the beginning.
    pub fn rewind(&mut self) -> Result<(), zx::Status> {
        let status = unsafe { zxio::zxio_dirent_iterator_rewind(&mut *self.iterator) };
        zx::ok(status)?;
        self.finished = false;
        Ok(())
    }
}

/// It is important that all methods here are &mut self, to require the client
/// to obtain exclusive access to the object, externally locking it.
impl Iterator for DirentIterator<'_> {
    type Item = Result<ZxioDirent, zx::Status>;

    /// Returns the next dir entry for this iterator.
    fn next(&mut self) -> Option<Result<ZxioDirent, zx::Status>> {
        if self.finished {
            return None;
        }
        let mut entry = zxio_dirent_t::default();
        let mut name_buffer = Vec::with_capacity(fio::MAX_FILENAME as usize);
        // The FFI interface expects a pointer to c_char which is i8 on x86_64.
        // The Rust str and OsStr types expect raw character data to be stored in a buffer u8 values.
        // The types are equivalent for all practical purposes and Rust permits casting between the types,
        // so we insert a type cast here in the FFI bindings.
        entry.name = name_buffer.as_mut_ptr() as *mut c_char;
        let status = unsafe { zxio_dirent_iterator_next(&mut *self.iterator.as_mut(), &mut entry) };
        let result = match zx::ok(status) {
            Ok(()) => {
                let result = ZxioDirent::from(entry, name_buffer);
                Ok(result)
            }
            Err(zx::Status::NOT_FOUND) => {
                self.finished = true;
                return None;
            }
            Err(e) => Err(e),
        };
        return Some(result);
    }
}

impl Drop for DirentIterator<'_> {
    fn drop(&mut self) {
        unsafe {
            zxio::zxio_dirent_iterator_destroy(&mut *self.iterator.as_mut());
        }
    }
}

unsafe impl Send for DirentIterator<'_> {}
unsafe impl Sync for DirentIterator<'_> {}

impl ZxioDirent {
    fn from(dirent: zxio_dirent_t, name_buffer: Vec<u8>) -> ZxioDirent {
        let protocols = if dirent.has.protocols { Some(dirent.protocols) } else { None };
        let abilities = if dirent.has.abilities { Some(dirent.abilities) } else { None };
        let id = if dirent.has.id { Some(dirent.id) } else { None };
        let mut name = name_buffer;
        unsafe { name.set_len(dirent.name_length as usize) };
        ZxioDirent { protocols, abilities, id, name: name.into() }
    }

    pub fn is_dir(&self) -> bool {
        self.protocols.map(|p| p & ZXIO_NODE_PROTOCOL_DIRECTORY > 0).unwrap_or(false)
    }

    pub fn is_file(&self) -> bool {
        self.protocols.map(|p| p & ZXIO_NODE_PROTOCOL_FILE > 0).unwrap_or(false)
    }
}

pub struct ZxioErrorCode(i16);
impl ZxioErrorCode {
    pub fn raw(&self) -> i16 {
        self.0
    }
}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum ControlMessage {
    IpTos(u8),
    IpTtl(u8),
    Ipv6Tclass(u8),
    Ipv6HopLimit(u8),
    Ipv6PacketInfo { iface: u32, local_addr: [u8; size_of::<zxio::in6_addr>()] },
    Timestamp { sec: i64, usec: i64 },
    TimestampNs { sec: i64, nsec: i64 },
}

const fn align_cmsg_size(len: usize) -> usize {
    (len + size_of::<usize>() - 1) & !(size_of::<usize>() - 1)
}

const CMSG_HEADER_SIZE: usize = align_cmsg_size(size_of::<zxio::cmsghdr>());

// Size of the buffer to allocate in recvmsg() for cmsgs buffer. We need a buffer that can fit
// Ipv6Tclass, Ipv6HopLimit and Ipv6HopLimit messages.
const MAX_CMSGS_BUFFER: usize =
    CMSG_HEADER_SIZE * 3 + align_cmsg_size(1) * 2 + align_cmsg_size(size_of::<zxio::in6_pktinfo>());

impl ControlMessage {
    pub fn get_data_size(&self) -> usize {
        match self {
            ControlMessage::IpTos(_) => 1,
            ControlMessage::IpTtl(_) => size_of::<c_int>(),
            ControlMessage::Ipv6Tclass(_) => size_of::<c_int>(),
            ControlMessage::Ipv6HopLimit(_) => size_of::<c_int>(),
            ControlMessage::Ipv6PacketInfo { .. } => size_of::<zxio::in6_pktinfo>(),
            ControlMessage::Timestamp { .. } => size_of::<zxio::timeval>(),
            ControlMessage::TimestampNs { .. } => size_of::<zxio::timespec>(),
        }
    }

    // Serializes the data in the format expected by ZXIO.
    fn serialize<'a>(&'a self, out: &'a mut [u8]) -> usize {
        let data = &mut out[CMSG_HEADER_SIZE..];
        let (size, level, type_) = match self {
            ControlMessage::IpTos(v) => {
                v.write_to_prefix(data).unwrap();
                (1, zxio::SOL_IP, zxio::IP_TOS)
            }
            ControlMessage::IpTtl(v) => {
                (*v as c_int).write_to_prefix(data).unwrap();
                (size_of::<c_int>(), zxio::SOL_IP, zxio::IP_TTL)
            }
            ControlMessage::Ipv6Tclass(v) => {
                (*v as c_int).write_to_prefix(data).unwrap();
                (size_of::<c_int>(), zxio::SOL_IPV6, zxio::IPV6_TCLASS)
            }
            ControlMessage::Ipv6HopLimit(v) => {
                (*v as c_int).write_to_prefix(data).unwrap();
                (size_of::<c_int>(), zxio::SOL_IPV6, zxio::IPV6_HOPLIMIT)
            }
            ControlMessage::Ipv6PacketInfo { iface, local_addr } => {
                let pktinfo = zxio::in6_pktinfo {
                    ipi6_addr: zxio::in6_addr {
                        __in6_union: zxio::in6_addr__bindgen_ty_1 { __s6_addr: *local_addr },
                    },
                    ipi6_ifindex: *iface,
                };
                pktinfo.write_to_prefix(data).unwrap();
                (size_of_val(&pktinfo), zxio::SOL_IPV6, zxio::IPV6_PKTINFO)
            }
            ControlMessage::Timestamp { sec, usec } => {
                let timeval = zxio::timeval { tv_sec: *sec, tv_usec: *usec };
                timeval.write_to_prefix(data).unwrap();
                (size_of_val(&timeval), zxio::SOL_SOCKET, zxio::SO_TIMESTAMP)
            }
            ControlMessage::TimestampNs { sec, nsec } => {
                let timespec = zxio::timespec { tv_sec: *sec, tv_nsec: *nsec };
                timespec.write_to_prefix(data).unwrap();
                (size_of_val(&timespec), zxio::SOL_SOCKET, zxio::SO_TIMESTAMPNS)
            }
        };
        let total_size = CMSG_HEADER_SIZE + size;
        let header = zxio::cmsghdr {
            cmsg_len: total_size as c_uint,
            cmsg_level: level as i32,
            cmsg_type: type_ as i32,
        };
        header.write_to_prefix(&mut out[..]).unwrap();

        total_size
    }
}

fn serialize_control_messages(messages: &[ControlMessage]) -> Vec<u8> {
    let size = messages
        .iter()
        .fold(0, |sum, x| sum + CMSG_HEADER_SIZE + align_cmsg_size(x.get_data_size()));
    let mut buffer = vec![0u8; size];
    let mut pos = 0;
    for msg in messages {
        pos += align_cmsg_size(msg.serialize(&mut buffer[pos..]));
    }
    assert_eq!(pos, buffer.len());
    buffer
}

fn parse_control_messages(data: &[u8]) -> Vec<ControlMessage> {
    let mut result = vec![];
    let mut pos = 0;
    loop {
        if pos >= data.len() {
            return result;
        }
        let header_data = &data[pos..];
        let header = match zxio::cmsghdr::read_from_prefix(header_data) {
            Some(h) if h.cmsg_len as usize > CMSG_HEADER_SIZE => h,
            _ => return result,
        };

        let msg_data = &data[pos + CMSG_HEADER_SIZE..pos + header.cmsg_len as usize];
        let msg = match (header.cmsg_level as u32, header.cmsg_type as u32) {
            (zxio::SOL_IP, zxio::IP_TOS) => {
                ControlMessage::IpTos(u8::read_from_prefix(msg_data).unwrap())
            }
            (zxio::SOL_IP, zxio::IP_TTL) => {
                ControlMessage::IpTtl(c_int::read_from_prefix(msg_data).unwrap() as u8)
            }
            (zxio::SOL_IPV6, zxio::IPV6_TCLASS) => {
                ControlMessage::Ipv6Tclass(c_int::read_from_prefix(msg_data).unwrap() as u8)
            }
            (zxio::SOL_IPV6, zxio::IPV6_HOPLIMIT) => {
                ControlMessage::Ipv6HopLimit(c_int::read_from_prefix(msg_data).unwrap() as u8)
            }
            (zxio::SOL_IPV6, zxio::IPV6_PKTINFO) => {
                let pkt_info = zxio::in6_pktinfo::read_from_prefix(msg_data).unwrap();
                ControlMessage::Ipv6PacketInfo {
                    local_addr: unsafe { pkt_info.ipi6_addr.__in6_union.__s6_addr },
                    iface: pkt_info.ipi6_ifindex,
                }
            }
            (zxio::SOL_SOCKET, zxio::SO_TIMESTAMP) => {
                let timeval = zxio::timeval::read_from_prefix(msg_data).unwrap();
                ControlMessage::Timestamp { sec: timeval.tv_sec, usec: timeval.tv_usec }
            }
            (zxio::SOL_SOCKET, zxio::SO_TIMESTAMPNS) => {
                let timespec = zxio::timespec::read_from_prefix(msg_data).unwrap();
                ControlMessage::TimestampNs { sec: timespec.tv_sec, nsec: timespec.tv_nsec }
            }
            _ => panic!(
                "ZXIO produced unexpected cmsg level={}, type={}",
                header.cmsg_level, header.cmsg_type
            ),
        };
        result.push(msg);

        pos += align_cmsg_size(header.cmsg_len as usize);
    }
}

pub struct RecvMessageInfo {
    pub address: Vec<u8>,
    pub bytes_read: usize,
    pub message_length: usize,
    pub control_messages: Vec<ControlMessage>,
    pub flags: i32,
}

pub enum CreationMode {
    Never,
    AllowExisting,
    Always,
}

impl From<CreationMode> for zxio::zxio_creation_mode_t {
    fn from(value: CreationMode) -> Self {
        match value {
            CreationMode::Never => zxio::ZXIO_CREATION_MODE_NEVER,
            CreationMode::AllowExisting => zxio::ZXIO_CREATION_MODE_ALLOW_EXISTING,
            CreationMode::Always => zxio::ZXIO_CREATION_MODE_ALWAYS,
        }
    }
}

/// Options for open2.
pub struct OpenOptions {
    /// If None, connects to a service.
    pub node_protocols: Option<fio::NodeProtocols>,

    /// Behaviour with respect ot existence. See fuchsia.io for precise semantics.
    pub mode: CreationMode,

    /// See fuchsia.io for semantics. If empty, then it is regarded as absent i.e. rights will be
    /// inherited.
    pub rights: fio::Operations,

    /// If an object is to be created, attributes that should be stored with the object at creation
    /// time. Not all servers support all attributes.
    pub create_attr: Option<zxio::zxio_node_attr>,
}

impl OpenOptions {
    /// Returns options to open a directory.
    pub fn directory(optional_rights: Option<fio::Operations>) -> Self {
        Self {
            node_protocols: Some(fio::NodeProtocols {
                directory: Some(fio::DirectoryProtocolOptions {
                    optional_rights,
                    ..Default::default()
                }),
                ..Default::default()
            }),
            ..Default::default()
        }
    }

    /// Returns options to open a file.
    pub fn file(flags: fio::FileProtocolFlags) -> Self {
        Self {
            node_protocols: Some(fio::NodeProtocols { file: Some(flags), ..Default::default() }),
            ..Default::default()
        }
    }
}

impl Default for OpenOptions {
    fn default() -> Self {
        Self {
            // Default to opening a node protocol.
            node_protocols: Some(fio::NodeProtocols::default()),
            mode: CreationMode::Never,
            rights: fio::Operations::empty(),
            create_attr: None,
        }
    }
}

/// Describes the mode of operation when setting an extended attribute.
#[derive(Copy, Clone, Debug)]
pub enum XattrSetMode {
    /// Create the extended attribute if it doesn't exist, replace the value if it does.
    Set = 1,
    /// Create the extended attribute if it doesn't exist, failing if it does.
    Create = 2,
    /// Replace the value of the extended attribute, failing if it doesn't exist.
    Replace = 3,
}

bitflags! {
    /// Describes the mode of operation when allocating disk space using Allocate.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct AllocateMode: u32 {
        const KEEP_SIZE = 1 << 0;
        const UNSHARE_RANGE = 1 << 1;
        const PUNCH_HOLE = 1 << 2;
        const COLLAPSE_RANGE = 1 << 3;
        const ZERO_RANGE = 1 << 4;
        const INSERT_RANGE = 1 << 5;
    }
}

const_assert_eq!(AllocateMode::KEEP_SIZE.bits(), zxio::ZXIO_ALLOCATE_KEEP_SIZE);
const_assert_eq!(AllocateMode::UNSHARE_RANGE.bits(), zxio::ZXIO_ALLOCATE_UNSHARE_RANGE);
const_assert_eq!(AllocateMode::PUNCH_HOLE.bits(), zxio::ZXIO_ALLOCATE_PUNCH_HOLE);
const_assert_eq!(AllocateMode::COLLAPSE_RANGE.bits(), zxio::ZXIO_ALLOCATE_COLLAPSE_RANGE);
const_assert_eq!(AllocateMode::ZERO_RANGE.bits(), zxio::ZXIO_ALLOCATE_ZERO_RANGE);
const_assert_eq!(AllocateMode::INSERT_RANGE.bits(), zxio::ZXIO_ALLOCATE_INSERT_RANGE);

// `ZxioStorage` is marked as `PhantomPinned` in order to prevent unsafe moves
// of the `zxio_storage_t`, because it may store self-referential types defined
// in zxio.
#[derive(Default)]
struct ZxioStorage {
    storage: zxio::zxio_storage_t,
    _pin: std::marker::PhantomPinned,
}

/// A handle to a zxio object.
///
/// Note: the underlying storage backing the object is pinned on the heap
/// because it can contain self referential data.
pub struct Zxio {
    inner: Pin<Box<ZxioStorage>>,
}

impl Default for Zxio {
    fn default() -> Self {
        Self { inner: Box::pin(ZxioStorage::default()) }
    }
}

impl std::fmt::Debug for Zxio {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Zxio").finish()
    }
}

/// A trait that provides functionality to connect a channel to a FIDL service.
//
// TODO(https://github.com/rust-lang/rust/issues/44291): allow clients to pass
// in a more general function pointer (`fn(&str, zx::Channel) -> zx::Status`)
// rather than having to implement this trait.
pub trait ServiceConnector {
    /// Returns a channel to the service named by `service_name`.
    fn connect(service_name: &str) -> Result<&'static zx::Channel, zx::Status>;
}

/// Sets `provider_handle` to a handle to the service named by `service_name`.
///
/// This function is intended to be passed to zxio_socket().
///
/// SAFETY: Dereferences the raw pointers `service_name` and `provider_handle`.
unsafe extern "C" fn service_connector<S: ServiceConnector>(
    service_name: *const c_char,
    provider_handle: *mut zx_handle_t,
) -> zx_status_t {
    let status: zx::Status = (|| {
        let service_name = CStr::from_ptr(service_name)
            .to_str()
            .map_err(|std::str::Utf8Error { .. }| zx::Status::INVALID_ARGS)?;

        S::connect(service_name).map(|channel| {
            *provider_handle = channel.raw_handle();
        })
    })()
    .into();
    status.into_raw()
}

/// Sets `out_storage` as the zxio_storage of `out_context`.
///
/// This function is intended to be passed to zxio_socket().
///
/// SAFETY: Dereferences the raw pointer `out_storage`.
unsafe extern "C" fn storage_allocator(
    _type: zxio_object_type_t,
    out_storage: *mut *mut zxio_storage_t,
    out_context: *mut *mut c_void,
) -> zx_status_t {
    let zxio_ptr_ptr = out_context as *mut *mut zxio_storage_t;
    let status: zx::Status = (|| {
        if let Some(zxio_ptr) = zxio_ptr_ptr.as_mut() {
            if let Some(zxio) = zxio_ptr.as_mut() {
                *out_storage = zxio;
                return Ok(());
            }
        }
        Err(zx::Status::NO_MEMORY)
    })()
    .into();
    status.into_raw()
}

pub const ZXIO_ROOT_HASH_LENGTH: usize = 64;

impl Zxio {
    pub fn new_socket<S: ServiceConnector>(
        domain: c_int,
        socket_type: c_int,
        protocol: c_int,
    ) -> Result<Result<Self, ZxioErrorCode>, zx::Status> {
        let zxio = Zxio::default();
        let mut out_context = zxio.as_storage_ptr() as *mut c_void;
        let mut out_code = 0;

        let status = unsafe {
            zxio::zxio_socket(
                Some(service_connector::<S>),
                domain,
                socket_type,
                protocol,
                Some(storage_allocator),
                &mut out_context as *mut *mut c_void,
                &mut out_code,
            )
        };
        zx::ok(status)?;
        match out_code {
            0 => Ok(Ok(zxio)),
            _ => Ok(Err(ZxioErrorCode(out_code))),
        }
    }

    fn as_ptr(&self) -> *mut zxio::zxio_t {
        &self.inner.storage.io as *const zxio::zxio_t as *mut zxio::zxio_t
    }

    fn as_storage_ptr(&self) -> *mut zxio::zxio_storage_t {
        &self.inner.storage as *const zxio::zxio_storage_t as *mut zxio::zxio_storage_t
    }

    pub fn create(handle: zx::Handle) -> Result<Zxio, zx::Status> {
        let zxio = Zxio::default();
        let status = unsafe { zxio::zxio_create(handle.into_raw(), zxio.as_storage_ptr()) };
        zx::ok(status)?;
        Ok(zxio)
    }

    pub fn create_with_on_open(handle: zx::Handle) -> Result<Zxio, zx::Status> {
        let zxio = Zxio::default();
        let status =
            unsafe { zxio::zxio_create_with_on_open(handle.into_raw(), zxio.as_storage_ptr()) };
        zx::ok(status)?;
        Ok(zxio)
    }

    pub fn release(self) -> Result<zx::Handle, zx::Status> {
        let mut handle = 0;
        let status = unsafe { zxio::zxio_release(self.as_ptr(), &mut handle) };
        zx::ok(status)?;
        unsafe { Ok(zx::Handle::from_raw(handle)) }
    }

    pub fn open(&self, flags: fio::OpenFlags, path: &str) -> Result<Self, zx::Status> {
        let zxio = Zxio::default();
        let status = unsafe {
            zxio::zxio_open(
                self.as_ptr(),
                flags.bits(),
                path.as_ptr() as *const c_char,
                path.len(),
                zxio.as_storage_ptr(),
            )
        };
        zx::ok(status)?;
        Ok(zxio)
    }

    pub fn open2(
        &self,
        path: &str,
        options: OpenOptions,
        attributes: Option<&mut zxio_node_attributes_t>,
    ) -> Result<Self, zx::Status> {
        let zxio = Zxio::default();

        let mut open_options = zxio::zxio_open_options::default();
        if let Some(p) = options.node_protocols {
            if let Some(dir_options) = p.directory {
                open_options.protocols |= ZXIO_NODE_PROTOCOL_DIRECTORY;
                open_options.optional_rights =
                    dir_options.optional_rights.unwrap_or(fio::Operations::empty()).bits();
            }
            if let Some(file_flags) = p.file {
                open_options.protocols |= ZXIO_NODE_PROTOCOL_FILE;
                open_options.file_flags = file_flags.bits();
            }
            if p.symlink.is_some() {
                open_options.protocols |= ZXIO_NODE_PROTOCOL_SYMLINK;
            }
            if open_options.protocols == 0 {
                // Ask for any protocol.
                open_options.protocols = ZXIO_NODE_PROTOCOL_DIRECTORY
                    | ZXIO_NODE_PROTOCOL_FILE
                    | ZXIO_NODE_PROTOCOL_SYMLINK;
            }
            open_options.mode = options.mode as u32;
            open_options.rights = options.rights.bits();
            open_options.create_attr =
                options.create_attr.as_ref().map(|a| a as *const _).unwrap_or(std::ptr::null());
        } else {
            open_options.protocols = ZXIO_NODE_PROTOCOL_CONNECTOR;
        }

        let status = unsafe {
            zxio::zxio_open2(
                self.as_ptr(),
                path.as_ptr() as *const c_char,
                path.len(),
                &open_options,
                attributes.map(|a| a as *mut _).unwrap_or(std::ptr::null_mut()),
                zxio.as_storage_ptr(),
            )
        };
        zx::ok(status)?;
        Ok(zxio)
    }

    pub fn create_with_on_representation(
        handle: zx::Handle,
        attributes: Option<&mut zxio_node_attributes_t>,
    ) -> Result<Zxio, zx::Status> {
        let zxio = Zxio::default();
        let status = unsafe {
            zxio::zxio_create_with_on_representation(
                handle.into_raw(),
                attributes.map(|a| a as *mut _).unwrap_or(std::ptr::null_mut()),
                zxio.as_storage_ptr(),
            )
        };
        zx::ok(status)?;
        Ok(zxio)
    }

    /// Opens a limited node connection (similar to O_PATH).
    pub fn open_node(
        &self,
        path: &str,
        node_flags: fio::NodeProtocolFlags,
        attributes: Option<&mut zxio_node_attributes_t>,
    ) -> Result<Self, zx::Status> {
        let zxio = Zxio::default();
        let status = unsafe {
            zxio::zxio_open2(
                self.as_ptr(),
                path.as_ptr() as *const c_char,
                path.len(),
                &zxio::zxio_open_options {
                    node_flags: node_flags.bits(),
                    mode: CreationMode::Never.into(),
                    ..Default::default()
                },
                attributes.map(|a| a as *mut _).unwrap_or(std::ptr::null_mut()),
                zxio.as_storage_ptr(),
            )
        };
        zx::ok(status)?;
        Ok(zxio)
    }

    pub fn unlink(&self, name: &str, flags: fio::UnlinkFlags) -> Result<(), zx::Status> {
        let flags_bits = flags.bits().try_into().map_err(|_| zx::Status::INVALID_ARGS)?;
        let status = unsafe {
            zxio::zxio_unlink(self.as_ptr(), name.as_ptr() as *const c_char, name.len(), flags_bits)
        };
        zx::ok(status)
    }

    pub fn read(&self, data: &mut [u8]) -> Result<usize, zx::Status> {
        let flags = zxio::zxio_flags_t::default();
        let mut actual = 0usize;
        let status = unsafe {
            zxio::zxio_read(
                self.as_ptr(),
                data.as_ptr() as *mut c_void,
                data.len(),
                flags,
                &mut actual,
            )
        };
        zx::ok(status)?;
        Ok(actual)
    }

    /// Performs a vectorized read, returning the number of bytes read to `data`.
    ///
    /// # Safety
    ///
    /// The caller must check the returned `Result` to make sure the buffers
    /// provided are valid. The caller must provide pointers that are compatible
    /// with the backing implementation of zxio.
    ///
    /// This call allows writing to arbitrary memory locations. It is up to the
    /// caller to make sure that calling this method does not result in undefined
    /// behaviour.
    pub unsafe fn readv(&self, data: &[zxio::zx_iovec]) -> Result<usize, zx::Status> {
        let flags = zxio::zxio_flags_t::default();
        let mut actual = 0usize;
        let status = zxio::zxio_readv(
            self.as_ptr(),
            data.as_ptr() as *const zxio::zx_iovec,
            data.len(),
            flags,
            &mut actual,
        );
        zx::ok(status)?;
        Ok(actual)
    }

    pub fn clone(&self) -> Result<Zxio, zx::Status> {
        let mut handle = 0;
        let status = unsafe { zxio::zxio_clone(self.as_ptr(), &mut handle) };
        zx::ok(status)?;
        unsafe { Zxio::create(zx::Handle::from_raw(handle)) }
    }

    pub fn read_at(&self, offset: u64, data: &mut [u8]) -> Result<usize, zx::Status> {
        let flags = zxio::zxio_flags_t::default();
        let mut actual = 0usize;
        let status = unsafe {
            zxio::zxio_read_at(
                self.as_ptr(),
                offset,
                data.as_ptr() as *mut c_void,
                data.len(),
                flags,
                &mut actual,
            )
        };
        zx::ok(status)?;
        Ok(actual)
    }

    /// Performs a vectorized read at an offset, returning the number of bytes
    /// read to `data`.
    ///
    /// # Safety
    ///
    /// The caller must check the returned `Result` to make sure the buffers
    /// provided are valid. The caller must provide pointers that are compatible
    /// with the backing implementation of zxio.
    ///
    /// This call allows writing to arbitrary memory locations. It is up to the
    /// caller to make sure that calling this method does not result in undefined
    /// behaviour.
    pub unsafe fn readv_at(
        &self,
        offset: u64,
        data: &[zxio::zx_iovec],
    ) -> Result<usize, zx::Status> {
        let flags = zxio::zxio_flags_t::default();
        let mut actual = 0usize;
        let status = zxio::zxio_readv_at(
            self.as_ptr(),
            offset,
            data.as_ptr() as *const zxio::zx_iovec,
            data.len(),
            flags,
            &mut actual,
        );
        zx::ok(status)?;
        Ok(actual)
    }

    pub fn write(&self, data: &[u8]) -> Result<usize, zx::Status> {
        let flags = zxio::zxio_flags_t::default();
        let mut actual = 0;
        let status = unsafe {
            zxio::zxio_write(
                self.as_ptr(),
                data.as_ptr() as *const c_void,
                data.len(),
                flags,
                &mut actual,
            )
        };
        zx::ok(status)?;
        Ok(actual)
    }

    /// Performs a vectorized write, returning the number of bytes written from
    /// `data`.
    ///
    /// # Safety
    ///
    /// The caller must check the returned `Result` to make sure the buffers
    /// provided are valid. The caller must provide pointers that are compatible
    /// with the backing implementation of zxio.
    ///
    /// This call allows reading from arbitrary memory locations. It is up to the
    /// caller to make sure that calling this method does not result in undefined
    /// behaviour.
    pub unsafe fn writev(&self, data: &[zxio::zx_iovec]) -> Result<usize, zx::Status> {
        let flags = zxio::zxio_flags_t::default();
        let mut actual = 0;
        let status = zxio::zxio_writev(
            self.as_ptr(),
            data.as_ptr() as *const zxio::zx_iovec,
            data.len(),
            flags,
            &mut actual,
        );
        zx::ok(status)?;
        Ok(actual)
    }

    pub fn write_at(&self, offset: u64, data: &[u8]) -> Result<usize, zx::Status> {
        let flags = zxio::zxio_flags_t::default();
        let mut actual = 0;
        let status = unsafe {
            zxio::zxio_write_at(
                self.as_ptr(),
                offset,
                data.as_ptr() as *const c_void,
                data.len(),
                flags,
                &mut actual,
            )
        };
        zx::ok(status)?;
        Ok(actual)
    }

    /// Performs a vectorized write at an offset, returning the number of bytes
    /// written from `data`.
    ///
    /// # Safety
    ///
    /// The caller must check the returned `Result` to make sure the buffers
    /// provided are valid. The caller must provide pointers that are compatible
    /// with the backing implementation of zxio.
    ///
    /// This call allows reading from arbitrary memory locations. It is up to the
    /// caller to make sure that calling this method does not result in undefined
    /// behaviour.
    pub unsafe fn writev_at(
        &self,
        offset: u64,
        data: &[zxio::zx_iovec],
    ) -> Result<usize, zx::Status> {
        let flags = zxio::zxio_flags_t::default();
        let mut actual = 0;
        let status = zxio::zxio_writev_at(
            self.as_ptr(),
            offset,
            data.as_ptr() as *const zxio::zx_iovec,
            data.len(),
            flags,
            &mut actual,
        );
        zx::ok(status)?;
        Ok(actual)
    }

    pub fn truncate(&self, length: u64) -> Result<(), zx::Status> {
        let status = unsafe { zxio::zxio_truncate(self.as_ptr(), length) };
        zx::ok(status)?;
        Ok(())
    }

    pub fn seek(&self, seek_origin: SeekOrigin, offset: i64) -> Result<usize, zx::Status> {
        let mut result = 0;
        let status =
            unsafe { zxio::zxio_seek(self.as_ptr(), seek_origin.into(), offset, &mut result) };
        zx::ok(status)?;
        Ok(result)
    }

    pub fn vmo_get(&self, flags: zx::VmarFlags) -> Result<zx::Vmo, zx::Status> {
        let mut vmo = 0;
        let status = unsafe { zxio::zxio_vmo_get(self.as_ptr(), flags.bits(), &mut vmo) };
        zx::ok(status)?;
        let handle = unsafe { zx::Handle::from_raw(vmo) };
        Ok(zx::Vmo::from(handle))
    }

    fn node_attributes_from_query(
        &self,
        query: zxio_node_attr_has_t,
        fsverity_root_hash: Option<&mut [u8; ZXIO_ROOT_HASH_LENGTH]>,
    ) -> zxio_node_attributes_t {
        if let Some(fsverity_root_hash) = fsverity_root_hash {
            zxio_node_attributes_t {
                has: query,
                fsverity_root_hash: fsverity_root_hash as *mut u8,
                ..Default::default()
            }
        } else {
            zxio_node_attributes_t { has: query, ..Default::default() }
        }
    }

    pub fn attr_get(
        &self,
        query: zxio_node_attr_has_t,
    ) -> Result<zxio_node_attributes_t, zx::Status> {
        let mut attributes = self.node_attributes_from_query(query, None);
        let status = unsafe { zxio::zxio_attr_get(self.as_ptr(), &mut attributes) };
        zx::ok(status)?;
        Ok(attributes)
    }

    /// Assumes that the caller has set `query.fsverity_root_hash` to true.
    pub fn attr_get_with_root_hash(
        &self,
        query: zxio_node_attr_has_t,
        fsverity_root_hash: &mut [u8; ZXIO_ROOT_HASH_LENGTH],
    ) -> Result<zxio_node_attributes_t, zx::Status> {
        let mut attributes = self.node_attributes_from_query(query, Some(fsverity_root_hash));
        let status = unsafe { zxio::zxio_attr_get(self.as_ptr(), &mut attributes) };
        zx::ok(status)?;
        Ok(attributes)
    }

    pub fn attr_set(&self, attributes: &zxio_node_attributes_t) -> Result<(), zx::Status> {
        let status = unsafe { zxio::zxio_attr_set(self.as_ptr(), attributes) };
        zx::ok(status)?;
        Ok(())
    }

    pub fn enable_verity(&self, descriptor: &zxio_fsverity_descriptor_t) -> Result<(), zx::Status> {
        let status = unsafe { zxio::zxio_enable_verity(self.as_ptr(), descriptor) };
        zx::ok(status)?;
        Ok(())
    }

    pub fn rename(
        &self,
        old_path: &str,
        new_directory: &Zxio,
        new_path: &str,
    ) -> Result<(), zx::Status> {
        let mut handle = zx::sys::ZX_HANDLE_INVALID;
        let status = unsafe { zxio::zxio_token_get(new_directory.as_ptr(), &mut handle) };
        zx::ok(status)?;
        let status = unsafe {
            zxio::zxio_rename(
                self.as_ptr(),
                old_path.as_ptr() as *const c_char,
                old_path.len(),
                handle,
                new_path.as_ptr() as *const c_char,
                new_path.len(),
            )
        };
        zx::ok(status)?;
        Ok(())
    }

    pub fn wait_begin(
        &self,
        zxio_signals: zxio_signals_t,
    ) -> (zx::Unowned<'_, zx::Handle>, zx::Signals) {
        let mut handle = zx::sys::ZX_HANDLE_INVALID;
        let mut zx_signals = zx::sys::ZX_SIGNAL_NONE;
        unsafe { zxio::zxio_wait_begin(self.as_ptr(), zxio_signals, &mut handle, &mut zx_signals) };
        let handle = unsafe { zx::Unowned::<zx::Handle>::from_raw_handle(handle) };
        let signals = zx::Signals::from_bits_truncate(zx_signals);
        (handle, signals)
    }

    pub fn wait_end(&self, signals: zx::Signals) -> zxio_signals_t {
        let mut zxio_signals = ZxioSignals::NONE.bits();
        unsafe {
            zxio::zxio_wait_end(self.as_ptr(), signals.bits(), &mut zxio_signals);
        }
        zxio_signals
    }

    pub fn create_dirent_iterator(&self) -> Result<DirentIterator<'_>, zx::Status> {
        let mut zxio_iterator = Box::default();
        let status = unsafe { zxio::zxio_dirent_iterator_init(&mut *zxio_iterator, self.as_ptr()) };
        zx::ok(status)?;
        let iterator =
            DirentIterator { iterator: zxio_iterator, _directory: PhantomData, finished: false };
        Ok(iterator)
    }

    pub fn connect(&self, addr: &[u8]) -> Result<Result<(), ZxioErrorCode>, zx::Status> {
        let mut out_code = 0;
        let status = unsafe {
            zxio::zxio_connect(
                self.as_ptr(),
                addr.as_ptr() as *const sockaddr,
                addr.len() as socklen_t,
                &mut out_code,
            )
        };
        zx::ok(status)?;
        match out_code {
            0 => Ok(Ok(())),
            _ => Ok(Err(ZxioErrorCode(out_code))),
        }
    }

    pub fn bind(&self, addr: &[u8]) -> Result<Result<(), ZxioErrorCode>, zx::Status> {
        let mut out_code = 0;
        let status = unsafe {
            zxio::zxio_bind(
                self.as_ptr(),
                addr.as_ptr() as *const sockaddr,
                addr.len() as socklen_t,
                &mut out_code,
            )
        };
        zx::ok(status)?;
        match out_code {
            0 => Ok(Ok(())),
            _ => Ok(Err(ZxioErrorCode(out_code))),
        }
    }

    pub fn listen(&self, backlog: i32) -> Result<Result<(), ZxioErrorCode>, zx::Status> {
        let mut out_code = 0;
        let status = unsafe { zxio::zxio_listen(self.as_ptr(), backlog as c_int, &mut out_code) };
        zx::ok(status)?;
        match out_code {
            0 => Ok(Ok(())),
            _ => Ok(Err(ZxioErrorCode(out_code))),
        }
    }

    pub fn accept(&self) -> Result<Result<Zxio, ZxioErrorCode>, zx::Status> {
        let mut addrlen = std::mem::size_of::<sockaddr_storage>() as socklen_t;
        let mut addr = vec![0u8; addrlen as usize];
        let zxio = Zxio::default();
        let mut out_code = 0;
        let status = unsafe {
            zxio::zxio_accept(
                self.as_ptr(),
                addr.as_mut_ptr() as *mut sockaddr,
                &mut addrlen,
                zxio.as_storage_ptr(),
                &mut out_code,
            )
        };
        zx::ok(status)?;
        match out_code {
            0 => Ok(Ok(zxio)),
            _ => Ok(Err(ZxioErrorCode(out_code))),
        }
    }

    pub fn getsockname(&self) -> Result<Result<Vec<u8>, ZxioErrorCode>, zx::Status> {
        let mut addrlen = std::mem::size_of::<sockaddr_storage>() as socklen_t;
        let mut addr = vec![0u8; addrlen as usize];
        let mut out_code = 0;
        let status = unsafe {
            zxio::zxio_getsockname(
                self.as_ptr(),
                addr.as_mut_ptr() as *mut sockaddr,
                &mut addrlen,
                &mut out_code,
            )
        };
        zx::ok(status)?;
        match out_code {
            0 => Ok(Ok(addr[..addrlen as usize].to_vec())),
            _ => Ok(Err(ZxioErrorCode(out_code))),
        }
    }

    pub fn getpeername(&self) -> Result<Result<Vec<u8>, ZxioErrorCode>, zx::Status> {
        let mut addrlen = std::mem::size_of::<sockaddr_storage>() as socklen_t;
        let mut addr = vec![0u8; addrlen as usize];
        let mut out_code = 0;
        let status = unsafe {
            zxio::zxio_getpeername(
                self.as_ptr(),
                addr.as_mut_ptr() as *mut sockaddr,
                &mut addrlen,
                &mut out_code,
            )
        };
        zx::ok(status)?;
        match out_code {
            0 => Ok(Ok(addr[..addrlen as usize].to_vec())),
            _ => Ok(Err(ZxioErrorCode(out_code))),
        }
    }

    pub fn getsockopt(
        &self,
        level: u32,
        optname: u32,
        mut optlen: socklen_t,
    ) -> Result<Result<Vec<u8>, ZxioErrorCode>, zx::Status> {
        let mut optval = vec![0u8; optlen as usize];
        let mut out_code = 0;
        let status = unsafe {
            zxio::zxio_getsockopt(
                self.as_ptr(),
                level as c_int,
                optname as c_int,
                optval.as_mut_ptr() as *mut c_void,
                &mut optlen,
                &mut out_code,
            )
        };
        zx::ok(status)?;
        match out_code {
            0 => Ok(Ok(optval[..optlen as usize].to_vec())),
            _ => Ok(Err(ZxioErrorCode(out_code))),
        }
    }

    pub fn setsockopt(
        &self,
        level: i32,
        optname: i32,
        optval: &[u8],
    ) -> Result<Result<(), ZxioErrorCode>, zx::Status> {
        let mut out_code = 0;
        let status = unsafe {
            zxio::zxio_setsockopt(
                self.as_ptr(),
                level,
                optname,
                optval.as_ptr() as *const c_void,
                optval.len() as socklen_t,
                &mut out_code,
            )
        };
        zx::ok(status)?;
        match out_code {
            0 => Ok(Ok(())),
            _ => Ok(Err(ZxioErrorCode(out_code))),
        }
    }

    pub fn shutdown(
        &self,
        flags: ZxioShutdownFlags,
    ) -> Result<Result<(), ZxioErrorCode>, zx::Status> {
        let mut out_code = 0;
        let status = unsafe { zxio::zxio_shutdown(self.as_ptr(), flags.bits(), &mut out_code) };
        zx::ok(status)?;
        match out_code {
            0 => Ok(Ok(())),
            _ => Ok(Err(ZxioErrorCode(out_code))),
        }
    }

    pub fn sendmsg(
        &self,
        addr: &mut [u8],
        buffer: &mut [zxio::iovec],
        cmsg: &[ControlMessage],
        flags: u32,
    ) -> Result<Result<usize, ZxioErrorCode>, zx::Status> {
        let mut msg = zxio::msghdr::default();
        msg.msg_name = match addr.len() {
            0 => std::ptr::null_mut() as *mut c_void,
            _ => addr.as_mut_ptr() as *mut c_void,
        };
        msg.msg_namelen = addr.len() as u32;

        msg.msg_iovlen =
            i32::try_from(buffer.len()).map_err(|_: TryFromIntError| zx::Status::INVALID_ARGS)?;
        msg.msg_iov = buffer.as_mut_ptr();

        let mut cmsg_buffer = serialize_control_messages(cmsg);
        msg.msg_control = cmsg_buffer.as_mut_ptr() as *mut c_void;
        msg.msg_controllen = cmsg_buffer.len() as u32;

        let mut out_code = 0;
        let mut out_actual = 0;

        let status = unsafe {
            zxio::zxio_sendmsg(self.as_ptr(), &msg, flags as c_int, &mut out_actual, &mut out_code)
        };

        zx::ok(status)?;
        match out_code {
            0 => Ok(Ok(out_actual)),
            _ => Ok(Err(ZxioErrorCode(out_code))),
        }
    }

    pub fn recvmsg(
        &self,
        buffer: &mut [zxio::iovec],
        flags: u32,
    ) -> Result<Result<RecvMessageInfo, ZxioErrorCode>, zx::Status> {
        let mut msg = msghdr::default();
        let mut addr = vec![0u8; std::mem::size_of::<sockaddr_storage>()];
        msg.msg_name = addr.as_mut_ptr() as *mut c_void;
        msg.msg_namelen = addr.len() as u32;

        let max_buffer_capacity = buffer.iter().map(|v| v.iov_len).sum();
        msg.msg_iovlen =
            i32::try_from(buffer.len()).map_err(|_: TryFromIntError| zx::Status::INVALID_ARGS)?;
        msg.msg_iov = buffer.as_mut_ptr();

        let mut cmsg_buffer = vec![0u8; MAX_CMSGS_BUFFER];
        msg.msg_control = cmsg_buffer.as_mut_ptr() as *mut c_void;
        msg.msg_controllen = cmsg_buffer.len() as u32;

        let mut out_code = 0;
        let mut out_actual = 0;
        let status = unsafe {
            zxio::zxio_recvmsg(
                self.as_ptr(),
                &mut msg,
                flags as c_int,
                &mut out_actual,
                &mut out_code,
            )
        };
        zx::ok(status)?;

        if out_code != 0 {
            return Ok(Err(ZxioErrorCode(out_code)));
        }

        let control_messages = parse_control_messages(&cmsg_buffer[..msg.msg_controllen as usize]);
        Ok(Ok(RecvMessageInfo {
            address: addr[..msg.msg_namelen as usize].to_vec(),
            bytes_read: std::cmp::min(max_buffer_capacity, out_actual),
            message_length: out_actual,
            control_messages,
            flags: msg.msg_flags,
        }))
    }

    pub fn read_link(&self) -> Result<&[u8], zx::Status> {
        let mut target = std::ptr::null();
        let mut target_len = 0;
        let status = unsafe { zxio::zxio_read_link(self.as_ptr(), &mut target, &mut target_len) };
        zx::ok(status)?;
        // SAFETY: target will live as long as the underlying zxio object lives.
        unsafe { Ok(std::slice::from_raw_parts(target, target_len)) }
    }

    pub fn create_symlink(&self, name: &str, target: &[u8]) -> Result<Zxio, zx::Status> {
        let name = name.as_bytes();
        let zxio = Zxio::default();
        let status = unsafe {
            zxio::zxio_create_symlink(
                self.as_ptr(),
                name.as_ptr() as *const c_char,
                name.len(),
                target.as_ptr(),
                target.len(),
                zxio.as_storage_ptr(),
            )
        };
        zx::ok(status)?;
        Ok(zxio)
    }

    pub fn xattr_list(&self) -> Result<Vec<Vec<u8>>, zx::Status> {
        unsafe extern "C" fn callback(context: *mut c_void, name: *const u8, name_len: usize) {
            let out_names = &mut *(context as *mut Vec<Vec<u8>>);
            let name_slice = std::slice::from_raw_parts(name, name_len);
            out_names.push(name_slice.to_vec());
        }
        let mut out_names = Vec::new();
        let status = unsafe {
            zxio::zxio_xattr_list(
                self.as_ptr(),
                Some(callback),
                &mut out_names as *mut _ as *mut c_void,
            )
        };
        zx::ok(status)?;
        Ok(out_names)
    }

    pub fn xattr_get(&self, name: &[u8]) -> Result<Vec<u8>, zx::Status> {
        unsafe extern "C" fn callback(
            context: *mut c_void,
            data: zxio::zxio_xattr_data_t,
        ) -> zx_status_t {
            let out_value = &mut *(context as *mut Vec<u8>);
            if data.data.is_null() {
                let value_vmo = zx::Unowned::<'_, zx::Vmo>::from_raw_handle(data.vmo);
                match value_vmo.read_to_vec(0, data.len as u64) {
                    Ok(vec) => *out_value = vec,
                    Err(status) => return status.into_raw(),
                }
            } else {
                let value_slice = std::slice::from_raw_parts(data.data as *mut u8, data.len);
                out_value.extend_from_slice(value_slice);
            }
            zx::Status::OK.into_raw()
        }
        let mut out_value = Vec::new();
        let status = unsafe {
            zxio::zxio_xattr_get(
                self.as_ptr(),
                name.as_ptr(),
                name.len(),
                Some(callback),
                &mut out_value as *mut _ as *mut c_void,
            )
        };
        zx::ok(status)?;
        Ok(out_value)
    }

    pub fn xattr_set(
        &self,
        name: &[u8],
        value: &[u8],
        mode: XattrSetMode,
    ) -> Result<(), zx::Status> {
        let status = unsafe {
            zxio::zxio_xattr_set(
                self.as_ptr(),
                name.as_ptr(),
                name.len(),
                value.as_ptr(),
                value.len(),
                mode as u32,
            )
        };
        zx::ok(status)
    }

    pub fn xattr_remove(&self, name: &[u8]) -> Result<(), zx::Status> {
        zx::ok(unsafe { zxio::zxio_xattr_remove(self.as_ptr(), name.as_ptr(), name.len()) })
    }

    pub fn link_into(&self, target_dir: &Zxio, name: &str) -> Result<(), zx::Status> {
        let mut handle = zx::sys::ZX_HANDLE_INVALID;
        zx::ok(unsafe { zxio::zxio_token_get(target_dir.as_ptr(), &mut handle) })?;
        zx::ok(unsafe {
            zxio::zxio_link_into(self.as_ptr(), handle, name.as_ptr() as *const c_char, name.len())
        })
    }

    pub fn allocate(&self, offset: u64, len: u64, mode: AllocateMode) -> Result<(), zx::Status> {
        let status = unsafe { zxio::zxio_allocate(self.as_ptr(), offset, len, mode.bits()) };
        zx::ok(status)
    }
}

impl Drop for Zxio {
    fn drop(&mut self) {
        unsafe {
            zxio::zxio_close(self.as_ptr(), true);
        };
    }
}

enum NodeKind {
    File,
    Directory,
    Unknown,
}

impl NodeKind {
    fn from(info: &fio::NodeInfoDeprecated) -> NodeKind {
        match info {
            fio::NodeInfoDeprecated::File(_) => NodeKind::File,
            fio::NodeInfoDeprecated::Directory(_) => NodeKind::Directory,
            _ => NodeKind::Unknown,
        }
    }

    fn from2(representation: &fio::Representation) -> NodeKind {
        match representation {
            fio::Representation::File(_) => NodeKind::File,
            fio::Representation::Directory(_) => NodeKind::Directory,
            _ => NodeKind::Unknown,
        }
    }
}

/// A fuchsia.io.Node along with its NodeInfoDeprecated.
///
/// The NodeInfoDeprecated provides information about the concrete protocol spoken by the
/// node.
struct DescribedNode {
    node: fio::NodeSynchronousProxy,
    kind: NodeKind,
}

/// Open the given path in the given directory.
///
/// The semantics for the flags argument are defined by the
/// fuchsia.io/Directory.Open message.
///
/// This function adds OPEN_FLAG_DESCRIBE to the given flags and then blocks
/// until the directory describes the newly opened node.
///
/// Returns the opened Node, along with its NodeInfoDeprecated, or an error.
fn directory_open(
    directory: &fio::DirectorySynchronousProxy,
    path: &str,
    flags: fio::OpenFlags,
    deadline: zx::Time,
) -> Result<DescribedNode, zx::Status> {
    let flags = flags | fio::OpenFlags::DESCRIBE;

    let (client_end, server_end) = zx::Channel::create();
    directory
        .open(flags, fio::ModeType::empty(), path, ServerEnd::new(server_end))
        .map_err(|_| zx::Status::IO)?;
    let node = fio::NodeSynchronousProxy::new(client_end);

    match node.wait_for_event(deadline).map_err(|_| zx::Status::IO)? {
        fio::NodeEvent::OnOpen_ { s: status, info } => {
            zx::Status::ok(status)?;
            Ok(DescribedNode { node, kind: NodeKind::from(&*info.ok_or(zx::Status::IO)?) })
        }
        fio::NodeEvent::OnRepresentation { payload } => {
            Ok(DescribedNode { node, kind: NodeKind::from2(&payload) })
        }
    }
}

/// Open a VMO at the given path in the given directory.
///
/// The semantics for the vmo_flags argument are defined by the
/// fuchsia.io/File.GetBackingMemory message (i.e., VmoFlags::*).
///
/// If the node at the given path is not a VMO, then this function returns
/// a zx::Status::IO error.
pub fn directory_open_vmo(
    directory: &fio::DirectorySynchronousProxy,
    path: &str,
    vmo_flags: fio::VmoFlags,
    deadline: zx::Time,
) -> Result<zx::Vmo, zx::Status> {
    let mut open_flags = fio::OpenFlags::empty();
    if vmo_flags.contains(fio::VmoFlags::WRITE) {
        open_flags |= fio::OpenFlags::RIGHT_WRITABLE;
    }
    if vmo_flags.contains(fio::VmoFlags::READ) {
        open_flags |= fio::OpenFlags::RIGHT_READABLE;
    }
    if vmo_flags.contains(fio::VmoFlags::EXECUTE) {
        open_flags |= fio::OpenFlags::RIGHT_EXECUTABLE;
    }

    let description = directory_open(directory, path, open_flags, deadline)?;
    let file = match description.kind {
        NodeKind::File => fio::FileSynchronousProxy::new(description.node.into_channel()),
        _ => return Err(zx::Status::IO),
    };

    let vmo = file
        .get_backing_memory(vmo_flags, deadline)
        .map_err(|_: fidl::Error| zx::Status::IO)?
        .map_err(zx::Status::from_raw)?;
    Ok(vmo)
}

/// Read the content of the file at the given path in the given directory.
///
/// If the node at the given path is not a file, then this function returns
/// a zx::Status::IO error.
pub fn directory_read_file(
    directory: &fio::DirectorySynchronousProxy,
    path: &str,
    deadline: zx::Time,
) -> Result<Vec<u8>, zx::Status> {
    let description = directory_open(directory, path, fio::OpenFlags::RIGHT_READABLE, deadline)?;
    let file = match description.kind {
        NodeKind::File => fio::FileSynchronousProxy::new(description.node.into_channel()),
        _ => return Err(zx::Status::IO),
    };

    let mut result = Vec::new();
    loop {
        let mut data = file
            .read(fio::MAX_TRANSFER_SIZE, deadline)
            .map_err(|_: fidl::Error| zx::Status::IO)?
            .map_err(zx::Status::from_raw)?;
        let finished = (data.len() as u64) < fio::MAX_TRANSFER_SIZE;
        result.append(&mut data);
        if finished {
            return Ok(result);
        }
    }
}

/// Open the given path in the given directory without blocking.
///
/// A zx::Channel to the opened node is returned (or an error).
///
/// It is an error to supply the OPEN_FLAG_DESCRIBE flag in flags.
///
/// This function will "succeed" even if the given path does not exist in the
/// given directory because this function does not wait for the directory to
/// confirm that the path exists.
pub fn directory_open_async(
    directory: &fio::DirectorySynchronousProxy,
    path: &str,
    flags: fio::OpenFlags,
) -> Result<zx::Channel, zx::Status> {
    if flags.intersects(fio::OpenFlags::DESCRIBE) {
        return Err(zx::Status::INVALID_ARGS);
    }

    let (client_end, server_end) = zx::Channel::create();
    directory
        .open(flags, fio::ModeType::empty(), path, ServerEnd::new(server_end))
        .map_err(|_| zx::Status::IO)?;
    Ok(client_end)
}

/// Open a directory at the given path in the given directory without blocking.
///
/// This function adds the OPEN_FLAG_DIRECTORY flag
/// to ensure that the open operation completes only
/// if the given path is actually a directory, which means clients can start
/// using the returned DirectorySynchronousProxy immediately without waiting
/// for the server to complete the operation.
///
/// This function will "succeed" even if the given path does not exist in the
/// given directory or if the path is not a directory because this function
/// does not wait for the directory to confirm that the path exists and is a
/// directory.
pub fn directory_open_directory_async(
    directory: &fio::DirectorySynchronousProxy,
    path: &str,
    flags: fio::OpenFlags,
) -> Result<fio::DirectorySynchronousProxy, zx::Status> {
    let flags = flags | fio::OpenFlags::DIRECTORY;
    let client = directory_open_async(directory, path, flags)?;
    Ok(fio::DirectorySynchronousProxy::new(client))
}

pub fn directory_clone(
    directory: &fio::DirectorySynchronousProxy,
    flags: fio::OpenFlags,
) -> Result<fio::DirectorySynchronousProxy, zx::Status> {
    let (client_end, server_end) = zx::Channel::create();
    directory.clone(flags, ServerEnd::new(server_end)).map_err(|_| zx::Status::IO)?;
    Ok(fio::DirectorySynchronousProxy::new(client_end))
}

pub fn file_clone(
    file: &fio::FileSynchronousProxy,
    flags: fio::OpenFlags,
) -> Result<fio::FileSynchronousProxy, zx::Status> {
    let (client_end, server_end) = zx::Channel::create();
    file.clone(flags, ServerEnd::new(server_end)).map_err(|_| zx::Status::IO)?;
    Ok(fio::FileSynchronousProxy::new(client_end))
}

#[cfg(test)]
mod test {
    use super::*;

    use anyhow::Error;
    use fidl::endpoints::Proxy as _;
    use fidl_fuchsia_io as fio;
    use fuchsia_async as fasync;
    use fuchsia_fs::directory;

    fn open_pkg() -> fio::DirectorySynchronousProxy {
        let pkg_proxy = directory::open_in_namespace(
            "/pkg",
            fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_EXECUTABLE,
        )
        .expect("failed to open /pkg");
        fio::DirectorySynchronousProxy::new(
            pkg_proxy
                .into_channel()
                .expect("failed to convert proxy into channel")
                .into_zx_channel(),
        )
    }

    #[fasync::run_singlethreaded(test)]
    async fn test_directory_open() -> Result<(), Error> {
        let pkg = open_pkg();
        let description = directory_open(
            &pkg,
            "bin/syncio_lib_test",
            fio::OpenFlags::RIGHT_READABLE,
            zx::Time::INFINITE,
        )?;
        assert!(match description.kind {
            NodeKind::File => true,
            _ => false,
        });
        Ok(())
    }

    #[fasync::run_singlethreaded(test)]
    async fn test_directory_open_vmo() -> Result<(), Error> {
        let pkg = open_pkg();
        let vmo = directory_open_vmo(
            &pkg,
            "bin/syncio_lib_test",
            fio::VmoFlags::READ | fio::VmoFlags::EXECUTE,
            zx::Time::INFINITE,
        )?;
        assert!(!vmo.is_invalid_handle());

        let info = vmo.basic_info()?;
        assert_eq!(zx::Rights::READ, info.rights & zx::Rights::READ);
        assert_eq!(zx::Rights::EXECUTE, info.rights & zx::Rights::EXECUTE);
        Ok(())
    }

    #[fasync::run_singlethreaded(test)]
    async fn test_directory_read_file() -> Result<(), Error> {
        let pkg = open_pkg();
        let data = directory_read_file(&pkg, "bin/syncio_lib_test", zx::Time::INFINITE)?;

        assert!(!data.is_empty());
        Ok(())
    }

    #[fasync::run_singlethreaded(test)]
    async fn test_directory_open_directory_async() -> Result<(), Error> {
        let pkg = open_pkg();
        let bin = directory_open_directory_async(
            &pkg,
            "bin",
            fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_EXECUTABLE,
        )?;
        let vmo = directory_open_vmo(
            &bin,
            "syncio_lib_test",
            fio::VmoFlags::READ | fio::VmoFlags::EXECUTE,
            zx::Time::INFINITE,
        )?;
        assert!(!vmo.is_invalid_handle());

        let info = vmo.basic_info()?;
        assert_eq!(zx::Rights::READ, info.rights & zx::Rights::READ);
        assert_eq!(zx::Rights::EXECUTE, info.rights & zx::Rights::EXECUTE);
        Ok(())
    }

    #[fasync::run_singlethreaded(test)]
    async fn test_directory_open_zxio_async() -> Result<(), Error> {
        let pkg_proxy = directory::open_in_namespace(
            "/pkg",
            fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_EXECUTABLE,
        )
        .expect("failed to open /pkg");
        let zx_channel = pkg_proxy
            .into_channel()
            .expect("failed to convert proxy into channel")
            .into_zx_channel();
        let storage = zxio::zxio_storage_t::default();
        let status = unsafe {
            zxio::zxio_create(
                zx_channel.into_raw(),
                &storage as *const zxio::zxio_storage_t as *mut zxio::zxio_storage_t,
            )
        };
        assert_eq!(status, zx::sys::ZX_OK);
        let io = &storage.io as *const zxio::zxio_t as *mut zxio::zxio_t;
        let close_status = unsafe { zxio::zxio_close(io, true) };
        assert_eq!(close_status, zx::sys::ZX_OK);
        Ok(())
    }

    #[fuchsia::test]
    async fn test_directory_enumerate() -> Result<(), Error> {
        let pkg_dir_handle = directory::open_in_namespace(
            "/pkg",
            fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_EXECUTABLE,
        )
        .expect("failed to open /pkg")
        .into_channel()
        .expect("could not unwrap channel")
        .into_zx_channel()
        .into();

        let io: Zxio = Zxio::create(pkg_dir_handle)?;
        let iter = io.create_dirent_iterator().expect("failed to create iterator");
        let expected_dir_names = vec![".", "bin", "lib", "meta"];
        let mut found_dir_names = iter
            .map(|e| {
                let dirent = e.expect("dirent");
                assert!(dirent.is_dir());
                std::str::from_utf8(&dirent.name).expect("name was not valid utf8").to_string()
            })
            .collect::<Vec<_>>();
        found_dir_names.sort();
        assert_eq!(expected_dir_names, found_dir_names);

        // Check all entry inside bin are either "." or a file
        let bin_io = io
            .open(fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_EXECUTABLE, "bin")
            .expect("open");
        for entry in bin_io.create_dirent_iterator().expect("failed to create iterator") {
            let dirent = entry.expect("dirent");
            if dirent.name == "." {
                assert!(dirent.is_dir());
            } else {
                assert!(dirent.is_file());
            }
        }

        Ok(())
    }

    #[fuchsia::test]
    fn test_storage_allocator() {
        let mut out_storage = zxio_storage_t::default();
        let mut out_storage_ptr = &mut out_storage as *mut zxio_storage_t;

        let mut out_context = Zxio::default();
        let mut out_context_ptr = &mut out_context as *mut Zxio;

        let out = unsafe {
            storage_allocator(
                0 as zxio_object_type_t,
                &mut out_storage_ptr as *mut *mut zxio_storage_t,
                &mut out_context_ptr as *mut *mut Zxio as *mut *mut c_void,
            )
        };
        assert_eq!(out, zx::sys::ZX_OK);
    }

    #[fuchsia::test]
    fn test_storage_allocator_bad_context() {
        let mut out_storage = zxio_storage_t::default();
        let mut out_storage_ptr = &mut out_storage as *mut zxio_storage_t;

        let out_context = std::ptr::null_mut();

        let out = unsafe {
            storage_allocator(
                0 as zxio_object_type_t,
                &mut out_storage_ptr as *mut *mut zxio_storage_t,
                out_context,
            )
        };
        assert_eq!(out, zx::sys::ZX_ERR_NO_MEMORY);
    }
}