Skip to content

Commit 1fff32a

Browse files
authored
fix(ios): keep one embed metadata linker flag across runs (#6218)
[skip ci]
1 parent e372139 commit 1fff32a

3 files changed

Lines changed: 320 additions & 6 deletions

File tree

‎lib/services/ios-project-service.ts‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,10 @@ import {
6363
getCompilationCachePath,
6464
getDerivedDataPath,
6565
} from "./ios/ios-build-paths";
66+
import {
67+
metadataSectionFlag,
68+
setMetadataSectionFlag,
69+
} from "./ios/embed-metadata-linker-flag";
6670

6771
interface INativeSourceCodeGroup {
6872
name: string;
@@ -790,10 +794,9 @@ export class IOSProjectService
790794
this.$options.hostProjectPath,
791795
buildFolderPath,
792796
);
793-
project.addToOtherLinkerFlags(
794-
JSON.stringify(
795-
`-sectcreate __DATA __TNSMetadata "${metadataPath}/metadata-arm64.bin"`,
796-
),
797+
setMetadataSectionFlag(
798+
project,
799+
metadataSectionFlag(`${metadataPath}/metadata-arm64.bin`),
797800
);
798801

799802
// // no shorthand way to get UUID of build phase that i can tell
@@ -827,8 +830,8 @@ export class IOSProjectService
827830

828831
this.savePbxProj(project, projectData);
829832
} catch (err) {
830-
this.$logger.trace(
831-
"Error adding NativeScript group to host project",
833+
this.$logger.error(
834+
`Error adding the NativeScript group to the host project ${this.$options.hostProjectPath}. The host project may be left partially configured.`,
832835
err,
833836
);
834837
}
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
/**
2+
* `ld` accepts a repeated `-sectcreate` for the same section and concatenates
3+
* the files, so the metadata directive must be set, never appended: each extra
4+
* copy adds a full metadata file to the host executable.
5+
*/
6+
7+
/**
8+
* A metadata directive and its path. The path is either quoted — optionally
9+
* carrying the JSON escaping an `OTHER_LDFLAGS` array entry has, i.e. `\"p\"` —
10+
* or unquoted with no spaces.
11+
*/
12+
const METADATA_DIRECTIVE =
13+
/-sectcreate\s+__DATA\s+__TNSMetadata\s+(?:\\"(?:[^"\\]|\\[\s\S])*?\\"|"(?:[^"\\]|\\[\s\S])*?"|[^\s"\\]+)/g;
14+
15+
const INHERITED = "$(inherited)";
16+
17+
/** The flag value as `nativescript-dev-xcode` stores it: one JSON-quoted string. */
18+
export function metadataSectionFlag(metadataFilePath: string): string {
19+
return JSON.stringify(
20+
`-sectcreate __DATA __TNSMetadata "${metadataFilePath}"`,
21+
);
22+
}
23+
24+
/**
25+
* Removes metadata directives from a single `OTHER_LDFLAGS` entry.
26+
*
27+
* Only the directive goes away: a scalar entry can hold several flags at once
28+
* (`"$(inherited)" -ObjC`), so its other flags — and the quote that closes the
29+
* entry — have to survive. Entries without a directive are returned untouched,
30+
* so unrelated spacing is never rewritten.
31+
*/
32+
function stripMetadataDirectives(entry: string): string {
33+
const directiveWithSurroundingSpace = new RegExp(
34+
`([ \\t]*)${METADATA_DIRECTIVE.source}([ \\t]*)`,
35+
"g",
36+
);
37+
let matched = false;
38+
const without = entry.replace(
39+
directiveWithSurroundingSpace,
40+
(_match, before: string, after: string) => {
41+
matched = true;
42+
return before && after ? " " : "";
43+
},
44+
);
45+
if (!matched) {
46+
return entry;
47+
}
48+
49+
return without.trim();
50+
}
51+
52+
/** True when an entry held nothing but the directive once it was removed. */
53+
function isEmptyEntry(entry: string): boolean {
54+
return /^[\s"']*$/.test(entry);
55+
}
56+
57+
/**
58+
* Rewrites the build configurations of `project`'s product so `OTHER_LDFLAGS`
59+
* ends up with exactly one metadata directive.
60+
*
61+
* Configurations are selected the same way `addToOtherLinkerFlags` selects them
62+
* (by the project's `PRODUCT_NAME`), so other targets in the host project keep
63+
* their own linker flags.
64+
*/
65+
export function setMetadataSectionFlag(project: any, flag: string): void {
66+
const configurations = project.pbxXCBuildConfigurationSection() || {};
67+
const productName = project.productName;
68+
69+
for (const key of Object.keys(configurations)) {
70+
if (/_comment$/.test(key)) {
71+
continue;
72+
}
73+
74+
const buildSettings = configurations[key].buildSettings;
75+
if (!buildSettings) {
76+
continue;
77+
}
78+
79+
const currentProductName = buildSettings.PRODUCT_NAME;
80+
const unquotedProductName =
81+
typeof currentProductName === "string"
82+
? currentProductName.replace(/^"(.*)"$/, "$1")
83+
: currentProductName;
84+
if (unquotedProductName !== productName) {
85+
continue;
86+
}
87+
88+
const current = buildSettings.OTHER_LDFLAGS;
89+
const entries: any[] = Array.isArray(current)
90+
? current
91+
: current === undefined
92+
? []
93+
: [current];
94+
95+
const kept: any[] = [];
96+
for (const entry of entries) {
97+
if (typeof entry !== "string") {
98+
kept.push(entry);
99+
continue;
100+
}
101+
102+
const stripped = stripMetadataDirectives(entry);
103+
if (!isEmptyEntry(stripped)) {
104+
kept.push(stripped);
105+
}
106+
}
107+
108+
// Seed `$(inherited)` only when nothing else is set, as
109+
// `addToOtherLinkerFlags` does: a host that left it out did so on purpose.
110+
if (kept.length === 0) {
111+
kept.push(JSON.stringify(INHERITED));
112+
}
113+
114+
kept.push(flag);
115+
buildSettings.OTHER_LDFLAGS = kept;
116+
}
117+
}

‎test/ios-project-service.ts‎

Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1567,6 +1567,200 @@ describe("workspace DerivedData location", () => {
15671567
});
15681568
});
15691569

1570+
describe("embed metadata linker flag", () => {
1571+
const projectName = "embedHost";
1572+
const targetName = "TNSBlank";
1573+
1574+
/**
1575+
* A host project with a real pbxproj (test/files/project.pbxproj), wired so
1576+
* the service reads and writes that file instead of a mock.
1577+
*/
1578+
function setup() {
1579+
const projectPath = mkdtempSync(
1580+
path.join(tmpdir(), "embedMetadataProject-"),
1581+
);
1582+
const hostProjectPath = mkdtempSync(
1583+
path.join(tmpdir(), "embedMetadataHost-"),
1584+
);
1585+
const pbxProjPath = path.join(
1586+
hostProjectPath,
1587+
`${targetName}.xcodeproj`,
1588+
"project.pbxproj",
1589+
);
1590+
require("fs").mkdirSync(path.dirname(pbxProjPath), { recursive: true });
1591+
require("fs").copyFileSync(
1592+
path.join(__dirname, "files", "project.pbxproj"),
1593+
pbxProjPath,
1594+
);
1595+
1596+
const testInjector = createTestInjector(projectPath, projectName, xcode);
1597+
const iOSProjectService: IOSProjectService =
1598+
testInjector.resolve("iOSProjectService");
1599+
(<any>testInjector.resolve("options")).hostProjectPath = hostProjectPath;
1600+
1601+
// `--hostProjectPath` moves the platform root into the host project.
1602+
iOSProjectService.getPlatformData(testInjector.resolve("projectData"));
1603+
testInjector.resolve("xcprojService").findXcodeProject = () =>
1604+
path.dirname(pbxProjPath);
1605+
1606+
const flagsOfTarget = (): any[] => {
1607+
const project = new xcode.project(pbxProjPath);
1608+
project.parseSync();
1609+
const configurations = project.pbxXCBuildConfigurationSection();
1610+
return Object.keys(configurations)
1611+
.filter((key) => !/_comment$/.test(key))
1612+
.map((key) => configurations[key].buildSettings)
1613+
.filter(
1614+
(buildSettings: any) =>
1615+
buildSettings && buildSettings.PRODUCT_NAME === targetName,
1616+
)
1617+
.map((buildSettings: any) => buildSettings.OTHER_LDFLAGS);
1618+
};
1619+
1620+
const seedFlags = (entries: string[]) => {
1621+
const project = new xcode.project(pbxProjPath);
1622+
project.parseSync();
1623+
const configurations = project.pbxXCBuildConfigurationSection();
1624+
for (const key of Object.keys(configurations)) {
1625+
if (/_comment$/.test(key)) {
1626+
continue;
1627+
}
1628+
const buildSettings = configurations[key].buildSettings;
1629+
if (buildSettings && buildSettings.PRODUCT_NAME === targetName) {
1630+
buildSettings.OTHER_LDFLAGS = entries;
1631+
}
1632+
}
1633+
require("fs").writeFileSync(pbxProjPath, project.writeSync({}));
1634+
};
1635+
1636+
const prepare = () =>
1637+
iOSProjectService.prepareProject(
1638+
testInjector.resolve("projectData"),
1639+
<any>{},
1640+
);
1641+
1642+
return { prepare, flagsOfTarget, seedFlags, projectName };
1643+
}
1644+
1645+
const metadataDirectives = (flags: any): string[] =>
1646+
(Array.isArray(flags) ? flags : [flags])
1647+
.filter((entry: any) => typeof entry === "string")
1648+
.filter((entry: string) => entry.includes("__TNSMetadata"));
1649+
1650+
it("keeps a single metadata directive no matter how often embed runs", async () => {
1651+
const { prepare, flagsOfTarget, projectName } = setup();
1652+
1653+
await prepare();
1654+
await prepare();
1655+
await prepare();
1656+
1657+
const configurations = flagsOfTarget();
1658+
assert.isNotEmpty(configurations);
1659+
for (const flags of configurations) {
1660+
const directives = metadataDirectives(flags);
1661+
assert.lengthOf(
1662+
directives,
1663+
1,
1664+
`expected one metadata directive, got ${JSON.stringify(flags)}`,
1665+
);
1666+
assert.include(directives[0], `${projectName}/metadata-arm64.bin`);
1667+
}
1668+
});
1669+
1670+
it("replaces duplicates left by earlier versions and keeps unrelated flags", async () => {
1671+
const stale = JSON.stringify(
1672+
'-sectcreate __DATA __TNSMetadata "../embedHost/metadata-arm64.bin"',
1673+
);
1674+
const unrelated = JSON.stringify("-ObjC");
1675+
const { prepare, flagsOfTarget, seedFlags, projectName } = setup();
1676+
seedFlags(['"$(inherited)"', unrelated, stale, stale]);
1677+
1678+
await prepare();
1679+
1680+
for (const flags of flagsOfTarget()) {
1681+
assert.lengthOf(metadataDirectives(flags), 1);
1682+
assert.include(flags, unrelated);
1683+
assert.include(flags, '"$(inherited)"');
1684+
assert.include(
1685+
JSON.stringify(flags),
1686+
`${projectName}/metadata-arm64.bin`,
1687+
);
1688+
}
1689+
});
1690+
1691+
it("does not add $(inherited) to a host that left it out", async () => {
1692+
const unrelated = JSON.stringify("-ObjC");
1693+
const { prepare, flagsOfTarget, seedFlags } = setup();
1694+
seedFlags([unrelated]);
1695+
1696+
await prepare();
1697+
1698+
for (const flags of flagsOfTarget()) {
1699+
assert.lengthOf(metadataDirectives(flags), 1);
1700+
assert.include(flags, unrelated);
1701+
assert.notInclude(flags, '"$(inherited)"');
1702+
}
1703+
});
1704+
1705+
it("preserves repeated whitespace in unrelated flag arguments when stripping a directive", async () => {
1706+
const combined = JSON.stringify(
1707+
'-force_load "libs/My Library.a" -sectcreate __DATA __TNSMetadata "../embedHost/metadata-arm64.bin"',
1708+
);
1709+
const { prepare, flagsOfTarget, seedFlags } = setup();
1710+
seedFlags(['"$(inherited)"', combined]);
1711+
1712+
await prepare();
1713+
1714+
for (const flags of flagsOfTarget()) {
1715+
assert.lengthOf(metadataDirectives(flags), 1);
1716+
assert.include(flags, JSON.stringify('-force_load "libs/My Library.a"'));
1717+
}
1718+
});
1719+
1720+
it("reports a broken host project instead of hiding it at trace level", async () => {
1721+
const logged: any[] = [];
1722+
const testInjector = createTestInjector(
1723+
mkdtempSync(path.join(tmpdir(), "embedMetadataBroken-")),
1724+
projectName,
1725+
xcode,
1726+
);
1727+
// Registered before the service resolves its logger.
1728+
testInjector.register("logger", {
1729+
error: (...args: any[]) => logged.push(args),
1730+
warn: (): void => undefined,
1731+
info: (): void => undefined,
1732+
debug: (): void => undefined,
1733+
trace: (...args: any[]) => logged.push(["trace", ...args]),
1734+
});
1735+
const iOSProjectService: IOSProjectService =
1736+
testInjector.resolve("iOSProjectService");
1737+
(<any>testInjector.resolve("options")).hostProjectPath = mkdtempSync(
1738+
path.join(tmpdir(), "embedMetadataBrokenHost-"),
1739+
);
1740+
// The host project's pbxproj exists but the group cannot be added to it.
1741+
testInjector.resolve("xcprojService").findXcodeProject = () =>
1742+
(<any>testInjector.resolve("options")).hostProjectPath;
1743+
(<any>iOSProjectService).createPbxProj = (): any => ({
1744+
addPbxGroup: () => {
1745+
throw new Error("host project is read-only");
1746+
},
1747+
pbxGroupByName: (): any => null,
1748+
});
1749+
1750+
await iOSProjectService.prepareProject(
1751+
testInjector.resolve("projectData"),
1752+
<any>{},
1753+
);
1754+
1755+
const reported = logged.filter((entry) => entry[0] !== "trace");
1756+
assert.isNotEmpty(
1757+
reported,
1758+
`host-project setup failures must not stay at trace level, got ${JSON.stringify(logged)}`,
1759+
);
1760+
assert.include(String(reported[0][0]), "host project");
1761+
});
1762+
});
1763+
15701764
describe("SPM Packages", () => {
15711765
it("should add SPM packages to the project", async () => {
15721766
// todo: add tests for SPM packages

0 commit comments

Comments
 (0)