File: SystemFileHandle.swift

package info (click to toggle)
swiftlang 6.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,791,532 kB
  • sloc: cpp: 9,901,743; ansic: 2,201,431; asm: 1,091,827; python: 308,252; objc: 82,166; f90: 80,126; lisp: 38,358; pascal: 25,559; sh: 20,429; ml: 5,058; perl: 4,745; makefile: 4,484; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (1379 lines) | stat: -rw-r--r-- 51,860 bytes parent folder | download
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2023 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Linux) || os(Android)
import NIOConcurrencyHelpers
import NIOCore
import NIOPosix
@preconcurrency import SystemPackage

#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#endif

/// An implementation of ``FileHandleProtocol`` which is backed by system calls and a file
/// descriptor.
@_spi(Testing)
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public final class SystemFileHandle {
    /// The executor on which to execute system calls.
    internal var threadPool: NIOThreadPool { self.sendableView.threadPool }

    /// The path used to open this handle.
    internal var path: FilePath { self.sendableView.path }

    @_spi(Testing)
    public struct Materialization: Sendable {
        /// The path of the file which was created.
        var created: FilePath
        /// The desired path of the file.
        var desired: FilePath
        /// Whether the ``desired`` file must be created exclusively. If `true` then if a file
        /// already exists at the ``desired`` path then an error is thrown, otherwise any existing
        /// file will be replaced.`
        var exclusive: Bool
        /// The mode used to materialize the file.
        var mode: Mode

        enum Mode {
            /// Rename the created file to become the desired file.
            case rename
            #if canImport(Glibc) || canImport(Musl)
            /// Link the unnamed file to the desired file using 'linkat(2)'.
            case link
            #endif
        }
    }

    fileprivate enum Lifecycle {
        case open(FileDescriptor)
        case detached
        case closed
    }

    @_spi(Testing)
    public let sendableView: SendableView

    /// The file handle may be for a non-seekable file, so it shouldn't be 'Sendable', however, most
    /// of the work performed on behalf of the handle is executed in a thread pool which means that
    /// its state must be 'Sendable'.
    @_spi(Testing)
    public struct SendableView: Sendable {
        /// The lifecycle of the file handle.
        fileprivate let lifecycle: NIOLockedValueBox<Lifecycle>

        /// The executor on which to execute system calls.
        internal let threadPool: NIOThreadPool

        /// The path used to open this handle.
        internal let path: FilePath

        /// An action to take when closing the file handle.
        fileprivate let materialization: Materialization?

        fileprivate init(
            lifecycle: Lifecycle,
            threadPool: NIOThreadPool,
            path: FilePath,
            materialization: Materialization?
        ) {
            self.lifecycle = NIOLockedValueBox(lifecycle)
            self.threadPool = threadPool
            self.path = path
            self.materialization = materialization
        }
    }

    /// Creates a handle which takes ownership of the provided descriptor.
    ///
    /// - Precondition: The descriptor must be open.
    /// - Parameters:
    ///   - descriptor: The open file descriptor.
    ///   - path: The path to the file used to open the descriptor.
    ///   - executor: The executor which system calls will be performed on.
    @_spi(Testing)
    public init(
        takingOwnershipOf descriptor: FileDescriptor,
        path: FilePath,
        materialization: Materialization? = nil,
        threadPool: NIOThreadPool
    ) {
        self.sendableView = SendableView(
            lifecycle: .open(descriptor),
            threadPool: threadPool,
            path: path,
            materialization: materialization
        )
    }

    deinit {
        self.sendableView.lifecycle.withLockedValue { lifecycle -> Void in
            switch lifecycle {
            case .open:
                fatalError(
                    """
                    Leaking file descriptor: the handle for '\(self.sendableView.path)' MUST be closed or \
                    detached with 'close()' or 'detachUnsafeFileDescriptor()' before the final \
                    reference to the handle is dropped.
                    """
                )
            case .detached, .closed:
                ()
            }
        }
    }
}

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension SystemFileHandle.SendableView {
    /// Returns the file descriptor if it's available; `nil` otherwise.
    internal func descriptorIfAvailable() -> FileDescriptor? {
        return self.lifecycle.withLockedValue {
            switch $0 {
            case let .open(descriptor):
                return descriptor
            case .detached, .closed:
                return nil
            }
        }
    }

    /// Executes a closure with the file descriptor it it's available otherwise throws the result
    /// of `onUnavailable`.
    internal func _withUnsafeDescriptor<R>(
        _ execute: (FileDescriptor) throws -> R,
        onUnavailable: () -> FileSystemError
    ) throws -> R {
        if let descriptor = self.descriptorIfAvailable() {
            return try execute(descriptor)
        } else {
            throw onUnavailable()
        }
    }

    /// Executes a closure with the file descriptor it it's available otherwise throws the result
    /// of `onUnavailable`.
    internal func _withUnsafeDescriptorResult<R>(
        _ execute: (FileDescriptor) -> Result<R, FileSystemError>,
        onUnavailable: () -> FileSystemError
    ) -> Result<R, FileSystemError> {
        if let descriptor = self.descriptorIfAvailable() {
            return execute(descriptor)
        } else {
            return .failure(onUnavailable())
        }
    }
}

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension SystemFileHandle: FileHandleProtocol {
    // Notes which apply to the following block of functions:
    //
    // 1. Documentation is inherited from ``FileHandleProtocol`` and is not repeated here.
    // 2. The functions should be annotated with @_spi(Testing); this is not possible with the
    //    conformance to FileHandleProtocol which requires them to be only marked public. However
    //    this is not an issue: the implementing type is annotated with @_spi(Testing) so the
    //    functions are not actually public.
    // 3. Most of these functions call through to a synchronous version prefixed with an underscore,
    //    this is to make testing possible with the system call mocking infrastructure we are
    //    currently using.

    public func info() async throws -> FileInfo {
        return try await self.threadPool.runIfActive { [sendableView] in
            try sendableView._info().get()
        }
    }

    public func replacePermissions(_ permissions: FilePermissions) async throws {
        return try await self.threadPool.runIfActive { [sendableView] in
            try sendableView._replacePermissions(permissions)
        }
    }

    public func addPermissions(_ permissions: FilePermissions) async throws -> FilePermissions {
        return try await self.threadPool.runIfActive { [sendableView] in
            try sendableView._addPermissions(permissions)
        }
    }

    public func removePermissions(_ permissions: FilePermissions) async throws -> FilePermissions {
        return try await self.threadPool.runIfActive { [sendableView] in
            try sendableView._removePermissions(permissions)
        }
    }

    public func attributeNames() async throws -> [String] {
        return try await self.threadPool.runIfActive { [sendableView] in
            try sendableView._attributeNames()
        }
    }

    public func valueForAttribute(_ name: String) async throws -> [UInt8] {
        return try await self.threadPool.runIfActive { [sendableView] in
            try sendableView._valueForAttribute(name)
        }
    }

    public func updateValueForAttribute(
        _ bytes: some (Sendable & RandomAccessCollection<UInt8>),
        attribute name: String
    ) async throws {
        return try await self.threadPool.runIfActive { [sendableView] in
            try sendableView._updateValueForAttribute(bytes, attribute: name)
        }
    }

    public func removeValueForAttribute(_ name: String) async throws {
        return try await self.threadPool.runIfActive { [sendableView] in
            try sendableView._removeValueForAttribute(name)
        }
    }

    public func synchronize() async throws {
        return try await self.threadPool.runIfActive { [sendableView] in
            try sendableView._synchronize()
        }
    }

    public func withUnsafeDescriptor<R: Sendable>(
        _ execute: @Sendable @escaping (FileDescriptor) throws -> R
    ) async throws -> R {
        try await self.threadPool.runIfActive { [sendableView] in
            try sendableView._withUnsafeDescriptor {
                return try execute($0)
            } onUnavailable: {
                FileSystemError(
                    code: .closed,
                    message: "File is closed ('\(sendableView.path)').",
                    cause: nil,
                    location: .here()
                )
            }
        }
    }

    public func detachUnsafeFileDescriptor() throws -> FileDescriptor {
        return try self.sendableView.lifecycle.withLockedValue { lifecycle in
            switch lifecycle {
            case let .open(descriptor):
                lifecycle = .detached

                // We need to be careful handling files which have delayed materialization to avoid
                // leftover temporary files.
                //
                // Where we use the 'link' mode we simply call materialize and return the
                // descriptor as it will be materialized when closed.
                //
                // For the 'rename' mode we create a hard link to the desired file and unlink the
                // created file.
                guard let materialization = self.sendableView.materialization else {
                    // File opened 'normally', just detach and return.
                    return descriptor
                }

                switch materialization.mode {
                #if canImport(Glibc) || canImport(Musl)
                case .link:
                    let result = self.sendableView._materializeLink(
                        descriptor: descriptor,
                        from: materialization.created,
                        to: materialization.desired,
                        exclusive: materialization.exclusive
                    )
                    return try result.map { descriptor }.get()
                #endif

                case .rename:
                    let result = Syscall.link(
                        from: materialization.created,
                        to: materialization.desired
                    ).mapError { errno in
                        FileSystemError.link(
                            errno: errno,
                            from: materialization.created,
                            to: materialization.desired,
                            location: .here()
                        )
                    }.flatMap {
                        Syscall.unlink(path: materialization.created).mapError { errno in
                            .unlink(errno: errno, path: materialization.created, location: .here())
                        }
                    }

                    return try result.map { descriptor }.get()
                }

            case .detached:
                throw FileSystemError(
                    code: .closed,
                    message: """
                        File descriptor has already been detached ('\(self.path)'). Handles may \
                        only be detached once.
                        """,
                    cause: nil,
                    location: .here()
                )

            case .closed:
                throw FileSystemError(
                    code: .closed,
                    message: """
                        Cannot detach descriptor for closed file ('\(self.path)'). Handles may \
                        only be detached while they are open.
                        """,
                    cause: nil,
                    location: .here()
                )
            }
        }
    }

    public func close() async throws {
        try await self.threadPool.runIfActive { [sendableView] in
            try sendableView._close(materialize: true).get()
        }
    }

    public func close(makeChangesVisible: Bool) async throws {
        try await self.threadPool.runIfActive { [sendableView] in
            try sendableView._close(materialize: makeChangesVisible).get()
        }
    }

    @_spi(Testing)
    public enum UpdatePermissionsOperation { case set, add, remove }
}

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension SystemFileHandle.SendableView {
    /// Returns a string in the format: "{message}, the file '{path}' is closed."
    private func fileIsClosed(_ message: String) -> String {
        return "\(message), the file '\(self.path)' is closed."
    }

    /// Returns a string in the format: "{message} for '{path}'."
    private func unknown(_ message: String) -> String {
        return "\(message) for '\(self.path)'."
    }

    @_spi(Testing)
    public func _info() -> Result<FileInfo, FileSystemError> {
        self._withUnsafeDescriptorResult { descriptor in
            return descriptor.status().map { stat in
                FileInfo(platformSpecificStatus: stat)
            }.mapError { errno in
                .stat("fstat", errno: errno, path: self.path, location: .here())
            }
        } onUnavailable: {
            FileSystemError(
                code: .closed,
                message: self.fileIsClosed("Unable to get information"),
                cause: nil,
                location: .here()
            )
        }
    }

    @_spi(Testing)
    public func _replacePermissions(_ permissions: FilePermissions) throws {
        try self._withUnsafeDescriptor { descriptor in
            try self.updatePermissions(
                permissions,
                operation: .set,
                operand: permissions,
                descriptor: descriptor
            )
        } onUnavailable: {
            FileSystemError(
                code: .closed,
                message: self.fileIsClosed("Unable to replace permissions"),
                cause: nil,
                location: .here()
            )
        }
    }

    @_spi(Testing)
    public func _addPermissions(_ permissions: FilePermissions) throws -> FilePermissions {
        try self._withUnsafeDescriptor { descriptor in
            switch descriptor.status() {
            case let .success(status):
                let info = FileInfo(platformSpecificStatus: status)
                let merged = info.permissions.union(permissions)

                // Check if we need to make any changes.
                if merged == info.permissions {
                    return merged
                }

                // Apply the new permissions.
                try self.updatePermissions(
                    merged,
                    operation: .add,
                    operand: permissions,
                    descriptor: descriptor
                )

                return merged

            case let .failure(errno):
                throw FileSystemError(
                    message: "Unable to add permissions.",
                    wrapping: .stat("fstat", errno: errno, path: self.path, location: .here())
                )
            }
        } onUnavailable: {
            FileSystemError(
                code: .closed,
                message: self.fileIsClosed("Unable to add permissions"),
                cause: nil,
                location: .here()
            )
        }
    }

    @_spi(Testing)
    public func _removePermissions(_ permissions: FilePermissions) throws -> FilePermissions {
        try self._withUnsafeDescriptor { descriptor in
            switch descriptor.status() {
            case let .success(status):
                let info = FileInfo(platformSpecificStatus: status)
                let merged = info.permissions.subtracting(permissions)

                // Check if we need to make any changes.
                if merged == info.permissions {
                    return merged
                }

                // Apply the new permissions.
                try self.updatePermissions(
                    merged,
                    operation: .remove,
                    operand: permissions,
                    descriptor: descriptor
                )

                return merged

            case let .failure(errno):
                throw FileSystemError(
                    message: "Unable to remove permissions.",
                    wrapping: .stat("fstat", errno: errno, path: self.path, location: .here())
                )

            }
        } onUnavailable: {
            FileSystemError(
                code: .closed,
                message: self.fileIsClosed("Unable to remove permissions"),
                cause: nil,
                location: .here()
            )
        }
    }

    private func updatePermissions(
        _ permissions: FilePermissions,
        operation: SystemFileHandle.UpdatePermissionsOperation,
        operand: FilePermissions,
        descriptor: FileDescriptor
    ) throws {
        return try descriptor.changeMode(permissions).mapError { errno in
            FileSystemError.fchmod(
                operation: operation,
                operand: operand,
                permissions: permissions,
                errno: errno,
                path: self.path,
                location: .here()
            )
        }.get()
    }

    @_spi(Testing)
    public func _attributeNames() throws -> [String] {
        return try self._withUnsafeDescriptor { descriptor in
            return try descriptor.listExtendedAttributes().mapError { errno in
                FileSystemError.flistxattr(errno: errno, path: self.path, location: .here())
            }.get()
        } onUnavailable: {
            FileSystemError(
                code: .closed,
                message: self.fileIsClosed("Could not list extended attributes"),
                cause: nil,
                location: .here()
            )
        }
    }

    @_spi(Testing)
    public func _valueForAttribute(_ name: String) throws -> [UInt8] {
        return try self._withUnsafeDescriptor { descriptor in
            return try descriptor.readExtendedAttribute(
                named: name
            ).flatMapError { errno -> Result<[UInt8], FileSystemError> in
                switch errno {
                #if canImport(Darwin)
                case .attributeNotFound:
                    // Okay, return empty value.
                    return .success([])
                #endif
                case .noData:
                    // Okay, return empty value.
                    return .success([])
                default:
                    let error = FileSystemError.fgetxattr(
                        attribute: name,
                        errno: errno,
                        path: self.path,
                        location: .here()
                    )
                    return .failure(error)
                }
            }.get()
        } onUnavailable: {
            FileSystemError(
                code: .closed,
                message: self.fileIsClosed(
                    "Could not get value for extended attribute ('\(name)')"
                ),
                cause: nil,
                location: .here()
            )
        }
    }

    @_spi(Testing)
    public func _updateValueForAttribute(
        _ bytes: some RandomAccessCollection<UInt8>,
        attribute name: String
    ) throws {
        return try self._withUnsafeDescriptor { descriptor in
            func withUnsafeBufferPointer(_ body: (UnsafeBufferPointer<UInt8>) throws -> Void) throws {
                try bytes.withContiguousStorageIfAvailable(body)
                    ?? Array(bytes).withUnsafeBufferPointer(body)
            }

            try withUnsafeBufferPointer { pointer in
                let rawBufferPointer = UnsafeRawBufferPointer(pointer)
                return try descriptor.setExtendedAttribute(
                    named: name,
                    to: rawBufferPointer
                ).mapError { errno in
                    FileSystemError.fsetxattr(
                        attribute: name,
                        errno: errno,
                        path: self.path,
                        location: .here()
                    )
                }.get()
            }
        } onUnavailable: {
            FileSystemError(
                code: .closed,
                message: self.fileIsClosed(
                    "Could not set value for extended attribute ('\(name)')"
                ),
                cause: nil,
                location: .here()
            )
        }
    }

    @_spi(Testing)
    public func _removeValueForAttribute(_ name: String) throws {
        return try self._withUnsafeDescriptor { descriptor in
            try descriptor.removeExtendedAttribute(name).mapError { errno in
                FileSystemError.fremovexattr(
                    attribute: name,
                    errno: errno,
                    path: self.path,
                    location: .here()
                )
            }.get()
        } onUnavailable: {
            FileSystemError(
                code: .closed,
                message: self.fileIsClosed("Could not remove extended attribute ('\(name)')"),
                cause: nil,
                location: .here()
            )
        }
    }

    @_spi(Testing)
    public func _synchronize() throws {
        try self._withUnsafeDescriptor { descriptor in
            try descriptor.synchronize().mapError { errno in
                FileSystemError.fsync(errno: errno, path: self.path, location: .here())
            }.get()
        } onUnavailable: {
            FileSystemError(
                code: .closed,
                message: self.fileIsClosed("Could not synchronize"),
                cause: nil,
                location: .here()
            )
        }
    }

    internal func _duplicate() -> Result<FileDescriptor, FileSystemError> {
        return self._withUnsafeDescriptorResult { descriptor in
            Result {
                try descriptor.duplicate()
            }.mapError { error in
                FileSystemError.dup(error: error, path: self.path, location: .here())
            }
        } onUnavailable: {
            FileSystemError(
                code: .closed,
                message: "Unable to duplicate descriptor of closed handle for '\(self.path)'.",
                cause: nil,
                location: .here()
            )
        }
    }

    @_spi(Testing)
    public func _close(materialize: Bool) -> Result<Void, FileSystemError> {
        let descriptor: FileDescriptor? = self.lifecycle.withLockedValue { lifecycle in
            switch lifecycle {
            case let .open(descriptor):
                lifecycle = .closed
                return descriptor
            case .detached, .closed:
                return nil
            }
        }

        guard let descriptor = descriptor else {
            return .success(())
        }

        // Materialize then close.
        let materializeResult = self._materialize(materialize, descriptor: descriptor)

        return Result {
            try descriptor.close()
        }.mapError { error in
            .close(error: error, path: self.path, location: .here())
        }.flatMap {
            materializeResult
        }
    }

    #if canImport(Glibc) || canImport(Musl)
    fileprivate func _materializeLink(
        descriptor: FileDescriptor,
        from createdPath: FilePath,
        to desiredPath: FilePath,
        exclusive: Bool
    ) -> Result<Void, FileSystemError> {
        func linkAtEmptyPath() -> Result<Void, Errno> {
            Syscall.linkAt(
                from: "",
                relativeTo: descriptor,
                to: desiredPath,
                relativeTo: .currentWorkingDirectory,
                flags: [.emptyPath]
            )
        }

        func linkAtProcFS() -> Result<Void, Errno> {
            Syscall.linkAt(
                from: FilePath("/proc/self/fd/\(descriptor.rawValue)"),
                relativeTo: .currentWorkingDirectory,
                to: desiredPath,
                relativeTo: .currentWorkingDirectory,
                flags: [.followSymbolicLinks]
            )
        }

        let result: Result<Void, FileSystemError>

        switch linkAtEmptyPath() {
        case .success:
            result = .success(())

        case .failure(.fileExists) where !exclusive:
            // File exists and materialization _isn't_ exclusive. Remove the existing
            // file and try again.
            let removeResult = Libc.remove(desiredPath).mapError { errno in
                FileSystemError.remove(errno: errno, path: desiredPath, location: .here())
            }

            let linkAtResult = linkAtEmptyPath().flatMapError { errno in
                // ENOENT means we likely didn't have the 'CAP_DAC_READ_SEARCH' capability
                // so try again by linking to the descriptor via procfs.
                if errno == .noSuchFileOrDirectory {
                    return linkAtProcFS()
                } else {
                    return .failure(errno)
                }
            }.mapError { errno in
                FileSystemError.link(
                    errno: errno,
                    from: createdPath,
                    to: desiredPath,
                    location: .here()
                )
            }

            result = removeResult.flatMap { linkAtResult }

        case .failure(.noSuchFileOrDirectory):
            result = linkAtProcFS().flatMapError { errno in
                if errno == .fileExists, !exclusive {
                    return Libc.remove(desiredPath).mapError { errno in
                        FileSystemError.remove(
                            errno: errno,
                            path: desiredPath,
                            location: .here()
                        )
                    }.flatMap {
                        return linkAtProcFS().mapError { errno in
                            FileSystemError.link(
                                errno: errno,
                                from: createdPath,
                                to: desiredPath,
                                location: .here()
                            )
                        }
                    }
                } else {
                    let error = FileSystemError.link(
                        errno: errno,
                        from: createdPath,
                        to: desiredPath,
                        location: .here()
                    )
                    return .failure(error)
                }
            }

        case .failure(let errno):
            result = .failure(
                .link(errno: errno, from: createdPath, to: desiredPath, location: .here())
            )
        }

        return result
    }
    #endif

    func _materialize(
        _ materialize: Bool,
        descriptor: FileDescriptor
    ) -> Result<Void, FileSystemError> {
        guard let materialization = self.materialization else { return .success(()) }

        let createdPath = materialization.created
        let desiredPath = materialization.desired

        let result: Result<Void, FileSystemError>
        switch materialization.mode {
        #if canImport(Glibc) || canImport(Musl)
        case .link:
            if materialize {
                result = self._materializeLink(
                    descriptor: descriptor,
                    from: createdPath,
                    to: desiredPath,
                    exclusive: materialization.exclusive
                )
            } else {
                result = .success(())
            }
        #endif

        case .rename:
            if materialize {
                let renameResult: Result<Void, Errno>
                #if canImport(Darwin)
                renameResult = Syscall.rename(
                    from: createdPath,
                    to: desiredPath,
                    options: materialization.exclusive ? [.exclusive] : []
                )
                #elseif canImport(Glibc) || canImport(Musl)
                // The created and desired paths are absolute, so the relative descriptors are
                // ignored. However, they must still be provided to 'rename' in order to pass
                // flags.
                renameResult = Syscall.rename(
                    from: createdPath,
                    relativeTo: .currentWorkingDirectory,
                    to: desiredPath,
                    relativeTo: .currentWorkingDirectory,
                    flags: materialization.exclusive ? [.exclusive] : []
                )
                #endif

                // A file exists at the desired path and the user specified exclusive creation,
                // clear up by removing the file we did create.
                if materialization.exclusive, case .failure(.fileExists) = renameResult {
                    _ = Libc.remove(createdPath)
                }

                result = renameResult.mapError { errno in
                    .rename(
                        errno: errno,
                        oldName: createdPath,
                        newName: desiredPath,
                        location: .here()
                    )
                }
            } else {
                // Don't materialize the source, remove it
                result = Libc.remove(createdPath).mapError {
                    .remove(errno: $0, path: createdPath, location: .here())
                }
            }
        }

        return result
    }
}

