native-search-tools-verify.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. import { readFileSync } from "node:fs";
  2. import { basename } from "node:path";
  3. import process from "node:process";
  4. import {
  5. LINUX_NATIVE_SEARCH_GLIBC_BASELINE,
  6. MACOS_NATIVE_SEARCH_DEPLOYMENT_TARGET,
  7. NATIVE_SEARCH_BFS_CONFIGURE_ARGS,
  8. NATIVE_SEARCH_OFFICIAL_RIPGREP_ASSETS,
  9. NATIVE_SEARCH_TOOL_VERSIONS,
  10. getExpectedUgrepFeatureContract,
  11. getNativeSearchRuntimeToolIdsForPlatform,
  12. normalizeNativeSearchArch,
  13. normalizeNativeSearchPlatform,
  14. } from "./native-search-tools-config.mjs";
  15. import { runCapture } from "./native-search-tools-process.mjs";
  16. import { verifyWindowsPeBinary } from "./native-search-tools-windows-pe.mjs";
  17. const MACHO_MAGIC_64 = 0xfeedfacf;
  18. const MACHO_EXECUTE_FILE_TYPE = 2;
  19. const MACHO_CPU_TYPES = Object.freeze({ arm64: 0x0100000c, x64: 0x01000007 });
  20. const ELF_MACHINE_TYPES = Object.freeze({ arm64: 0xb7, x64: 0x3e });
  21. function fail(message) {
  22. throw new Error(message);
  23. }
  24. function verifyMachOTarget(binaryPath, arch) {
  25. const buffer = readFileSync(binaryPath);
  26. if (
  27. buffer.length < 16 ||
  28. buffer.readUInt32LE(0) !== MACHO_MAGIC_64 ||
  29. buffer.readUInt32LE(12) !== MACHO_EXECUTE_FILE_TYPE
  30. ) {
  31. fail(`${basename(binaryPath)} is not a 64-bit Mach-O executable`);
  32. }
  33. const cpuType = buffer.readUInt32LE(4);
  34. const expectedCpuType = MACHO_CPU_TYPES[arch];
  35. if (cpuType !== expectedCpuType) {
  36. fail(
  37. `${basename(binaryPath)} has Mach-O CPU type 0x${cpuType.toString(16)}; expected 0x${expectedCpuType.toString(16)} for ${arch}`,
  38. );
  39. }
  40. }
  41. function verifyElfTarget(binaryPath, arch) {
  42. const buffer = readFileSync(binaryPath);
  43. const isElf =
  44. buffer.length >= 20 &&
  45. buffer[0] === 0x7f &&
  46. buffer.toString("ascii", 1, 4) === "ELF" &&
  47. buffer[4] === 2 &&
  48. buffer[5] === 1;
  49. const fileType = isElf ? buffer.readUInt16LE(16) : 0;
  50. if (!isElf || (fileType !== 2 && fileType !== 3)) {
  51. fail(`${basename(binaryPath)} is not a 64-bit little-endian ELF executable`);
  52. }
  53. const machine = buffer.readUInt16LE(18);
  54. const expectedMachine = ELF_MACHINE_TYPES[arch];
  55. if (machine !== expectedMachine) {
  56. fail(
  57. `${basename(binaryPath)} has ELF machine 0x${machine.toString(16)}; expected 0x${expectedMachine.toString(16)} for ${arch}`,
  58. );
  59. }
  60. }
  61. export function verifyNativeSearchBinaryTarget(binaryPath, { platform, arch }) {
  62. const normalizedPlatform = normalizeNativeSearchPlatform(platform);
  63. const normalizedArch = normalizeNativeSearchArch(arch);
  64. switch (normalizedPlatform) {
  65. case "darwin":
  66. verifyMachOTarget(binaryPath, normalizedArch);
  67. return;
  68. case "linux":
  69. verifyElfTarget(binaryPath, normalizedArch);
  70. return;
  71. case "win32":
  72. verifyWindowsPeBinary(binaryPath, normalizedArch);
  73. return;
  74. }
  75. }
  76. function verifyBfsContract(bfsPath) {
  77. const bfsVersion = runCapture(bfsPath, ["--version"]);
  78. const expectedConfigureFlags = `CONFFLAGS := ${NATIVE_SEARCH_BFS_CONFIGURE_ARGS.join(" ")}`;
  79. if (
  80. !bfsVersion.startsWith(`bfs ${NATIVE_SEARCH_TOOL_VERSIONS.bfs}\n`) ||
  81. !bfsVersion.includes(expectedConfigureFlags)
  82. ) {
  83. fail(`unexpected bfs version output:\n${bfsVersion}`);
  84. }
  85. const regexTypes = runCapture(bfsPath, ["-regextype", "help"]);
  86. if (!regexTypes.includes("findutils-default")) {
  87. fail("bfs does not support -regextype findutils-default");
  88. }
  89. }
  90. function verifyUgrepContract(ugrepPath, platform) {
  91. const ugrepVersion = runCapture(ugrepPath, ["--version"]);
  92. const expectedFeatures = getExpectedUgrepFeatureContract(platform);
  93. if (
  94. !ugrepVersion.startsWith(`ugrep ${NATIVE_SEARCH_TOOL_VERSIONS.ugrep} `) ||
  95. !ugrepVersion.includes(expectedFeatures)
  96. ) {
  97. fail(`unexpected ugrep feature output:\n${ugrepVersion}`);
  98. }
  99. }
  100. function verifyRipgrepContract(rgPath, { arch, platform }) {
  101. const version = runCapture(rgPath, ["--version"]);
  102. const platformKey = `${platform}-${arch}`;
  103. const ripgrepAsset = NATIVE_SEARCH_OFFICIAL_RIPGREP_ASSETS[platformKey];
  104. if (!ripgrepAsset) {
  105. fail(`no verified ripgrep asset contract for ${platformKey}`);
  106. }
  107. const expectedRevision = ripgrepAsset.revision;
  108. const expectedVersionLine = expectedRevision
  109. ? `ripgrep ${NATIVE_SEARCH_TOOL_VERSIONS.ripgrep} (rev ${expectedRevision})`
  110. : `ripgrep ${NATIVE_SEARCH_TOOL_VERSIONS.ripgrep}`;
  111. if (
  112. version.split("\n", 1)[0] !== expectedVersionLine ||
  113. !version.includes("features:+pcre2") ||
  114. !version.includes("PCRE2 10.43 is available")
  115. ) {
  116. fail(`unexpected ripgrep feature output:\n${version}`);
  117. }
  118. }
  119. function compareDottedVersions(left, right) {
  120. const leftParts = left.split(".").map(Number);
  121. const rightParts = right.split(".").map(Number);
  122. const partCount = Math.max(leftParts.length, rightParts.length);
  123. for (let index = 0; index < partCount; index += 1) {
  124. const difference = (leftParts[index] ?? 0) - (rightParts[index] ?? 0);
  125. if (difference !== 0) return difference;
  126. }
  127. return 0;
  128. }
  129. export function getRequiredGlibcVersions(versionInfo) {
  130. const versions = new Set(
  131. [...String(versionInfo).matchAll(/\bGLIBC_(\d+(?:\.\d+)+)\b/gu)].map((match) => match[1]),
  132. );
  133. return [...versions].sort(compareDottedVersions);
  134. }
  135. export function verifyLinuxGlibcBaseline(
  136. versionInfo,
  137. binaryName,
  138. baseline = LINUX_NATIVE_SEARCH_GLIBC_BASELINE,
  139. ) {
  140. const versions = getRequiredGlibcVersions(versionInfo);
  141. if (versions.length === 0) {
  142. fail(`${binaryName} is missing GLIBC symbol versions`);
  143. }
  144. const unsupportedVersion = versions.find(
  145. (version) => compareDottedVersions(version, baseline) > 0,
  146. );
  147. if (unsupportedVersion) {
  148. fail(
  149. `${binaryName} requires GLIBC_${unsupportedVersion}; maximum supported version is GLIBC_${baseline}`,
  150. );
  151. }
  152. }
  153. export function verifyMacosDeploymentTarget(
  154. buildVersion,
  155. binaryName,
  156. { allowLowerDeploymentTarget = false } = {},
  157. ) {
  158. // Microsoft x64 归档使用旧式 LC_VERSION_MIN_MACOSX,且更低的 target 不应被拒绝。
  159. const deploymentTargets = [
  160. ...[...buildVersion.matchAll(/^\s*minos\s+(\S+)\s*$/gmu)].map((match) => match[1]),
  161. ...[
  162. ...buildVersion.matchAll(
  163. /^\s*cmd\s+LC_VERSION_MIN_MACOSX\s*\n\s*cmdsize\s+\d+\s*\n\s*version\s+(\S+)\s*$/gmu,
  164. ),
  165. ].map((match) => match[1]),
  166. ];
  167. const targetComparison =
  168. deploymentTargets.length === 1
  169. ? compareDottedVersions(deploymentTargets[0], MACOS_NATIVE_SEARCH_DEPLOYMENT_TARGET)
  170. : undefined;
  171. if (
  172. targetComparison === undefined ||
  173. (allowLowerDeploymentTarget ? targetComparison > 0 : targetComparison !== 0)
  174. ) {
  175. const targetContract = allowLowerDeploymentTarget
  176. ? `maximum supported target is ${MACOS_NATIVE_SEARCH_DEPLOYMENT_TARGET}`
  177. : `expected target is ${MACOS_NATIVE_SEARCH_DEPLOYMENT_TARGET}`;
  178. fail(
  179. `${binaryName} has unsupported macOS deployment target: ${deploymentTargets.join(", ") || "missing"}; ${targetContract}`,
  180. );
  181. }
  182. }
  183. function verifyMacosBinary(
  184. binaryPath,
  185. { arch, allowedDependencies, allowLowerDeploymentTarget = false },
  186. ) {
  187. const fileOutput = runCapture("file", [binaryPath]);
  188. const expectedArchitecture = arch === "arm64" ? "arm64" : "x86_64";
  189. if (
  190. !fileOutput.includes("Mach-O 64-bit executable") ||
  191. !fileOutput.includes(expectedArchitecture)
  192. ) {
  193. fail(`unexpected ${basename(binaryPath)} architecture:\n${fileOutput}`);
  194. }
  195. const dependencies = runCapture("otool", ["-L", binaryPath])
  196. .split("\n")
  197. .slice(1)
  198. .map((line) => line.trim().split(" ")[0])
  199. .filter(Boolean);
  200. const unexpectedDependencies = dependencies.filter(
  201. (dependency) => !allowedDependencies.includes(dependency),
  202. );
  203. if (unexpectedDependencies.length > 0) {
  204. fail(
  205. `${basename(binaryPath)} has non-system runtime dependencies: ${unexpectedDependencies.join(", ")}`,
  206. );
  207. }
  208. const buildVersion = runCapture("vtool", ["-show-build", binaryPath]);
  209. verifyMacosDeploymentTarget(buildVersion, basename(binaryPath), {
  210. allowLowerDeploymentTarget,
  211. });
  212. }
  213. function verifyLinuxBinary(binaryPath, { arch, allowedDependencies, glibcBaseline }) {
  214. const fileOutput = runCapture("file", [binaryPath]);
  215. const expectedArchitecture = arch === "arm64" ? "ARM aarch64" : "x86-64";
  216. if (!fileOutput.includes("ELF 64-bit") || !fileOutput.includes(expectedArchitecture)) {
  217. fail(`unexpected ${basename(binaryPath)} architecture:\n${fileOutput}`);
  218. }
  219. const dynamicSection = runCapture("readelf", ["-d", binaryPath]);
  220. const dependencies = [
  221. ...dynamicSection.matchAll(/\(NEEDED\).*Shared library: \[([^\]]+)\]/gu),
  222. ].map((match) => match[1]);
  223. const unexpectedDependencies = dependencies.filter(
  224. (dependency) => !allowedDependencies.includes(dependency),
  225. );
  226. if (unexpectedDependencies.length > 0) {
  227. fail(
  228. `${basename(binaryPath)} has unexpected runtime dependencies: ${unexpectedDependencies.join(", ")}`,
  229. );
  230. }
  231. if (glibcBaseline) {
  232. const versionInfo = runCapture("readelf", ["--version-info", binaryPath]);
  233. verifyLinuxGlibcBaseline(versionInfo, basename(binaryPath), glibcBaseline);
  234. }
  235. }
  236. export function getAllowedLinuxNativeSearchDependencies(toolId, arch) {
  237. const dynamicLoader = arch === "arm64" ? "ld-linux-aarch64.so.1" : "ld-linux-x86-64.so.2";
  238. const commonDependencies = [
  239. dynamicLoader,
  240. "libc.so.6",
  241. "libdl.so.2",
  242. "libm.so.6",
  243. "libpthread.so.0",
  244. "librt.so.1",
  245. ];
  246. switch (toolId) {
  247. case "bfs":
  248. case "ugrep":
  249. return commonDependencies;
  250. case "ripgrep":
  251. // 两种 Linux rg 都固定为 Microsoft musl 静态包,因此不应携带动态依赖。
  252. return [];
  253. default:
  254. fail(`unsupported Linux native search tool ${toolId}`);
  255. }
  256. }
  257. function verifyNativeSearchToolSet({
  258. bfsPath,
  259. rgPath,
  260. ugrepPath,
  261. platform,
  262. arch,
  263. toolIds,
  264. hostArch = process.arch,
  265. hostPlatform = process.platform,
  266. }) {
  267. const normalizedPlatform = normalizeNativeSearchPlatform(platform);
  268. const normalizedArch = normalizeNativeSearchArch(arch);
  269. const includes = (toolId) => toolIds.includes(toolId);
  270. switch (normalizedPlatform) {
  271. case "darwin":
  272. if (includes("bfs")) {
  273. if (!bfsPath) fail("macOS native search tools are missing bfs");
  274. verifyBfsContract(bfsPath);
  275. verifyMacosBinary(bfsPath, {
  276. arch: normalizedArch,
  277. allowedDependencies: ["/usr/lib/libSystem.B.dylib"],
  278. });
  279. }
  280. if (includes("ugrep")) {
  281. if (!ugrepPath) fail("macOS native search tools are missing ugrep");
  282. verifyUgrepContract(ugrepPath, normalizedPlatform);
  283. verifyMacosBinary(ugrepPath, {
  284. arch: normalizedArch,
  285. allowedDependencies: ["/usr/lib/libSystem.B.dylib", "/usr/lib/libc++.1.dylib"],
  286. });
  287. }
  288. if (includes("ripgrep")) {
  289. if (!rgPath) fail("macOS native search tools are missing ripgrep");
  290. verifyRipgrepContract(rgPath, { arch: normalizedArch, platform: normalizedPlatform });
  291. verifyMacosBinary(rgPath, {
  292. arch: normalizedArch,
  293. allowedDependencies: ["/usr/lib/libSystem.B.dylib", "/usr/lib/libiconv.2.dylib"],
  294. allowLowerDeploymentTarget: true,
  295. });
  296. }
  297. return;
  298. case "linux": {
  299. if (includes("bfs")) {
  300. if (!bfsPath) fail("Linux native search tools are missing bfs");
  301. verifyLinuxBinary(bfsPath, {
  302. arch: normalizedArch,
  303. allowedDependencies: getAllowedLinuxNativeSearchDependencies("bfs", normalizedArch),
  304. glibcBaseline: LINUX_NATIVE_SEARCH_GLIBC_BASELINE,
  305. });
  306. verifyBfsContract(bfsPath);
  307. }
  308. if (includes("ugrep")) {
  309. if (!ugrepPath) fail("Linux native search tools are missing ugrep");
  310. verifyLinuxBinary(ugrepPath, {
  311. arch: normalizedArch,
  312. allowedDependencies: getAllowedLinuxNativeSearchDependencies("ugrep", normalizedArch),
  313. glibcBaseline: LINUX_NATIVE_SEARCH_GLIBC_BASELINE,
  314. });
  315. verifyUgrepContract(ugrepPath, normalizedPlatform);
  316. }
  317. if (includes("ripgrep")) {
  318. if (!rgPath) fail("Linux native search tools are missing ripgrep");
  319. verifyRipgrepContract(rgPath, { arch: normalizedArch, platform: normalizedPlatform });
  320. verifyLinuxBinary(rgPath, {
  321. arch: normalizedArch,
  322. allowedDependencies: getAllowedLinuxNativeSearchDependencies("ripgrep", normalizedArch),
  323. });
  324. }
  325. return;
  326. }
  327. case "win32": {
  328. if (includes("ugrep")) {
  329. if (!ugrepPath) fail("Windows native search tools are missing ugrep");
  330. verifyWindowsPeBinary(ugrepPath, normalizedArch);
  331. }
  332. if (includes("ripgrep")) {
  333. if (!rgPath) fail("Windows native search tools are missing ripgrep");
  334. verifyWindowsPeBinary(rgPath, normalizedArch);
  335. }
  336. // host 与 PE 目标架构相同不代表当前系统能执行 Windows 二进制。
  337. if (
  338. normalizeNativeSearchPlatform(hostPlatform) === "win32" &&
  339. normalizeNativeSearchArch(hostArch) === normalizedArch
  340. ) {
  341. if (includes("ugrep")) verifyUgrepContract(ugrepPath, normalizedPlatform);
  342. if (includes("ripgrep")) {
  343. verifyRipgrepContract(rgPath, {
  344. arch: normalizedArch,
  345. platform: normalizedPlatform,
  346. });
  347. }
  348. }
  349. return;
  350. }
  351. default:
  352. fail(`native search verification does not support platform ${normalizedPlatform}`);
  353. }
  354. }
  355. export function verifyBuiltNativeSearchProducerOutputs(options) {
  356. return verifyNativeSearchToolSet({
  357. ...options,
  358. toolIds: options.producerOutputIds,
  359. });
  360. }
  361. export function verifyBuiltNativeSearchTools(options) {
  362. return verifyNativeSearchToolSet({
  363. ...options,
  364. toolIds: getNativeSearchRuntimeToolIdsForPlatform(options.platform),
  365. });
  366. }