forked from swiftlang/swift-build
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXCFramework.swift
More file actions
1384 lines (1132 loc) · 68.9 KB
/
Copy pathXCFramework.swift
File metadata and controls
1384 lines (1132 loc) · 68.9 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
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
public import SWBUtil
public import struct Foundation.Data
public import class Foundation.PropertyListDecoder
public import class Foundation.PropertyListEncoder
public import protocol Foundation.LocalizedError
public import SWBMacro
import Synchronization
/// Represents the various types of error cases possible when constructing an `XCFramework` type.
///
/// - remark: When adding to this enum, add a test for it to `XCFrameworkTests.testXCFrameworkValidationErrors()`.
public enum XCFrameworkValidationError: Error, Equatable {
/// The version specified is not a supported format version.
case unsupportedVersion(version: String)
/// The `libraries` set is empty, which is an invalid state.
case noLibraries
/// An unsupported library type was used. The library type and the identifier of the library within the XCFramework is also identified.
case unsupportedLibraryType(libraryType: XCFramework.LibraryType, libraryIdentifier: String)
/// An XCFramework only supports homogeneous library types.
case mixedLibraryTypes(libraryType: XCFramework.LibraryType, otherLibraryType: XCFramework.LibraryType)
/// The library path is empty.
case libraryPathEmpty(libraryIdentifier: String)
/// The supported platform is empty.
case supportedPlatformEmpty(libraryIdentifier: String)
/// The headers path is empty.
case headersPathEmpty(libraryIdentifier: String)
/// The debug symbols path is empty.
case debugSymbolsPathEmpty(libraryIdentifier: String)
/// The platform variant is empty.
case platformVariantEmpty(libraryIdentifier: String)
/// The library type does not support specifying a headers location.
case headerPathNotSupported(libraryType: XCFramework.LibraryType, libraryIdentifier: String)
/// When multiple libraries can be matched based on platform and platform variant. This would result in `findLibrary()` having multiple matches.
case conflictingLibraryDefinitions(libraryIdentifier: String, otherLibraryIdentifier: String)
/// When multiple libraries contain the same library identifier. This is used as the path within the XCFramework, so it must be unique.
case duplicateLibraryIdentifier(libraryIdentifier: String)
/// The Info.plist file is missing from the XCFramework.
case missingInfoPlist(path: Path)
/// Error message when the `Info.plist` defines a key describing a path location that should exist on disk but is missing.
case missingPathEntry(xcframeworkPath: Path, libraryIdentifier: String, plistKey: String, plistValue: String)
/// The actual XCFramework is missing on disk.
case missingXCFramework(path: Path)
/// The library is marked as having mergeable metadata but is of a type which doesn't support that.
/// - remark: Xcode support for mergeable libraries involves special code for embedding the product, so explicit support for new types will need to be added. Users can't just create some random bundle and expect Xcode to handle it properly.
case libraryTypeDoesNotSupportMergeableMetadata(libraryType: XCFramework.LibraryType)
/// The library is marked as having mergeable metadata but does not have a binary path, which is needed to process such libraries.
case mergeableLibraryBinaryPathEmpty(libraryIdentifier: String)
}
extension XCFrameworkValidationError: LocalizedError {
/// The user-facing error message to output for any given `XCFrameworkValidationError`.
public var errorDescription: String? {
func libraryErrorMessage(_ text: String, libraryIdentifier: String) -> String {
return "\(text) in library '\(libraryIdentifier)'."
}
switch self {
case let .unsupportedVersion(version):
return "Version \(version) is not supported (maximum version \(XCFramework.currentVersion))."
case .noLibraries:
return "There are no libraries provided for the XCFramework."
case let .unsupportedLibraryType(libraryType, libraryIdentifier):
return libraryErrorMessage("Unknown library type with extension '\(libraryType.fileExtension)'", libraryIdentifier: libraryIdentifier)
case let .mixedLibraryTypes(libraryType, otherLibraryType):
return "An XCFramework cannot be composed of different library types: '\(libraryType.libraryTypeName)' and '\(otherLibraryType.libraryTypeName)'."
case let .libraryPathEmpty(libraryIdentifier):
return libraryErrorMessage("The '\(XCFrameworkInfoPlist_V1.Library.CodingKeys.libraryPath.stringValue)' is empty", libraryIdentifier: libraryIdentifier)
case let .supportedPlatformEmpty(libraryIdentifier):
return libraryErrorMessage("The '\(XCFrameworkInfoPlist_V1.Library.CodingKeys.supportedPlatform.stringValue)' is empty", libraryIdentifier: libraryIdentifier)
case let .headersPathEmpty(libraryIdentifier):
return libraryErrorMessage("The '\(XCFrameworkInfoPlist_V1.Library.CodingKeys.headersPath.stringValue)' is empty", libraryIdentifier: libraryIdentifier)
case let .debugSymbolsPathEmpty(libraryIdentifier):
return libraryErrorMessage("The '\(XCFrameworkInfoPlist_V1.Library.CodingKeys.debugSymbolsPath.stringValue)' is empty", libraryIdentifier: libraryIdentifier)
case let .platformVariantEmpty(libraryIdentifier):
return libraryErrorMessage("The '\(XCFrameworkInfoPlist_V1.Library.CodingKeys.platformVariant.stringValue)' is empty", libraryIdentifier: libraryIdentifier)
case let .headerPathNotSupported(libraryType, libraryIdentifier):
return libraryErrorMessage("'\(XCFrameworkInfoPlist_V1.Library.CodingKeys.headersPath.stringValue)' is not supported for a '\(libraryType.libraryTypeName)'", libraryIdentifier: libraryIdentifier)
case let .conflictingLibraryDefinitions(libraryIdentifier, otherLibraryIdentifier):
return "Both '\(libraryIdentifier)' and '\(otherLibraryIdentifier)' represent two equivalent library definitions."
case let .duplicateLibraryIdentifier(libraryIdentifier):
return "A library with the identifier '\(libraryIdentifier)' already exists."
case let .missingInfoPlist(path):
return "There is no Info.plist found at '\(path.str)'."
case let .missingPathEntry(xcframeworkPath, libraryIdentifier, plistKey, plistValue):
let path = xcframeworkPath.join(libraryIdentifier).join(plistValue)
return "Missing path (\(path.str)) from XCFramework '\(xcframeworkPath.basename)' as defined by '\(plistKey)' in its `Info.plist` file"
case let .missingXCFramework(path):
return "There is no XCFramework found at '\(path.str)'."
case let .libraryTypeDoesNotSupportMergeableMetadata(libraryType):
switch libraryType {
case .staticLibrary:
return "Static libraries do not support mergeable metadata, only frameworks and dynamic libraries are supported."
case .unknown(let fileExtension):
return "Files with extension '\(fileExtension) do not support mergeable metadata, only frameworks and dynamic libraries are supported."
case .framework, .dynamicLibrary:
// We should not have been created with one of these types.
return "Internal error: libraryTypeDoesNotSupportMergeableMetadata created for type \(libraryType.libraryTypeName) even though that type supports mergeable metadata."
}
case let .mergeableLibraryBinaryPathEmpty(libraryIdentifier):
return libraryErrorMessage("'\(XCFrameworkInfoPlist_V1.Library.CodingKeys.mergeableMetadata.stringValue)' is true but the '\(XCFrameworkInfoPlist_V1.Library.CodingKeys.binaryPath.stringValue)' is empty", libraryIdentifier: libraryIdentifier)
}
}
}
/// Represents and error that happens during the creation of an xcframework.
public struct XCFrameworkCreationError: Error {
/// The message for the error.
@_spi(Testing) public let message: String
}
extension XCFrameworkCreationError: LocalizedError {
/// Provide a better error message when using `localizedDescription` on error types.
public var errorDescription: String? {
return message
}
}
/// Defines the structure format for an XCFramework wrapper.
public struct XCFramework: Hashable, Sendable {
/// The list of supported library types and their extensions.
public enum LibraryType: Equatable, CustomStringConvertible, Sendable {
/// A framework type. Currently no distinction is made between static or dynamic.
case framework
/// A dynamic library.
case dynamicLibrary
/// A static library.
case staticLibrary
/// An unknown library type.
case unknown(fileExtension: String)
/// Determines if the given library type supports being packaged with headers.
public var canHaveHeaders: Bool {
switch self {
case .dynamicLibrary: return true
case .staticLibrary: return true
default: return false
}
}
/// A user-facing description of the type of library contained within.
public var description: String {
switch self {
case .framework: return "framework"
default: return "library"
}
}
/// A user-facing name for each of the given library types.
public var libraryTypeName: String {
switch self {
case .framework: return "framework"
case .dynamicLibrary: return "dynamic library"
case .staticLibrary: return "static library"
case .unknown(let fileExtension): return "unknown (\(fileExtension))"
}
}
/// Returns the file extension for the given `XCFramework.LibraryType`.
public var fileExtension: String {
switch self {
case .framework: return "framework"
case .dynamicLibrary: return "dylib"
case .staticLibrary: return "a"
case .unknown(let fileExtension): return fileExtension
}
}
/// Creates a new `LibraryType` from the given file extension.
public init(fileExtension: String) {
let ext = fileExtension.lowercased()
switch ext {
case "framework": self = .framework; break
case "dylib", "so": self = .dynamicLibrary; break
case "a": self = .staticLibrary; break
default: self = .unknown(fileExtension: ext)
}
}
}
/// Information on the libraries the xcframework bundles.
public struct Library: Sendable {
/// A unique identifier for the library. This will typically be in the target-triple form: `x86_64-apple-macos`. However, it can be any unique string amongst the other available libraries.
///
/// This identifier is also used as the name of the directory the library and any other related contents can be found.
///
/// This string needs to be a valid path identifier.
public let libraryIdentifier: String
/// The platform the library corresponds to.
///
/// These are the same values as the OS field of an LLVM target triple. Examples of recognized values therefore include but are not limited to:
/// - driverkit
/// - ios
/// - macos
/// - tvos
/// - watchos
///
/// Note that a Mac Catalyst library will have a `platform` of 'ios' - not 'macos' - but a `platformVariant` of 'macabi'.
public let supportedPlatform: String
/// The listing of supported architectures.
///
/// These are the same values as the arch + subarch field of an LLVM target triple. Examples of recognized values therefore include but are not limited to:
/// - arm64
/// - arm64_32
/// - arm64e
/// - armv7
/// - armv7k
/// - armv7s
/// - i386
/// - x86_64
/// - x86_64h
public let supportedArchitectures: OrderedSet<String>
/// Used to specify a specific variant that should be used, such as macCatalyst or the simulator.
///
/// These are the same values as the environment field of an LLVM target triple. Examples of recognized values therefore include but are not limited to:
/// - macabi
/// - simulator
public let platformVariant: String?
/// The relative path to the top-level library or framework. Typically just the name of the library or framework.
public let libraryPath: Path
/// The relative path to the binary. For a library this will just be the name of the library. For a framework this will be the path starting with the name of the framework. This is mainly needed to deal with the macOS framework bundle layout.
/// - remark: This property is optional because it is new in Xcode 15, but is always archived to version 1.0 plists because older versions of Xcode can ignore it.
public let binaryPath: Path?
/// The relative path to the headers. Typically 'Headers'.
public let headersPath: Path?
/// The relative path to the debug symbols. Typically 'dSYMs'.
public let debugSymbolsPath: Path?
/// If true, then the library contains mergeable metadata (an `LC_ATOM_INFO` section) in all of its architecture slices).
/// - remark: XCFrameworks which declare this property can only be used by Xcodes which support v1.1 or later.
public let mergeableMetadata: Bool
/// The library type for the given `Library`.
public let libraryType: LibraryType
public init(libraryIdentifier: String, supportedPlatform: String, supportedArchitectures: OrderedSet<String>, platformVariant: String?, libraryPath: Path, binaryPath: Path?, headersPath: Path?, debugSymbolsPath: Path? = nil, mergeableMetadata: Bool = false) {
self.libraryIdentifier = libraryIdentifier
self.supportedPlatform = supportedPlatform
self.supportedArchitectures = supportedArchitectures
self.platformVariant = platformVariant?.nilIfEmpty // remove the property if it is empty
self.libraryPath = libraryPath
self.binaryPath = binaryPath
self.headersPath = headersPath
self.debugSymbolsPath = debugSymbolsPath
self.mergeableMetadata = mergeableMetadata
self.libraryType = XCFramework.LibraryType(fileExtension: libraryPath.fileExtension)
}
}
/// The version of the bundle format. Follows semver.
public let version: Version
/// A set of each of the available bundles.
public let libraries: OrderedSet<Library>
/// Creates a new instance validating that new XCFramework will be valid. Any validation errors will be surfaced with an `XCFrameworkValidationError`.
public init(version: Version, libraries: OrderedSet<Library>) throws {
self.version = version
self.libraries = libraries
try self.validate()
}
/// Creates a new instance validating that new XCFramework will be valid. Any validation errors will be surfaced with an `XCFrameworkValidationError`.
public init(version: Version, libraries: [Library]) throws {
self.version = version
var libs = OrderedSet<Library>()
for lib in libraries {
if libs.append(lib).inserted == false {
throw XCFrameworkValidationError.duplicateLibraryIdentifier(libraryIdentifier: lib.libraryIdentifier)
}
}
self.libraries = libs
try self.validate()
}
/// Creates a new instance validating that new XCFramework will be valid. Any validation errors will be surfaced with an `XCFrameworkValidationError`. The version will be computed from the libraries passed in.
public init(libraries: [Library]) throws {
let version = Self.xcframeworkVersion(for: libraries)
try self.init(version: version, libraries: libraries)
}
/// Computes the version of the XCFramework being created based on the contents of the `Library`s passed in.
fileprivate static func xcframeworkVersion(for libraries: [Library]) -> Version {
var version = Version(1, 0)
// We work through all of the properties which are not supported by older versions, and end up with a version which supports the newest property which is present.
func setVersionIfNewer(_ candidate: Version) {
if version < candidate {
version = candidate
}
}
// We only bump to the mergeableMetadataVersion if at least one library has mergeableMetadata set to true.
if libraries.contains(where: { $0.mergeableMetadata }) {
setVersionIfNewer(mergeableMetadataVersion)
}
return version
}
/// The highest XCFramework version which this Swift Build supports.
static let currentVersion = Version(1, 1)
/// The minimum XCFramework version required to support mergeable metadata.
@_spi(Testing) public static let mergeableMetadataVersion = Version(1, 1)
/// Whether the platform ships one slice per architecture (no fat binaries).
static func hasPerArchSlices(_ platform: String) -> Bool {
return BuildVersion.Platform(platform: platform, environment: nil) == nil
}
/// Searches the `libraries` based on the current SDK being used.
public func findLibrary(sdk: SDK?, sdkVariant: SDKVariant?, architectures: [String] = []) -> XCFramework.Library? {
// Lookup the LC_BUILD_VERSION information as that it is how xcframeworks platform and variant values are defined.
guard let platformName = sdkVariant?.llvmTargetTripleSys else {
return nil
}
return findLibrary(platform: platformName, platformVariant: sdkVariant?.llvmTargetTripleEnvironment ?? "", architectures: architectures)
}
/// Given a platform and the variant, attempt to find an library within the XCFramework that can be used.
public func findLibrary(platform: String, platformVariant: String = "", architectures: [String] = []) -> XCFramework.Library? {
guard Self.hasPerArchSlices(platform) else {
return self.libraries.filter { lib in
// Due to the fact that macro evaluation of empty settings returns empty strings, there is no meaningful distinction between nil and empty here.
lib.supportedPlatform == platform && (lib.platformVariant ?? "") == platformVariant
}.first
}
// Non-Apple platforms ship per-arch XCFramework slices and typically omit SupportedPlatformVariant, so for
// those platforms, require exactly one target arch and allow a no-variant fallback.
guard let targetArch = architectures.only else { return nil }
let variants: [String] = platformVariant.isEmpty ? [""] : [platformVariant, ""]
for variant in variants {
if let match = libraries.first(where: {
$0.supportedPlatform == platform
&& ($0.platformVariant ?? "") == variant
&& $0.supportedArchitectures.contains(targetArch)
}) {
return match
}
}
return nil
}
}
extension XCFramework {
private struct LibraryKey: Hashable {
let identifier: String
let platform: String
let platformVariant: String?
let architectures: [String]
func hash(into hasher: inout Hasher) {
// identifier is only used for tracking the offending library
hasher.combine(platform)
hasher.combine(platformVariant)
hasher.combine(architectures)
}
static func == (lhs: LibraryKey, rhs: LibraryKey) -> Bool {
return lhs.platform == rhs.platform
&& lhs.platformVariant == rhs.platformVariant
&& lhs.architectures == rhs.architectures
}
}
/// Performs the necessary set of validations on the elements within the XCFramework. This is used during construction time.
fileprivate func validate() throws {
guard self.version <= Self.currentVersion else {
throw XCFrameworkValidationError.unsupportedVersion(version: self.version.description)
}
guard let library = self.libraries.first else {
throw XCFrameworkValidationError.noLibraries
}
let firstLibraryType = library.libraryType
var libraryKeys = Set<LibraryKey>()
for library in self.libraries {
// Implementation Note: This validation *must* come before the library type check, otherwise, this error will never be surfaced due to the fact that the library type will be `unknown` for an empty library path.
guard !library.libraryPath.isEmpty else {
throw XCFrameworkValidationError.libraryPathEmpty(libraryIdentifier: library.libraryIdentifier)
}
if case .unknown(_) = library.libraryType {
throw XCFrameworkValidationError.unsupportedLibraryType(libraryType: library.libraryType, libraryIdentifier: library.libraryIdentifier)
}
guard firstLibraryType == library.libraryType else {
throw XCFrameworkValidationError.mixedLibraryTypes(libraryType: firstLibraryType, otherLibraryType: library.libraryType)
}
guard !library.supportedPlatform.isEmpty else {
throw XCFrameworkValidationError.supportedPlatformEmpty(libraryIdentifier: library.libraryIdentifier)
}
if let headersPath = library.headersPath {
guard !headersPath.isEmpty else {
throw XCFrameworkValidationError.headersPathEmpty(libraryIdentifier: library.libraryIdentifier)
}
}
if let debugSymbolsPath = library.debugSymbolsPath {
guard !debugSymbolsPath.isEmpty else {
throw XCFrameworkValidationError.debugSymbolsPathEmpty(libraryIdentifier: library.libraryIdentifier)
}
}
if let platformVariant = library.platformVariant {
guard !platformVariant.isEmpty else {
throw XCFrameworkValidationError.platformVariantEmpty(libraryIdentifier: library.libraryIdentifier)
}
}
if library.mergeableMetadata {
// Only frameworks and dylibs support mergeable metadata.
switch library.libraryType {
case .framework, .dynamicLibrary:
// These are fine.
break
default:
throw XCFrameworkValidationError.libraryTypeDoesNotSupportMergeableMetadata(libraryType: library.libraryType)
}
// There must be a binaryPath if mergeableMetadata is true.
if library.binaryPath == nil || library.binaryPath!.isEmpty {
throw XCFrameworkValidationError.mergeableLibraryBinaryPathEmpty(libraryIdentifier: library.libraryIdentifier)
}
}
if case .framework = library.libraryType, library.headersPath != nil {
throw XCFrameworkValidationError.headerPathNotSupported(libraryType: library.libraryType, libraryIdentifier: library.libraryIdentifier)
}
// Per-arch platforms discriminate slices on arch; fat-binary platforms don't.
var keyArchitectures: [String] = []
if Self.hasPerArchSlices(library.supportedPlatform) {
keyArchitectures = library.supportedArchitectures.sorted()
}
let (added, oldMember) = libraryKeys.insert(LibraryKey(identifier: library.libraryIdentifier, platform: library.supportedPlatform, platformVariant: library.platformVariant, architectures: keyArchitectures))
guard added == true else {
throw XCFrameworkValidationError.conflictingLibraryDefinitions(libraryIdentifier: oldMember.identifier, otherLibraryIdentifier: library.libraryIdentifier)
}
}
}
}
extension XCFramework.Library: Hashable {
/// The `libraryIdentifier` is used to determine if two XCFrameworks are unique.
public func hash(into hasher: inout Hasher) {
hasher.combine(self.libraryIdentifier)
}
/// Returns `true` iff the `libraryIdentifiers` are equal. The rest of the library components are not used for equality.
static public func ==(lhs: XCFramework.Library, rhs: XCFramework.Library) -> Bool {
return lhs.libraryIdentifier == rhs.libraryIdentifier
}
}
// MARK: XCFramework (v1) Info.plist parsing.
/// This is an internal representation of the plist structure for v1 of the XCFramework. This is used in order to completely decouple the parsing structure from the actual data model structure. Doing this gains us better ability to version the XCFrameworks, and provides us a better mechanism to catch parsing errors vs. validation errors; if we only used the data model, certain validation errors would be lost in the `Codable` translation.
///
/// - remark: See the `XCFramework` struct and its nested structs for documentation about the individual fields. This struct only documents details about archiving the contents, not the meaning of the contents.
///
/// - remark: As time of writing this is the only version, and we can iterate on it as needed. If we ever radically transform the format (rather than just adding and removing keys) then we may create a new struct for the reworked version.
@_spi(Testing) public struct XCFrameworkInfoPlist_V1: Codable {
struct Library: Codable {
let libraryIdentifier: String
let supportedPlatform: String
let supportedArchitectures: [String]
let platformVariant: String?
let libraryPath: String
// This is optional because XCFrameworks created with Xcode 14.x and earlier will not define it, but should still be usable.
let binaryPath: String?
let headersPath: String?
let debugSymbolsPath: String?
// This is optional because we only want to encode it if the XCFramework is at least of the version which supports it, but this struct doesn't know what that is, so we capture that characteristic in XCFramework.serialize() where the version is available.
let mergeableMetadata: Bool?
enum CodingKeys: String, CodingKey {
case libraryIdentifier = "LibraryIdentifier"
case supportedPlatform = "SupportedPlatform"
case supportedArchitectures = "SupportedArchitectures"
case platformVariant = "SupportedPlatformVariant"
case libraryPath = "LibraryPath"
case binaryPath = "BinaryPath"
case headersPath = "HeadersPath"
case debugSymbolsPath = "DebugSymbolsPath"
case mergeableMetadata = "MergeableMetadata"
// Bitcode is no longer supported, but we still recognize the key for older XCFrameworks which define it.
case bitcodeSymbolMapsPath = "BitcodeSymbolMapsPath"
}
init(libraryIdentifier: String, supportedPlatform: String, supportedArchitectures: [String], platformVariant: String?, libraryPath: String, binaryPath: String?, headersPath: String?, debugSymbolsPath: String?, mergeableMetadata: Bool?) {
self.libraryIdentifier = libraryIdentifier
self.supportedPlatform = supportedPlatform
self.supportedArchitectures = supportedArchitectures
self.platformVariant = platformVariant
self.libraryPath = libraryPath
self.binaryPath = binaryPath
self.headersPath = headersPath
self.debugSymbolsPath = debugSymbolsPath
self.mergeableMetadata = mergeableMetadata
}
// NOTE: The mappings for maccatalyst are so that "macabi" is used as that is what is directly matched in the LC_BUILD_VERSION info.
func encode(to encoder: any Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(libraryIdentifier, forKey: .libraryIdentifier)
try container.encode(supportedPlatform, forKey: .supportedPlatform)
try container.encode(supportedArchitectures, forKey: .supportedArchitectures)
if platformVariant == "macabi" {
try container.encode("maccatalyst", forKey: .platformVariant)
}
else {
try container.encodeIfPresent(platformVariant, forKey: .platformVariant)
}
try container.encode(libraryPath, forKey: .libraryPath)
try container.encode(binaryPath, forKey: .binaryPath)
try container.encodeIfPresent(headersPath, forKey: .headersPath)
try container.encodeIfPresent(debugSymbolsPath, forKey: .debugSymbolsPath)
try container.encodeIfPresent(mergeableMetadata, forKey: .mergeableMetadata)
}
init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.libraryIdentifier = try container.decode(String.self, forKey: .libraryIdentifier)
self.supportedPlatform = try container.decode(String.self, forKey: .supportedPlatform)
self.supportedArchitectures = try container.decode([String].self, forKey: .supportedArchitectures)
var platformVariant = try container.decodeIfPresent(String.self, forKey: .platformVariant)
if platformVariant == "maccatalyst" {
platformVariant = "macabi"
}
self.platformVariant = platformVariant
self.libraryPath = try container.decode(String.self, forKey: .libraryPath)
self.binaryPath = try container.decodeIfPresent(String.self, forKey: .binaryPath)
self.headersPath = try container.decodeIfPresent(String.self, forKey: .headersPath)
self.debugSymbolsPath = try container.decodeIfPresent(String.self, forKey: .debugSymbolsPath)
self.mergeableMetadata = try container.decodeIfPresent(Bool.self, forKey: .mergeableMetadata)
// Bitcode is no longer supported, but we still recognize the key for older XCFrameworks which define it.
let _ = try container.decodeIfPresent(String.self, forKey: .bitcodeSymbolMapsPath)
}
}
let version: String
let libraries: [Library]
let bundleCode: String = "XFWK"
enum CodingKeys: String, CodingKey {
case version = "XCFrameworkFormatVersion"
case libraries = "AvailableLibraries"
case bundleCode = "CFBundlePackageType"
}
}
extension XCFramework {
public init(path: Path, fs: any FSProxy) throws {
let decoder = PropertyListDecoder()
guard fs.exists(path) else {
throw XCFrameworkValidationError.missingXCFramework(path: path)
}
let plistPath = path.join("Info.plist")
guard fs.exists(plistPath) else {
throw XCFrameworkValidationError.missingInfoPlist(path: plistPath)
}
let data = Data(try fs.read(plistPath).bytes)
let xcframeworkv1: XCFrameworkInfoPlist_V1
do {
xcframeworkv1 = try decoder.decode(XCFrameworkInfoPlist_V1.self, from: data)
} catch {
throw StubError.error("Failed to decode XCFramework Info.plist at '\(plistPath.str)': \(error.localizedDescription)")
}
do {
try self.init(other: xcframeworkv1)
} catch {
throw StubError.error("Failed to load XCFramework at '\(path.str)': \(error.localizedDescription)")
}
}
@_spi(Testing) public init(other: XCFrameworkInfoPlist_V1) throws {
let version: Version
let libraries: [XCFramework.Library]
do {
version = try Version(other.version)
}
catch {
throw XCFrameworkValidationError.unsupportedVersion(version: other.version)
}
libraries = other.libraries.map { XCFramework.Library(other: $0) }
try self.init(version: version, libraries: libraries)
}
public func serialize() throws -> Data {
let libraries = self.libraries.map { lib in
// We only archive the mergeableMetadata property if we're the version which supports it or higher, so we set it to nil if we're a lower version.
let mergeableMetadata: Bool? = (version >= type(of: self).mergeableMetadataVersion) ? lib.mergeableMetadata : nil
return XCFrameworkInfoPlist_V1.Library(libraryIdentifier: lib.libraryIdentifier, supportedPlatform: lib.supportedPlatform, supportedArchitectures: lib.supportedArchitectures.elements, platformVariant: lib.platformVariant, libraryPath: lib.libraryPath.str, binaryPath: lib.binaryPath?.str, headersPath: lib.headersPath?.str, debugSymbolsPath: lib.debugSymbolsPath?.str, mergeableMetadata: mergeableMetadata)
}
let xcframeworkV1 = XCFrameworkInfoPlist_V1(version: version.description, libraries: libraries)
let encoder = PropertyListEncoder()
encoder.outputFormat = .xml
return try encoder.encode(xcframeworkV1)
}
}
extension XCFramework.Library {
init(other: XCFrameworkInfoPlist_V1.Library) {
let libraryIdentifier = other.libraryIdentifier
let supportedPlatform = other.supportedPlatform
// silently ignoring supported architectures is fine as there is not real impact on the data model processing
let supportedArchitectures = OrderedSet(other.supportedArchitectures)
let platformVariant = other.platformVariant
let libraryPath = Path(other.libraryPath)
let binaryPath = other.binaryPath.flatMap { Path($0) }
let headersPath = other.headersPath.flatMap { Path($0) }
let debugSymbolsPath = other.debugSymbolsPath.flatMap { Path($0) }
let mergeableMetadata = other.mergeableMetadata ?? false
self.init(libraryIdentifier: libraryIdentifier, supportedPlatform: supportedPlatform, supportedArchitectures: supportedArchitectures, platformVariant: platformVariant, libraryPath: libraryPath, binaryPath: binaryPath, headersPath: headersPath, debugSymbolsPath: debugSymbolsPath, mergeableMetadata: mergeableMetadata)
}
}
// MARK: XCFramework Extensions
extension XCFramework {
/// Determines the location that the processed xcframework output should go to.
public static func computeOutputDirectory(_ scope: MacroEvaluationScope) -> Path {
let subfolder: Path
if scope.evaluate(BuiltinMacros.DEPLOYMENT_LOCATION) {
subfolder = scope.evaluate(BuiltinMacros.BUILT_PRODUCTS_DIR)
}
else {
subfolder = scope.unmodifiedTargetBuildDir
}
// Trim any trailing slashes, as the result is directly combined in spec files.
return subfolder.withoutTrailingSlash()
}
}
// MARK: XCFramework CLI creation
extension XCFramework {
/// Represents one of the possible command line arguments passed.
@_spi(Testing) public enum Argument: Equatable {
case framework(path: Path, debugSymbolPaths: [Path] = [])
case library(path: Path, headersPath: Path?, debugSymbolPaths: [Path] = [])
case output(path: Path)
case internalDistribution
var libraryPath: Path? {
if case let .library(path, _, _) = self { return path }
else { return nil }
}
var headersPath: Path? {
if case let .library(_, path, _) = self { return path }
else { return nil }
}
var debugSymbolPaths: [Path] {
if case let .library(_, _, path) = self { return path }
if case let .framework(_, path) = self { return path }
return []
}
var outputPath: Path? {
if case let .output(path) = self { return path }
return nil
}
}
public static func usage() -> String {
return
"""
OVERVIEW: Utility for packaging multiple build configurations of a given library or framework into a single xcframework.
USAGE:
xcodebuild -create-xcframework -framework <path> [-framework <path>...] -output <path>
xcodebuild -create-xcframework -library <path> [-headers <path>] [-library <path> [-headers <path>]...] -output <path>
OPTIONS:
-archive <path> Adds a framework or library from the archive at the given <path>. Use with -framework or -library.
-framework <path|name> Adds a framework from the given <path>.
When used with -archive, this should be the name of the framework instead of the full path.
-library <path|name> Adds a static or dynamic library from the given <path>.
When used with -archive, this should be the name of the library instead of the full path.
-headers <path> Adds the headers from the given <path>. Only applicable with -library.
-debug-symbols <path> Adds the debug symbols (dSYMs or bcsymbolmaps) from the given <path>. Can be applied multiple times. Must be used with -framework or -library.
-output <path> The <path> to write the xcframework to.
-allow-internal-distribution Specifies that the created xcframework contains information not suitable for public distribution.
-help Show this help content.
"""
}
@_spi(Testing) public enum CommandLineParsingResult {
case arguments([Argument], allowInternalDistribution: Bool)
case help
}
@_spi(Testing) public static func rewriteCommandLine(_ commandLine: [String], cwd currentWorkingDirectory: Path, fs: any FSProxy) -> [String] {
precondition(currentWorkingDirectory.isAbsolute)
func rewriteDebugSymbolCommandLine(_ archiveRoot: Path, _ name: String, _ fs: any FSProxy, _ newCommandLine: inout [String]) {
let dsym = archiveRoot.join("dSYMs").join("\(name).dSYM")
if fs.isDirectory(dsym) || fs.exists(dsym) {
newCommandLine.append("-debug-symbols")
newCommandLine.append(dsym.str)
}
}
// If the '-archive' flag is used, then all -framework/-library usages will be prefixed with their corresponding path into the archive. Also, the '-headers' and '-debug-symbols' will be added pointing into the archive. This function does not handle any of the error handling, but lets the rest of the system deal with duplicate or improper usage.
var newCommandLine: [String] = []
var archiveRoot: Path?
var entries = commandLine
while !entries.isEmpty {
let entry = entries.removeFirst()
switch entry {
case "-archive":
archiveRoot = Path(entries.removeFirst()).makeAbsolute(relativeTo: currentWorkingDirectory)?.normalize()
case "-framework":
if let archiveRoot {
let name = entries.removeFirst()
newCommandLine.append("-framework")
let root = Path("Products/Library/Frameworks")
newCommandLine.append(archiveRoot.join(root).join(name).str)
rewriteDebugSymbolCommandLine(archiveRoot, name, fs, &newCommandLine)
}
else {
newCommandLine.append(entry)
}
case "-library":
if let archiveRoot {
let name = entries.removeFirst()
newCommandLine.append("-library")
let root = Path("Products/usr/local/lib")
newCommandLine.append(archiveRoot.join(root).join(name).str)
let headers = archiveRoot.join("Products/usr/local/include")
if fs.exists(headers) {
newCommandLine.append("-headers")
newCommandLine.append(headers.str)
}
rewriteDebugSymbolCommandLine(archiveRoot, name, fs, &newCommandLine)
}
else {
newCommandLine.append(entry)
}
default:
newCommandLine.append(entry)
}
}
return newCommandLine
}
@_spi(Testing) public static func parseCommandLine(args commandLine: [String], currentWorkingDirectory: Path, fs: any FSProxy = PseudoFS()) -> Result<CommandLineParsingResult, XCFrameworkCreationError> {
enum ParseState {
case next
case framework
case library
case libraryHeader
case debugSymbols
case output
case end
}
// Determines if the current parse state is expecting additional command line arguments.
func expectingAdditionalArguments(_ state: ParseState) -> Bool {
switch state {
case .framework: return true
case .library: return true
case .libraryHeader: return true
case .output: return true
case .debugSymbols: return true
default: return false
}
}
func normalize(path: String, cwd: Path) -> Path {
precondition(cwd.isAbsolute)
return Path(path).makeAbsolute(relativeTo: cwd)!.normalize()
}
precondition(currentWorkingDirectory.isAbsolute, "path '\(currentWorkingDirectory.str)' is not absolute")
// The -archive flag is handled in a very special way; it re-writes the user's entered command line by emitting the corresponding -framework/-library, -headers, -debug-symbols arguments.
let commandLine = rewriteCommandLine(commandLine, cwd: currentWorkingDirectory, fs: fs)
var arguments = [Argument]()
var argumentIndex = commandLine.startIndex
var parseState = ParseState.next
var allowInternalDistribution = false
while parseState != .end {
guard argumentIndex != commandLine.endIndex else {
guard !expectingAdditionalArguments(parseState) else {
return .failure(XCFrameworkCreationError(message: "error: expected parameter to argument."))
}
// Exit the parsing loop. Do NOT simply return as there are additional validations that happen later.
parseState = .end
continue
}
let arg = commandLine[argumentIndex]
// If help is requested, simply show it and stop the command line argument processing.
if arg == "-help" {
return .success(.help)
}
switch parseState {
case .next:
switch arg {
case "createXCFramework": parseState = .next // the main command from Swift Build
case "-create-xcframework": parseState = .next // passed through via xcodebuild's parameter passing splat
case "-framework": parseState = .framework
case "-library": parseState = .library
case "-headers": parseState = .libraryHeader
case "-debug-symbols": parseState = .debugSymbols
case "-output": parseState = .output
case "-allow-internal-distribution":
allowInternalDistribution = true
parseState = .next
default:
// When running via `xcodebuild`, there are additional arguments passed that we want to safely ignore.
if arg.hasPrefix("-DVT") || arg.hasPrefix("-ExtraPlugInFolders") {
parseState = .next
}
else {
return .failure(XCFrameworkCreationError(message: "error: invalid argument '\(arg)'."))
}
}
case .framework:
arguments.append(.framework(path: normalize(path: arg, cwd: currentWorkingDirectory), debugSymbolPaths: []))
parseState = .next
case .library:
arguments.append(.library(path: normalize(path: arg, cwd: currentWorkingDirectory), headersPath: nil, debugSymbolPaths: []))
parseState = .next
case .libraryHeader:
let lastArgument = arguments.last
guard let path = lastArgument?.libraryPath else {
return .failure(XCFrameworkCreationError(message: "error: headers are only allowed with the use of '-library'."))
}
arguments.removeLast()
arguments.append(.library(path: path, headersPath: normalize(path: arg, cwd: currentWorkingDirectory), debugSymbolPaths: lastArgument?.debugSymbolPaths ?? []))
parseState = .next
case .debugSymbols:
let debugSymbolPath = Path(arg)
// This is a little-bit hacky, but it is what it is.
switch arguments.last {
case let .framework(path, debugSymbolPaths):
arguments.removeLast()
arguments.append(.framework(path: path, debugSymbolPaths: debugSymbolPaths + [debugSymbolPath]))
case let .library(path, headersPath, debugSymbolPaths):
arguments.removeLast()
arguments.append(.library(path: path, headersPath: headersPath, debugSymbolPaths: debugSymbolPaths + [debugSymbolPath]))
default:
return .failure(XCFrameworkCreationError(message: "error: debug symbols can only be specified using '-framework' or '-library'."))
}
parseState = .next
case .output:
guard arg.hasSuffix(".xcframework") else {
return .failure(XCFrameworkCreationError(message: "error: the output path must end with the extension 'xcframework'."))
}
arguments.append(.output(path: normalize(path: arg, cwd: currentWorkingDirectory)))
parseState = .next
case .end: break // do nothing
}
// Time to grab the next index.
argumentIndex += 1
}
let (frameworkCount, libraryCount, outputCount) = arguments.reduce((0, 0, 0)) { (acc, arg) in
switch arg {
case .framework(_,_): return (acc.0 + 1, acc.1, acc.2)
case .library(_,_,_): return (acc.0, acc.1 + 1, acc.2)
case .output(_): return (acc.0, acc.1, acc.2 + 1)
case .internalDistribution: return acc
}
}
if frameworkCount == 0 && libraryCount == 0 {
return .failure(XCFrameworkCreationError(message: "error: at least one framework or library must be specified."))
}
if frameworkCount != 0 && libraryCount != 0 {
return .failure(XCFrameworkCreationError(message: "error: an xcframework cannot contain both frameworks and libraries."))
}
if outputCount == 0 {
return .failure(XCFrameworkCreationError(message: "error: no output was specified."))
}
if outputCount > 1 {
return .failure(XCFrameworkCreationError(message: "error: only a single output location may be specified."))
}
return .success(.arguments(arguments, allowInternalDistribution: allowInternalDistribution))
}
@_spi(Testing) public static func framework(from path: Path, debugSymbolPaths: [Path] = [], fs: any FSProxy = localFS, infoLookup: any PlatformInfoLookup) -> Result<XCFramework.Library, XCFrameworkCreationError> {