// Reads the executable header and reports {format, arch}. Used to refuse packaging a core built for // another OS/CPU. node scripts/binary-arch.mjs [--expect linux-arm64] import { openSync, readSync, closeSync } from 'node:fs'; import { pathToFileURL } from 'node:url'; const PE_MACHINES = { 0x8664: 'x64', 0xaa64: 'arm64', 0x014c: 'ia32' }; const ELF_MACHINES = { 0x3e: 'x64', 0xb7: 'arm64', 0x03: 'ia32', 0x28: 'armv7l' }; const MACHO_CPUS = { 0x01000007: 'x64', 0x0100000c: 'arm64' }; export function binaryArch(file) { const fd = openSync(file, 'r'); try { const head = Buffer.alloc(4096); const n = readSync(fd, head, 0, head.length, 0); if (n >= 64 && head.readUInt16LE(0) === 0x5a4d) { const pe = head.readUInt32LE(0x3c); if (pe + 6 <= n && head.readUInt32LE(pe) === 0x00004550) { return { os: 'win', arch: PE_MACHINES[head.readUInt16LE(pe + 4)] ?? `pe-0x${head.readUInt16LE(pe + 4).toString(16)}` }; } } if (n >= 20 && head.readUInt32BE(0) === 0x7f454c46) { const little = head[5] === 1; const machine = little ? head.readUInt16LE(18) : head.readUInt16BE(18); return { os: 'linux', arch: ELF_MACHINES[machine] ?? `elf-0x${machine.toString(16)}` }; } if (n >= 8 && head.readUInt32LE(0) === 0xfeedfacf) { return { os: 'mac', arch: MACHO_CPUS[head.readUInt32LE(4)] ?? `macho-0x${head.readUInt32LE(4).toString(16)}` }; } if (n >= 8 && head.readUInt32BE(0) === 0xcafebabe) return { os: 'mac', arch: 'universal' }; return { os: 'unknown', arch: 'unknown' }; } finally { closeSync(fd); } } if (import.meta.url === pathToFileURL(process.argv[1]).href) { const file = process.argv[2]; const expectIdx = process.argv.indexOf('--expect'); const info = binaryArch(file); console.log(JSON.stringify({ file, ...info })); if (expectIdx > 0) { const want = process.argv[expectIdx + 1]; if (`${info.os}-${info.arch}` !== want) { console.error(`expected ${want}, got ${info.os}-${info.arch}`); process.exit(1); } } }