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
//! file control options
use crate::errno::Errno;
#[cfg(all(target_os = "freebsd", target_arch = "x86_64"))]
use core::slice;
use libc::{c_int, c_uint, size_t, ssize_t};
#[cfg(any(
    target_os = "netbsd",
    apple_targets,
    target_os = "dragonfly",
    all(target_os = "freebsd", target_arch = "x86_64"),
))]
use std::ffi::CStr;
use std::ffi::OsString;
#[cfg(not(any(target_os = "redox", target_os = "solaris")))]
use std::ops::{Deref, DerefMut};
use std::os::unix::ffi::OsStringExt;
#[cfg(not(any(target_os = "redox", target_os = "solaris")))]
use std::os::unix::io::OwnedFd;
use std::os::unix::io::RawFd;
#[cfg(any(
    target_os = "netbsd",
    apple_targets,
    target_os = "dragonfly",
    all(target_os = "freebsd", target_arch = "x86_64"),
))]
use std::path::PathBuf;
#[cfg(any(linux_android, target_os = "freebsd"))]
use std::ptr;

#[cfg(feature = "fs")]
use crate::{sys::stat::Mode, NixPath, Result};

#[cfg(any(
    linux_android,
    target_os = "emscripten",
    target_os = "fuchsia",
    target_os = "wasi",
    target_env = "uclibc",
    target_os = "freebsd"
))]
#[cfg(feature = "fs")]
pub use self::posix_fadvise::{posix_fadvise, PosixFadviseAdvice};

/// A file descriptor referring to the working directory of the current process
/// **that should be ONLY passed to the `dirfd` argument of those `xxat()` functions**.
///
/// # Examples
///
/// Use it in [`openat()`]:
///
/// ```no_run
/// use nix::fcntl::AT_FDCWD;
/// use nix::fcntl::openat;
/// use nix::fcntl::OFlag;
/// use nix::sys::stat::Mode;
///
/// let fd = openat(AT_FDCWD, "foo", OFlag::O_RDONLY | OFlag::O_CLOEXEC, Mode::empty()).unwrap();
/// ```
///
/// # WARNING
///
/// Do NOT pass this symbol to non-`xxat()` functions, it won't work:
///
/// ```should_panic
/// use nix::errno::Errno;
/// use nix::fcntl::AT_FDCWD;
/// use nix::sys::stat::fstat;
///
/// let never = fstat(AT_FDCWD).unwrap();
/// ```
//
// SAFETY:
// 1. `AT_FDCWD` is usable for the whole process life, so it is `'static`.
// 2. It is not a valid file descriptor, but OS will handle it for us when passed
//    to `xxat(2)` calls.
#[cfg(not(target_os = "redox"))] // Redox does not have this
pub const AT_FDCWD: std::os::fd::BorrowedFd<'static> =
    unsafe { std::os::fd::BorrowedFd::borrow_raw(libc::AT_FDCWD) };

#[cfg(not(target_os = "redox"))]
#[cfg(any(feature = "fs", feature = "process", feature = "user"))]
libc_bitflags! {
    /// Flags that control how the various *at syscalls behave.
    #[cfg_attr(docsrs, doc(cfg(any(feature = "fs", feature = "process"))))]
    pub struct AtFlags: c_int {
        #[allow(missing_docs)]
        #[doc(hidden)]
        // Should not be used by the public API, but only internally.
        AT_REMOVEDIR;
        /// Used with [`linkat`](crate::unistd::linkat`) to create a link to a symbolic link's
        /// target, instead of to the symbolic link itself.
        AT_SYMLINK_FOLLOW;
        /// Used with functions like [`fstatat`](crate::sys::stat::fstatat`) to operate on a link
        /// itself, instead of the symbolic link's target.
        AT_SYMLINK_NOFOLLOW;
        /// Don't automount the terminal ("basename") component of pathname if it is a directory
        /// that is an automount point.
        #[cfg(linux_android)]
        AT_NO_AUTOMOUNT;
        /// If the provided path is an empty string, operate on the provided directory file
        /// descriptor instead.
        #[cfg(any(linux_android, target_os = "freebsd", target_os = "hurd"))]
        AT_EMPTY_PATH;
        /// Used with [`faccessat`](crate::unistd::faccessat), the checks for accessibility are
        /// performed using the effective user and group IDs instead of the real user and group ID
        #[cfg(not(target_os = "android"))]
        AT_EACCESS;
    }
}

#[cfg(any(
    feature = "fs",
    feature = "term",
    all(feature = "fanotify", target_os = "linux")
))]
libc_bitflags!(
    /// Configuration options for opened files.
    #[cfg_attr(docsrs, doc(cfg(any(feature = "fs", feature = "term", all(feature = "fanotify", target_os = "linux")))))]
    pub struct OFlag: c_int {
        /// Mask for the access mode of the file.
        O_ACCMODE;
        /// Use alternate I/O semantics.
        #[cfg(target_os = "netbsd")]
        O_ALT_IO;
        /// Open the file in append-only mode.
        O_APPEND;
        /// Generate a signal when input or output becomes possible.
        #[cfg(not(any(
            solarish,
            target_os = "aix",
            target_os = "haiku"
        )))]
        O_ASYNC;
        /// Closes the file descriptor once an `execve` call is made.
        ///
        /// Also sets the file offset to the beginning of the file.
        O_CLOEXEC;
        /// Create the file if it does not exist.
        O_CREAT;
        /// Try to minimize cache effects of the I/O for this file.
        #[cfg(any(
            freebsdlike,
            linux_android,
            solarish,
            target_os = "netbsd"
        ))]
        O_DIRECT;
        /// If the specified path isn't a directory, fail.
        O_DIRECTORY;
        /// Implicitly follow each `write()` with an `fdatasync()`.
        #[cfg(any(linux_android, apple_targets, target_os = "freebsd", netbsdlike))]
        O_DSYNC;
        /// Error out if a file was not created.
        O_EXCL;
        /// Open for execute only.
        #[cfg(target_os = "freebsd")]
        O_EXEC;
        /// Open with an exclusive file lock.
        #[cfg(any(bsd, target_os = "redox"))]
        O_EXLOCK;
        /// Same as `O_SYNC`.
        #[cfg(any(bsd,
                  all(target_os = "linux", not(target_env = "musl"), not(target_env = "ohos")),
                  target_os = "redox"))]
        O_FSYNC;
        /// Allow files whose sizes can't be represented in an `off_t` to be opened.
        #[cfg(linux_android)]
        O_LARGEFILE;
        /// Do not update the file last access time during `read(2)`s.
        #[cfg(linux_android)]
        O_NOATIME;
        /// Don't attach the device as the process' controlling terminal.
        #[cfg(not(target_os = "redox"))]
        O_NOCTTY;
        /// Same as `O_NONBLOCK`.
        #[cfg(not(any(target_os = "redox", target_os = "haiku")))]
        O_NDELAY;
        /// `open()` will fail if the given path is a symbolic link.
        O_NOFOLLOW;
        /// When possible, open the file in nonblocking mode.
        O_NONBLOCK;
        /// Don't deliver `SIGPIPE`.
        #[cfg(target_os = "netbsd")]
        O_NOSIGPIPE;
        /// Obtain a file descriptor for low-level access.
        ///
        /// The file itself is not opened and other file operations will fail.
        #[cfg(any(linux_android, target_os = "redox", target_os = "freebsd", target_os = "fuchsia"))]
        O_PATH;
        /// Only allow reading.
        ///
        /// This should not be combined with `O_WRONLY` or `O_RDWR`.
        O_RDONLY;
        /// Allow both reading and writing.
        ///
        /// This should not be combined with `O_WRONLY` or `O_RDONLY`.
        O_RDWR;
        /// Similar to `O_DSYNC` but applies to `read`s instead.
        #[cfg(any(target_os = "linux", netbsdlike))]
        O_RSYNC;
        /// Open directory for search only. Skip search permission checks on
        /// later `openat()` calls using the obtained file descriptor.
        #[cfg(any(
            apple_targets,
            solarish,
            target_os = "netbsd",
            target_os = "freebsd",
            target_os = "fuchsia",
            target_os = "emscripten",
            target_os = "aix",
            target_os = "wasi"
        ))]
        O_SEARCH;
        /// Open with a shared file lock.
        #[cfg(any(bsd, target_os = "redox"))]
        O_SHLOCK;
        /// Implicitly follow each `write()` with an `fsync()`.
        #[cfg(not(target_os = "redox"))]
        O_SYNC;
        /// Create an unnamed temporary file.
        #[cfg(linux_android)]
        O_TMPFILE;
        /// Truncate an existing regular file to 0 length if it allows writing.
        O_TRUNC;
        /// Restore default TTY attributes.
        #[cfg(target_os = "freebsd")]
        O_TTY_INIT;
        /// Only allow writing.
        ///
        /// This should not be combined with `O_RDONLY` or `O_RDWR`.
        O_WRONLY;
    }
);

