build-windows-runtime-host.mjs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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", "installer-process-helper.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 hostBytes = await readFile(join(outputDir, "zcode-runtime-host.exe"));
  57. const helperBytes = await readFile(join(outputDir, "zcode-installer-process-helper.exe"));
  58. verifyRuntimeHostPe(hostBytes, arch);
  59. verifyRuntimeHostPe(helperBytes, arch);
  60. const manifest = JSON.parse(await readFile(join(outputDir, "build.json"), "utf8"));
  61. return (
  62. manifest.source === (await sourceDigest()) &&
  63. manifest.binary === createHash("sha256").update(hostBytes).digest("hex") &&
  64. manifest.installerProcessHelper === createHash("sha256").update(helperBytes).digest("hex")
  65. );
  66. } catch {
  67. return false;
  68. }
  69. }
  70. export async function buildRuntimeHost({ arch, outputDir }) {
  71. const plan = resolveRuntimeHostBuild(arch);
  72. const work = await mkdtemp(join(tmpdir(), "zcode-runtime-host-"));
  73. try {
  74. await run(["-S", source, "-B", work, ...plan.configureArgs, "-DCMAKE_BUILD_TYPE=Release"]);
  75. await run([
  76. "--build",
  77. work,
  78. "--config",
  79. "Release",
  80. "--target",
  81. "zcode-runtime-host",
  82. "zcode-installer-process-helper",
  83. ]);
  84. const releaseDir = join(work, ...(process.platform === "win32" ? ["Release"] : []));
  85. const hostBytes = await readFile(join(releaseDir, "zcode-runtime-host.exe"));
  86. const helperBytes = await readFile(join(releaseDir, "zcode-installer-process-helper.exe"));
  87. verifyRuntimeHostPe(hostBytes, arch);
  88. verifyRuntimeHostPe(helperBytes, arch);
  89. await mkdir(outputDir, { recursive: true });
  90. await copyFile(
  91. join(releaseDir, "zcode-runtime-host.exe"),
  92. join(outputDir, "zcode-runtime-host.exe"),
  93. );
  94. await copyFile(
  95. join(releaseDir, "zcode-installer-process-helper.exe"),
  96. join(outputDir, "zcode-installer-process-helper.exe"),
  97. );
  98. await writeFile(
  99. join(outputDir, "build.json"),
  100. JSON.stringify({
  101. source: await sourceDigest(),
  102. binary: createHash("sha256").update(hostBytes).digest("hex"),
  103. installerProcessHelper: createHash("sha256").update(helperBytes).digest("hex"),
  104. }),
  105. );
  106. } finally {
  107. await rm(work, { recursive: true, force: true });
  108. }
  109. }
  110. if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
  111. const args = process.argv.slice(2);
  112. const arch =
  113. args.find((arg) => arg.startsWith("--arch="))?.slice(7) ||
  114. process.env.ZCODE_TARGET_ARCH ||
  115. process.arch;
  116. const outputDir =
  117. args.find((arg) => arg.startsWith("--output-dir="))?.slice(13) ||
  118. join(root, "packages/desktop/bundled-tools", `win32-${arch}`, "runtime-host");
  119. if (!args.includes("--if-windows") || process.platform === "win32") {
  120. if (!args.includes("--ensure") || !(await isRuntimeHostReady(outputDir, arch))) {
  121. await buildRuntimeHost({ arch, outputDir });
  122. }
  123. }
  124. }