Skip to content

Commit 30c8d3d

Browse files
committed
fix(ios): keep one embed metadata linker flag across runs
`ns embed ios` forces a prepare on every run, and addToOtherLinkerFlags appends unconditionally, so the host project's OTHER_LDFLAGS gained another -sectcreate __DATA __TNSMetadata directive each time. ld concatenates the referenced files, so every re-run added a full metadata copy (roughly 9-12 MB) to the host executable; the runtime only reads from the start of the section, which is why it went unnoticed. Set the directive instead of appending it: drop existing metadata directives (stale paths, other architectures, duplicates from earlier runs), leave every other linker flag as it is, and add the wanted directive once. Failures while setting up the host project used to be logged at trace level, leaving the host half configured with no visible error. Log them as errors. Refs #6168
1 parent 745347c commit 30c8d3d

3 files changed

Lines changed: 302 additions & 6 deletions

File tree

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

Lines changed: 16 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,13 @@ 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+
// Set the directive rather than append it: an embed forces a prepare
798+
// on every run, so appending left one more copy in OTHER_LDFLAGS per
799+
// run, and the linker concatenates the referenced files, adding a
800+
// full metadata file to the host executable each time.
801+
setMetadataSectionFlag(
802+
project,
803+
metadataSectionFlag(`${metadataPath}/metadata-arm64.bin`),
797804
);
798805

799806
// // no shorthand way to get UUID of build phase that i can tell
@@ -827,8 +834,11 @@ export class IOSProjectService
827834