feature! {
#![feature = "fs"]

/// open or create a file for reading, writing or executing
///
/// # See Also
/// [`open`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html)
// The conversion is not identical on all operating systems.
#[allow(clippy::useless_conversion)]
pub fn open<P: ?Sized + NixPath>(
    path: &P,
    oflag: OFlag,
    mode: Mode,
) -> Result<std::os::fd::OwnedFd> {
    use std::os::fd::FromRawFd;

    let fd = path.with_nix_path(|cstr| unsafe {
        libc::open(cstr.as_ptr(), oflag.bits(), mode.bits() as c_uint)
    })?;
    Errno::result(fd)?;

    // SAFETY:
    //
    // `open(2)` should return a valid owned fd on success
    Ok( unsafe { std::os::fd::OwnedFd::from_raw_fd(fd)  } )
}

/// open or create a file for reading, writing or executing
///
/// The `openat` function is equivalent to the [`open`] function except in the case where the path
/// specifies a relative path.  In that case, the file to be opened is determined relative to the
/// directory associated with the file descriptor `dirfd`.
///
/// # See Also
/// [`openat`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/openat.html)
// The conversion is not identical on all operating systems.
#[allow(clippy::useless_conversion)]
#[cfg(not(target_os = "redox"))]
pub fn openat<P: ?Sized + NixPath, Fd: std::os::fd::AsFd>(
    dirfd: Fd,
    path: &P,
    oflag: OFlag,
    mode: Mode,
) -> Result<OwnedFd> {
    use std::os::fd::AsRawFd;
    use std::os::fd::FromRawFd;

    let fd = path.with_nix_path(|cstr| unsafe {
        libc::openat(dirfd.as_fd().as_raw_fd(), cstr.as_ptr(), oflag.bits(), mode.bits() as c_uint)
    })?;
    Errno::result(fd)?;

    // SAFETY:
    //
    // `openat(2)` should return a valid owned fd on success
    Ok( unsafe { OwnedFd::from_raw_fd(fd)  } )
}

cfg_if::cfg_if! {
    if #[cfg(target_os = "linux")] {
        libc_bitflags! {
            /// Path resolution flags.
            ///
            /// See [path resolution(7)](https://man7.org/linux/man-pages/man7/path_resolution.7.html)
            /// for details of the resolution process.
            pub struct ResolveFlag: libc::c_ulonglong {
                /// Do not permit the path resolution to succeed if any component of
                /// the resolution is not a descendant of the directory indicated by
                /// dirfd.  This causes absolute symbolic links (and absolute values of
                /// pathname) to be rejected.
                RESOLVE_BENEATH;

                /// Treat the directory referred to by dirfd as the root directory
                /// while resolving pathname.
                RESOLVE_IN_ROOT;

                /// Disallow all magic-link resolution during path resolution. Magic
                /// links are symbolic link-like objects that are most notably found
                /// in proc(5);  examples include `/proc/[pid]/exe` and `/proc/[pid]/fd/*`.
                ///
                /// See symlink(7) for more details.
                RESOLVE_NO_MAGICLINKS;

                /// Disallow resolution of symbolic links during path resolution. This
                /// option implies RESOLVE_NO_MAGICLINKS.
                RESOLVE_NO_SYMLINKS;

                /// Disallow traversal of mount points during path resolution (including
                /// all bind mounts).
                RESOLVE_NO_XDEV;
            }
        }

        /// Specifies how [`openat2()`] should open a pathname.
        ///
        /// # Reference
        ///
        /// * [Linux](https://man7.org/linux/man-pages/man2/open_how.2type.html)
        #[repr(transparent)]
        #[derive(Clone, Copy, Debug)]
        pub struct OpenHow(libc::open_how);

        impl OpenHow {
            /// Create a new zero-filled `open_how`.
            pub fn new() -> Self {
                // safety: according to the man page, open_how MUST be zero-initialized
                // on init so that unknown fields are also zeroed.
                Self(unsafe {
                    std::mem::MaybeUninit::zeroed().assume_init()
                })
            }

            /// Set the open flags used to open a file, completely overwriting any
            /// existing flags.
            pub fn flags(mut self, flags: OFlag) -> Self {
                let flags = flags.bits() as libc::c_ulonglong;
                self.0.flags = flags;
                self
            }

            /// Set the file mode new files will be created with, overwriting any
            /// existing flags.
            pub fn mode(mut self, mode: Mode) -> Self {
                let mode = mode.bits() as libc::c_ulonglong;
                self.0.mode = mode;
                self
            }

            /// Set resolve flags, completely overwriting any existing flags.
            ///
            /// See [ResolveFlag] for more detail.
            pub fn resolve(mut self, resolve: ResolveFlag) -> Self {
                let resolve = resolve.bits();
                self.0.resolve = resolve;
                self
            }
        }

        // safety: default isn't derivable because libc::open_how must be zeroed
        impl Default for OpenHow {
            fn default() -> Self {
                Self::new()
            }
        }

        /// Open or create a file for reading, writing or executing.
        ///
        /// `openat2` is an extension of the [`openat`] function that allows the caller
        /// to control how path resolution happens.
        ///
        /// # See also
        ///
        /// [openat2](https://man7.org/linux/man-pages/man2/openat2.2.html)
        pub fn openat2<P: ?Sized + NixPath, Fd: std::os::fd::AsFd>(
            dirfd: Fd,
            path: &P,
            mut how: OpenHow,
        ) -> Result<OwnedFd> {
            use std::os::fd::AsRawFd;
            use std::os::fd::FromRawFd;

            let fd = path.with_nix_path(|cstr| unsafe {
                libc::syscall(
                    libc::SYS_openat2,
                    dirfd.as_fd().as_raw_fd(),
                    cstr.as_ptr(),
                    &mut how as *mut OpenHow,
                    std::mem::size_of::<libc::open_how>(),
                )
            })? as RawFd;
            Errno::result(fd)?;

            // SAFETY:
            //
            // `openat2(2)` should return a valid owned fd on success
            Ok( unsafe { OwnedFd::from_raw_fd(fd)  } )
        }
    }
}