// MARK: - Readable File Handle

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension SystemFileHandle: ReadableFileHandleProtocol {
    // Notes which apply to the following block of functions:
    //
    // 1. Documentation is inherited from ``FileHandleProtocol`` and is not repeated here.
    // 2. The functions should be annotated with @_spi(Testing); this is not possible with the
    //    conformance to FileHandleProtocol which requires them to be only marked public. However
    //    this is not an issue: the implementing type is annotated with @_spi(Testing) so the
    //    functions are not actually public.

    public func readChunk(
        fromAbsoluteOffset offset: Int64,
        length: ByteCount
    ) async throws -> ByteBuffer {
        return try await self.threadPool.runIfActive { [sendableView] in
            return try sendableView._withUnsafeDescriptor { descriptor in
                try descriptor.readChunk(
                    fromAbsoluteOffset: offset,
                    length: length.bytes
                ).flatMapError { error in
                    if let errno = error as? Errno, errno == .illegalSeek {
                        guard offset == 0 else {
                            return .failure(
                                FileSystemError(
                                    code: .unsupported,
                                    message: "File is unseekable.",
                                    cause: nil,
                                    location: .here()
                                )
                            )
                        }

                        return descriptor.readChunk(length: length.bytes).mapError { error in
                            FileSystemError.read(
                                usingSyscall: .read,
                                error: error,
                                path: sendableView.path,
                                location: .here()
                            )
                        }
                    } else {
                        return .failure(
                            FileSystemError.read(
                                usingSyscall: .pread,
                                error: error,
                                path: sendableView.path,
                                location: .here()
                            )
                        )
                    }
                }
                .get()
            } onUnavailable: {
                FileSystemError(
                    code: .closed,
                    message: "Couldn't read chunk, the file '\(sendableView.path)' is closed.",
                    cause: nil,
                    location: .here()
                )
            }
        }
    }

    public func readChunks(
        in range: Range<Int64>,
        chunkLength size: ByteCount
    ) -> FileChunks {
        return FileChunks(handle: self, chunkLength: size, range: range)
    }
}

