build-windows-runtime-host.mjs 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. import { spawn } from "node:child_process";
  2. import { createHash } from "node:crypto";
  3. import { copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join, resolve } from "node:path";
  6. import { pathToFileURL } from "node:url";
  7. const root = resolve(import.meta.dirname, "..");
  8. const source = join(root, "scripts/windows-runtime-host");
  9. export function resolveRuntimeHostBuild(
  10. arch,
  11. hostPlatform = process.platform,
  12. compiler = process.env.ZCODE_WINDOWS_CXX,
  13. ) {
  14. if (arch !== "x64" && arch !== "arm64")
  15. throw new Error(`Unsupported runtime host architecture: ${arch}`);
  16. return {
  17. configureArgs:
  18. hostPlatform === "win32"
  19. ? ["-G", "Visual Studio 17 2022", "-A", arch === "arm64" ? "ARM64" : "x64"]
  20. : [
  21. "-DCMAKE_SYSTEM_NAME=Windows",
  22. `-DCMAKE_CXX_COMPILER=${compiler || (arch === "arm64" ? "aarch64-w64-mingw32-clang++" : "x86_64-w64-mingw32-g++")}`,
  23. ],
  24. };
  25. }
  26. export function verifyRuntimeHostPe(bytes, arch) {
  27. const header = bytes.length >= 64 ? bytes.readUInt32LE(60) : -1;
  28. if (
  29. bytes.toString("ascii", 0, 2) !== "MZ" ||
  30. header < 0 ||
  31. header + 6 > bytes.length ||
  32. bytes.toString("ascii", header, header + 4) !== "PE\0\0"
  33. ) {
  34. throw new Error("Invalid runtime host PE binary");
  35. }
  36. if (bytes.readUInt16LE(header + 4) !== (arch === "arm64" ? 0xaa64 : 0x8664))
  37. throw new Error("Runtime host architecture mismatch");
  38. }
  39. async function sourceDigest() {
  40. const hash = createHash("sha256");
  41. for (const name of ["main.cpp", "CMakeLists.txt"])
  42. hash.update(await readFile(join(source, name)));
  43. return hash.digest("hex");
  44. }
  45. function run(args) {
  46. return new Promise((resolveRun, reject) => {
  47. const child = spawn(process.env.CMAKE || "cmake", args, { stdio: "inherit" });
  48. child.once("error", reject);
  49. child.once("exit", (code) =>
  50. code === 0 ? resolveRun() : reject(new Error(`Runtime host CMake failed: ${code}`)),
  51. );
  52. });
  53. }
  54. export async function isRuntimeHostReady(outputDir, arch) {
  55. try {
  56. const bytes = await readFile(join(outputDir, "zcode-runtime-host.exe"));
  57. verifyRuntimeHostPe(bytes, arch);
  58. const manifest = JSON.parse(await readFile(join(outputDir, "build.json"), "utf8"));
  59. return (
  60. manifest.source === (await sourceDigest()) &&
  61. manifest.binary === createHash("sha256").update(bytes).digest("hex")
  62. );
  63. } catch {
  64. return false;
  65. }
  66. }
  67. export async function buildRuntimeHost({ arch, outputDir }) {
  68. const plan = resolveRuntimeHostBuild(arch);
  69. const work = await mkdtemp(join(tmpdir(), "zcode-runtime-host-"));
  70. try {
  71. await run(["-S", source, "-B", work, ...plan.configureArgs, "-DCMAKE_BUILD_TYPE=Release"]);
  72. await run(["--build", work, "--config", "Release", "--target", "zcode-runtime-host"]);
  73. const binary = join(
  74. work,
  75. ...(process.platform === "win32" ? ["Release"] : []),
  76. "zcode-runtime-host.exe",
  77. );
  78. const bytes = await readFile(binary);
  79. verifyRuntimeHostPe(bytes, arch);
  80. await mkdir(outputDir, { recursive: true });
  81. await copyFile(binary, join(outputDir, "zcode-runtime-host.exe"));
  82. await writeFile(
  83. join(outputDir, "build.json"),
  84. JSON.stringify({
  85. source: await sourceDigest(),
  86. binary: createHash("sha256").update(bytes).digest("hex"),
  87. }),
  88. );
  89. } finally {
  90. await rm(work, { recursive: true, force: true });
  91. }
  92. }
  93. if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
  94. const args = process.argv.slice(2);
  95. const arch =
  96. args.find((arg) => arg.startsWith("--arch="))?.slice(7) ||
  97. process.env.ZCODE_TARGET_ARCH ||
  98. process.arch;
  99. const outputDir =
  100. args.find((arg) => arg.startsWith("--output-dir="))?.slice(13) ||
  101. join(root, "packages/desktop/bundled-tools", `win32-${arch}`, "runtime-host");
  102. if (!args.includes("--if-windows") || process.platform === "win32") {
  103. if (!args.includes("--ensure") || !(await isRuntimeHostReady(outputDir, arch))) {
  104. await buildRuntimeHost({ arch, outputDir });
  105. }
  106. }
  107. }