/// Change the name of a file.
///
/// The `renameat` function is equivalent to `rename` except in the case where either `old_path`
/// or `new_path` specifies a relative path.  In such cases, the file to be renamed (or the its new
/// name, respectively) is located relative to `old_dirfd` or `new_dirfd`, respectively
///
/// # See Also
/// [`renameat`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/rename.html)
#[cfg(not(target_os = "redox"))]
pub fn renameat<P1: ?Sized + NixPath, P2: ?Sized + NixPath, Fd1: std::os::fd::AsFd, Fd2: std::os::fd::AsFd>(
    old_dirfd: Fd1,
    old_path: &P1,
    new_dirfd: Fd2,
    new_path: &P2,
) -> Result<()> {
    use std::os::fd::AsRawFd;

    let res = old_path.with_nix_path(|old_cstr| {
        new_path.with_nix_path(|new_cstr| unsafe {
            libc::renameat(
                old_dirfd.as_fd().as_raw_fd(),
                old_cstr.as_ptr(),
                new_dirfd.as_fd().as_raw_fd(),
                new_cstr.as_ptr(),
            )
        })
    })??;
    Errno::result(res).map(drop)
}
}

#[cfg(all(target_os = "linux", target_env = "gnu"))]
#[cfg(feature = "fs")]
libc_bitflags! {
    /// Flags for use with [`renameat2`].
    #[cfg_attr(docsrs, doc(cfg(feature = "fs")))]
    pub struct RenameFlags: u32 {
        /// Atomically exchange `old_path` and `new_path`.
        RENAME_EXCHANGE;
        /// Don't overwrite `new_path` of the rename.  Return an error if `new_path` already
        /// exists.
        RENAME_NOREPLACE;
        /// creates a "whiteout" object at the source of the rename at the same time as performing
        /// the rename.
        ///
        /// This operation makes sense only for overlay/union filesystem implementations.
        RENAME_WHITEOUT;
    }
}

feature! {
#![feature = "fs"]
/// Like [`renameat`], but with an additional `flags` argument.
///
/// A `renameat2` call with an empty flags argument is equivalent to `renameat`.
///
/// # See Also
/// * [`rename`](https://man7.org/linux/man-pages/man2/rename.2.html)
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pub fn renameat2<P1: ?Sized + NixPath, P2: ?Sized + NixPath, Fd1: std::os::fd::AsFd, Fd2: std::os::fd::AsFd>(
    old_dirfd: Fd1,
    old_path: &P1,
    new_dirfd: Fd2,
    new_path: &P2,
    flags: RenameFlags,
) -> Result<()> {
    use std::os::fd::AsRawFd;

    let res = old_path.with_nix_path(|old_cstr| {
        new_path.with_nix_path(|new_cstr| unsafe {
            libc::renameat2(
                old_dirfd.as_fd().as_raw_fd(),
                old_cstr.as_ptr(),
                new_dirfd.as_fd().as_raw_fd(),
                new_cstr.as_ptr(),
                flags.bits(),
            )
        })
    })??;
    Errno::result(res).map(drop)
}

fn wrap_readlink_result(mut v: Vec<u8>, len: ssize_t) -> Result<OsString> {
    unsafe { v.set_len(len as usize) }
    v.shrink_to_fit();
    Ok(OsString::from_vec(v.to_vec()))
}

/// Read the symlink specified by `path` and `dirfd` and put the contents in `v`.
/// Return the number of bytes placed in `v`.
///
/// This function can call `readlink(2)` or `readlinkat(2)` depending on if `dirfd`
/// is some, if it is, then `readlinkat(2)` is called, otherwise, call `readlink(2)`.
///
/// # Safety
///
/// This function is not I/O-safe considering it employs the `RawFd` type.
unsafe fn readlink_maybe_at<P: ?Sized + NixPath>(
    dirfd: Option<RawFd>,
    path: &P,
    v: &mut Vec<u8>,
) -> Result<libc::ssize_t> {
    path.with_nix_path(|cstr| unsafe {
        match dirfd {
            #[cfg(target_os = "redox")]
            Some(_) => unreachable!("redox does not have readlinkat(2)"),
            #[cfg(not(target_os = "redox"))]
            Some(dirfd) => libc::readlinkat(
                dirfd,
                cstr.as_ptr(),
                v.as_mut_ptr().cast(),
                v.capacity() as size_t,
            ),
            None => libc::readlink(
                cstr.as_ptr(),
                v.as_mut_ptr().cast(),
                v.capacity() as size_t,
            ),
        }
    })
}

/// The actual implementation of [`readlink(2)`] or [`readlinkat(2)`].
///
/// This function can call `readlink(2)` or `readlinkat(2)` depending on if `dirfd`
/// is some, if it is, then `readlinkat(2)` is called, otherwise, call `readlink(2)`.
///
/// # Safety
///
/// This function is marked unsafe because it uses `RawFd`.
unsafe fn inner_readlink<P: ?Sized + NixPath>(
    dirfd: Option<RawFd>,
    path: &P,
) -> Result<OsString> {
    #[cfg(not(target_os = "hurd"))]
    const PATH_MAX: usize = libc::PATH_MAX as usize;
    #[cfg(target_os = "hurd")]
    const PATH_MAX: usize = 1024; // Hurd does not define a hard limit, so try a guess first
    let mut v = Vec::with_capacity(PATH_MAX);

    {
        // simple case: result is strictly less than `PATH_MAX`

        // SAFETY:
        //
        // If this call of `readlink_maybe_at()` is safe or not depends on the
        // usage of `unsafe fn inner_readlink()`.
        let res = unsafe { readlink_maybe_at(dirfd, path, &mut v)? };
        let len = Errno::result(res)?;
        debug_assert!(len >= 0);
        if (len as usize) < v.capacity() {
            return wrap_readlink_result(v, res);
        }
    }

    // Uh oh, the result is too long...
    // Let's try to ask lstat how many bytes to allocate.
    let mut try_size = {
        let reported_size = match dirfd {
            #[cfg(target_os = "redox")]
            Some(_) => unreachable!("redox does not have readlinkat(2)"),
            #[cfg(any(linux_android, target_os = "freebsd", target_os = "hurd"))]
            Some(dirfd) => {
                // SAFETY:
                //
                // If this call of `borrow_raw()` is safe or not depends on the
                // usage of `unsafe fn inner_readlink()`.
                let dirfd = unsafe {
                    std::os::fd::BorrowedFd::borrow_raw(dirfd)
                };
                let flags = if path.is_empty() {
                    AtFlags::AT_EMPTY_PATH
                } else {
                    AtFlags::empty()
                };
                super::sys::stat::fstatat(
                    dirfd,
                    path,
                    flags | AtFlags::AT_SYMLINK_NOFOLLOW,
                )
            }
            #[cfg(not(any(
                linux_android,
                target_os = "redox",
                target_os = "freebsd",
                target_os = "hurd"
            )))]
            Some(dirfd) => {
                // SAFETY:
                //
                // If this call of `borrow_raw()` is safe or not depends on the
                // usage of `unsafe fn inner_readlink()`.
                let dirfd = unsafe {
                    std::os::fd::BorrowedFd::borrow_raw(dirfd)
                };
                super::sys::stat::fstatat(dirfd, path, AtFlags::AT_SYMLINK_NOFOLLOW)
            },
            None => super::sys::stat::lstat(path),
        }
        .map(|x| x.st_size)
        .unwrap_or(0);

        if reported_size > 0 {
            // Note: even if `lstat`'s apparently valid answer turns out to be
            // wrong, we will still read the full symlink no matter what.
            reported_size as usize + 1
        } else {
            // If lstat doesn't cooperate, or reports an error, be a little less
            // precise.
            PATH_MAX.max(128) << 1
        }
    };

    loop {
        {
            v.reserve_exact(try_size);
            // SAFETY:
            //
            // If this call of `readlink_maybe_at()` is safe or not depends on the
            // usage of `unsafe fn inner_readlink()`.
            let res = unsafe { readlink_maybe_at(dirfd, path, &mut v)? };
            let len = Errno::result(res)?;
            debug_assert!(len >= 0);
            if (len as usize) < v.capacity() {
                return wrap_readlink_result(v, res);
            }
        }

        // Ugh! Still not big enough!
        match try_size.checked_shl(1) {
            Some(next_size) => try_size = next_size,
            // It's absurd that this would happen, but handle it sanely
            // anyway.
            None => break Err(Errno::ENAMETOOLONG),
        }
    }
}