// MARK: - Writable File Handle

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension SystemFileHandle: WritableFileHandleProtocol {
    @discardableResult
    public func write(
        contentsOf bytes: some (Sequence<UInt8> & Sendable),
        toAbsoluteOffset offset: Int64
    ) async throws -> Int64 {
        return try await self.threadPool.runIfActive { [sendableView] in
            return try sendableView._withUnsafeDescriptor { descriptor in
                try descriptor.write(contentsOf: bytes, toAbsoluteOffset: offset)
                    .flatMapError { error in
                        if let errno = error as? Errno, errno == .illegalSeek {
                            guard offset == 0 else {
                                return .failure(
                                    FileSystemError(
                                        code: .unsupported,
                                        message: "File is unseekable.",
                                        cause: nil,
                                        location: .here()
                                    )
                                )
                            }

                            return descriptor.write(contentsOf: bytes)
                                .mapError { error in
                                    FileSystemError.write(
                                        usingSyscall: .write,
                                        error: error,
                                        path: sendableView.path,
                                        location: .here()
                                    )
                                }
                        } else {
                            return .failure(
                                FileSystemError.write(
                                    usingSyscall: .pwrite,
                                    error: error,
                                    path: sendableView.path,
                                    location: .here()
                                )
                            )
                        }
                    }
                    .get()
            } onUnavailable: {
                FileSystemError(
                    code: .closed,
                    message: "Couldn't write bytes, the file '\(sendableView.path)' is closed.",
                    cause: nil,
                    location: .here()
                )
            }
        }
    }

    public func resize(to size: ByteCount) async throws {
        try await self.threadPool.runIfActive { [sendableView] in
            try sendableView._resize(to: size).get()
        }
    }
}

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension SystemFileHandle.SendableView {
    func _resize(to size: ByteCount) -> Result<(), FileSystemError> {
        return self._withUnsafeDescriptorResult { descriptor in
            Result {
                try descriptor.resize(to: size.bytes, retryOnInterrupt: true)
            }.mapError { error in
                FileSystemError.ftruncate(error: error, path: self.path, location: .here())
            }
        } onUnavailable: {
            FileSystemError(
                code: .closed,
                message: "Unable to resize file '\(self.path)'.",
                cause: nil,
                location: .here()
            )
        }
    }
}