828835
this.savePbxProj(project, projectData);
829836
} catch (err) {
830-
this.$logger.trace(
831-
"Error adding NativeScript group to host project",
837+
// A failure here leaves the host project partially set up — the
838+
// NativeScript group may exist without its linker flag. Trace-only
839+
// logging hid that, so surface it as an error.
840+
this.$logger.error(
841+
`Error adding the NativeScript group to the host project ${this.$options.hostProjectPath}. The host project may be left partially configured.`,
832842
err,
833843
);
834844
}
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
/**
2+
* Keeps the host project's `-sectcreate __DATA __TNSMetadata` linker flag in a
3+
* sane state when a project is prepared for embedding.
4+
*
5+
* `ns embed ios` forces a prepare on every run, and `addToOtherLinkerFlags`
6+
* appends unconditionally — so every run added another copy of the directive,
7+
* and `ld` concatenates the referenced files, growing the host executable by a
8+
* full metadata copy (roughly 9–12 MB) per run. The runtime only reads from the
9+
* start of the section, which is why the extra copies went unnoticed.
10+
*
11+
* The flag therefore has to be set, not appended: drop every existing metadata
12+
* directive (stale ones naming another architecture or path, plus duplicates
13+
* left by earlier runs), keep all other linker flags intact, and append the
14+
* wanted directive once.
15+
*/
16+
17+
/**
18+
* A metadata directive and its path. The path is either quoted — optionally
19+
* carrying the JSON escaping an `OTHER_LDFLAGS` array entry has, i.e. `\"p\"` —
20+
* or unquoted with no spaces.
21+
*/
22+
const METADATA_DIRECTIVE =
23+
/-sectcreate\s+__DATA\s+__TNSMetadata\s+(?:\\"(?:[^"\\]|\\[\s\S])*?\\"|"(?:[^"\\]|\\[\s\S])*?"|[^\s"\\]+)/g;
24+
25+
const INHERITED = "$(inherited)";
26+
27+
/** The flag value as `nativescript-dev-xcode` stores it: one JSON-quoted string. */
28+
export function metadataSectionFlag(metadataFilePath: string): string {
29+
return JSON.stringify(
30+
`-sectcreate __DATA __TNSMetadata "${metadataFilePath}"`,
31+
);
32+
}
33+
34+
/**
35+
* Removes metadata directives from a single `OTHER_LDFLAGS` entry.
36+
*
37+
* Only the directive goes away: a scalar entry can hold several flags at once
38+
* (`"$(inherited)" -ObjC`), so its other flags — and the quote that closes the
39+
* entry — have to survive. Entries without a directive are returned untouched,
40+
* so unrelated spacing is never rewritten.
41+
*/
42+
function stripMetadataDirectives(entry: string): string {
43+
const without = entry.replace(METADATA_DIRECTIVE, " ");
44+
if (without === entry) {
45+
return entry;
46+
}
47+
48+
return without.replace(/[ \t]{2,}/g, " ").trim();
49+
}
50+
51+
/** True when an entry held nothing but the directive once it was removed. */
52+
function isEmptyEntry(entry: string): boolean {
53+
return /^[\s"']*$/.test(entry);
54+
}
55+
56+
/**
57+
* Rewrites the build configurations of `project`'s product so `OTHER_LDFLAGS`
58+
* ends up with exactly one metadata directive.
59+
*
60+
* Configurations are selected the same way `addToOtherLinkerFlags` selects them
61+
* (by the project's `PRODUCT_NAME`), so other targets in the host project keep
62+
* their own linker flags.
63+
*/
64+
export function setMetadataSectionFlag(project: any, flag: string): void {
65+
const configurations = project.pbxXCBuildConfigurationSection() || {};
66+
const productName = project.productName;
67+
68+
for (const key of Object.keys(configurations)) {
69+
if (/_comment$/.test(key)) {
70+
continue;
71+
}
72+
73+
const buildSettings = configurations[key].buildSettings;
74+
if (!buildSettings) {
75+
continue;
76+
}
77+
78+
const currentProductName = buildSettings.PRODUCT_NAME;
79+
const unquotedProductName =
80+
typeof currentProductName === "string"
81+
? currentProductName.replace(/^"(.*)"$/, "$1")
82+
: currentProductName;
83+
if (unquotedProductName !== productName) {
84+
continue;
85+
}
86+
87+
const current = buildSettings.OTHER_LDFLAGS;
88+
const entries: any[] = Array.isArray(current)
89+
? current
90+
: current === undefined
91+
? []
92+
: [current];
93+
94+
const kept: any[] = [];
95+
for (const entry of entries) {
96+
if (typeof entry !== "string") {
97+
kept.push(entry);
98+
continue;
99+
}
100+
101+
const stripped = stripMetadataDirectives(entry);
102+
if (!isEmptyEntry(stripped)) {
103+
kept.push(stripped);
104+
}
105+
}
106+
107+
// The host's flags are usually inherited from an xcconfig file, so
108+
// `$(inherited)` has to stay in the list; `addToOtherLinkerFlags` seeds it
109+
// the same way whenever the setting is missing.
110+
const hasInherited = kept.some(
111+
(entry) => typeof entry === "string" && entry.includes(INHERITED),
112+
);
113+
if (!hasInherited) {
114+
kept.unshift(JSON.stringify(INHERITED));
115+
}
116+
117+
kept.push(flag);
118+
buildSettings.OTHER_LDFLAGS = kept;
119+
}
120+
}

‎test/ios-project-service.ts‎

Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1567,6 +1567,172 @@ 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("reports a broken host project instead of hiding it at trace level", async () => {
1692+
const logged: any[] = [];
1693+
const testInjector = createTestInjector(
1694+
mkdtempSync(path.join(tmpdir(), "embedMetadataBroken-")),
1695+
projectName,
1696+
xcode,
1697+
);
1698+
// Registered before the service resolves its logger.
1699+
testInjector.register("logger", {
1700+
error: (...args: any[]) => logged.push(args),
1701+
warn: (): void => undefined,
1702+
info: (): void => undefined,
1703+
debug: (): void => undefined,
1704+
trace: (...args: any[]) => logged.push(["trace", ...args]),
1705+
});
1706+
const iOSProjectService: IOSProjectService =
1707+
testInjector.resolve("iOSProjectService");
1708+
(<any>testInjector.resolve("options")).hostProjectPath = mkdtempSync(
1709+
path.join(tmpdir(), "embedMetadataBrokenHost-"),
1710+
);
1711+
// The host project's pbxproj exists but the group cannot be added to it —
1712+
// the failure mode that used to leave a half-configured host.
1713+
testInjector.resolve("xcprojService").findXcodeProject = () =>
1714+
(<any>testInjector.resolve("options")).hostProjectPath;
1715+
(<any>iOSProjectService).createPbxProj = (): any => ({
1716+
addPbxGroup: () => {
1717+
throw new Error("host project is read-only");
1718+
},
1719+
pbxGroupByName: (): any => null,
1720+
});
1721+
1722+
await iOSProjectService.prepareProject(
1723+
testInjector.resolve("projectData"),
1724+
<any>{},
1725+
);
1726+
1727+
const reported = logged.filter((entry) => entry[0] !== "trace");
1728+
assert.isNotEmpty(
1729+
reported,
1730+
`host-project setup failures must not stay at trace level, got ${JSON.stringify(logged)}`,
1731+
);
1732+
assert.include(String(reported[0][0]), "host project");
1733+
});
1734+
});
1735+
15701736
describe("SPM Packages", () => {
15711737
it("should add SPM packages to the project", async () => {
15721738
// todo: add tests for SPM packages

0 commit comments

Comments
 (0)