/// Read value of a symbolic link
///
/// # See Also
/// * [`readlink`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/readlink.html)
pub fn readlink<P: ?Sized + NixPath>(path: &P) -> Result<OsString> {
    // argument `dirfd` should be `None` since we call it from `readlink()`
    //
    // Do NOT call it with `Some(AT_CWD)` as in that way, we are emulating
    // `readlink(2)` with `readlinkat(2)`, which will make us lose `readlink(2)`
    // on Redox.
    //
    // SAFETY:
    //
    // It is definitely safe because the argument involving `RawFd` is `None`
    unsafe { inner_readlink(None, path) }
}

/// Read value of a symbolic link.
///
/// Equivalent to [`readlink` ] except for the case where `path` specifies a
/// relative path, `path` will be interpreted relative to the path specified
/// by `dirfd`. (Use [`AT_FDCWD`] to make it relative to the working directory).
///
/// # See Also
/// * [`readlink`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/readlink.html)
#[cfg(not(target_os = "redox"))]
pub fn readlinkat<Fd: std::os::fd::AsFd,P: ?Sized + NixPath>(
    dirfd: Fd,
    path: &P,
) -> Result<OsString> {
    use std::os::fd::AsRawFd;

    // argument `dirfd` should be `Some` since we call it from `readlinkat()`
    //
    // SAFETY:
    //
    // The passed `RawFd` should be valid since it is borrowed from `Fd: AsFd`.
    unsafe { inner_readlink(Some(dirfd.as_fd().as_raw_fd()), path) }
}
}

#[cfg(any(linux_android, target_os = "freebsd"))]
#[cfg(feature = "fs")]
libc_bitflags!(
    /// Additional flags for file sealing, which allows for limiting operations on a file.
    #[cfg_attr(docsrs, doc(cfg(feature = "fs")))]
    pub struct SealFlag: c_int {
        /// Prevents further calls to `fcntl()` with `F_ADD_SEALS`.
        F_SEAL_SEAL;
        /// The file cannot be reduced in size.
        F_SEAL_SHRINK;
        /// The size of the file cannot be increased.
        F_SEAL_GROW;
        /// The file contents cannot be modified.
        F_SEAL_WRITE;
        /// The file contents cannot be modified, except via shared writable mappings that were
        /// created prior to the seal being set. Since Linux 5.1.
        #[cfg(linux_android)]
        F_SEAL_FUTURE_WRITE;
    }
);

#[cfg(feature = "fs")]
libc_bitflags!(
    /// Additional configuration flags for `fcntl`'s `F_SETFD`.
    #[cfg_attr(docsrs, doc(cfg(feature = "fs")))]
    pub struct FdFlag: c_int {
        /// The file descriptor will automatically be closed during a successful `execve(2)`.
        FD_CLOEXEC;
    }
);