// MARK: - Directory File Handle

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension SystemFileHandle: DirectoryFileHandleProtocol {
    public typealias ReadFileHandle = SystemFileHandle
    public typealias WriteFileHandle = SystemFileHandle
    public typealias ReadWriteFileHandle = SystemFileHandle

    public func listContents(recursive: Bool) -> DirectoryEntries {
        return DirectoryEntries(handle: self, recursive: recursive)
    }

    public func openFile(
        forReadingAt path: FilePath,
        options: OpenOptions.Read
    ) async throws -> SystemFileHandle {
        let opts = options.descriptorOptions.union(.nonBlocking)
        let handle = try await self.threadPool.runIfActive { [sendableView] in
            let handle = try sendableView._open(
                atPath: path,
                mode: .readOnly,
                options: opts,
                transactionalIfPossible: false
            ).get()
            // Okay to transfer: we just created it and are now moving back to the callers task.
            return UnsafeTransfer(handle)
        }
        return handle.wrappedValue
    }

    public func openFile(
        forReadingAndWritingAt path: FilePath,
        options: OpenOptions.Write
    ) async throws -> SystemFileHandle {
        let perms = options.permissionsForRegularFile
        let opts = options.descriptorOptions.union(.nonBlocking)
        let handle = try await self.threadPool.runIfActive { [sendableView] in
            let handle = try sendableView._open(
                atPath: path,
                mode: .readWrite,
                options: opts,
                permissions: perms,
                transactionalIfPossible: options.newFile?.transactionalCreation ?? false
            ).get()
            // Okay to transfer: we just created it and are now moving back to the callers task.
            return UnsafeTransfer(handle)
        }
        return handle.wrappedValue
    }

    public func openFile(
        forWritingAt path: FilePath,
        options: OpenOptions.Write
    ) async throws -> SystemFileHandle {
        let perms = options.permissionsForRegularFile
        let opts = options.descriptorOptions.union(.nonBlocking)
        let handle = try await self.threadPool.runIfActive { [sendableView] in
            let handle = try sendableView._open(
                atPath: path,
                mode: .writeOnly,
                options: opts,
                permissions: perms,
                transactionalIfPossible: options.newFile?.transactionalCreation ?? false
            ).get()
            // Okay to transfer: we just created it and are now moving back to the callers task.
            return UnsafeTransfer(handle)
        }
        return handle.wrappedValue
    }

    public func openDirectory(
        atPath path: FilePath,
        options: OpenOptions.Directory
    ) async throws -> SystemFileHandle {
        let opts = options.descriptorOptions.union(.nonBlocking)
        let handle = try await self.threadPool.runIfActive { [sendableView] in
            let handle = try sendableView._open(
                atPath: path,
                mode: .readOnly,
                options: opts,
                transactionalIfPossible: false
            ).get()
            // Okay to transfer: we just created it and are now moving back to the callers task.
            return UnsafeTransfer(handle)
        }
        return handle.wrappedValue
    }
}

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension SystemFileHandle.SendableView {
    func _open(
        atPath path: FilePath,
        mode: FileDescriptor.AccessMode,
        options: FileDescriptor.OpenOptions,
        permissions: FilePermissions? = nil,
        transactionalIfPossible transactional: Bool
    ) -> Result<SystemFileHandle, FileSystemError> {
        if transactional {
            if path.isAbsolute {
                // The provided path is absolute: just open the handle normally.
                return SystemFileHandle.syncOpen(
                    atPath: path,
                    mode: mode,
                    options: options,
                    permissions: permissions,
                    transactionalIfPossible: transactional,
                    threadPool: self.threadPool
                )
            } else if self.path.isAbsolute {
                // The parent path is absolute and the provided path is relative; combine them.
                return SystemFileHandle.syncOpen(
                    atPath: self.path.appending(path.components),
                    mode: mode,
                    options: options,
                    permissions: permissions,
                    transactionalIfPossible: transactional,
                    threadPool: self.threadPool
                )
            }

            // At this point transactional file creation isn't possible. Fallback to
            // non-transactional.
        }

        // Provided and parent paths are relative. There's no way we can safely delay
        // materialization as we don't know if the parent descriptor will be available when
        // closing the opened file.
        return self._withUnsafeDescriptorResult { descriptor in
            descriptor.open(
                atPath: path,
                mode: mode,
                options: options,
                permissions: permissions
            ).map { newDescriptor in
                SystemFileHandle(
                    takingOwnershipOf: newDescriptor,
                    path: self.path.appending(path.components).lexicallyNormalized(),
                    threadPool: self.threadPool
                )
            }.mapError { errno in
                .open("openat", error: errno, path: self.path, location: .here())
            }
        } onUnavailable: {
            FileSystemError(
                code: .closed,
                message: """
                    Unable to open file at path '\(path)' relative to '\(self.path)', the file \
                    is closed.
                    """,
                cause: nil,
                location: .here()
            )
        }
    }
}

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension SystemFileHandle {
    static func syncOpen(
        atPath path: FilePath,
        mode: FileDescriptor.AccessMode,
        options: FileDescriptor.OpenOptions,
        permissions: FilePermissions?,
        transactionalIfPossible transactional: Bool,
        threadPool: NIOThreadPool
    ) -> Result<SystemFileHandle, FileSystemError> {
        let isWritable = (mode == .writeOnly || mode == .readWrite)
        let exclusiveCreate = options.contains(.exclusiveCreate)
        let truncate = options.contains(.truncate)
        let delayMaterialization = transactional && isWritable && (exclusiveCreate || truncate)

        if delayMaterialization {
            // When opening in this mode we can more "atomically" create the file, that is, by not
            // leaving the user with a half written file should e.g. the system crash or throw an
            // error while writing. On non-Android Linux we do this by opening the directory for
            // the path with `O_TMPFILE` and creating a hard link when closing the file. On other
            // platforms we generate a dot file with a randomised suffix name and rename it to the
            // destination.
            #if os(Android)
            let temporaryHardLink = false
            #else
            let temporaryHardLink = true
            #endif
            return Self.syncOpenWithMaterialization(
                atPath: path,
                mode: mode,
                options: options,
                permissions: permissions,
                threadPool: threadPool,
                useTemporaryFileIfPossible: temporaryHardLink
            )
        } else {
            return Self.syncOpen(
                atPath: path,
                mode: mode,
                options: options,
                permissions: permissions,
                threadPool: threadPool
            )
        }
    }

    static func syncOpen(
        atPath path: FilePath,
        mode: FileDescriptor.AccessMode,
        options: FileDescriptor.OpenOptions,
        permissions: FilePermissions?,
        threadPool: NIOThreadPool
    ) -> Result<SystemFileHandle, FileSystemError> {
        return Result {
            try FileDescriptor.open(
                path,
                mode,
                options: options,
                permissions: permissions
            )
        }.map { descriptor in
            SystemFileHandle(
                takingOwnershipOf: descriptor,
                path: path,
                threadPool: threadPool
            )
        }.mapError { errno in
            FileSystemError.open("open", error: errno, path: path, location: .here())
        }
    }

    static func syncOpenWithMaterialization(
        atPath path: FilePath,
        mode: FileDescriptor.AccessMode,
        options originalOptions: FileDescriptor.OpenOptions,
        permissions: FilePermissions?,
        threadPool: NIOThreadPool,
        useTemporaryFileIfPossible: Bool = true
    ) -> Result<SystemFileHandle, FileSystemError> {
        let openedPath: FilePath
        let desiredPath: FilePath

        // There are two different approaches to materializing the file. On Linux, and where
        // supported, we can open the file with the 'O_TMPFILE' flag which creates a temporary
        // unnamed file. If we later decide the make the file visible we use 'linkat(2)' with
        // the appropriate flags to link the unnamed temporary file to the desired file path.
        //
        // On other platforms, and when not supported on Linux, we create a regular file as we
        // normally would and when we decide to materialize it we simply rename it to the desired
        // name (or remove it if we aren't materializing it).
        //
        // There are, however, some wrinkles.
        //
        // Normally when a file is opened the system will open files specified with relative paths
        // relative to the current working directory. However, when we delay making a file visible
        // the current working directory could change which introduces an awkward race. Consider
        // the following sequence of events:
        //
        // 1. User opens a file with delay materialization using a relative path
        // 2. A temporary file is opened relative to the current working directory
        // 3. The current working directory is changed
        // 4. The file is closed.
        //
        // Where is the file created? It *should* be relative to the working directory at the time
        // the user opened the file. However, if materializing the file relative to the new
        // working directory would be very surprising behaviour for the user.
        //
        // To work around this we will get the current working directory only if the provided path
        // is relative. That way all operations can be done on a path relative to a fixed point
        // (i.e. the current working directory at this point in time).
        if path.isRelative {
            let currentWorkingDirectory: FilePath

            switch Libc.getcwd() {
            case .success(let path):
                currentWorkingDirectory = path
            case .failure(let errno):
                let error = FileSystemError(
                    message: """
                        Can't open relative '\(path)' as the current working directory couldn't \
                        be determined.
                        """,
                    wrapping: .getcwd(errno: errno, location: .here())
                )
                return .failure(error)
            }

            func makePath() -> FilePath {
                #if canImport(Glibc) || canImport(Musl)
                if useTemporaryFileIfPossible {
                    return currentWorkingDirectory.appending(path.components.dropLast())
                }
                #endif
                return currentWorkingDirectory.appending(path.components.dropLast())
                    .appending(".tmp-" + String(randomAlphaNumericOfLength: 6))
            }

            openedPath = makePath()
            desiredPath = currentWorkingDirectory.appending(path.components)
        } else {
            func makePath() -> FilePath {
                #if canImport(Glibc) || canImport(Musl)
                if useTemporaryFileIfPossible {
                    return path.removingLastComponent()
                }
                #endif
                return path.removingLastComponent()
                    .appending(".tmp-" + String(randomAlphaNumericOfLength: 6))
            }

            openedPath = makePath()
            desiredPath = path
        }

        let materializationMode: Materialization.Mode
        let options: FileDescriptor.OpenOptions

        #if canImport(Glibc) || canImport(Musl)
        if useTemporaryFileIfPossible {
            options = [.temporaryFile]
            materializationMode = .link
        } else {
            options = originalOptions
            materializationMode = .rename
        }
        #else
        options = originalOptions
        materializationMode = .rename
        #endif

        let materialization = Materialization(
            created: openedPath,
            desired: desiredPath,
            exclusive: originalOptions.contains(.exclusiveCreate),
            mode: materializationMode
        )

        do {
            let descriptor = try FileDescriptor.open(
                openedPath,
                mode,
                options: options,
                permissions: permissions
            )

            let handle = SystemFileHandle(
                takingOwnershipOf: descriptor,
                path: openedPath,
                materialization: materialization,
                threadPool: threadPool
            )

            return .success(handle)
        } catch {
          #if canImport(Glibc) || canImport(Musl)
            // 'O_TMPFILE' isn't supported for the current file system, try again but using
            // rename instead.
            if useTemporaryFileIfPossible, let errno = error as? Errno, errno == .notSupported {
                return Self.syncOpenWithMaterialization(
                    atPath: path,
                    mode: mode,
                    options: originalOptions,
                    permissions: permissions,
                    threadPool: threadPool,
                    useTemporaryFileIfPossible: false
                )
            }
            #endif
            return .failure(.open("open", error: error, path: path, location: .here()))
        }
    }
}

#endif