Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions lib/services/ios-project-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -790,10 +794,9 @@ export class IOSProjectService
this.$options.hostProjectPath,
buildFolderPath,
);
project.addToOtherLinkerFlags(
JSON.stringify(
`-sectcreate __DATA __TNSMetadata "${metadataPath}/metadata-arm64.bin"`,
),
setMetadataSectionFlag(
project,
metadataSectionFlag(`${metadataPath}/metadata-arm64.bin`),
);

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

this.savePbxProj(project, projectData);
} catch (err) {
this.$logger.trace(
"Error adding NativeScript group to host project",
this.$logger.error(
`Error adding the NativeScript group to the host project ${this.$options.hostProjectPath}. The host project may be left partially configured.`,
err,
);
}
Expand Down
117 changes: 117 additions & 0 deletions lib/services/ios/embed-metadata-linker-flag.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/**
* `ld` accepts a repeated `-sectcreate` for the same section and concatenates
* the files, so the metadata directive must be set, never appended: each extra
* copy adds a full metadata file to the host executable.
*/

/**
* 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 directiveWithSurroundingSpace = new RegExp(
`([ \\t]*)${METADATA_DIRECTIVE.source}([ \\t]*)`,
"g",
);
let matched = false;
const without = entry.replace(
directiveWithSurroundingSpace,
(_match, before: string, after: string) => {
matched = true;
return before && after ? " " : "";
},
);
if (!matched) {
return entry;
}

return without.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);
}
}

// Seed `$(inherited)` only when nothing else is set, as
// `addToOtherLinkerFlags` does: a host that left it out did so on purpose.
if (kept.length === 0) {
kept.push(JSON.stringify(INHERITED));
}

kept.push(flag);
buildSettings.OTHER_LDFLAGS = kept;
}
}
194 changes: 194 additions & 0 deletions test/ios-project-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1567,6 +1567,200 @@ 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");
(<any>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"),
<any>{},
);

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("does not add $(inherited) to a host that left it out", async () => {
const unrelated = JSON.stringify("-ObjC");
const { prepare, flagsOfTarget, seedFlags } = setup();
seedFlags([unrelated]);

await prepare();

for (const flags of flagsOfTarget()) {
assert.lengthOf(metadataDirectives(flags), 1);
assert.include(flags, unrelated);
assert.notInclude(flags, '"$(inherited)"');
}
});

it("preserves repeated whitespace in unrelated flag arguments when stripping a directive", async () => {
const combined = JSON.stringify(
'-force_load "libs/My Library.a" -sectcreate __DATA __TNSMetadata "../embedHost/metadata-arm64.bin"',
);
const { prepare, flagsOfTarget, seedFlags } = setup();
seedFlags(['"$(inherited)"', combined]);

await prepare();

for (const flags of flagsOfTarget()) {
assert.lengthOf(metadataDirectives(flags), 1);
assert.include(flags, JSON.stringify('-force_load "libs/My Library.a"'));
}
});

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");
(<any>testInjector.resolve("options")).hostProjectPath = mkdtempSync(
path.join(tmpdir(), "embedMetadataBrokenHost-"),
);
// The host project's pbxproj exists but the group cannot be added to it.
testInjector.resolve("xcprojService").findXcodeProject = () =>
(<any>testInjector.resolve("options")).hostProjectPath;
(<any>iOSProjectService).createPbxProj = (): any => ({
addPbxGroup: () => {
throw new Error("host project is read-only");
},
pbxGroupByName: (): any => null,
});

await iOSProjectService.prepareProject(
testInjector.resolve("projectData"),
<any>{},
);

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
Expand Down