feature! {
#![feature = "fs"]

/// Commands for use with [`fcntl`].
#[cfg(not(target_os = "redox"))]
#[derive(Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum FcntlArg<'a> {
    /// Duplicate the provided file descriptor
    F_DUPFD(RawFd),
    /// Duplicate the provided file descriptor and set the `FD_CLOEXEC` flag on it.
    F_DUPFD_CLOEXEC(RawFd),
    /// Get the close-on-exec flag associated with the file descriptor
    F_GETFD,
    /// Set the close-on-exec flag associated with the file descriptor
    F_SETFD(FdFlag), // FD_FLAGS
    /// Get descriptor status flags
    F_GETFL,
    /// Set descriptor status flags
    F_SETFL(OFlag), // O_NONBLOCK
    /// Set or clear a file segment lock
    F_SETLK(&'a libc::flock),
    /// Like [`F_SETLK`](FcntlArg::F_SETLK) except that if a shared or exclusive lock is blocked by
    /// other locks, the process waits until the request can be satisfied.
    F_SETLKW(&'a libc::flock),
    /// Get the first lock that blocks the lock description
    F_GETLK(&'a mut libc::flock),
    /// Acquire or release an open file description lock
    #[cfg(linux_android)]
    F_OFD_SETLK(&'a libc::flock),
    /// Like [`F_OFD_SETLK`](FcntlArg::F_OFD_SETLK) except that if a conflicting lock is held on
    /// the file, then wait for that lock to be released.
    #[cfg(linux_android)]
    F_OFD_SETLKW(&'a libc::flock),
    /// Determine whether it would be possible to create the given lock.  If not, return details
    /// about one existing lock that would prevent it.
    #[cfg(linux_android)]
    F_OFD_GETLK(&'a mut libc::flock),
    /// Add seals to the file
    #[cfg(any(
        linux_android,
        target_os = "freebsd"
    ))]
    F_ADD_SEALS(SealFlag),
    /// Get seals associated with the file
    #[cfg(any(
        linux_android,
        target_os = "freebsd"
    ))]
    F_GET_SEALS,
    /// Asks the drive to flush all buffered data to permanent storage.
    #[cfg(apple_targets)]
    F_FULLFSYNC,
    /// fsync + issue barrier to drive
    #[cfg(apple_targets)]
    F_BARRIERFSYNC,
    /// Return the capacity of a pipe
    #[cfg(linux_android)]
    F_GETPIPE_SZ,
    /// Change the capacity of a pipe
    #[cfg(linux_android)]
    F_SETPIPE_SZ(c_int),
    /// Look up the path of an open file descriptor, if possible.
    #[cfg(any(
        target_os = "netbsd",
        target_os = "dragonfly",
        apple_targets,
    ))]
    F_GETPATH(&'a mut PathBuf),
    /// Look up the path of an open file descriptor, if possible.
    #[cfg(all(target_os = "freebsd", target_arch = "x86_64"))]
    F_KINFO(&'a mut PathBuf),
    /// Return the full path without firmlinks of the fd.
    #[cfg(apple_targets)]
    F_GETPATH_NOFIRMLINK(&'a mut PathBuf),
    /// Issue an advisory read async with no copy to user
    #[cfg(apple_targets)]
    F_RDADVISE(libc::radvisory),
    /// Turn read ahead off/on
    #[cfg(apple_targets)]
    F_RDAHEAD(bool),
    /// Pre-allocate storage with different policies on fd.
    /// Note that we want a mutable reference for the OUT
    /// fstore_t field fst_bytesalloc.
    #[cfg(apple_targets)]
    F_PREALLOCATE(&'a mut libc::fstore_t),
    #[cfg(apple_targets)]
    /// Get disk device information. In practice,
    /// only the file offset data is set.
    F_LOG2PHYS(&'a mut libc::off_t),
    #[cfg(apple_targets)]
    /// Get disk device information. In practice,
    /// only the file offset data is set.
    /// The difference with F_LOG2PHYS is the struct passed
    /// is used as both IN/OUT as both its l2p_devoffset and
    /// l2p_contigbytes can be used for more specific queries.
    F_LOG2PHYS_EXT(&'a mut libc::log2phys),
    // TODO: Rest of flags
}

/// Commands for use with [`fcntl`].
#[cfg(target_os = "redox")]
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum FcntlArg {
    /// Duplicate the provided file descriptor
    F_DUPFD(RawFd),
    /// Duplicate the provided file descriptor and set the `FD_CLOEXEC` flag on it.
    F_DUPFD_CLOEXEC(RawFd),
    /// Get the close-on-exec flag associated with the file descriptor
    F_GETFD,
    /// Set the close-on-exec flag associated with the file descriptor
    F_SETFD(FdFlag), // FD_FLAGS
    /// Get descriptor status flags
    F_GETFL,
    /// Set descriptor status flags
    F_SETFL(OFlag), // O_NONBLOCK
}
pub use self::FcntlArg::*;

/// Perform various operations on open file descriptors.
///
/// # See Also
/// * [`fcntl`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fcntl.html)
// TODO: Figure out how to handle value fcntl returns
pub fn fcntl<Fd: std::os::fd::AsFd>(fd: Fd, arg: FcntlArg) -> Result<c_int> {
    use std::os::fd::AsRawFd;

    let fd = fd.as_fd().as_raw_fd();
    let res = unsafe {
        match arg {
            F_DUPFD(rawfd) => libc::fcntl(fd, libc::F_DUPFD, rawfd),
            F_DUPFD_CLOEXEC(rawfd) => {
                libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, rawfd)
            }
            F_GETFD => libc::fcntl(fd, libc::F_GETFD),
            F_SETFD(flag) => libc::fcntl(fd, libc::F_SETFD, flag.bits()),
            F_GETFL => libc::fcntl(fd, libc::F_GETFL),
            F_SETFL(flag) => libc::fcntl(fd, libc::F_SETFL, flag.bits()),
            #[cfg(not(target_os = "redox"))]
            F_SETLK(flock) => libc::fcntl(fd, libc::F_SETLK, flock),
            #[cfg(not(target_os = "redox"))]
            F_SETLKW(flock) => libc::fcntl(fd, libc::F_SETLKW, flock),
            #[cfg(not(target_os = "redox"))]
            F_GETLK(flock) => libc::fcntl(fd, libc::F_GETLK, flock),
            #[cfg(linux_android)]
            F_OFD_SETLK(flock) => libc::fcntl(fd, libc::F_OFD_SETLK, flock),
            #[cfg(linux_android)]
            F_OFD_SETLKW(flock) => libc::fcntl(fd, libc::F_OFD_SETLKW, flock),
            #[cfg(linux_android)]
            F_OFD_GETLK(flock) => libc::fcntl(fd, libc::F_OFD_GETLK, flock),
            #[cfg(any(
                linux_android,
                target_os = "freebsd"
            ))]
            F_ADD_SEALS(flag) => {
                libc::fcntl(fd, libc::F_ADD_SEALS, flag.bits())
            }
            #[cfg(any(
                linux_android,
                target_os = "freebsd"
            ))]
            F_GET_SEALS => libc::fcntl(fd, libc::F_GET_SEALS),
            #[cfg(apple_targets)]
            F_FULLFSYNC => libc::fcntl(fd, libc::F_FULLFSYNC),
            #[cfg(apple_targets)]
            F_BARRIERFSYNC => libc::fcntl(fd, libc::F_BARRIERFSYNC),
            #[cfg(linux_android)]
            F_GETPIPE_SZ => libc::fcntl(fd, libc::F_GETPIPE_SZ),
            #[cfg(linux_android)]
            F_SETPIPE_SZ(size) => libc::fcntl(fd, libc::F_SETPIPE_SZ, size),
            #[cfg(any(
                target_os = "dragonfly",
                target_os = "netbsd",
                apple_targets,
            ))]
            F_GETPATH(path) => {
                let mut buffer = vec![0; libc::PATH_MAX as usize];
                let res = libc::fcntl(fd, libc::F_GETPATH, buffer.as_mut_ptr());
                let ok_res = Errno::result(res)?;
                let optr = CStr::from_bytes_until_nul(&buffer).unwrap();
                *path = PathBuf::from(OsString::from(optr.to_str().unwrap()));
                return Ok(ok_res)
            },
            #[cfg(all(target_os = "freebsd", target_arch = "x86_64"))]
            F_KINFO(path) => {
                let mut info: libc::kinfo_file = std::mem::zeroed();
                info.kf_structsize = std::mem::size_of::<libc::kinfo_file>() as i32;
                let res = libc::fcntl(fd, libc::F_KINFO, &mut info);
                let ok_res = Errno::result(res)?;
                let p = info.kf_path;
                let u8_slice = slice::from_raw_parts(p.as_ptr().cast(), p.len());
                let optr = CStr::from_bytes_until_nul(u8_slice).unwrap();
                *path = PathBuf::from(OsString::from(optr.to_str().unwrap()));
                return Ok(ok_res)
            },
            #[cfg(apple_targets)]
            F_GETPATH_NOFIRMLINK(path) => {
                let mut buffer = vec![0; libc::PATH_MAX as usize];
                let res = libc::fcntl(fd, libc::F_GETPATH_NOFIRMLINK, buffer.as_mut_ptr());
                let ok_res = Errno::result(res)?;
                let optr = CStr::from_bytes_until_nul(&buffer).unwrap();
                *path = PathBuf::from(OsString::from(optr.to_str().unwrap()));
                return Ok(ok_res)
            },
            #[cfg(apple_targets)]
            F_RDADVISE(rad) => {
                libc::fcntl(fd, libc::F_RDADVISE, &rad)
            },
            #[cfg(apple_targets)]
            F_LOG2PHYS(offset) => {
                let mut info: libc::log2phys = std::mem::zeroed();
                let res = libc::fcntl(fd, libc::F_LOG2PHYS, &mut info);
                let ok_res = Errno::result(res)?;
                *offset = info.l2p_devoffset;
                return Ok(ok_res)
            }
            #[cfg(apple_targets)]
            F_LOG2PHYS_EXT(info) => {
                libc::fcntl(fd, libc::F_LOG2PHYS_EXT, info)
            }
            #[cfg(apple_targets)]
            F_RDAHEAD(on) => {
                let val = if on { 1 } else { 0 };
                libc::fcntl(fd, libc::F_RDAHEAD, val)
            },
            #[cfg(apple_targets)]
            F_PREALLOCATE(st) => {
                libc::fcntl(fd, libc::F_PREALLOCATE, st)
            },
        }
    };

    Errno::result(res)
}

