From 30c8d3d97b515e25f21001cf6ec0774fac658774 Mon Sep 17 00:00:00 2001 From: Goldloli <39011904+Goldloli@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:00:36 +0800 Subject: [PATCH] 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 --- lib/services/ios-project-service.ts | 22 ++- .../ios/embed-metadata-linker-flag.ts | 120 +++++++++++++ test/ios-project-service.ts | 166 ++++++++++++++++++ 3 files changed, 302 insertions(+), 6 deletions(-) create mode 100644 lib/services/ios/embed-metadata-linker-flag.ts diff --git a/lib/services/ios-project-service.ts b/lib/services/ios-project-service.ts index d67dc0c08c..3f6f0d9672 100644 --- a/lib/services/ios-project-service.ts +++ b/lib/services/ios-project-service.ts @@ -63,6 +63,10 @@ import { getCompilationCachePath, getDerivedDataPath, } from "./ios/ios-build-paths"; +import { + metadataSectionFlag, + setMetadataSectionFlag, +} from "./ios/embed-metadata-linker-flag"; interface INativeSourceCodeGroup { name: string; @@ -790,10 +794,13 @@ export class IOSProjectService this.$options.hostProjectPath, buildFolderPath, ); - project.addToOtherLinkerFlags( - JSON.stringify( - `-sectcreate __DATA __TNSMetadata "${metadataPath}/metadata-arm64.bin"`, - ), + // Set the directive rather than append it: an embed forces a prepare + // on every run, so appending left one more copy in OTHER_LDFLAGS per + // run, and the linker concatenates the referenced files, adding a + // full metadata file to the host executable each time. + setMetadataSectionFlag( + project, + metadataSectionFlag(`${metadataPath}/metadata-arm64.bin`), ); // // no shorthand way to get UUID of build phase that i can tell @@ -827,8 +834,11 @@ export class IOSProjectService this.savePbxProj(project, projectData); } catch (err) { - this.$logger.trace( - "Error adding NativeScript group to host project", + // A failure here leaves the host project partially set up — the + // NativeScript group may exist without its linker flag. Trace-only + // logging hid that, so surface it as an error. + this.$logger.error( + `Error adding the NativeScript group to the host project ${this.$options.hostProjectPath}. The host project may be left partially configured.`, err, ); } diff --git a/lib/services/ios/embed-metadata-linker-flag.ts b/lib/services/ios/embed-metadata-linker-flag.ts new file mode 100644 index 0000000000..bd78fb04c2 --- /dev/null +++ b/lib/services/ios/embed-metadata-linker-flag.ts @@ -0,0 +1,120 @@ +/** + * Keeps the host project's `-sectcreate __DATA __TNSMetadata` linker flag in a + * sane state when a project is prepared for embedding. + * + * `ns embed ios` forces a prepare on every run, and `addToOtherLinkerFlags` + * appends unconditionally — so every run added another copy of the directive, + * and `ld` concatenates the referenced files, growing the host executable by a + * full metadata copy (roughly 9–12 MB) per run. The runtime only reads from the + * start of the section, which is why the extra copies went unnoticed. + * + * The flag therefore has to be set, not appended: drop every existing metadata + * directive (stale ones naming another architecture or path, plus duplicates + * left by earlier runs), keep all other linker flags intact, and append the + * wanted directive once. + */ + +/** + * A metadata directive and its path. The path is either quoted — optionally + * carrying the JSON escaping an `OTHER_LDFLAGS` array entry has, i.e. `\"p\"` — + * or unquoted with no spaces. + */ +const METADATA_DIRECTIVE = + /-sectcreate\s+__DATA\s+__TNSMetadata\s+(?:\\"(?:[^"\\]|\\[\s\S])*?\\"|"(?:[^"\\]|\\[\s\S])*?"|[^\s"\\]+)/g; + +const INHERITED = "$(inherited)"; + +/** The flag value as `nativescript-dev-xcode` stores it: one JSON-quoted string. */ +export function metadataSectionFlag(metadataFilePath: string): string { + return JSON.stringify( + `-sectcreate __DATA __TNSMetadata "${metadataFilePath}"`, + ); +} + +/** + * Removes metadata directives from a single `OTHER_LDFLAGS` entry. + * + * Only the directive goes away: a scalar entry can hold several flags at once + * (`"$(inherited)" -ObjC`), so its other flags — and the quote that closes the + * entry — have to survive. Entries without a directive are returned untouched, + * so unrelated spacing is never rewritten. + */ +function stripMetadataDirectives(entry: string): string { + const without = entry.replace(METADATA_DIRECTIVE, " "); + if (without === entry) { + return entry; + } + + return without.replace(/[ \t]{2,}/g, " ").trim(); +} + +/** True when an entry held nothing but the directive once it was removed. */ +function isEmptyEntry(entry: string): boolean { + return /^[\s"']*$/.test(entry); +} + +/** + * Rewrites the build configurations of `project`'s product so `OTHER_LDFLAGS` + * ends up with exactly one metadata directive. + * + * Configurations are selected the same way `addToOtherLinkerFlags` selects them + * (by the project's `PRODUCT_NAME`), so other targets in the host project keep + * their own linker flags. + */ +export function setMetadataSectionFlag(project: any, flag: string): void { + const configurations = project.pbxXCBuildConfigurationSection() || {}; + const productName = project.productName; + + for (const key of Object.keys(configurations)) { + if (/_comment$/.test(key)) { + continue; + } + + const buildSettings = configurations[key].buildSettings; + if (!buildSettings) { + continue; + } + + const currentProductName = buildSettings.PRODUCT_NAME; + const unquotedProductName = + typeof currentProductName === "string" + ? currentProductName.replace(/^"(.*)"$/, "$1") + : currentProductName; + if (unquotedProductName !== productName) { + continue; + } + + const current = buildSettings.OTHER_LDFLAGS; + const entries: any[] = Array.isArray(current) + ? current + : current === undefined + ? [] + : [current]; + + const kept: any[] = []; + for (const entry of entries) { + if (typeof entry !== "string") { + kept.push(entry); + continue; + } + + const stripped = stripMetadataDirectives(entry); + if (!isEmptyEntry(stripped)) { + kept.push(stripped); + } + } + + // The host's flags are usually inherited from an xcconfig file, so + // `$(inherited)` has to stay in the list; `addToOtherLinkerFlags` seeds it + // the same way whenever the setting is missing. + const hasInherited = kept.some( + (entry) => typeof entry === "string" && entry.includes(INHERITED), + ); + if (!hasInherited) { + kept.unshift(JSON.stringify(INHERITED)); + } + + kept.push(flag); + buildSettings.OTHER_LDFLAGS = kept; + } +} diff --git a/test/ios-project-service.ts b/test/ios-project-service.ts index 4d54f6477d..a939c8d4ca 100644 --- a/test/ios-project-service.ts +++ b/test/ios-project-service.ts @@ -1567,6 +1567,172 @@ describe("workspace DerivedData location", () => { }); }); +describe("embed metadata linker flag", () => { + const projectName = "embedHost"; + const targetName = "TNSBlank"; + + /** + * A host project with a real pbxproj (test/files/project.pbxproj), wired so + * the service reads and writes that file instead of a mock. + */ + function setup() { + const projectPath = mkdtempSync( + path.join(tmpdir(), "embedMetadataProject-"), + ); + const hostProjectPath = mkdtempSync( + path.join(tmpdir(), "embedMetadataHost-"), + ); + const pbxProjPath = path.join( + hostProjectPath, + `${targetName}.xcodeproj`, + "project.pbxproj", + ); + require("fs").mkdirSync(path.dirname(pbxProjPath), { recursive: true }); + require("fs").copyFileSync( + path.join(__dirname, "files", "project.pbxproj"), + pbxProjPath, + ); + + const testInjector = createTestInjector(projectPath, projectName, xcode); + const iOSProjectService: IOSProjectService = + testInjector.resolve("iOSProjectService"); + (testInjector.resolve("options")).hostProjectPath = hostProjectPath; + + // `--hostProjectPath` moves the platform root into the host project. + iOSProjectService.getPlatformData(testInjector.resolve("projectData")); + testInjector.resolve("xcprojService").findXcodeProject = () => + path.dirname(pbxProjPath); + + const flagsOfTarget = (): any[] => { + const project = new xcode.project(pbxProjPath); + project.parseSync(); + const configurations = project.pbxXCBuildConfigurationSection(); + return Object.keys(configurations) + .filter((key) => !/_comment$/.test(key)) + .map((key) => configurations[key].buildSettings) + .filter( + (buildSettings: any) => + buildSettings && buildSettings.PRODUCT_NAME === targetName, + ) + .map((buildSettings: any) => buildSettings.OTHER_LDFLAGS); + }; + + const seedFlags = (entries: string[]) => { + const project = new xcode.project(pbxProjPath); + project.parseSync(); + const configurations = project.pbxXCBuildConfigurationSection(); + for (const key of Object.keys(configurations)) { + if (/_comment$/.test(key)) { + continue; + } + const buildSettings = configurations[key].buildSettings; + if (buildSettings && buildSettings.PRODUCT_NAME === targetName) { + buildSettings.OTHER_LDFLAGS = entries; + } + } + require("fs").writeFileSync(pbxProjPath, project.writeSync({})); + }; + + const prepare = () => + iOSProjectService.prepareProject( + testInjector.resolve("projectData"), + {}, + ); + + return { prepare, flagsOfTarget, seedFlags, projectName }; + } + + const metadataDirectives = (flags: any): string[] => + (Array.isArray(flags) ? flags : [flags]) + .filter((entry: any) => typeof entry === "string") + .filter((entry: string) => entry.includes("__TNSMetadata")); + + it("keeps a single metadata directive no matter how often embed runs", async () => { + const { prepare, flagsOfTarget, projectName } = setup(); + + await prepare(); + await prepare(); + await prepare(); + + const configurations = flagsOfTarget(); + assert.isNotEmpty(configurations); + for (const flags of configurations) { + const directives = metadataDirectives(flags); + assert.lengthOf( + directives, + 1, + `expected one metadata directive, got ${JSON.stringify(flags)}`, + ); + assert.include(directives[0], `${projectName}/metadata-arm64.bin`); + } + }); + + it("replaces duplicates left by earlier versions and keeps unrelated flags", async () => { + const stale = JSON.stringify( + '-sectcreate __DATA __TNSMetadata "../embedHost/metadata-arm64.bin"', + ); + const unrelated = JSON.stringify("-ObjC"); + const { prepare, flagsOfTarget, seedFlags, projectName } = setup(); + seedFlags(['"$(inherited)"', unrelated, stale, stale]); + + await prepare(); + + for (const flags of flagsOfTarget()) { + assert.lengthOf(metadataDirectives(flags), 1); + assert.include(flags, unrelated); + assert.include(flags, '"$(inherited)"'); + assert.include( + JSON.stringify(flags), + `${projectName}/metadata-arm64.bin`, + ); + } + }); + + it("reports a broken host project instead of hiding it at trace level", async () => { + const logged: any[] = []; + const testInjector = createTestInjector( + mkdtempSync(path.join(tmpdir(), "embedMetadataBroken-")), + projectName, + xcode, + ); + // Registered before the service resolves its logger. + testInjector.register("logger", { + error: (...args: any[]) => logged.push(args), + warn: (): void => undefined, + info: (): void => undefined, + debug: (): void => undefined, + trace: (...args: any[]) => logged.push(["trace", ...args]), + }); + const iOSProjectService: IOSProjectService = + testInjector.resolve("iOSProjectService"); + (testInjector.resolve("options")).hostProjectPath = mkdtempSync( + path.join(tmpdir(), "embedMetadataBrokenHost-"), + ); + // The host project's pbxproj exists but the group cannot be added to it — + // the failure mode that used to leave a half-configured host. + testInjector.resolve("xcprojService").findXcodeProject = () => + (testInjector.resolve("options")).hostProjectPath; + (iOSProjectService).createPbxProj = (): any => ({ + addPbxGroup: () => { + throw new Error("host project is read-only"); + }, + pbxGroupByName: (): any => null, + }); + + await iOSProjectService.prepareProject( + testInjector.resolve("projectData"), + {}, + ); + + const reported = logged.filter((entry) => entry[0] !== "trace"); + assert.isNotEmpty( + reported, + `host-project setup failures must not stay at trace level, got ${JSON.stringify(logged)}`, + ); + assert.include(String(reported[0][0]), "host project"); + }); +}); + describe("SPM Packages", () => { it("should add SPM packages to the project", async () => { // todo: add tests for SPM packages