forked from swiftlang/swift-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathData+Writing.swift
More file actions
775 lines (675 loc) · 34.8 KB
/
Data+Writing.swift
File metadata and controls
775 lines (675 loc) · 34.8 KB
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if FOUNDATION_FRAMEWORK
internal import _ForSwiftFoundation
#if !NO_FILESYSTEM
internal import DarwinPrivate // for VREG
#endif
#endif
internal import _FoundationCShims
#if canImport(Darwin)
import Darwin
#elseif canImport(Android)
@preconcurrency import Android
import unistd
#elseif canImport(Glibc)
@preconcurrency import Glibc
#elseif canImport(Musl)
@preconcurrency import Musl
#elseif os(Windows)
import CRT
import WinSDK
#elseif os(WASI)
@preconcurrency import WASILibc
#endif
#if !NO_FILESYSTEM
// MARK: - Helpers
#if os(Windows)
private func openFileDescriptorProtected(path: UnsafePointer<UInt16>, flags: Int32, options: Data.WritingOptions) -> Int32 {
var fd: CInt = 0
_ = _wsopen_s(&fd, path, flags, _SH_DENYNO, _S_IREAD | _S_IWRITE)
return fd
}
#else
private func openFileDescriptorProtected(path: UnsafePointer<CChar>, flags: Int32, options: Data.WritingOptions) -> Int32 {
#if FOUNDATION_FRAMEWORK
// Use file protection on this platform
return _NSOpenFileDescriptor_Protected(path, Int(flags), options, 0o666)
#else
return open(path, flags, 0o666)
#endif
}
#endif
private func writeToFileDescriptorWithProgress(_ fd: Int32, buffer: RawSpan, reportProgress: Bool) throws -> Int {
// Fetch this once
let length = buffer.byteCount
let preferredChunkSize: Int
let localProgress: Progress?
if reportProgress && Progress.current() != nil {
// To report progress, we have to try writing in smaller chunks than the whole file.
// Aim for about 1% increments in progress updates.
preferredChunkSize = max(length / 100, 1024 * 4)
localProgress = Progress(totalUnitCount: Int64(length))
} else {
preferredChunkSize = length
localProgress = nil
}
var remaining = buffer
while !remaining.isEmpty {
if let localProgress, localProgress.isCancelled {
throw CocoaError(.userCancelled)
}
// Don't ever attempt to write more than (2GB - 1 byte). Some platforms will return an error over that amount.
let numBytesRequested = CInt(clamping: min(preferredChunkSize, Int(CInt.max)))
let smallestAmountToRead = min(Int(numBytesRequested), remaining.byteCount)
let chunk = remaining.extracting(first: smallestAmountToRead)
var numBytesWritten: CInt
repeat {
if let localProgress, localProgress.isCancelled {
throw CocoaError(.userCancelled)
}
numBytesWritten = chunk.withUnsafeBytes { buf in
#if os(Windows)
_write(fd, buf.baseAddress, CUnsignedInt(buf.count))
#else
CInt(clamping: write(fd, buf.baseAddress!, buf.count))
#endif
}
if numBytesWritten < 0 {
let savedErrno = errno
logFileIOErrno(savedErrno, at: "write")
errno = savedErrno
// The write failed. Return a value which causes an error.
return -1
} else if numBytesWritten == 0 {
// Return the number of bytes written so far (which is compatible with the way write() would work with just one call)
break
} else {
remaining = remaining.extracting(droppingFirst: Int(numBytesWritten))
if let localProgress {
localProgress.completedUnitCount = Int64(length - remaining.byteCount)
}
// Anytime we write less than actually requested, stop, since the length is considered the "max" for socket calls
if numBytesWritten < chunk.byteCount {
break
}
}
} while numBytesWritten < 0 && errno == EINTR
}
let bytesWritten = length - remaining.byteCount
return bytesWritten
}
private func cleanupTemporaryDirectory(at inPath: String?) {
guard let inPath else { return }
#if canImport(Darwin) || os(Linux)
// Since we expect the directory to be empty at this point, try rmdir which is much faster than Darwin's removefile(3) for known empty directories
if inPath.withFileSystemRepresentation({ $0.flatMap(rmdir) }) == 0 {
return
}
#endif
// Attempt to use FileManager, ignore error
try? FileManager.default.removeItem(atPath: inPath)
}
/// Caller is responsible for calling `close` on the `Int32` file descriptor.
#if os(WASI)
@available(*, unavailable, message: "WASI does not have temporary directories")
#endif
private func createTemporaryFile(at destinationPath: String, inPath: borrowing some FileSystemRepresentable & ~Copyable, prefix: String, options: Data.WritingOptions, variant: String? = nil) throws -> (Int32, String) {
#if os(WASI)
// WASI does not have temp directories
throw CocoaError(.featureUnsupported)
#else
var directoryPath = destinationPath
if !directoryPath.isEmpty && directoryPath.last! != "/" {
directoryPath.append("/")
}
let pidString = String(ProcessInfo.processInfo.processIdentifier, radix: 16, uppercase: true)
let template = directoryPath + prefix + pidString + ".XXXXXX"
let maxCount = 7
for _ in 0 ..< maxCount {
#if FOUNDATION_FRAMEWORK
let (sandboxResult, amkrErrno) = inPath.withFileSystemRepresentation { inPathFileSystemRep -> ((Int32, String)?, Int32?) in
guard let inPathFileSystemRep else {
return (nil, nil)
}
// First, try _amkrtemp to carry over any sandbox extensions for inPath to the temporary file (even if the application isn't sandboxed)
guard let uniqueTempFile = _amkrtemp(inPathFileSystemRep) else {
return (nil, errno)
}
defer { free(uniqueTempFile) }
let fd = openFileDescriptorProtected(path: uniqueTempFile, flags: O_CREAT | O_EXCL | O_RDWR, options: options)
if fd >= 0 {
// Got a good fd
return ((fd, String(cString: uniqueTempFile)), nil)
}
return (nil, errno)
}
// If _amkrtemp succeeded, return its result
if let sandboxResult {
return sandboxResult
}
// If we have no result and also no errno, just fail immediately because we failed to produce a file system representation for the path
guard let amkrErrno else {
throw CocoaError.errorWithFilePath(.fileReadInvalidFileName, inPath.path)
}
// If _amkrtemp failed with EEXIST, just retry
if amkrErrno == EEXIST {
continue
}
// Otherwise, fall through to mktemp below
#endif
let result = try template.withMutableFileSystemRepresentation { templateFileSystemRep -> (Int32, String)? in
guard let templateFileSystemRep else {
throw CocoaError(.fileWriteInvalidFileName)
}
// The warning diligently tells us we shouldn't be using mktemp() because blindly opening the returned path opens us up to a TOCTOU race. However, in this case, we're being careful by doing O_CREAT|O_EXCL and repeating, just like the implementation of mkstemp.
// Furthermore, we can't compatibly switch to mkstemp() until we have the ability to set fchmod correctly, which requires the ability to query the current umask, which we don't have. (22033100)
#if os(Windows)
guard _mktemp_s(templateFileSystemRep, strlen(templateFileSystemRep) + 1) == 0 else {
throw CocoaError.errorWithFilePath(inPath, errno: errno, reading: false, variant: variant)
}
let fd = try String(cString: templateFileSystemRep).withNTPathRepresentation {
openFileDescriptorProtected(path: $0, flags: _O_BINARY | _O_CREAT | _O_EXCL | _O_RDWR, options: options)
}
#else
guard mktemp(templateFileSystemRep) != nil else {
throw CocoaError.errorWithFilePath(inPath, errno: errno, reading: false, variant: variant)
}
let fd = openFileDescriptorProtected(path: templateFileSystemRep, flags: O_CREAT | O_EXCL | O_RDWR, options: options)
#endif
if fd >= 0 {
// Got a good fd
return (fd, String(cString: templateFileSystemRep))
}
// If the file exists, we repeat. Otherwise throw the error.
if errno != EEXIST {
#if FOUNDATION_FRAMEWORK
let debugDescription = "Creating a temporary file via mktemp failed. Creating the temporary file via _amkrtemp previously also failed with errno \(amkrErrno)"
#else
let debugDescription: String? = nil
#endif
throw CocoaError.errorWithFilePath(inPath, errno: errno, reading: false, variant: variant, debugDescription: debugDescription)
}
// Try again
return nil
}
if let result {
return result
}
}
// We hit max count, prevent an infinite loop; even if the error is obscure
throw CocoaError(.fileWriteUnknown)
#endif // os(WASI)
}
/// Returns `(file descriptor, temporary file path, temporary directory path)`
/// Caller is responsible for calling `close` on the `Int32` file descriptor and calling `cleanupTemporaryDirectory` on the temporary directory path. The temporary directory path may be nil, if it does not need to be cleaned up.
#if os(WASI)
@available(*, unavailable, message: "WASI does not have temporary directories")
#endif
private func createProtectedTemporaryFile(at destinationPath: String, inPath: borrowing some FileSystemRepresentable & ~Copyable, options: Data.WritingOptions, variant: String? = nil) throws -> (Int32, String, String?) {
#if os(WASI)
// WASI does not have temp directories
throw CocoaError(.featureUnsupported)
#else
#if FOUNDATION_FRAMEWORK
if _foundation_sandbox_check(getpid(), nil) != 0 {
// Convert the path back into a string
let url = URL(fileURLWithPath: destinationPath, isDirectory: false)
var temporaryDirectoryPath: String
do {
temporaryDirectoryPath = try FileManager.default.url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: url, create: true).path(percentEncoded: false)
} catch {
if let variant, let cocoaError = error as? CocoaError {
let code = cocoaError.code
var userInfo = cocoaError.userInfo
userInfo[NSUserStringVariantErrorKey] = variant
throw CocoaError(code, userInfo: userInfo)
} else {
throw error
}
}
let updatedOptions = _NSDataWritingOptionsForRelocatedAtomicWrite(options, destinationPath)
let auxFile = temporaryDirectoryPath.appendingPathComponent(destinationPath.lastPathComponent)
return try auxFile.withFileSystemRepresentation { auxFileFileSystemRep in
guard let auxFileFileSystemRep else {
throw CocoaError(.fileWriteInvalidFileName)
}
let fd = openFileDescriptorProtected(path: auxFileFileSystemRep, flags: O_CREAT | O_EXCL | O_RDWR, options: updatedOptions)
if fd >= 0 {
return (fd, auxFile, temporaryDirectoryPath)
} else {
let savedErrno = errno
cleanupTemporaryDirectory(at: temporaryDirectoryPath)
throw CocoaError.errorWithFilePath(inPath, errno: savedErrno, reading: false, variant: variant)
}
}
}
#endif
let temporaryDirectoryPath = destinationPath.deletingLastPathComponent()
let (fd, auxFile) = try createTemporaryFile(at: temporaryDirectoryPath, inPath: inPath, prefix: ".dat.nosync", options: options, variant: variant)
return (fd, auxFile, nil)
#endif // os(WASI)
}
private func write(buffer: RawSpan, toFileDescriptor fd: Int32, path: borrowing some FileSystemRepresentable & ~Copyable, parentProgress: Progress?) throws {
let count = buffer.byteCount
parentProgress?.becomeCurrent(withPendingUnitCount: Int64(count))
defer {
parentProgress?.resignCurrent()
}
if count > 0 {
let result = try writeToFileDescriptorWithProgress(fd, buffer: buffer, reportProgress: parentProgress != nil)
if result != count {
throw CocoaError.errorWithFilePath(path, errno: errno, reading: false)
}
}
if !buffer.isEmpty {
#if os(Windows)
let hFile: HANDLE? = HANDLE(bitPattern: _get_osfhandle(fd))
// On Windows, only call _commit if the fd corresponds to an actual file
// on disk.
let res: CInt = if let hFile, GetFileType(hFile) == FILE_TYPE_DISK {
_commit(fd)
} else {
0
}
#else
let res = fsync(fd)
#endif
if res < 0 {
let savedErrno = errno
let error = CocoaError.errorWithFilePath(path, errno: savedErrno, reading: false)
#if os(Linux)
// Linux returns -1 and errno == EINVAL if trying to sync a special file, eg a fifo, character device etc which can be ignored.
if savedErrno != EINVAL {
throw error
}
#else
throw error
#endif
}
}
}
// MARK: - Entry points
#if FOUNDATION_FRAMEWORK
extension NSData {
/// Objective-C entry point to Swift `Data` writing.
@objc(_writeDataToPath:data:options:reportProgress:error:)
internal static func _writeData(toPath path: String, data: NSData, options: Data.WritingOptions, reportProgress: Bool) throws {
try autoreleasepool {
let span = RawSpan(_unsafeStart: data.bytes, byteCount: data.count)
try writeToFile(path: path, buffer: span, options: options, attributes: [:], reportProgress: reportProgress)
}
}
@objc(_writeDataToPath:data:options:stringEncodingAttributeData:reportProgress:error:)
internal static func _writeData(toPath path: String, data: NSData, options: Data.WritingOptions, stringEncodingAttributeData: Data, reportProgress: Bool) throws {
try autoreleasepool {
let span = RawSpan(_unsafeStart: data.bytes, byteCount: data.count)
try writeToFile(path: path, buffer: span, options: options, attributes: [NSFileAttributeStringEncoding : stringEncodingAttributeData], reportProgress: reportProgress)
}
}
}
#endif
internal func writeToFile(path inPath: borrowing some FileSystemRepresentable & ~Copyable, buffer: RawSpan, options: Data.WritingOptions, attributes: [String : Data] = [:], reportProgress: Bool = false) throws {
#if os(WASI) // `.atomic` is unavailable on WASI
try writeToFileNoAux(path: inPath, buffer: buffer, options: options, attributes: attributes, reportProgress: reportProgress)
#else
if options.contains(.atomic) {
try writeToFileAux(path: inPath, buffer: buffer, options: options, attributes: attributes, reportProgress: reportProgress)
} else {
try writeToFileNoAux(path: inPath, buffer: buffer, options: options, attributes: attributes, reportProgress: reportProgress)
}
#endif
}
/// Create a new file out of `Data` at a path, using atomic writing.
#if os(WASI)
@available(*, unavailable, message: "atomic writing is unavailable in WASI because temporary files are not supported")
#endif
private func writeToFileAux(path inPath: borrowing some FileSystemRepresentable & ~Copyable, buffer: RawSpan, options: Data.WritingOptions, attributes: [String : Data], reportProgress: Bool) throws {
#if os(WASI)
// `.atomic` is unavailable on WASI
throw CocoaError(.featureUnsupported)
#else
assert(options.contains(.atomic))
// TODO: Somehow avoid copying back and forth to a String to hold the path
#if os(Windows)
var (fd, auxPath, temporaryDirectoryPath) = try createProtectedTemporaryFile(at: inPath.path, inPath: inPath, options: options, variant: "Folder")
// Cleanup temporary directory
defer { cleanupTemporaryDirectory(at: temporaryDirectoryPath) }
guard fd >= 0 else {
throw CocoaError.errorWithFilePath(inPath, errno: errno, reading: false)
}
defer { if fd >= 0 { _close(fd) } }
let callback = (reportProgress && Progress.current() != nil) ? Progress(totalUnitCount: Int64(buffer.byteCount)) : nil
do {
try write(buffer: buffer, toFileDescriptor: fd, path: inPath, parentProgress: callback)
} catch {
try auxPath.withNTPathRepresentation { pwszAuxPath in
_ = DeleteFileW(pwszAuxPath)
}
if callback?.isCancelled ?? false {
throw CocoaError(.userCancelled)
} else {
throw CocoaError.errorWithFilePath(inPath, errno: errno, reading: false)
}
}
writeExtendedAttributes(fd: fd, attributes: attributes)
_close(fd)
fd = -1
try auxPath.withNTPathRepresentation { pwszAuxiliaryPath in
defer { _ = DeleteFileW(pwszAuxiliaryPath) }
var hFile = CreateFileW(pwszAuxiliaryPath, DELETE,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nil, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
nil)
if hFile == INVALID_HANDLE_VALUE {
throw CocoaError.errorWithFilePath(inPath, win32: GetLastError(), reading: false)
}
defer {
switch hFile {
case INVALID_HANDLE_VALUE:
break
default:
_ = CloseHandle(hFile)
}
}
try inPath.path.withNTPathRepresentation { pwszPath in
let cchLength = wcslen(pwszPath)
let cbSize = cchLength * MemoryLayout<WCHAR>.size
let dwSize = DWORD(MemoryLayout<FILE_RENAME_INFO>.size + cbSize + MemoryLayout<WCHAR>.size)
try withUnsafeTemporaryAllocation(byteCount: Int(dwSize),
alignment: MemoryLayout<FILE_RENAME_INFO>.alignment) { pBuffer in
var pInfo = pBuffer.baseAddress?.bindMemory(to: FILE_RENAME_INFO.self, capacity: 1)
pInfo?.pointee.Flags = FILE_RENAME_FLAG_POSIX_SEMANTICS | FILE_RENAME_FLAG_REPLACE_IF_EXISTS
pInfo?.pointee.RootDirectory = nil
pInfo?.pointee.FileNameLength = DWORD(cbSize)
pBuffer.baseAddress?.advanced(by: MemoryLayout<FILE_RENAME_INFO>.offset(of: \.FileName)!)
.withMemoryRebound(to: WCHAR.self, capacity: cchLength + 1) {
wcscpy_s($0, cchLength + 1, pwszPath)
}
if !SetFileInformationByHandle(hFile, FileRenameInfoEx, pInfo, dwSize) {
let dwError = GetLastError()
guard dwError == ERROR_NOT_SAME_DEVICE else {
throw CocoaError.errorWithFilePath(inPath, win32: dwError, reading: false)
}
_ = CloseHandle(hFile)
hFile = INVALID_HANDLE_VALUE
// The move is across volumes.
guard MoveFileExW(pwszAuxiliaryPath, pwszPath, MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) else {
throw CocoaError.errorWithFilePath(inPath, win32: GetLastError(), reading: false)
}
}
}
}
}
#else
try inPath.withFileSystemRepresentation { inPathFileSystemRep in
guard let inPathFileSystemRep else {
throw CocoaError(.fileWriteInvalidFileName)
}
var mode: mode_t?
#if FOUNDATION_FRAMEWORK
var newPath = inPath.path
var preRenameAttributes = PreRenameAttributes()
var attrs = attrlist(bitmapcount: u_short(ATTR_BIT_MAP_COUNT), reserved: 0, commonattr: attrgroup_t(ATTR_CMN_OBJTYPE | ATTR_CMN_ACCESSMASK | ATTR_CMN_FULLPATH), volattr: .init(), dirattr: .init(), fileattr: .init(ATTR_FILE_LINKCOUNT), forkattr: .init())
// Provide FSOPT_UNIQUE to ensure that the file is a regular file with a single hard link (so that we can rely on ATTR_CMN_FULLPATH)
let result = getattrlist(inPathFileSystemRep, &attrs, &preRenameAttributes, MemoryLayout<PreRenameAttributes>.size, .init(FSOPT_NOFOLLOW | FSOPT_UNIQUE))
if result == 0 {
// Use the path from the buffer
mode = mode_t(preRenameAttributes.mode)
// Copy the contents of the getattrlist buffer for the string into a Swift String
withUnsafePointer(to: preRenameAttributes.fullPathBuf) { ptrToTuple in
// The length of the string is passed back to us in the same struct as the C string itself
// n.b. Length includes the null-termination byte. Use this size for the buffer.
let length = Int(preRenameAttributes.fullPathAttr.attr_length)
ptrToTuple.withMemoryRebound(to: CChar.self, capacity: length) { pointer in
newPath = String(cString: pointer)
}
}
} else if (errno != ENOENT) && (errno != ENAMETOOLONG) && (errno != ENOTCAPABLE) {
throw CocoaError.errorWithFilePath(inPath, errno: errno, reading: false)
}
#else
let newPath = inPath.path
#endif
var (fd, auxPath, temporaryDirectoryPath) = try createProtectedTemporaryFile(at: newPath, inPath: inPath, options: options, variant: "Folder")
guard fd >= 0 else {
let savedErrno = errno
// Cleanup temporary directory
cleanupTemporaryDirectory(at: temporaryDirectoryPath)
throw CocoaError.errorWithFilePath(inPath, errno: savedErrno, reading: false)
}
defer { close(fd) }
let parentProgress = (reportProgress && Progress.current() != nil) ? Progress(totalUnitCount: Int64(buffer.byteCount)) : nil
do {
try write(buffer: buffer, toFileDescriptor: fd, path: inPath, parentProgress: parentProgress)
} catch {
let savedError = errno
auxPath.withFileSystemRepresentation { pathFileSystemRep in
guard let pathFileSystemRep else { return }
unlink(pathFileSystemRep)
}
cleanupTemporaryDirectory(at: temporaryDirectoryPath)
if parentProgress?.isCancelled ?? false {
throw CocoaError(.userCancelled)
} else {
throw CocoaError.errorWithFilePath(inPath, errno: savedError, reading: false)
}
}
writeExtendedAttributes(fd: fd, attributes: attributes)
try auxPath.withFileSystemRepresentation { auxPathFileSystemRep in
guard let auxPathFileSystemRep else {
// The aux path is not a valid file name
throw CocoaError(.fileWriteInvalidFileName)
}
try newPath.withFileSystemRepresentation { newPathFileSystemRep in
guard let newPathFileSystemRep else {
// The new path is not a valid file name
throw CocoaError(.fileWriteInvalidFileName)
}
if rename(auxPathFileSystemRep, newPathFileSystemRep) != 0 {
if errno == EINVAL {
// rename() fails on DOS file systems if newname already exists.
// Makes "atomically" next to meaningless, but...
// We try a little harder but this is not thread-safe nor atomic
let (fd2, auxPath2, temporaryDirectoryPath2) = try createProtectedTemporaryFile(at: newPath, inPath: inPath, options: options)
close(fd2)
try auxPath2.withFileSystemRepresentation { auxPath2FileSystemRep in
guard let auxPath2FileSystemRep else {
// The aux path (2) is not a valid file name
throw CocoaError(.fileWriteInvalidFileName)
}
unlink(auxPath2FileSystemRep)
if rename(newPathFileSystemRep, auxPath2FileSystemRep) != 0 || rename(auxPathFileSystemRep, newPathFileSystemRep) != 0 {
// Swap failed
let savedErrno = errno
unlink(auxPath2FileSystemRep)
unlink(auxPathFileSystemRep)
cleanupTemporaryDirectory(at: temporaryDirectoryPath)
cleanupTemporaryDirectory(at: temporaryDirectoryPath2)
throw CocoaError.errorWithFilePath(inPath, errno: savedErrno, reading: false)
}
unlink(auxPath2FileSystemRep)
cleanupTemporaryDirectory(at: temporaryDirectoryPath2)
}
} else if errno == EBUSY {
// EBUSY may mean it was an HFS+ file system and something (perhaps another process) still had a reference to resources (vm pages, fd) associated with the file. Try again, non-atomically.
unlink(auxPathFileSystemRep)
cleanupTemporaryDirectory(at: temporaryDirectoryPath)
// We also throw away any other options, and do not report progress. This may or may not be a bug.
return try writeToFile(path: inPath, buffer: buffer, options: [], attributes: attributes, reportProgress: false)
} else {
let savedErrno = errno
unlink(auxPathFileSystemRep)
cleanupTemporaryDirectory(at: temporaryDirectoryPath)
throw CocoaError.errorWithFilePath(inPath, errno: savedErrno, reading: false)
}
}
cleanupTemporaryDirectory(at: temporaryDirectoryPath)
if let mode {
// Try to change the mode if the path has not changed. Do our best, but don't report an error.
#if FOUNDATION_FRAMEWORK
var attrs = attrlist(bitmapcount: u_short(ATTR_BIT_MAP_COUNT), reserved: 0, commonattr: attrgroup_t(ATTR_CMN_FULLPATH), volattr: .init(), dirattr: .init(), fileattr: .init(), forkattr: .init())
var buffer = FullPathAttributes()
let result = fgetattrlist(fd, &attrs, &buffer, MemoryLayout<FullPathAttributes>.size, .init(FSOPT_NOFOLLOW | FSOPT_UNIQUE))
// Compare the last one to this one
if result == 0 {
withUnsafePointer(to: buffer.fullPathBuf) { ptrToTuple in
let newPathLength = strlen(newPathFileSystemRep) + 1 // Account for the null terminator, because we compare it to fullPathLength
let fullPathLength = Int(buffer.fullPathAttr.attr_length) // This includes the null terminator
ptrToTuple.withMemoryRebound(to: CChar.self, capacity: fullPathLength) { newNewPathFileSystemRep in
if fullPathLength == newPathLength && strncmp(newPathFileSystemRep, newNewPathFileSystemRep, fullPathLength) == 0 {
// Try to change the mode
fchmod(fd, mode)
}
}
}
}
#else
fchmod(fd, mode)
#endif
}
}
}
}
#endif
#endif // os(WASI)
}
/// Create a new file out of `Data` at a path, not using atomic writing.
private func writeToFileNoAux(path inPath: borrowing some FileSystemRepresentable & ~Copyable, buffer: RawSpan, options: Data.WritingOptions, attributes: [String : Data], reportProgress: Bool) throws {
#if !os(WASI) // `.atomic` is unavailable on WASI
assert(!options.contains(.atomic))
#endif
#if os(Windows)
try inPath.path.withNTPathRepresentation { pwszPath in
let hFile = CreateFileW(pwszPath, GENERIC_WRITE, FILE_SHARE_READ, nil, options.contains(.withoutOverwriting) ? CREATE_NEW : CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nil)
if hFile == INVALID_HANDLE_VALUE {
throw CocoaError.errorWithFilePath(inPath, win32: GetLastError(), reading: false)
}
let fd = _open_osfhandle(Int(bitPattern: hFile), _O_RDWR | _O_APPEND)
if fd == -1 {
throw CocoaError.errorWithFilePath(inPath, errno: errno, reading: false)
}
defer { _close(fd) }
let callback: Progress? = (reportProgress && Progress.current() != nil) ? Progress(totalUnitCount: Int64(buffer.byteCount)) : nil
do {
try write(buffer: buffer, toFileDescriptor: fd, path: inPath, parentProgress: callback)
} catch {
let savedError = errno
if callback?.isCancelled ?? false {
throw CocoaError(.userCancelled)
} else {
throw CocoaError.errorWithFilePath(inPath, errno: savedError, reading: false)
}
}
writeExtendedAttributes(fd: fd, attributes: attributes)
}
#else
try inPath.withFileSystemRepresentation { pathFileSystemRep in
guard let pathFileSystemRep else {
throw CocoaError(.fileWriteInvalidFileName)
}
var flags: Int32 = O_WRONLY | O_CREAT | O_TRUNC
if options.contains(.withoutOverwriting) {
flags = flags | O_EXCL
}
let fd = openFileDescriptorProtected(path: pathFileSystemRep, flags: flags, options: options)
guard fd >= 0 else {
let savedErrno = errno
throw CocoaError.errorWithFilePath(inPath, errno: savedErrno, reading: false)
}
defer { close(fd) }
let parentProgress = (reportProgress && Progress.current() != nil) ? Progress(totalUnitCount: Int64(buffer.byteCount)) : nil
do {
try write(buffer: buffer, toFileDescriptor: fd, path: inPath, parentProgress: parentProgress)
} catch {
let savedError = errno
if parentProgress?.isCancelled ?? false {
// We could have deleted the partially written data above, but for max binary compatibility we'll only delete if a progress is in use.
// Ignore any error; it doesn't matter at this point.
unlink(pathFileSystemRep)
throw CocoaError(.userCancelled)
} else {
throw CocoaError.errorWithFilePath(inPath, errno: savedError, reading: false)
}
}
writeExtendedAttributes(fd: fd, attributes: attributes)
}
#endif
}
private func writeExtendedAttributes(fd: Int32, attributes: [String : Data]) {
// Write extended attributes
for (key, value) in attributes {
value.withUnsafeBytes { valueBuf in
// Returns non-zero on error, but we ignore them
#if canImport(Darwin)
_ = fsetxattr(fd, key, valueBuf.baseAddress!, valueBuf.count, 0, 0)
#elseif os(FreeBSD)
_ = extattr_set_fd(fd, EXTATTR_NAMESPACE_USER, key, valueBuf.baseAddress!, valueBuf.count)
#elseif os(OpenBSD)
return
#elseif canImport(Glibc) || canImport(Musl)
_ = fsetxattr(fd, key, valueBuf.baseAddress!, valueBuf.count, 0)
#endif
}
}
}
#endif // !NO_FILESYSTEM
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
extension Data {
#if FOUNDATION_FRAMEWORK
public typealias WritingOptions = NSData.WritingOptions
#else
// This is imported from the ObjC 'option set', which is actually a combination of an option and an enumeration (file protection).
public struct WritingOptions : OptionSet, Sendable {
public let rawValue: UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
/// An option to write data to an auxiliary file first and then replace the original file with the auxiliary file when the write completes.
#if os(WASI)
@available(*, unavailable, message: "atomic writing is unavailable in WASI because temporary files are not supported")
#endif
public static let atomic = WritingOptions(rawValue: 1 << 0)
/// An option that attempts to write data to a file and fails with an error if the destination file already exists.
public static let withoutOverwriting = WritingOptions(rawValue: 1 << 1)
/// An option to not encrypt the file when writing it out.
public static let noFileProtection = WritingOptions(rawValue: 0x10000000)
/// An option to make the file accessible only while the device is unlocked.
public static let completeFileProtection = WritingOptions(rawValue: 0x20000000)
/// An option to allow the file to be accessible while the device is unlocked or the file is already open.
public static let completeFileProtectionUnlessOpen = WritingOptions(rawValue: 0x30000000)
/// An option to allow the file to be accessible after a user first unlocks the device.
public static let completeFileProtectionUntilFirstUserAuthentication = WritingOptions(rawValue: 0x40000000)
/// An option the system uses when determining the file protection options that the system assigns to the data.
public static let fileProtectionMask = WritingOptions(rawValue: 0xf0000000)
}
#endif
/// Write the contents of the `Data` to a location.
///
/// - parameter url: The location to write the data into.
/// - parameter options: Options for writing the data. Default value is `[]`.
/// - throws: An error in the Cocoa domain, if there is an error writing to the `URL`.
public func write(to url: URL, options: Data.WritingOptions = []) throws {
#if !os(WASI) // `.atomic` is unavailable on WASI
if options.contains(.withoutOverwriting) && options.contains(.atomic) {
fatalError("withoutOverwriting is not supported with atomic")
}
#endif
guard url.isFileURL else {
throw CocoaError(.fileWriteUnsupportedScheme)
}
#if !NO_FILESYSTEM
try writeToFile(path: url, buffer: self.bytes, options: options, reportProgress: true)
#else
throw CocoaError(.featureUnsupported)
#endif
}
}