native-binary-archs.mjs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { readFileSync } from "node:fs";
  2. // 被开源导出的 SEA 打包脚本复用;build-cua-helper-app.mjs 不导出到开源树,不能从那里取。
  3. export const MACHO_ARCH_BY_CPU_TYPE = new Map([
  4. [0x01000007, "x64"],
  5. [0x0100000c, "arm64"],
  6. ]);
  7. export const THIN_MACHO_MAGIC = new Map([
  8. ["feedface", "be"],
  9. ["feedfacf", "be"],
  10. ["cefaedfe", "le"],
  11. ["cffaedfe", "le"],
  12. ]);
  13. export const FAT_MACHO_MAGIC = new Map([
  14. ["cafebabe", { endian: "be", archBytes: 20 }],
  15. ["cafebabf", { endian: "be", archBytes: 32 }],
  16. ["bebafeca", { endian: "le", archBytes: 20 }],
  17. ["bfbafeca", { endian: "le", archBytes: 32 }],
  18. ]);
  19. export function readU32(buffer, offset, endian) {
  20. return endian === "be" ? buffer.readUInt32BE(offset) : buffer.readUInt32LE(offset);
  21. }
  22. export function readMachOArchs(filePath) {
  23. const buffer = readFileSync(filePath);
  24. if (buffer.length < 8) {
  25. throw new Error(`Mach-O provenance check failed for ${filePath}: file is too small`);
  26. }
  27. const magic = buffer.subarray(0, 4).toString("hex");
  28. const thinEndian = THIN_MACHO_MAGIC.get(magic);
  29. if (thinEndian) {
  30. const arch = MACHO_ARCH_BY_CPU_TYPE.get(readU32(buffer, 4, thinEndian));
  31. return arch ? [arch] : [];
  32. }
  33. const fat = FAT_MACHO_MAGIC.get(magic);
  34. if (!fat) return [];
  35. const archCount = readU32(buffer, 4, fat.endian);
  36. const archs = [];
  37. for (let index = 0; index < archCount; index += 1) {
  38. const offset = 8 + index * fat.archBytes;
  39. if (offset + 4 > buffer.length) break;
  40. const arch = MACHO_ARCH_BY_CPU_TYPE.get(readU32(buffer, offset, fat.endian));
  41. if (arch && !archs.includes(arch)) archs.push(arch);
  42. }
  43. return archs;
  44. }
  45. const PE_ARCH_BY_MACHINE = new Map([
  46. [0x8664, "x64"],
  47. [0xaa64, "arm64"],
  48. ]);
  49. export function readPeArchs(filePath) {
  50. const buffer = readFileSync(filePath);
  51. if (buffer.length < 0x40 || buffer.toString("ascii", 0, 2) !== "MZ") return [];
  52. const peOffset = buffer.readUInt32LE(0x3c);
  53. if (peOffset > buffer.length - 6 || buffer.toString("binary", peOffset, peOffset + 4) !== "PE\u0000\u0000") {
  54. return [];
  55. }
  56. const arch = PE_ARCH_BY_MACHINE.get(buffer.readUInt16LE(peOffset + 4));
  57. return arch ? [arch] : [];
  58. }