Skip to content

Commit 8bbb03f

Browse files
committed
fix(ios): embed SwiftPM products only into targets that host frameworks
Embedding is limited to apps, App Clips and WatchKit extensions (which hold a watchOS 2 app's code). Framework targets, such as watch folder modules, now only link, like app extensions: a framework nested in another framework fails validation. A package that lists `embed` but reaches only link-only targets in a batch is warned about, since nothing would copy its products into the bundle that hosts them. A product removed from `embed` loses its copy entry on the next prepare, while a build file another target still lists is kept. Products without an explicit type use automatic linkage rather than being guaranteed static; the `embed` docs say so.
1 parent f41fcaa commit 8bbb03f

4 files changed

Lines changed: 219 additions & 22 deletions

File tree

‎lib/definitions/ios.d.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,8 @@ declare global {
5454
* Products built as dynamic libraries (`.library(type: .dynamic)`) must
5555
* also be copied into the app bundle. Lists the subset of `libs` to
5656
* embed; a dynamic product that is linked but not embedded fails in dyld
57-
* at launch on devices. Extension `targets` only link these products and
58-
* load them from the app's bundle.
57+
* at launch on devices. App extensions and frameworks listed in `targets`
58+
* only link these products and load them from the app's bundle.
5959
*/
6060
embed?: string[];
6161
}

‎lib/definitions/project.d.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -115,11 +115,12 @@ interface IOSSPMPackageBase {
115115
* Optional: products built as dynamic libraries (`.library(type: .dynamic)`)
116116
* must also be copied into the app bundle. List the subset of `libs` to
117117
* embed; a dynamic product that is linked but not embedded builds fine but
118-
* fails in dyld at launch on a device. Extensions listed in `targets` only
119-
* link these products and load them from the app's bundle.
118+
* fails in dyld at launch on a device. App extensions and frameworks listed
119+
* in `targets` only link these products and load them from the app's bundle.
120120
*
121-
* A `.library(...)` without a type is static and is compiled into the app
122-
* executable, so it needs no embedding.
121+
* A `.library(...)` without a type uses automatic linkage, which Xcode links
122+
* statically into the target, so it needs no embedding; list only products
123+
* declared `type: .dynamic`.
123124
*/
124125
embed?: string[];
125126
}

‎lib/services/ios/spm-pbxproj-service.ts‎

Lines changed: 86 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,22 @@ import { injector } from "../../common/yok";
44
import { IFileSystem } from "../../common/declarations";
55

66
/**
7-
* Extensions (widgets, watch extensions, ...) load embedded frameworks from the
8-
* host app's Frameworks folder through their `@executable_path/../../Frameworks`
9-
* runpath; App Store validation rejects a framework copied into an extension's
10-
* own bundle (ITMS-90206).
7+
* Target types whose bundle carries its own Frameworks folder. App extensions
8+
* and frameworks only link: they load embedded frameworks from the bundle that
9+
* hosts them, and App Store validation rejects frameworks nested in an app
10+
* extension (ITMS-90206) or another framework. A watchOS 2 app keeps its code,
11+
* and so its frameworks, in its WatchKit extension.
1112
*/
12-
function isExtensionTarget(target: any): boolean {
13-
return /extension/.test(String(target?.productType ?? ""));
13+
const EMBEDDING_PRODUCT_TYPES = new Set([
14+
"com.apple.product-type.application",
15+
"com.apple.product-type.application.on-demand-install-capable",
16+
"com.apple.product-type.watchkit2-extension",
17+
]);
18+
19+
function canEmbedFrameworks(target: any): boolean {
20+
return EMBEDDING_PRODUCT_TYPES.has(
21+
String(target?.productType ?? "").replace(/^"|"$/g, ""),
22+
);
1423
}
1524

1625
/**
@@ -28,10 +37,10 @@ function isExtensionTarget(target: any): boolean {
2837
* `packageProductDependencies`.
2938
*
3039
* A product listed in `embed` additionally gets a second `PBXBuildFile` in the
31-
* "Embed Frameworks" copy phase of each non-extension target, which is how
32-
* Xcode itself records a dynamic package product added through "Frameworks,
33-
* Libraries, and Embedded Content" — linking alone leaves the framework out of
34-
* the app bundle.
40+
* "Embed Frameworks" copy phase of each target that can embed
41+
* (`EMBEDDING_PRODUCT_TYPES`), which is how Xcode itself records a dynamic
42+
* package product added through "Frameworks, Libraries, and Embedded Content"
43+
* — linking alone leaves the framework out of the app bundle.
3544
*
3645
* Every entry is keyed by its pbxproj comment (e.g. `XCRemoteSwiftPackageReference
3746
* "Auth0"`), and an existing entry is updated in place rather than duplicated —
@@ -72,6 +81,8 @@ export class SPMPbxprojService implements ISPMPbxprojService {
7281
project.parseSync();
7382

7483
let added = false;
84+
const embeddedPackages = new Set<string>();
85+
const linkOnlyTargets = new Map<string, string[]>();
7586
for (const { targetName, package: pkg } of assignments) {
7687
const targetId = this.findTargetId(project, targetName);
7788
if (!targetId) {
@@ -83,6 +94,25 @@ export class SPMPbxprojService implements ISPMPbxprojService {
8394

8495
if (this.addPackageToTarget(project, targetId, pkg, projectRoot)) {
8596
added = true;
97+
if (pkg.embed?.length) {
98+
const target = project.pbxNativeTargetSection()[targetId];
99+
if (canEmbedFrameworks(target)) {
100+
embeddedPackages.add(pkg.name);
101+
} else {
102+
linkOnlyTargets.set(pkg.name, [
103+
...(linkOnlyTargets.get(pkg.name) ?? []),
104+
targetName,
105+
]);
106+
}
107+
}
108+
}
109+
}
110+
111+
for (const [packageName, targetNames] of linkOnlyTargets) {
112+
if (!embeddedPackages.has(packageName)) {
113+
this.$logger.warn(
114+
`SPM: package "${packageName}" lists products in embed, but its targets (${targetNames.join(", ")}) load frameworks from the app or WatchKit extension that hosts them. Add the package to that target too, or the products fail to load at launch.`,
115+
);
86116
}
87117
}
88118

@@ -226,9 +256,9 @@ export class SPMPbxprojService implements ISPMPbxprojService {
226256
);
227257
}
228258
}
229-
if (embedLibs.size && isExtensionTarget(target)) {
259+
if (embedLibs.size && !canEmbedFrameworks(target)) {
230260
this.$logger.trace(
231-
`SPM: linking ${[...embedLibs].join(", ")} into extension target ${target.name} without embedding; it loads them from the host app's bundle.`,
261+
`SPM: linking ${[...embedLibs].join(", ")} into ${target.name} without embedding; it loads them from the bundle that hosts it.`,
232262
);
233263
embedLibs.clear();
234264
}
@@ -289,6 +319,7 @@ export class SPMPbxprojService implements ISPMPbxprojService {
289319
});
290320

291321
if (!embedLibs.has(lib)) {
322+
this.removeEmbedEntries(project, target, spmProductDependencyUUID);
292323
continue;
293324
}
294325

@@ -328,6 +359,49 @@ export class SPMPbxprojService implements ISPMPbxprojService {
328359
return null;
329360
}
330361

362+
/**
363+
* Drops a product from this target's Embed Frameworks phases, and its
364+
* build file once no other copy phase lists it.
365+
*/
366+
private removeEmbedEntries(
367+
project: any,
368+
target: any,
369+
productRef: string,
370+
): void {
371+
const buildFiles = project.hash.project.objects["PBXBuildFile"] ?? {};
372+
const copyPhases =
373+
project.hash.project.objects["PBXCopyFilesBuildPhase"] ?? {};
374+
const isProductFile = (file: any) =>
375+
buildFiles[file.value]?.productRef === productRef;
376+
377+
const removed = new Set<string>();
378+
for (const phase of target.buildPhases ?? []) {
379+
const phaseObj = copyPhases[phase.value];
380+
if (!phaseObj?.files || String(phaseObj.dstSubfolderSpec) !== "10") {
381+
continue;
382+
}
383+
for (const file of phaseObj.files.filter(isProductFile)) {
384+
removed.add(file.value);
385+
}
386+
phaseObj.files = phaseObj.files.filter(
387+
(file: any) => !isProductFile(file),
388+
);
389+
}
390+
391+
const stillListed = new Set(
392+
Object.keys(copyPhases)
393+
.filter((key) => !key.endsWith("_comment"))
394+
.flatMap((key) => copyPhases[key].files ?? [])
395+
.map((file: any) => file.value),
396+
);
397+
for (const uuid of removed) {
398+
if (!stillListed.has(uuid)) {
399+
delete buildFiles[uuid];
400+
delete buildFiles[`${uuid}_comment`];
401+
}
402+
}
403+
}
404+
331405
/**
332406
* Finds the "Embed Frameworks" copy phase listed in this target's own
333407
* buildPhases, creating one when the target has none. Matched on the

‎test/services/ios/spm-pbxproj-service.ts‎

Lines changed: 126 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -111,10 +111,14 @@ function parsePbxproj(projectRoot: string): any {
111111
return project;
112112
}
113113

114-
/** Adds an app extension target with its own Frameworks phase to the fixture, returning its uuid. */
115-
function addExtensionTarget(projectRoot: string, name: string): string {
114+
/** Adds a target with its own Frameworks phase to the fixture, returning its uuid. */
115+
function addTarget(
116+
projectRoot: string,
117+
name: string,
118+
type: "app_extension" | "framework" | "watch_extension",
119+
): string {
116120
const project = parsePbxproj(projectRoot);
117-
const target = project.addTarget(name, "app_extension", name);
121+
const target = project.addTarget(name, type, name);
118122
project.addBuildPhase(
119123
[],
120124
"PBXFrameworksBuildPhase",
@@ -128,6 +132,17 @@ function addExtensionTarget(projectRoot: string, name: string): string {
128132
return target.uuid;
129133
}
130134

135+
/** The comments of the files in a target's Embed Frameworks copy phases. */
136+
function embeddedIn(project: any, targetId: string): string[] {
137+
const target = project.pbxNativeTargetSection()[targetId];
138+
const copyPhases = project.hash.project.objects["PBXCopyFilesBuildPhase"];
139+
return (target.buildPhases as any[])
140+
.map((phase) => copyPhases?.[phase.value])
141+
.filter((phase) => phase && String(phase.dstSubfolderSpec) === "10")
142+
.flatMap((phase) => phase.files ?? [])
143+
.map((file: any) => file.comment);
144+
}
145+
131146
/** The uuids of the build files in the fixture target's "Embed Frameworks" phase. */
132147
function embedPhaseFileUuids(project: any): string[] {
133148
const targets = project.pbxNativeTargetSection();
@@ -479,7 +494,7 @@ describe("SPMPbxprojService", () => {
479494
});
480495

481496
it("links an embedded product into an extension target without embedding it there", () => {
482-
const extensionId = addExtensionTarget(projectRoot, "Widget");
497+
const extensionId = addTarget(projectRoot, "Widget", "app_extension");
483498

484499
assert.isTrue(
485500
service.addPackages(projectRoot, [
@@ -511,6 +526,113 @@ describe("SPMPbxprojService", () => {
511526
]);
512527
});
513528

529+
it("links an embedded product into a framework target without embedding it there", () => {
530+
const frameworkId = addTarget(projectRoot, "Module", "framework");
531+
532+
assert.isTrue(
533+
service.addPackages(projectRoot, [
534+
{ targetName: TARGET_NAME, package: dynamicPackage },
535+
{ targetName: "Module", package: dynamicPackage },
536+
]),
537+
);
538+
539+
const project = parsePbxproj(projectRoot);
540+
assert.deepEqual(embeddedIn(project, frameworkId), []);
541+
assert.lengthOf(embedPhaseFileUuids(project), 1);
542+
assert.isEmpty(warnings);
543+
});
544+
545+
it("embeds into a WatchKit extension, which hosts the watch app's code", () => {
546+
const watchExtensionId = addTarget(
547+
projectRoot,
548+
"WatchExtension",
549+
"watch_extension",
550+
);
551+
552+
assert.isTrue(
553+
service.addPackages(projectRoot, [
554+
{ targetName: "WatchExtension", package: dynamicPackage },
555+
]),
556+
);
557+
558+
assert.deepEqual(
559+
embeddedIn(parsePbxproj(projectRoot), watchExtensionId),
560+
["DynamicProduct in Embed Frameworks"],
561+
);
562+
assert.isEmpty(warnings);
563+
});
564+
565+
it("warns when no target the package is applied to can embed it", () => {
566+
addTarget(projectRoot, "Widget", "app_extension");
567+
568+
assert.isTrue(
569+
service.addPackages(projectRoot, [
570+
{ targetName: "Widget", package: dynamicPackage },
571+
]),
572+
);
573+
574+
assert.isTrue(
575+
warnings.some(
576+
(w) => w.includes("DynamicPkg") && w.includes("Widget"),
577+
),
578+
`expected a warning naming the package and target, got: ${warnings}`,
579+
);
580+
assert.notInclude(readPbxproj(projectRoot), "in Embed Frameworks");
581+
});
582+
583+
it("removes the embed entry when a product leaves embed, and keeps it linked", () => {
584+
assert.isTrue(
585+
service.addPackages(projectRoot, [
586+
{ targetName: TARGET_NAME, package: dynamicPackage },
587+
]),
588+
);
589+
assert.isTrue(
590+
service.addPackages(projectRoot, [
591+
{
592+
targetName: TARGET_NAME,
593+
package: { ...dynamicPackage, embed: [] },
594+
},
595+
]),
596+
);
597+
598+
const contents = readPbxproj(projectRoot);
599+
assert.notInclude(contents, "DynamicProduct in Embed Frameworks");
600+
assert.include(contents, "DynamicProduct in Frameworks");
601+
assert.lengthOf(embedPhaseFileUuids(parsePbxproj(projectRoot)), 0);
602+
});
603+
604+
it("keeps an embed entry another target still lists", () => {
605+
const watchExtensionId = addTarget(
606+
projectRoot,
607+
"WatchExtension",
608+
"watch_extension",
609+
);
610+
assert.isTrue(
611+
service.addPackages(projectRoot, [
612+
{ targetName: TARGET_NAME, package: dynamicPackage },
613+
{ targetName: "WatchExtension", package: dynamicPackage },
614+
]),
615+
);
616+
assert.isTrue(
617+
service.addPackages(projectRoot, [
618+
{
619+
targetName: TARGET_NAME,
620+
package: { ...dynamicPackage, embed: [] },
621+
},
622+
]),
623+
);
624+
625+
const project = parsePbxproj(projectRoot);
626+
assert.lengthOf(embedPhaseFileUuids(project), 0);
627+
assert.deepEqual(embeddedIn(project, watchExtensionId), [
628+
"DynamicProduct in Embed Frameworks",
629+
]);
630+
assert.include(
631+
readPbxproj(projectRoot),
632+
"DynamicProduct in Embed Frameworks */ = {",
633+
);
634+
});
635+
514636
it("warns about an embed entry that is not a linked lib, and skips it", () => {
515637
assert.isTrue(
516638
service.addPackages(projectRoot, [

0 commit comments

Comments
 (0)