-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathunxip.swift
1608 lines (1380 loc) · 45.2 KB
/
unxip.swift
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
#if canImport(Glibc)
@preconcurrency import SwiftGlibc // stdout, stderr
#else
@preconcurrency import unistd // optind
#endif
import Foundation
#if canImport(Compression)
import Compression
#else
import FoundationXML
import GNUSource
@preconcurrency import getopt // optind
import lzma
import zlib
#endif
#if canImport(UIKit) // Embedded, in other words
import libxml2
#endif
// MARK: - Internal utilities
#if PROFILING
import os
let readLog = { true }() ? OSLog(subsystem: "com.saagarjha.unxip.read", category: "Read") : .disabled
let decompressionLog = { true }() ? OSLog(subsystem: "com.saagarjha.unxip.chunk", category: "Decompression") : .disabled
let compressionLog = { true }() ? OSLog(subsystem: "com.saagarjha.unxip.compression", category: "Compression") : .disabled
let filesystemLog = { true }() ? OSLog(subsystem: "com.saagarjha.unxip.filesystem", category: "Filesystem") : .disabled
#endif
actor Condition {
enum State {
case indeterminate
case waiting(CheckedContinuation<Void, Never>)
case signaled
}
var state = State.indeterminate
nonisolated func signal() {
Task {
await _signal()
}
}
func _signal() {
switch state {
case .signaled:
preconditionFailure("Condition has already been signaled")
case .waiting(let continuation):
continuation.resume()
fallthrough
case .indeterminate:
state = .signaled
}
}
func wait() async {
switch state {
case .waiting(_):
preconditionFailure("Condition is already waiting")
case .indeterminate:
await withCheckedContinuation {
state = .waiting($0)
}
case .signaled:
break
}
}
}
struct Queue<Element> {
var buffer = [Element?.none]
var readIndex = 0 {
didSet {
readIndex %= buffer.count
}
}
var writeIndex = 0 {
didSet {
writeIndex %= buffer.count
}
}
var empty: Bool {
buffer[readIndex] == nil
}
mutating func push(_ element: Element) {
if readIndex == writeIndex,
!empty
{
resize()
}
buffer[writeIndex] = element
writeIndex += 1
}
mutating func pop() -> Element {
defer {
buffer[readIndex] = nil
readIndex += 1
}
return buffer[readIndex]!
}
mutating func resize() {
var buffer = [Element?](repeating: nil, count: self.buffer.count * 2)
let slice1 = self.buffer[readIndex..<self.buffer.endIndex]
let slice2 = self.buffer[self.buffer.startIndex..<readIndex]
buffer[0..<slice1.count] = slice1
buffer[slice1.count..<slice1.count + slice2.count] = slice2
self.buffer = buffer
readIndex = 0
writeIndex = slice1.count + slice2.count
}
}
protocol ErasedIterator<Element>: AsyncIteratorProtocol, Sendable {
}
public struct ErasedSequence<Element>: AsyncSequence {
struct ErasedButBarelyLikeWithThosePinkPearlThingsSequence<S: AsyncSequence>: AsyncSequence where S.AsyncIterator: Sendable {
struct Iterator: ErasedIterator {
var iterator: S.AsyncIterator
mutating func next() async throws -> S.Element? {
try await iterator.next()
}
}
let sequence: S
func makeAsyncIterator() -> Iterator {
.init(iterator: sequence.makeAsyncIterator())
}
}
public struct Iterator<T>: AsyncIteratorProtocol, Sendable {
var iterator: any ErasedIterator<Element>
public mutating func next() async throws -> Element? {
try await iterator.next()
}
}
let iterator: any ErasedIterator<Element>
init<S: AsyncSequence>(sequence: S) where S.Element == Element, S.AsyncIterator: Sendable {
iterator = ErasedButBarelyLikeWithThosePinkPearlThingsSequence(sequence: sequence).makeAsyncIterator()
}
public func makeAsyncIterator() -> Iterator<Element> {
.init(iterator: iterator)
}
}
extension AsyncThrowingStream where Element: Sendable, Failure == Error {
actor PermissiveActionLink<S: AsyncSequence> where S.Element == Element, S.AsyncIterator: Sendable {
var iterator: S.AsyncIterator
let count: Int
var queued = [CheckedContinuation<Element?, Error>]()
init(iterator: sending S.AsyncIterator, count: Int) {
self.iterator = iterator
self.count = count
}
func next() async throws -> Element? {
try await withCheckedThrowingContinuation { continuation in
queued.append(continuation)
if queued.count == count {
Task {
await step()
}
}
}
}
func step() async {
var iterator = self.iterator
let next: Result<Element?, Error>
do {
next = .success(try await iterator.next())
} catch {
next = .failure(error)
}
self.iterator = iterator
for continuation in queued {
continuation.resume(with: next)
}
queued.removeAll()
}
}
}
protocol BackpressureProvider {
associatedtype Element
var loaded: Bool { get }
mutating func enqueue(_: Element)
mutating func dequeue(_: Element)
}
final class CountedBackpressure<Element>: BackpressureProvider {
var count = 0
let max: Int
var loaded: Bool {
count >= max
}
init(max: Int) {
self.max = max
}
func enqueue(_: Element) {
count += 1
}
func dequeue(_: Element) {
count -= 1
}
}
final class FileBackpressure: BackpressureProvider {
var size = 0
let maxSize: Int
var loaded: Bool {
size >= maxSize
}
init(maxSize: Int) {
self.maxSize = maxSize
}
func enqueue(_ file: File) {
size += file.data.map(\.count).reduce(0, +)
}
func dequeue(_ file: File) {
size -= file.data.map(\.count).reduce(0, +)
}
}
actor BackpressureStream<Element: Sendable, Backpressure: BackpressureProvider>: AsyncSequence where Backpressure.Element == Element {
struct Iterator: AsyncIteratorProtocol {
let stream: BackpressureStream
func next() async throws -> Element? {
try await stream.next()
}
}
// In-place mutation of an enum is not currently supported, so this avoids
// copies of the queue when modifying the .results case on reassignment.
// See: https://forums.swift.org/t/in-place-mutation-of-an-enum-associated-value/11747
class QueueWrapper {
var queue: Queue<Element> = .init()
}
enum Results {
case results(QueueWrapper)
case error(Error)
}
var backpressure: Backpressure
var results = Results.results(.init())
var finished = false
var yieldCondition: Condition?
var nextCondition: Condition?
init(backpressure: Backpressure, of: Element.Type = Element.self) {
self.backpressure = backpressure
}
nonisolated func makeAsyncIterator() -> Iterator {
AsyncIterator(stream: self)
}
func yield(_ element: Element) async {
assert(yieldCondition == nil)
precondition(!backpressure.loaded)
precondition(!finished)
switch results {
case .results(let results):
results.queue.push(element)
backpressure.enqueue(element)
nextCondition?.signal()
nextCondition = nil
while backpressure.loaded {
yieldCondition = Condition()
await yieldCondition?.wait()
}
case .error(_):
preconditionFailure()
}
}
private func next() async throws -> Element? {
switch results {
case .results(let results):
if results.queue.empty {
if !finished {
nextCondition = .init()
await nextCondition?.wait()
return try await next()
} else {
return nil
}
}
let result = results.queue.pop()
backpressure.dequeue(result)
yieldCondition?.signal()
yieldCondition = nil
return result
case .error(let error):
throw error
}
}
nonisolated func finish() {
Task {
await _finish()
}
}
func _finish() {
finished = true
nextCondition?.signal()
}
nonisolated func finish(throwing error: Error) {
Task {
await _finish(throwing: error)
}
}
func _finish(throwing error: Error) {
results = .error(error)
nextCondition?.signal()
}
@discardableResult
nonisolated func task<Success>(body: sending @escaping () async throws -> Success) -> Task<Success, Error> {
Task {
do {
return try await body()
} catch {
finish(throwing: error)
throw error
}
}
}
}
actor ConcurrentStream<Element: Sendable> {
let results: AsyncThrowingStream<Element, Error>
let continuation: AsyncThrowingStream<Element, Error>.Continuation
let batchSize: Int
var index = -1
var finishedIndex = Int?.none
var completedIndex = -1
var widthConditions = [Int: Condition]()
var orderingConditions = [Int: Condition]()
init(batchSize: Int = 2 * ProcessInfo.processInfo.activeProcessorCount, consumeResults: Bool = false) {
self.batchSize = batchSize
(results, continuation) = AsyncThrowingStream.makeStream(of: Element.self, throwing: Error.self)
if consumeResults {
Task {
for try await _ in results {
}
}
}
}
@discardableResult
func addTask(_ operation: @escaping @Sendable () async throws -> Element) async -> Task<Element, Error> {
index += 1
let index = index
let widthCondition = Condition()
widthConditions[index] = widthCondition
let orderingCondition = Condition()
orderingConditions[index] = orderingCondition
await ensureWidth(index: index)
return Task {
let result = await Task {
try await operation()
}.result
await produce(result: result, for: index)
return try result.get()
}
}
func ensureWidth(index: Int) async {
if index >= batchSize {
await widthConditions[index - batchSize]!.wait()
widthConditions.removeValue(forKey: index - batchSize)
}
}
func produce(result: Result<Element, Error>, for index: Int) async {
if index != 0 {
await orderingConditions[index - 1]!.wait()
orderingConditions.removeValue(forKey: index - 1)
}
orderingConditions[index]!.signal()
continuation.yield(with: result)
if index == finishedIndex {
continuation.finish()
}
widthConditions[index]!.signal()
completedIndex += 1
}
func finish() {
finishedIndex = index
if finishedIndex == completedIndex {
continuation.finish()
}
}
}
extension option {
init(name: StaticString, has_arg: CInt, flag: UnsafeMutablePointer<CInt>?, val: StringLiteralType) {
let _option = name.withUTF8Buffer {
$0.withMemoryRebound(to: CChar.self) {
option(name: $0.baseAddress, has_arg: has_arg, flag: flag, val: CInt(UnicodeScalar(val)!.value))
}
}
self = _option
}
}
// MARK: - Public API
enum UnxipError: Error {
case truncated
case invalid
static func `throw`<T>(_ error: @autoclosure () -> Self, ifNil expression: @autoclosure () async throws -> T?) async throws -> T {
if let value = try await expression() {
return value
} else {
throw error()
}
}
static func `throw`<T>(_ error: @autoclosure () -> Self, ifNil expression: @autoclosure () throws -> T?) throws -> T {
if let value = try expression() {
return value
} else {
throw error()
}
}
static func `throw`(_ error: @autoclosure () -> Self, if expression: @autoclosure () async throws -> Bool) async throws {
if try await expression() {
throw error()
}
}
static func `throw`(_ error: @autoclosure () -> Self, if expression: @autoclosure () throws -> Bool) throws {
if try expression() {
throw error()
}
}
}
public struct DataReader<S: AsyncSequence> where S.Element: RandomAccessCollection, S.Element.Element == UInt8 {
public var position: Int = 0 {
didSet {
if let cap = cap {
precondition(position <= cap)
}
}
}
var current: (S.Element.Index, S.Element)?
var iterator: S.AsyncIterator
public var cap: Int?
public init(data: S) {
self.iterator = data.makeAsyncIterator()
}
mutating func read(upTo n: Int) async throws -> [UInt8] {
var data = [UInt8]()
var index = 0
while index != n {
let current: (S.Element.Index, S.Element)
if let _current = self.current,
_current.0 != _current.1.endIndex
{
current = _current
} else {
let new = try await iterator.next()
guard let new = new else {
return data
}
current = (new.startIndex, new)
}
let count = min(n - index, current.1.distance(from: current.0, to: current.1.endIndex))
let end = current.1.index(current.0, offsetBy: count)
data.append(contentsOf: current.1[current.0..<end])
self.current = (end, current.1)
index += count
position += count
}
return data
}
mutating func read(_ n: Int) async throws -> [UInt8] {
let data = try await read(upTo: n)
try await UnxipError.throw(.truncated, if: data.count != n)
return data
}
mutating func read<Integer: BinaryInteger>(_ type: Integer.Type) async throws -> Integer {
try await read(MemoryLayout<Integer>.size).reduce(into: 0) { result, next in
result <<= 8
result |= Integer(next)
}
}
}
extension DataReader where S == ErasedSequence<[UInt8]> {
public init(descriptor: CInt) {
self.init(data: Self.data(readingFrom: descriptor))
}
public static func data(readingFrom descriptor: CInt) -> S {
let stream = BackpressureStream(backpressure: CountedBackpressure(max: 16), of: [UInt8].self)
let io = DispatchIO(type: .stream, fileDescriptor: descriptor, queue: .main) { _ in
}
#if os(macOS)
let readSize = Int(PIPE_SIZE) * 16
#elseif canImport(Glibc)
let pipeSize = fcntl(descriptor, F_GETPIPE_SZ)
let readSize = (pipeSize > 0 ? Int(pipeSize) : sysconf(CInt(_SC_PAGESIZE))) * 16
#else
let readSize = sysconf(CInt(_SC_PAGESIZE)) * 16
#endif
Task {
while await withCheckedContinuation({ continuation in
#if PROFILING
let id = OSSignpostID(log: readLog)
os_signpost(.begin, log: readLog, name: "Read", signpostID: id, "Starting read")
#endif
var chunk = DispatchData.empty
io.read(offset: 0, length: readSize, queue: .main) { done, data, error in
guard error == 0 else {
stream.finish(throwing: NSError(domain: NSPOSIXErrorDomain, code: Int(error)))
continuation.resume(returning: false)
return
}
chunk.append(data!)
#if PROFILING
os_signpost(.event, log: readLog, name: "Read", signpostID: id, "Read %td bytes", data!.count)
#endif
if done {
if chunk.isEmpty {
#if PROFILING
os_signpost(.end, log: readLog, name: "Read", signpostID: id, "Ended final read")
#endif
stream.finish()
continuation.resume(returning: false)
} else {
#if PROFILING
os_signpost(.end, log: readLog, name: "Read", signpostID: id, "Ended read")
#endif
let chunk = [UInt8](unsafeUninitializedCapacity: chunk.count) { buffer, count in
_ = chunk.copyBytes(to: buffer, from: nil)
count = chunk.count
}
Task {
await stream.yield(chunk)
continuation.resume(returning: true)
}
}
}
}
}) {
}
}
return .init(sequence: stream)
}
}
public struct Chunk: Sendable {
public let buffer: [UInt8]
public let decompressed: Bool
init(data: [UInt8], decompressedSize: Int?, lzmaDecompressor: ([UInt8], Int) throws -> [UInt8]) rethrows {
if let decompressedSize = decompressedSize {
buffer = try lzmaDecompressor(data, decompressedSize)
decompressed = true
} else {
buffer = data
decompressed = false
}
}
}
public struct File: Sendable {
public let dev: Int
public let ino: Int
public let mode: Int
public let name: String
public internal(set) var data = [ArraySlice<UInt8>]()
var looksIncompressible = false
struct Identifier: Hashable {
let dev: Int
let ino: Int
}
var identifier: Identifier {
Identifier(dev: dev, ino: ino)
}
public enum `Type` {
case regular
case directory
case symlink
}
public var type: Type {
// The types we care about, anyways
let typeMask = C_ISLNK | C_ISDIR | C_ISREG
switch CInt(mode) & typeMask {
case C_ISLNK:
return .symlink
case C_ISDIR:
return .directory
case C_ISREG:
return .regular
default:
fatalError("\(name) with \(mode) is a type that is unhandled")
}
}
public var sticky: Bool {
mode & Int(C_ISVTX) != 0
}
#if canImport(Darwin)
static let blocksize = {
var buffer = stat()
// FIXME: This relies on a previous chdir to the output directory
stat(".", &buffer)
return buffer.st_blksize
}()
func compressedData() async -> [UInt8]? {
guard !looksIncompressible else {
return nil
}
// There is no benefit on APFS to using transparent compression if
// the data is less than one allocation block.
let totalSize = self.data.map(\.count).reduce(0, +)
guard totalSize > Self.blocksize else {
return nil
}
var _data = [UInt8]()
_data.reserveCapacity(totalSize)
let data = self.data.reduce(into: _data, +=)
let compressionStream = ConcurrentStream<[UInt8]?>()
#if PROFILING
let id = OSSignpostID(log: compressionLog)
os_signpost(.begin, log: compressionLog, name: "Data compression", signpostID: id, "Starting compression of %s (uncompressed size = %td)", name, data.count)
#endif
let blockSize = 64 << 10 // LZFSE with 64K block size
Task {
var position = data.startIndex
while position < data.endIndex {
let _position = position
await compressionStream.addTask {
try Task.checkCancellation()
let position = _position
let end = min(position + blockSize, data.endIndex)
let data = [UInt8](unsafeUninitializedCapacity: (end - position) + (end - position) / 16) { buffer, count in
data[position..<end].withUnsafeBufferPointer { data in
count = compression_encode_buffer(buffer.baseAddress!, buffer.count, data.baseAddress!, data.count, nil, COMPRESSION_LZFSE)
guard count < buffer.count else {
count = 0
return
}
}
}
return !data.isEmpty ? data : nil
}
position += blockSize
}
await compressionStream.finish()
}
var chunks = [[UInt8]]()
do {
for try await chunk in compressionStream.results {
if let chunk = chunk {
chunks.append(chunk)
} else {
#if PROFILING
os_signpost(.end, log: compressionLog, name: "Data compression", signpostID: id, "Ended compression (did not compress)")
#endif
return nil
}
}
} catch {
fatalError()
}
let tableSize = (chunks.count + 1) * MemoryLayout<UInt32>.size
let size = tableSize + chunks.map(\.count).reduce(0, +)
#if PROFILING
defer {
os_signpost(.end, log: compressionLog, name: "Data compression", signpostID: id, "Ended compression (compressed size = %td)", size)
}
#endif
guard size < data.count else {
return nil
}
return [UInt8](unsafeUninitializedCapacity: size) { buffer, count in
var position = tableSize
func writePosition(toTableIndex index: Int) {
precondition(position < UInt32.max)
for i in 0..<MemoryLayout<UInt32>.size {
buffer[index * MemoryLayout<UInt32>.size + i] = UInt8(position >> (i * 8) & 0xff)
}
}
writePosition(toTableIndex: 0)
for (index, chunk) in zip(1..., chunks) {
_ = UnsafeMutableBufferPointer(rebasing: buffer.suffix(from: position)).initialize(from: chunk)
position += chunk.count
writePosition(toTableIndex: index)
}
count = size
}
}
func write(compressedData data: [UInt8], toDescriptor descriptor: CInt) -> Bool {
let uncompressedSize = self.data.map(\.count).reduce(0, +)
let attribute =
"cmpf".utf8.reversed() // magic
+ [0x0c, 0x00, 0x00, 0x00] // LZFSE, 64K chunks
+ ([
(uncompressedSize >> 0) & 0xff,
(uncompressedSize >> 8) & 0xff,
(uncompressedSize >> 16) & 0xff,
(uncompressedSize >> 24) & 0xff,
(uncompressedSize >> 32) & 0xff,
(uncompressedSize >> 40) & 0xff,
(uncompressedSize >> 48) & 0xff,
(uncompressedSize >> 56) & 0xff,
].map(UInt8.init) as [UInt8])
guard fsetxattr(descriptor, "com.apple.decmpfs", attribute, attribute.count, 0, XATTR_SHOWCOMPRESSION) == 0 else {
return false
}
let resourceForkDescriptor = open(name + _PATH_RSRCFORKSPEC, O_WRONLY | O_CREAT, 0o666)
guard resourceForkDescriptor >= 0 else {
return false
}
defer {
close(resourceForkDescriptor)
}
var written: Int
repeat {
#if PROFILING
let id = OSSignpostID(log: filesystemLog)
os_signpost(.begin, log: filesystemLog, name: "compressed pwrite", signpostID: id, "Starting compressed pwrite for %s", name)
#endif
// TODO: handle partial writes smarter
written = pwrite(resourceForkDescriptor, data, data.count, 0)
guard written >= 0 else {
return false
}
#if PROFILING
os_signpost(.end, log: filesystemLog, name: "compressed pwrite", signpostID: id, "Ended")
#endif
} while written != data.count
guard fchflags(descriptor, UInt32(UF_COMPRESSED)) == 0 else {
return false
}
return true
}
#endif
}
public protocol StreamAperture {
associatedtype Input
associatedtype Next: StreamAperture
associatedtype Options: Sendable
static func transform(_: sending Input, options: Options?) -> Next.Input
}
protocol Decompressor {
static func decompress(data: [UInt8], decompressedSize: Int) throws -> [UInt8]
}
public enum DefaultDecompressor {
enum Zlib: Decompressor {
static func decompress(data: [UInt8], decompressedSize: Int) throws -> [UInt8] {
return try [UInt8](unsafeUninitializedCapacity: decompressedSize) { buffer, count in
#if canImport(Compression)
let zlibSkip = 2 // Apple's decoder doesn't want to see CMF/FLG (see RFC 1950)
try data[data.index(data.startIndex, offsetBy: zlibSkip)...].withUnsafeBufferPointer {
try UnxipError.throw(.invalid, if: compression_decode_buffer(buffer.baseAddress!, decompressedSize, $0.baseAddress!, $0.count, nil, COMPRESSION_ZLIB) != decompressedSize)
}
#else
var size = decompressedSize
try UnxipError.throw(.invalid, if: uncompress(buffer.baseAddress!, &size, data, UInt(data.count)) != Z_OK)
try UnxipError.throw(.invalid, if: size != decompressedSize)
#endif
count = decompressedSize
}
}
}
enum LZMA: Decompressor {
static func decompress(data: [UInt8], decompressedSize: Int) throws -> [UInt8] {
let magic = [0xfd] + "7zX".utf8
try UnxipError.throw(.invalid, if: !data.prefix(magic.count).elementsEqual(magic))
return try [UInt8](unsafeUninitializedCapacity: decompressedSize) { buffer, count in
#if canImport(Compression)
try UnxipError.throw(.invalid, if: compression_decode_buffer(buffer.baseAddress!, decompressedSize, data, data.count, nil, COMPRESSION_LZMA) != decompressedSize)
#else
var memlimit = UInt64.max
var inIndex = 0
var outIndex = 0
try UnxipError.throw(.invalid, if: lzma_stream_buffer_decode(&memlimit, 0, nil, data, &inIndex, data.count, buffer.baseAddress, &outIndex, decompressedSize) != LZMA_OK)
try UnxipError.throw(.invalid, if: inIndex != data.count || outIndex != decompressedSize)
#endif
count = decompressedSize
}
}
}
}
public enum XIP<S: AsyncSequence>: StreamAperture where S.Element: RandomAccessCollection, S.Element.Element == UInt8 {
public typealias Input = DataReader<S>
public typealias Next = Chunks
public struct Options: Sendable {
let zlibDecompressor: @Sendable ([UInt8], Int) throws -> [UInt8]
let lzmaDecompressor: @Sendable ([UInt8], Int) throws -> [UInt8]
init<Zlib: Decompressor, LZMA: Decompressor>(zlibDecompressor: Zlib.Type, lzmaDecompressor: LZMA.Type) {
self.zlibDecompressor = Zlib.decompress
self.lzmaDecompressor = LZMA.decompress
}
}
static var defaultOptions: Options {
.init(zlibDecompressor: DefaultDecompressor.Zlib.self, lzmaDecompressor: DefaultDecompressor.LZMA.self)
}
static func locateContent(in file: inout DataReader<some AsyncSequence>, options: Options) async throws {
let fileStart = file.position
let magic = "xar!".utf8
try await UnxipError.throw(.invalid, if: await !file.read(magic.count).elementsEqual(magic))
let headerSize = try await file.read(UInt16.self)
try await UnxipError.throw(.invalid, if: await file.read(UInt16.self) != 1) // version
let tocCompressedSize = try await file.read(UInt64.self)
let tocDecompressedSize = try await file.read(UInt64.self)
_ = try await file.read(UInt32.self) // checksum
_ = try await file.read(fileStart + Int(headerSize) - file.position)
let compressedTOC = try await file.read(Int(tocCompressedSize))
let toc = try options.zlibDecompressor(compressedTOC, Int(tocDecompressedSize))
#if canImport(UIKit)
let document = xmlReadMemory(toc, CInt(toc.count), "", nil, 0)
defer {
xmlFreeDoc(document)
}
let context = xmlXPathNewContext(document)
defer {
xmlXPathFreeContext(context)
}
func evaluateXPath(node: xmlNodePtr!, xpath: String) throws -> String {
let result = try UnxipError.throw(.invalid, ifNil: xmlXPathNodeEval(node, xpath, context))
defer {
xmlXPathFreeObject(result)
}
try UnxipError.throw(.invalid, if: result.pointee.type != XPATH_NODESET || result.pointee.nodesetval.pointee.nodeNr != 1)
let string = xmlNodeListGetString(document, result.pointee.nodesetval.pointee.nodeTab.pointee!.pointee.children, 1)!
defer {
xmlFree(string)
}
return String(cString: string)
}
let result = try UnxipError.throw(.invalid, ifNil: xmlXPathEvalExpression("/xar/toc/file", context))
defer {
xmlXPathFreeObject(result)
}
try UnxipError.throw(.invalid, if: result.pointee.type != XPATH_NODESET)
let content = try UnxipError.throw(
.invalid,
ifNil: result.pointee.nodesetval.pointee.nodeTab[
(0..<Int(result.pointee.nodesetval.pointee.nodeNr)).first {
try evaluateXPath(node: result.pointee.nodesetval.pointee.nodeTab[$0], xpath: "name") == "Content"
}!])
let contentOffset = try UnxipError.throw(.invalid, ifNil: Int(evaluateXPath(node: content, xpath: "data/offset")))
let contentSize = try UnxipError.throw(.invalid, ifNil: Int(evaluateXPath(node: content, xpath: "data/length")))
#else
let document = try XMLDocument(data: Data(toc))
let content = try await UnxipError.throw(
.invalid,
ifNil: document.nodes(forXPath: "/xar/toc/file").first {
try $0.nodes(forXPath: "name").first?.stringValue == "Content"
})
let contentOffset = try await UnxipError.throw(.invalid, ifNil: content.nodes(forXPath: "data/offset").first?.stringValue.map(Int.init) ?? nil)
let contentSize = try await UnxipError.throw(.invalid, ifNil: content.nodes(forXPath: "data/length").first?.stringValue.map(Int.init) ?? nil)
#endif
_ = try await file.read(fileStart + Int(headerSize) + Int(tocCompressedSize) + contentOffset - file.position)
file.cap = file.position + contentSize
}
public static func transform(_ data: sending Input, options: Options?) -> Next.Input {
let options = options ?? Self.defaultOptions
let decompressionStream = ConcurrentStream<Void>(consumeResults: true)
let chunkStream = BackpressureStream(backpressure: CountedBackpressure(max: 16), of: Chunk.self)
chunkStream.task {
var content = data
try await locateContent(in: &content, options: options)
let magic = "pbzx".utf8
try await UnxipError.throw(.invalid, if: await !content.read(magic.count).elementsEqual(magic))
let chunkSize = try await content.read(UInt64.self)
var decompressedSize: UInt64 = 0
var previousYield: Task<Void, Error>?
var chunkNumber = 0
repeat {
decompressedSize = try await content.read(UInt64.self)
let compressedSize = try await content.read(UInt64.self)
let block = try await content.read(Int(compressedSize))
let _decompressedSize = decompressedSize
let _previousYield = previousYield
let _chunkNumber = chunkNumber
previousYield = await decompressionStream.addTask {
let decompressedSize = _decompressedSize
let previousYield = _previousYield
let chunkNumber = _chunkNumber
let compressed = compressedSize != chunkSize
#if PROFILING
let id = OSSignpostID(log: decompressionLog)
os_signpost(.begin, log: decompressionLog, name: "Decompress", signpostID: id, compressed ? "Starting %td (compressed size = %td)" : "Starting %td (uncompressed size = %td)", chunkNumber, compressedSize)
#endif
let chunk = try Chunk(data: block, decompressedSize: compressed ? Int(decompressedSize) : nil, lzmaDecompressor: options.lzmaDecompressor)
#if PROFILING
os_signpost(.end, log: decompressionLog, name: "Decompress", signpostID: id, "Ended %td (decompressed size = %td)", chunkNumber, decompressedSize)
#endif
_ = await previousYield?.result
await chunkStream.yield(chunk)
}
chunkNumber += 1
} while decompressedSize == chunkSize
_ = await previousYield?.result
chunkStream.finish()