build-windows-preinstalled-entry-shim.mjs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. #!/usr/bin/env node
  2. // Windows 入口 shim 的构建、校验和隔离副本;规格见 docs/preinstalled-tools/windows-entry-shim.md。
  3. import { execFile } from "node:child_process";
  4. import { createHash, randomUUID } from "node:crypto";
  5. import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
  6. import { arch, platform, tmpdir } from "node:os";
  7. import { dirname, join, resolve } from "node:path";
  8. import { pathToFileURL } from "node:url";
  9. import { promisify } from "node:util";
  10. import { withE2EDesktopBuildLock } from "./ensure-e2e-desktop-build.mjs";
  11. import { spawnCancellableStep } from "./e2e-step-process.mjs";
  12. const exec = promisify(execFile);
  13. const desktopRoot = resolve(import.meta.dirname, "..");
  14. const sourceRoot = join(desktopRoot, "native/windows-preinstalled-entry-shim");
  15. const outputName = "zcode-preinstalled-entry-shim.exe";
  16. const BUILD_TIMEOUT_MS = 5 * 60_000;
  17. export const PREINSTALLED_ENTRY_SHIM_PROCESS_TIMEOUT_MS = 6 * 60_000;
  18. const digest = (bytes) => createHash("sha256").update(bytes).digest("hex");
  19. function argument(args, name) {
  20. const index = args.indexOf(name);
  21. if (index >= 0) {
  22. if (!args[index + 1] || args[index + 1].startsWith("--"))
  23. throw new Error(`Missing ${name} value`);
  24. return args[index + 1];
  25. }
  26. return args.find((item) => item.startsWith(`${name}=`))?.slice(name.length + 1);
  27. }
  28. async function sourceDigest() {
  29. const hash = createHash("sha256");
  30. for (const path of [
  31. join(sourceRoot, "CMakeLists.txt"),
  32. join(sourceRoot, "shim.c"),
  33. import.meta.filename,
  34. ]) {
  35. hash.update(await readFile(path));
  36. }
  37. return hash.digest("hex");
  38. }
  39. function verifyPe(bytes, targetArch) {
  40. const header = bytes.length >= 64 ? bytes.readUInt32LE(60) : -1;
  41. if (
  42. bytes.toString("ascii", 0, 2) !== "MZ" ||
  43. header < 0 ||
  44. header + 6 > bytes.length ||
  45. bytes.toString("ascii", header, header + 4) !== "PE\0\0" ||
  46. bytes.readUInt16LE(header + 4) !== (targetArch === "arm64" ? 0xaa64 : 0x8664)
  47. )
  48. throw new Error(`Invalid Windows entry shim PE for ${targetArch}`);
  49. }
  50. async function readyBuild(outputDir, targetArch, source) {
  51. try {
  52. const bytes = await readFile(join(outputDir, outputName));
  53. verifyPe(bytes, targetArch);
  54. const manifest = JSON.parse(await readFile(join(outputDir, "build.json"), "utf8"));
  55. return manifest.version === 1 &&
  56. manifest.arch === targetArch &&
  57. manifest.source === source &&
  58. manifest.binary === digest(bytes)
  59. ? { bytes, manifest }
  60. : undefined;
  61. } catch {
  62. return undefined;
  63. }
  64. }
  65. async function writeAtomic(path, bytes) {
  66. await mkdir(dirname(path), { recursive: true });
  67. const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
  68. try {
  69. await writeFile(temporary, bytes, { flag: "wx" });
  70. await rename(temporary, path);
  71. } finally {
  72. await rm(temporary, { force: true });
  73. }
  74. }
  75. function remaining(deadline) {
  76. const duration = deadline - Date.now();
  77. if (duration <= 0) throw new Error("Windows entry shim preparation timed out");
  78. return duration;
  79. }
  80. /** 只装 Build Tools 时按 vswhere 查找 CMake;查询也属于同一个准备预算。 */
  81. async function resolveCmake(deadline) {
  82. if (process.env.CMAKE?.trim()) return process.env.CMAKE.trim();
  83. const vswhere = join(
  84. process.env["ProgramFiles(x86)"] ?? "C:/Program Files (x86)",
  85. "Microsoft Visual Studio/Installer/vswhere.exe",
  86. );
  87. try {
  88. const { stdout } = await exec(
  89. vswhere,
  90. [
  91. "-latest",
  92. "-products",
  93. "*",
  94. "-requires",
  95. "Microsoft.VisualStudio.Component.VC.CMake.Project",
  96. "-find",
  97. "Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/bin/cmake.exe",
  98. ],
  99. { timeout: remaining(deadline), killSignal: "SIGKILL", encoding: "utf8", windowsHide: true },
  100. );
  101. return stdout.split(/\r?\n/).find(Boolean)?.trim() || "cmake";
  102. } catch (error) {
  103. if (error.code !== "ENOENT") throw error;
  104. return "cmake";
  105. }
  106. }
  107. async function runCmake(command, args, deadline) {
  108. const { result } = spawnCancellableStep({
  109. command,
  110. args,
  111. env: process.env,
  112. timeoutMs: remaining(deadline),
  113. killProcessTree: true,
  114. killSignal: "SIGKILL",
  115. });
  116. const outcome = await result;
  117. if (outcome.error || outcome.exitCode !== 0)
  118. throw new Error(outcome.error || `Windows entry shim CMake failed: ${outcome.exitCode}`);
  119. }
  120. async function build(outputDir, targetArch, source, deadline) {
  121. const command = await resolveCmake(deadline);
  122. const work = await mkdtemp(join(tmpdir(), "zcode-preinstalled-entry-shim-"));
  123. try {
  124. const buildDir = join(work, "build");
  125. const builtDir = join(work, "out");
  126. await runCmake(
  127. command,
  128. [
  129. "-S",
  130. sourceRoot,
  131. "-B",
  132. buildDir,
  133. "-G",
  134. "Visual Studio 17 2022",
  135. "-A",
  136. targetArch === "arm64" ? "ARM64" : "x64",
  137. `-DZCODE_SHIM_OUTPUT_DIR=${builtDir.replaceAll("\\", "/")}`,
  138. ],
  139. deadline,
  140. );
  141. await runCmake(command, ["--build", buildDir, "--config", "Release"], deadline);
  142. const bytes = await readFile(join(builtDir, outputName));
  143. verifyPe(bytes, targetArch);
  144. if ((await sourceDigest()) !== source)
  145. throw new Error("Windows entry shim sources changed during build");
  146. const manifest = { version: 1, arch: targetArch, source, binary: digest(bytes) };
  147. // 同源码无需改写正在被旧调用方读取的文件;新字节先完整写入,再原子发布。
  148. const previous = await readFile(join(outputDir, outputName)).catch(() => undefined);
  149. if (!previous?.equals(bytes)) await writeAtomic(join(outputDir, outputName), bytes);
  150. await writeAtomic(join(outputDir, "build.json"), JSON.stringify(manifest));
  151. console.log(`[preinstalled-entry-shim] built ${join(outputDir, outputName)}`);
  152. return { bytes, manifest };
  153. } finally {
  154. await rm(work, { recursive: true, force: true });
  155. }
  156. }
  157. async function main(args) {
  158. if (platform() !== "win32") {
  159. console.log("[preinstalled-entry-shim] skip: Windows shim is built only on Windows");
  160. return;
  161. }
  162. if (args.includes("--check") && args.includes("--ensure"))
  163. throw new Error("--check and --ensure are mutually exclusive");
  164. const targetArch = (
  165. argument(args, "--arch") ??
  166. process.env.ZCODE_TARGET_ARCH ??
  167. arch()
  168. ).toLowerCase();
  169. if (targetArch !== "x64" && targetArch !== "arm64")
  170. throw new Error(`Unsupported Windows preinstalled entry shim architecture: ${targetArch}`);
  171. const outputDir = resolve(
  172. argument(args, "--output-dir") ??
  173. join(desktopRoot, `bundled-tools/win32-${targetArch}/preinstalled-entry-shim`),
  174. );
  175. const stageDir = argument(args, "--stage-dir");
  176. const timeout = Number(argument(args, "--timeout-ms") ?? BUILD_TIMEOUT_MS);
  177. if (!Number.isSafeInteger(timeout) || timeout <= 0)
  178. throw new Error("Invalid shim preparation timeout");
  179. const deadline = Date.now() + timeout;
  180. await mkdir(dirname(outputDir), { recursive: true });
  181. // 所有发布、校验和快照共用这把锁。锁只存在于准备进程;运行中的 shard 读取独立副本。
  182. await withE2EDesktopBuildLock(
  183. { lockPath: `${outputDir}.build.lock`, timeoutMs: timeout },
  184. async () => {
  185. const source = await sourceDigest();
  186. let ready = await readyBuild(outputDir, targetArch, source);
  187. if (args.includes("--check") && !ready)
  188. throw new Error(
  189. "Windows entry shim cache is missing, stale or damaged; prepare it in the parent runner first",
  190. );
  191. if (!args.includes("--check") && (!args.includes("--ensure") || !ready))
  192. ready = await build(outputDir, targetArch, source, deadline);
  193. else console.log(`[preinstalled-entry-shim] ready ${join(outputDir, outputName)}`);
  194. if (stageDir) {
  195. // 使用校验过的同一份字节,避免 hash 与 copy 分别读取共享源形成 TOCTOU。
  196. await writeAtomic(join(resolve(stageDir), outputName), ready.bytes);
  197. await writeAtomic(join(resolve(stageDir), "build.json"), JSON.stringify(ready.manifest));
  198. }
  199. },
  200. );
  201. }
  202. if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
  203. // WDIO 的配置加载器会同步解析依赖;入口使用 Promise 收口,避免顶层 await 阻断加载。
  204. void main(process.argv.slice(2)).catch((error) => {
  205. console.error(error);
  206. process.exitCode = 1;
  207. });
  208. }