/// Operations for use with [`Flock::lock`].
#[cfg(not(any(target_os = "redox", target_os = "solaris")))]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum FlockArg {
    /// shared file lock
    LockShared,
    /// exclusive file lock
    LockExclusive,
    /// Unlock file
    Unlock,
    /// Shared lock.  Do not block when locking.
    LockSharedNonblock,
    /// Exclusive lock.  Do not block when locking.
    LockExclusiveNonblock,
    #[allow(missing_docs)]
    #[deprecated(since = "0.28.0", note = "Use FlockArg::Unlock instead")]
    UnlockNonblock,
}

#[allow(missing_docs)]
#[cfg(not(any(target_os = "redox", target_os = "solaris")))]
#[deprecated(since = "0.28.0", note = "`fcntl::Flock` should be used instead.")]
pub fn flock(fd: RawFd, arg: FlockArg) -> Result<()> {
    use self::FlockArg::*;

    let res = unsafe {
        match arg {
            LockShared => libc::flock(fd, libc::LOCK_SH),
            LockExclusive => libc::flock(fd, libc::LOCK_EX),
            Unlock => libc::flock(fd, libc::LOCK_UN),
            LockSharedNonblock => {
                libc::flock(fd, libc::LOCK_SH | libc::LOCK_NB)
            }
            LockExclusiveNonblock => {
                libc::flock(fd, libc::LOCK_EX | libc::LOCK_NB)
            }
            #[allow(deprecated)]
            UnlockNonblock => libc::flock(fd, libc::LOCK_UN | libc::LOCK_NB),
        }
    };

    Errno::result(res).map(drop)
}

/// Represents valid types for flock.
///
/// # Safety
/// Types implementing this must not be `Clone`.
#[cfg(not(any(target_os = "redox", target_os = "solaris")))]
pub unsafe trait Flockable: std::os::fd::AsRawFd {}

/// Represents an owned flock, which unlocks on drop.
///
/// See [flock(2)](https://linux.die.net/man/2/flock) for details on locking semantics.
#[cfg(not(any(target_os = "redox", target_os = "solaris")))]
#[derive(Debug)]
pub struct Flock<T: Flockable>(T);

#[cfg(not(any(target_os = "redox", target_os = "solaris")))]
impl<T: Flockable> Drop for Flock<T> {
    fn drop(&mut self) {
        let res = Errno::result(unsafe { libc::flock(self.0.as_raw_fd(), libc::LOCK_UN) });
        if res.is_err() && !std::thread::panicking() {
            panic!("Failed to remove flock: {}", res.unwrap_err());
        }
    }
}

#[cfg(not(any(target_os = "redox", target_os = "solaris")))]
impl<T: Flockable> Deref for Flock<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
#[cfg(not(any(target_os = "redox", target_os = "solaris")))]
impl<T: Flockable> DerefMut for Flock<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[cfg(not(any(target_os = "redox", target_os = "solaris")))]
impl<T: Flockable> Flock<T> {
    /// Obtain a/an flock.
    ///
    /// # Example
    /// ```
    /// # use std::io::Write;
    /// # use std::fs::File;
    /// # use nix::fcntl::{Flock, FlockArg};
    /// # fn do_stuff(file: File) {
    ///   let mut file = match Flock::lock(file, FlockArg::LockExclusive) {
    ///       Ok(l) => l,
    ///       Err(_) => return,
    ///   };
    ///
    ///   // Do stuff
    ///   let data = "Foo bar";
    ///   _ = file.write(data.as_bytes());
    ///   _ = file.sync_data();
    /// # }
    pub fn lock(t: T, args: FlockArg) -> std::result::Result<Self, (T, Errno)> {
        let flags = match args {
            FlockArg::LockShared => libc::LOCK_SH,
            FlockArg::LockExclusive => libc::LOCK_EX,
            FlockArg::LockSharedNonblock => libc::LOCK_SH | libc::LOCK_NB,
            FlockArg::LockExclusiveNonblock => libc::LOCK_EX | libc::LOCK_NB,
            #[allow(deprecated)]
            FlockArg::Unlock | FlockArg::UnlockNonblock => return Err((t, Errno::EINVAL)),
        };
        match Errno::result(unsafe { libc::flock(t.as_raw_fd(), flags) }) {
            Ok(_) => Ok(Self(t)),
            Err(errno) => Err((t, errno)),
        }
    }

    /// Remove the lock and return the object wrapped within.
    ///
    /// # Example
    /// ```
    /// # use std::fs::File;
    /// # use nix::fcntl::{Flock, FlockArg};
    /// fn do_stuff(file: File) -> nix::Result<()> {
    ///     let mut lock = match Flock::lock(file, FlockArg::LockExclusive) {
    ///         Ok(l) => l,
    ///         Err((_,e)) => return Err(e),
    ///     };
    ///
    ///     // Do critical section
    ///
    ///     // Unlock
    ///     let file = match lock.unlock() {
    ///         Ok(f) => f,
    ///         Err((_, e)) => return Err(e),
    ///     };
    ///
    ///     // Do anything else
    ///
    ///     Ok(())
    /// }
    pub fn unlock(self) -> std::result::Result<T, (Self, Errno)> {
        let inner = unsafe { match Errno::result(libc::flock(self.0.as_raw_fd(), libc::LOCK_UN)) {
            Ok(_) => std::ptr::read(&self.0),
            Err(errno) => return Err((self, errno)),
        }};

        std::mem::forget(self);
        Ok(inner)
    }

    /// Relock the file.  This can upgrade or downgrade the lock type.
    ///
    /// # Example
    /// ```
    /// # use std::fs::File;
    /// # use nix::fcntl::{Flock, FlockArg};
    /// # use tempfile::tempfile;
    /// let f: std::fs::File = tempfile().unwrap();
    /// let locked_file = Flock::lock(f, FlockArg::LockExclusive).unwrap();
    /// // Do stuff, then downgrade the lock
    /// locked_file.relock(FlockArg::LockShared).unwrap();
    /// ```
    pub fn relock(&self, arg: FlockArg) -> Result<()> {
         let flags = match arg {
            FlockArg::LockShared => libc::LOCK_SH,
            FlockArg::LockExclusive => libc::LOCK_EX,
            FlockArg::LockSharedNonblock => libc::LOCK_SH | libc::LOCK_NB,
            FlockArg::LockExclusiveNonblock => libc::LOCK_EX | libc::LOCK_NB,
            #[allow(deprecated)]
            FlockArg::Unlock | FlockArg::UnlockNonblock => return Err(Errno::EINVAL),
        };
        Errno::result(unsafe { libc::flock(self.as_raw_fd(), flags) }).map(drop)
    }
}

// Safety: `File` is not [std::clone::Clone].
#[cfg(not(any(target_os = "redox", target_os = "solaris")))]
unsafe impl Flockable for std::fs::File {}

// Safety: `OwnedFd` is not [std::clone::Clone].
#[cfg(not(any(target_os = "redox", target_os = "solaris")))]
unsafe impl Flockable for OwnedFd {}
}

#[cfg(linux_android)]
#[cfg(feature = "zerocopy")]
libc_bitflags! {
    /// Additional flags to `splice` and friends.
    #[cfg_attr(docsrs, doc(cfg(feature = "zerocopy")))]
    pub struct SpliceFFlags: c_uint {
        /// Request that pages be moved instead of copied.
        ///
        /// Not applicable to `vmsplice`.
        SPLICE_F_MOVE;
        /// Do not block on I/O.
        SPLICE_F_NONBLOCK;
        /// Hint that more data will be coming in a subsequent splice.
        ///
        /// Not applicable to `vmsplice`.
        SPLICE_F_MORE;
        /// Gift the user pages to the kernel.
        ///
        /// Not applicable to `splice`.
        SPLICE_F_GIFT;
    }
}

feature! {
#![feature = "zerocopy"]

/// Copy a range of data from one file to another
///
/// The `copy_file_range` system call performs an in-kernel copy between
/// file descriptors `fd_in` and `fd_out` without the additional cost of
/// transferring data from the kernel to user space and back again. There may be
/// additional optimizations for specific file systems.  It copies up to `len`
/// bytes of data from file descriptor `fd_in` to file descriptor `fd_out`,
/// overwriting any data that exists within the requested range of the target
/// file.
///
/// If the `off_in` and/or `off_out` arguments are used, the values
/// will be mutated to reflect the new position within the file after
/// copying. If they are not used, the relevant file descriptors will be seeked
/// to the new position.
///
/// On successful completion the number of bytes actually copied will be
/// returned.
// Note: FreeBSD defines the offset argument as "off_t".  Linux and Android
// define it as "loff_t".  But on both OSes, on all supported platforms, those
// are 64 bits.  So Nix uses i64 to make the docs simple and consistent.
#[cfg(any(linux_android, target_os = "freebsd"))]
pub fn copy_file_range<Fd1: std::os::fd::AsFd, Fd2: std::os::fd::AsFd>(
    fd_in: Fd1,
    off_in: Option<&mut i64>,
    fd_out: Fd2,
    off_out: Option<&mut i64>,
    len: usize,
) -> Result<usize> {
    use std::os::fd::AsRawFd;

    let off_in = off_in
        .map(|offset| offset as *mut i64)
        .unwrap_or(ptr::null_mut());
    let off_out = off_out
        .map(|offset| offset as *mut i64)
        .unwrap_or(ptr::null_mut());

    cfg_if::cfg_if! {
        if #[cfg(target_os = "freebsd")] {
            let ret = unsafe {
                libc::copy_file_range(
                    fd_in.as_fd().as_raw_fd(),
                    off_in,
                    fd_out.as_fd().as_raw_fd(),
                    off_out,
                    len,
                    0,
                )
            };
        } else {
            // May Linux distros still don't include copy_file_range in their
            // libc implementations, so we need to make a direct syscall.
            let ret = unsafe {
                libc::syscall(
                    libc::SYS_copy_file_range,
                    fd_in.as_fd().as_raw_fd(),
                    off_in,
                    fd_out.as_fd().as_raw_fd(),
                    off_out,
                    len,
                    0,
                )
            };
        }
    }
    Errno::result(ret).map(|r| r as usize)
}

/// Splice data to/from a pipe
///
/// # See Also
/// *[`splice`](https://man7.org/linux/man-pages/man2/splice.2.html)
#[cfg(linux_android)]
pub fn splice<Fd1: std::os::fd::AsFd, Fd2: std::os::fd::AsFd>(
    fd_in: Fd1,
    off_in: Option<&mut libc::loff_t>,
    fd_out: Fd2,
    off_out: Option<&mut libc::loff_t>,
    len: usize,
    flags: SpliceFFlags,
) -> Result<usize> {
    use std::os::fd::AsRawFd;

    let off_in = off_in
        .map(|offset| offset as *mut libc::loff_t)
        .unwrap_or(ptr::null_mut());
    let off_out = off_out
        .map(|offset| offset as *mut libc::loff_t)
        .unwrap_or(ptr::null_mut());

    let ret = unsafe {
        libc::splice(fd_in.as_fd().as_raw_fd(), off_in, fd_out.as_fd().as_raw_fd(), off_out, len, flags.bits())
    };
    Errno::result(ret).map(|r| r as usize)
}

/// Duplicate pipe content
///
/// # See Also
/// *[`tee`](https://man7.org/linux/man-pages/man2/tee.2.html)
#[cfg(linux_android)]
pub fn tee<Fd1: std::os::fd::AsFd, Fd2: std::os::fd::AsFd>(
    fd_in: Fd1,
    fd_out: Fd2,
    len: usize,
    flags: SpliceFFlags,
) -> Result<usize> {
    use std::os::fd::AsRawFd;

    let ret = unsafe { libc::tee(fd_in.as_fd().as_raw_fd(), fd_out.as_fd().as_raw_fd(), len, flags.bits()) };
    Errno::result(ret).map(|r| r as usize)
}

/// Splice user pages to/from a pipe
///
/// # See Also
/// *[`vmsplice`](https://man7.org/linux/man-pages/man2/vmsplice.2.html)
#[cfg(linux_android)]
pub fn vmsplice<F: std::os::fd::AsFd>(
    fd: F,
    iov: &[std::io::IoSlice<'_>],
    flags: SpliceFFlags,
) -> Result<usize> {
    use std::os::fd::AsRawFd;

    let ret = unsafe {
        libc::vmsplice(
            fd.as_fd().as_raw_fd(),
            iov.as_ptr().cast(),
            iov.len(),
            flags.bits(),
        )
    };
    Errno::result(ret).map(|r| r as usize)
}
}

#[cfg(target_os = "linux")]
#[cfg(feature = "fs")]
libc_bitflags!(
    /// Mode argument flags for fallocate determining operation performed on a given range.
    #[cfg_attr(docsrs, doc(cfg(feature = "fs")))]
    pub struct FallocateFlags: c_int {
        /// File size is not changed.
        ///
        /// offset + len can be greater than file size.
        FALLOC_FL_KEEP_SIZE;
        /// Deallocates space by creating a hole.
        ///
        /// Must be ORed with FALLOC_FL_KEEP_SIZE. Byte range starts at offset and continues for len bytes.
        FALLOC_FL_PUNCH_HOLE;
        /// Removes byte range from a file without leaving a hole.
        ///
        /// Byte range to collapse starts at offset and continues for len bytes.
        FALLOC_FL_COLLAPSE_RANGE;
        /// Zeroes space in specified byte range.
        ///
        /// Byte range starts at offset and continues for len bytes.
        FALLOC_FL_ZERO_RANGE;
        /// Increases file space by inserting a hole within the file size.
        ///
        /// Does not overwrite existing data. Hole starts at offset and continues for len bytes.
        FALLOC_FL_INSERT_RANGE;
        /// Shared file data extants are made private to the file.
        ///
        /// Gaurantees that a subsequent write will not fail due to lack of space.
        FALLOC_FL_UNSHARE_RANGE;
    }
);

feature! {
#![feature = "fs"]

/// Manipulates file space.
///
/// Allows the caller to directly manipulate the allocated disk space for the
/// file referred to by fd.
#[cfg(target_os = "linux")]
#[cfg(feature = "fs")]
pub fn fallocate<Fd: std::os::fd::AsFd>(
    fd: Fd,
    mode: FallocateFlags,
    offset: libc::off_t,
    len: libc::off_t,
) -> Result<()> {
    use std::os::fd::AsRawFd;

    let res = unsafe { libc::fallocate(fd.as_fd().as_raw_fd(), mode.bits(), offset, len) };
    Errno::result(res).map(drop)
}

/// Argument to [`fspacectl`] describing the range to zero.  The first member is
/// the file offset, and the second is the length of the region.
#[cfg(any(target_os = "freebsd"))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SpacectlRange(pub libc::off_t, pub libc::off_t);

#[cfg(any(target_os = "freebsd"))]
impl SpacectlRange {
    /// Is the range empty?
    ///
    /// After a successful call to [`fspacectl`], A value of `true` for `SpacectlRange::is_empty`
    /// indicates that the operation is complete.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.1 == 0
    }

    /// Remaining length of the range
    #[inline]
    pub fn len(&self) -> libc::off_t {
        self.1
    }

    /// Next file offset to operate on
    #[inline]
    pub fn offset(&self) -> libc::off_t {
        self.0
    }
}

/// Punch holes in a file.
///
/// `fspacectl` instructs the file system to deallocate a portion of a file.
/// After a successful operation, this region of the file will return all zeroes
/// if read.  If the file system supports deallocation, then it may free the
/// underlying storage, too.
///
/// # Arguments
///
/// - `fd`      -   File to operate on
/// - `range.0` -   File offset at which to begin deallocation
/// - `range.1` -   Length of the region to deallocate
///
/// # Returns
///
/// The operation may deallocate less than the entire requested region.  On
/// success, it returns the region that still remains to be deallocated.  The
/// caller should loop until the returned region is empty.
///
/// # Example
///
#[cfg_attr(fbsd14, doc = " ```")]
#[cfg_attr(not(fbsd14), doc = " ```no_run")]
/// # use std::io::Write;
/// # use std::os::unix::fs::FileExt;
/// # use std::os::unix::io::AsRawFd;
/// # use nix::fcntl::*;
/// # use tempfile::tempfile;
/// const INITIAL: &[u8] = b"0123456789abcdef";
/// let mut f = tempfile().unwrap();
/// f.write_all(INITIAL).unwrap();
/// let mut range = SpacectlRange(3, 6);
/// while (!range.is_empty()) {
///     range = fspacectl(&f, range).unwrap();
/// }
/// let mut buf = vec![0; INITIAL.len()];
/// f.read_exact_at(&mut buf, 0).unwrap();
/// assert_eq!(buf, b"012\0\0\0\0\0\09abcdef");
/// ```
#[cfg(target_os = "freebsd")]
#[inline] // Delays codegen, preventing linker errors with dylibs and --no-allow-shlib-undefined
pub fn fspacectl<Fd: std::os::fd::AsFd>(fd: Fd, range: SpacectlRange) -> Result<SpacectlRange> {
    use std::os::fd::AsRawFd;

    let mut rqsr = libc::spacectl_range {
        r_offset: range.0,
        r_len: range.1,
    };
    let res = unsafe {
        libc::fspacectl(
            fd.as_fd().as_raw_fd(),
            libc::SPACECTL_DEALLOC, // Only one command is supported ATM
            &rqsr,
            0, // No flags are currently supported
            &mut rqsr,
        )
    };
    Errno::result(res).map(|_| SpacectlRange(rqsr.r_offset, rqsr.r_len))
}

/// Like [`fspacectl`], but will never return incomplete.
///
/// # Arguments
///
/// - `fd`      -   File to operate on
/// - `offset`  -   File offset at which to begin deallocation
/// - `len`     -   Length of the region to deallocate
///
/// # Returns
///
/// Returns `()` on success.  On failure, the region may or may not be partially
/// deallocated.
///
/// # Example
///
#[cfg_attr(fbsd14, doc = " ```")]
#[cfg_attr(not(fbsd14), doc = " ```no_run")]
/// # use std::io::Write;
/// # use std::os::unix::fs::FileExt;
/// # use std::os::unix::io::AsRawFd;
/// # use nix::fcntl::*;
/// # use tempfile::tempfile;
/// const INITIAL: &[u8] = b"0123456789abcdef";
/// let mut f = tempfile().unwrap();
/// f.write_all(INITIAL).unwrap();
/// fspacectl_all(&f, 3, 6).unwrap();
/// let mut buf = vec![0; INITIAL.len()];
/// f.read_exact_at(&mut buf, 0).unwrap();
/// assert_eq!(buf, b"012\0\0\0\0\0\09abcdef");
/// ```
#[cfg(target_os = "freebsd")]
#[inline] // Delays codegen, preventing linker errors with dylibs and --no-allow-shlib-undefined
pub fn fspacectl_all<Fd: std::os::fd::AsFd>(
    fd: Fd,
    offset: libc::off_t,
    len: libc::off_t,
) -> Result<()> {
    use std::os::fd::AsRawFd;

    let mut rqsr = libc::spacectl_range {
        r_offset: offset,
        r_len: len,
    };
    while rqsr.r_len > 0 {
        let res = unsafe {
            libc::fspacectl(
                fd.as_fd().as_raw_fd(),
                libc::SPACECTL_DEALLOC, // Only one command is supported ATM
                &rqsr,
                0, // No flags are currently supported
                &mut rqsr,
            )
        };
        Errno::result(res)?;
    }
    Ok(())
}

#[cfg(any(
    linux_android,
    target_os = "emscripten",
    target_os = "fuchsia",
    target_os = "wasi",
    target_env = "uclibc",
    target_os = "freebsd"
))]
mod posix_fadvise {
    use crate::errno::Errno;
    use crate::Result;

    #[cfg(feature = "fs")]
    libc_enum! {
        /// The specific advice provided to [`posix_fadvise`].
        #[repr(i32)]
        #[non_exhaustive]
        #[cfg_attr(docsrs, doc(cfg(feature = "fs")))]
        pub enum PosixFadviseAdvice {
            /// Revert to the default data access behavior.
            POSIX_FADV_NORMAL,
            /// The file data will be accessed sequentially.
            POSIX_FADV_SEQUENTIAL,
            /// A hint that file data will be accessed randomly, and prefetching is likely not
            /// advantageous.
            POSIX_FADV_RANDOM,
            /// The specified data will only be accessed once and then not reused.
            POSIX_FADV_NOREUSE,
            /// The specified data will be accessed in the near future.
            POSIX_FADV_WILLNEED,
            /// The specified data will not be accessed in the near future.
            POSIX_FADV_DONTNEED,
        }
    }

    feature! {
    #![feature = "fs"]
    /// Allows a process to describe to the system its data access behavior for an open file
    /// descriptor.
    ///
    /// # See Also
    /// * [`posix_fadvise`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_fadvise.html)
    pub fn posix_fadvise<Fd: std::os::fd::AsFd>(
        fd: Fd,
        offset: libc::off_t,
        len: libc::off_t,
        advice: PosixFadviseAdvice,
    ) -> Result<()> {
        use std::os::fd::AsRawFd;

        let res = unsafe { libc::posix_fadvise(fd.as_fd().as_raw_fd(), offset, len, advice as libc::c_int) };

        if res == 0 {
            Ok(())
        } else {
            Err(Errno::from_raw(res))
        }
    }
    }
}

/// Pre-allocate storage for a range in a file
///
/// # See Also
/// * [`posix_fallocate`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_fallocate.html)
#[cfg(any(
    linux_android,
    freebsdlike,
    target_os = "emscripten",
    target_os = "fuchsia",
    target_os = "wasi",
))]
pub fn posix_fallocate<Fd: std::os::fd::AsFd>(
    fd: Fd,
    offset: libc::off_t,
    len: libc::off_t,
) -> Result<()> {
    use std::os::fd::AsRawFd;

    let res = unsafe { libc::posix_fallocate(fd.as_fd().as_raw_fd(), offset, len) };
    match Errno::result(res) {
        Err(err) => Err(err),
        Ok(0) => Ok(()),
        Ok(errno) => Err(Errno::from_raw(errno)),
    }
}
}