diff --git a/docs/src/content/docs/contributing.md b/docs/src/content/docs/contributing.md index a3d0c9bc9d..6a88bcf06f 100644 --- a/docs/src/content/docs/contributing.md +++ b/docs/src/content/docs/contributing.md @@ -59,7 +59,7 @@ cli/ │ │ ├── code-mappings/# upload │ │ ├── dart-symbol-map/# upload │ │ ├── dashboard/ # add, create, delete, edit, list, restore, revisions, view -│ │ ├── debug-files/ # bundle-jvm, bundle-sources, check, print-sources, upload +│ │ ├── debug-files/ # bundle-jvm, bundle-sources, check, find, print-sources, upload │ │ ├── event/ # list, send, view │ │ ├── issue/ # archive, events, explain, list, merge, plan, resolve, unresolve, view │ │ ├── local/ # run, serve diff --git a/docs/src/fragments/commands/debug-files.md b/docs/src/fragments/commands/debug-files.md index 6d0a8e4846..979839c150 100644 --- a/docs/src/fragments/commands/debug-files.md +++ b/docs/src/fragments/commands/debug-files.md @@ -13,6 +13,11 @@ sentry debug-files check ./app.pdb --json sentry debug-files print-sources ./libexample.so sentry debug-files print-sources ./app.pdb --json +# Locate debug files for one or more debug identifiers on disk +sentry debug-files find +sentry debug-files find --type dsym --path ./build +sentry debug-files find --no-cwd --no-well-known -p /symbols --json + # Bundle a debug file's referenced source files (run on the build machine) sentry debug-files bundle-sources ./libexample.so sentry debug-files bundle-sources ./app.pdb --output ./app.src.zip @@ -46,6 +51,19 @@ sentry debug-files upload ./build --il2cpp-mapping --include-sources sentry debug-files upload ./build --no-upload ``` +## Notes on `find` + +- `debug-files find` locates debug files **locally** by debug identifier — it + makes no API calls. It searches Xcode's `DerivedData` (for dSYMs, unless + `--no-well-known`), the current directory (unless `--no-cwd`), and any + `--path`/`-p` directories, recursively. +- Restrict the search with `--type`/`-t` (repeatable): `dsym`, `elf`, `pe`, + `pdb`, `portablepdb`, `sourcebundle`, `breakpad`, `proguard`, `jvm`. +- A debug identifier must match exactly, including any PE/PDB age suffix. A + Breakpad symbol file is listed when it matches, but does **not** satisfy the + request (the id is still reported as missing). +- Exits non-zero if any requested identifier could not be located. + ## Important Notes - `check`, `print-sources`, `bundle-sources`, and `bundle-jvm` are **local-only** diff --git a/plugins/sentry-cli/skills/sentry-cli/SKILL.md b/plugins/sentry-cli/skills/sentry-cli/SKILL.md index 0bf05de498..cd4c20e80a 100644 --- a/plugins/sentry-cli/skills/sentry-cli/SKILL.md +++ b/plugins/sentry-cli/skills/sentry-cli/SKILL.md @@ -420,6 +420,7 @@ Work with Dart/Flutter symbol maps Work with debug information files - `sentry debug-files check ` — Inspect a debug information file +- `sentry debug-files find ` — Locate debug files for given debug identifiers - `sentry debug-files upload ` — Upload debug information files to Sentry - `sentry debug-files print-sources ` — List the source files a debug file references - `sentry debug-files bundle-sources ` — Bundle a debug file's source files for source context diff --git a/plugins/sentry-cli/skills/sentry-cli/references/debug-files.md b/plugins/sentry-cli/skills/sentry-cli/references/debug-files.md index ed5f083ab2..40cf5ea810 100644 --- a/plugins/sentry-cli/skills/sentry-cli/references/debug-files.md +++ b/plugins/sentry-cli/skills/sentry-cli/references/debug-files.md @@ -15,6 +15,16 @@ Work with debug information files Inspect a debug information file +### `sentry debug-files find ` + +Locate debug files for given debug identifiers + +**Flags:** +- `-t, --type ... - Only consider debug files of the given type (repeatable). Default: all` +- `--no-well-known - Do not look for debug files in well-known locations` +- `--no-cwd - Do not look for debug files in the current directory` +- `-p, --path ... - Add a directory to search recursively (repeatable)` + ### `sentry debug-files upload ` Upload debug information files to Sentry @@ -66,6 +76,11 @@ sentry debug-files check ./app.pdb --json sentry debug-files print-sources ./libexample.so sentry debug-files print-sources ./app.pdb --json +# Locate debug files for one or more debug identifiers on disk +sentry debug-files find +sentry debug-files find --type dsym --path ./build +sentry debug-files find --no-cwd --no-well-known -p /symbols --json + # Bundle a debug file's referenced source files (run on the build machine) sentry debug-files bundle-sources ./libexample.so sentry debug-files bundle-sources ./app.pdb --output ./app.src.zip diff --git a/src/commands/debug-files/find.ts b/src/commands/debug-files/find.ts new file mode 100644 index 0000000000..2c0c75598f --- /dev/null +++ b/src/commands/debug-files/find.ts @@ -0,0 +1,194 @@ +/** + * sentry debug-files find ... + * + * Locate debug-information files for one or more debug identifiers by searching + * well-known locations (Xcode DerivedData), the current directory, and any + * extra `--path` directories. Local-only — no API calls. + * + * Exits non-zero when any requested id could not be located, mirroring the + * legacy `sentry-cli difutil find`. + */ + +import { stat } from "node:fs/promises"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import type { SentryContext } from "../../context.js"; +import { buildCommand } from "../../lib/command.js"; +import { + FIND_DIF_TYPES, + type FindResult, + findDebugFiles, +} from "../../lib/dif/find.js"; +import { ValidationError } from "../../lib/errors.js"; +import { colorTag, renderMarkdown } from "../../lib/formatters/markdown.js"; +import { CommandOutput } from "../../lib/formatters/output.js"; +import { logger } from "../../lib/logger.js"; + +const log = logger.withTag("debug-files.find"); + +/** Xcode's DerivedData location (well-known dSYM store on macOS). */ +const DERIVED_DATA = "Library/Developer/Xcode/DerivedData"; + +/** Flags accepted by `debug-files find`. */ +type FindFlags = { + type?: string[]; + "no-well-known"?: boolean; + "no-cwd"?: boolean; + path?: string[]; +}; + +/** Human-readable formatter for the find result. */ +function formatFindResult(data: FindResult): string { + const sections: string[] = []; + if (data.matches.length > 0) { + sections.push( + data.matches + .map( + (m) => + `${colorTag("muted", m.id)} \`${m.path}\` [${colorTag( + "yellow", + m.type + )}]` + ) + .join("\n") + ); + } else { + sections.push(colorTag("muted", "No debug information files found.")); + } + if (data.missing.length > 0) { + const lines = data.missing.map((m) => ` ${m.id} (${m.hint})`).join("\n"); + sections.push( + `${colorTag("yellow", "Missing debug information files:")}\n${lines}` + ); + } + return renderMarkdown(sections.join("\n\n")); +} + +/** Resolve the requested types, validating each against the known set. */ +function resolveTypes(flags: FindFlags): string[] { + if (!(flags.type && flags.type.length > 0)) { + return [...FIND_DIF_TYPES]; + } + const types = flags.type.map((t) => t.trim().toLowerCase()); + for (const type of types) { + if (!FIND_DIF_TYPES.includes(type)) { + throw new ValidationError( + `Unknown debug file type '${type}'. Valid types: ${FIND_DIF_TYPES.join( + ", " + )}`, + "type" + ); + } + } + return types; +} + +/** Build the ordered, de-duplicated list of directories to search. */ +async function resolveSearchPaths( + flags: FindFlags, + types: string[], + cwd: string +): Promise { + const paths: string[] = []; + // dSYMs live in Xcode DerivedData; only search it when dSYMs are wanted. + if (!flags["no-well-known"] && types.includes("dsym")) { + const derived = join(homedir(), DERIVED_DATA); + const info = await stat(derived).catch(() => null); + if (info?.isDirectory()) { + paths.push(derived); + } + } + if (!flags["no-cwd"]) { + paths.push(cwd); + } + if (flags.path) { + paths.push(...flags.path); + } + return paths; +} + +export const findCommand = buildCommand({ + docs: { + brief: "Locate debug files for given debug identifiers", + fullDescription: + "Locate debug-information files for one or more debug identifiers.\n\n" + + "Searches Xcode's DerivedData (for dSYMs), the current directory, and " + + "any extra `--path` directories, matching each file's embedded debug id " + + "against the requested ids. Local-only — no API calls.\n\n" + + "Exits non-zero if any id could not be located.\n\n" + + "Usage:\n" + + " sentry debug-files find [...]\n" + + " sentry debug-files find --type dsym --path ./build\n" + + " sentry debug-files find --no-cwd --no-well-known -p /symbols", + }, + // Purely local filesystem search — no Sentry API calls, no auth needed. + auth: false, + output: { + human: formatFindResult, + }, + parameters: { + positional: { + kind: "array", + parameter: { + placeholder: "id", + brief: "Debug identifier(s) to search for", + parse: String, + }, + }, + flags: { + type: { + kind: "parsed", + parse: String, + variadic: true, + brief: + "Only consider debug files of the given type (repeatable). Default: all", + optional: true, + }, + "no-well-known": { + kind: "boolean", + brief: "Do not look for debug files in well-known locations", + optional: true, + }, + "no-cwd": { + kind: "boolean", + brief: "Do not look for debug files in the current directory", + optional: true, + }, + path: { + kind: "parsed", + parse: String, + variadic: true, + brief: "Add a directory to search recursively (repeatable)", + optional: true, + }, + }, + aliases: { + t: "type", + p: "path", + }, + }, + async *func(this: SentryContext, flags: FindFlags, ...ids: string[]) { + if (ids.length === 0) { + yield new CommandOutput({ matches: [], missing: [] }); + return { hint: "Provide one or more debug identifiers to search for." }; + } + + const types = resolveTypes(flags); + const paths = await resolveSearchPaths(flags, types, this.cwd); + + const result = await findDebugFiles({ ids, types, paths }); + log.debug( + `Located ${result.matches.length} file(s); ${result.missing.length} id(s) missing` + ); + + yield new CommandOutput(result); + if (result.missing.length > 0) { + // Mirror the legacy CLI: a missing id is a non-zero exit. + this.process.exitCode = 1; + return { + hint: `${result.missing.length} debug identifier(s) could not be located.`, + }; + } + return { hint: "All requested debug files were located." }; + }, +}); diff --git a/src/commands/debug-files/index.ts b/src/commands/debug-files/index.ts index d270ef6d23..6584544a5a 100644 --- a/src/commands/debug-files/index.ts +++ b/src/commands/debug-files/index.ts @@ -8,12 +8,14 @@ import { buildRouteMap } from "../../lib/route-map.js"; import { bundleJvmCommand } from "./bundle-jvm.js"; import { bundleSourcesCommand } from "./bundle-sources.js"; import { checkCommand } from "./check.js"; +import { findCommand } from "./find.js"; import { printSourcesCommand } from "./print-sources.js"; import { uploadCommand } from "./upload.js"; export const debugFilesRoute = buildRouteMap({ routes: { check: checkCommand, + find: findCommand, upload: uploadCommand, "print-sources": printSourcesCommand, "bundle-sources": bundleSourcesCommand, diff --git a/src/lib/dif/find.ts b/src/lib/dif/find.ts new file mode 100644 index 0000000000..91d7c7fa42 --- /dev/null +++ b/src/lib/dif/find.ts @@ -0,0 +1,334 @@ +/** + * Locate debug-information files on disk by debug ID. + * + * Backs `debug-files find`: walks a set of directories and, for each file, + * cheaply peeks its header to detect a debug-file format, then fully parses + * only candidates whose format is wanted, matching their embedded debug IDs + * against the requested set. ProGuard mappings (plain-text, no magic) are + * matched separately by computing their deterministic UUID. + * + * Mirrors the legacy Rust `debug_files find` command. + */ + +import { open, readFile, stat } from "node:fs/promises"; +import { extname, resolve } from "node:path"; +import { computeProguardUuid } from "../proguard.js"; +import { walkFiles } from "../scan/walker.js"; +import { parseDebugFile, peekFormat } from "./index.js"; +import { normalizeDebugId } from "./scan.js"; + +/** Text mapping files larger than this are never treated as ProGuard files. */ +const MAX_MAPPING_FILE = 32 * 1024 * 1024; + +/** Bytes read from each file's header for format detection. */ +const PEEK_BYTES = 4096; + +/** DIF types accepted by `debug-files find` (`--type`). */ +export const FIND_DIF_TYPES: readonly string[] = [ + "dsym", + "elf", + "pe", + "pdb", + "portablepdb", + "sourcebundle", + "breakpad", + "proguard", + "jvm", + "wasm", +]; + +/** Map a requested type to the object format `peekFormat` reports. */ +const TYPE_TO_FORMAT: Readonly> = { + dsym: "macho", + elf: "elf", + pe: "pe", + pdb: "pdb", + portablepdb: "portablepdb", + sourcebundle: "sourcebundle", + jvm: "sourcebundle", + breakpad: "breakpad", + wasm: "wasm", +}; + +/** Map a detected object format back to a display DIF type. */ +const FORMAT_TO_TYPE: Readonly> = { + macho: "dsym", + elf: "elf", + pe: "pe", + pdb: "pdb", + portablepdb: "portablepdb", + sourcebundle: "sourcebundle", + breakpad: "breakpad", + wasm: "wasm", +}; + +/** A located debug file matching a requested id. */ +export type DifMatch = { + /** DIF type (e.g. `dsym`, `elf`, `proguard`). */ + type: string; + /** The matched debug id (as requested/normalized). */ + id: string; + /** Absolute path to the file. */ + path: string; +}; + +/** A requested id that was not located, with a heuristic hint. */ +export type MissingId = { + /** The normalized debug id. */ + id: string; + /** A guess at the likely file type based on the id's shape. */ + hint: string; +}; + +/** Outcome of a {@link findDebugFiles} search. */ +export type FindResult = { + /** Located files (in discovery order). */ + matches: DifMatch[]; + /** Requested ids that were not located. */ + missing: MissingId[]; +}; + +/** Options for {@link findDebugFiles}. */ +export type FindOptions = { + /** Requested debug ids (raw; normalized internally). */ + ids: string[]; + /** Requested DIF types; when omitted or empty, all types are considered. */ + types?: string[]; + /** Directories (or files) to search recursively. */ + paths: string[]; + /** Optional progress callback (files matched so far, current file name). */ + onProgress?: (matched: number, current: string) => void; +}; + +/** + * Heuristic hint for a not-found id, from the shape of the id. + * + * @param normalized - A normalized debug id. + */ +export function idHint(normalized: string): string { + const parts = normalized.split("-"); + if (parts.length > 5) { + return "likely PDB"; + } + const version = parts[2]?.[0]; + if (version === "5") { + return "likely Proguard"; + } + if (version === "3") { + return "likely dSYM"; + } + if (version === "1" || version === "2" || version === "4") { + return "unknown"; + } + return "likely ELF Debug"; +} + +/** Whether a normalized id is shaped like a ProGuard (UUIDv5) mapping id. */ +function isProguardId(normalized: string): boolean { + return normalized.split("-")[2]?.[0] === "5"; +} + +/** + * Choose the display label for a `sourcebundle`-format match. Both `sourcebundle` + * and `jvm` map to that format, so label a match with whichever the user asked + * for, preferring `sourcebundle`. + */ +function sourcebundleDisplayType(wantedTypes: readonly string[]): string { + const lowered = wantedTypes.map((t) => t.toLowerCase()); + if (!lowered.includes("sourcebundle") && lowered.includes("jvm")) { + return "jvm"; + } + return "sourcebundle"; +} + +/** Mutable search state threaded through the walk. */ +type SearchState = { + /** Ids still being searched for (normalized). */ + remaining: Set; + /** Ids matched only by a breakpad file (still considered missing). */ + breakpadFound: Set; + /** Wanted object formats (peekFormat names). */ + formats: Set; + /** Display type to use for a `sourcebundle` match (`sourcebundle` or `jvm`). */ + sourcebundleType: string; + /** Whether ProGuard mappings should be considered. */ + wantProguard: boolean; + /** Accumulated matches. */ + matches: DifMatch[]; +}; + +/** Find the remaining id that matches `debugId`, or undefined. */ +function matchRemaining( + state: SearchState, + debugId: string +): string | undefined { + const normalized = normalizeDebugId(debugId); + return state.remaining.has(normalized) ? normalized : undefined; +} + +/** Try to match a plain-text ProGuard mapping file. */ +async function tryProguard( + path: string, + size: number, + state: SearchState +): Promise { + if ( + !state.wantProguard || + extname(path).toLowerCase() !== ".txt" || + size >= MAX_MAPPING_FILE + ) { + return; + } + // Only worth hashing when a ProGuard-shaped id is still sought. + if (![...state.remaining].some(isProguardId)) { + return; + } + let uuid: string; + try { + uuid = computeProguardUuid(await readFile(path)); + } catch { + return; + } + const matched = matchRemaining(state, uuid); + if (matched) { + state.matches.push({ type: "proguard", id: matched, path }); + satisfy(state, matched); + } +} + +/** Mark an id as located by a real debug file (clears any breakpad-only flag). */ +function satisfy(state: SearchState, id: string): void { + state.remaining.delete(id); + // A real match supersedes a prior breakpad-only match for the same id, so the + // id is no longer "missing" (the legacy CLI failed to clear this). + state.breakpadFound.delete(id); +} + +/** Try to match an object debug file (ELF/Mach-O/PE/PDB/breakpad/…). */ +async function tryObject( + path: string, + size: number, + state: SearchState +): Promise { + let format: string; + try { + const fd = await open(path, "r"); + try { + const buf = Buffer.alloc(Math.min(PEEK_BYTES, size)); + await fd.read(buf, 0, buf.length, 0); + format = peekFormat(buf); + } finally { + await fd.close(); + } + } catch { + return; + } + if (!state.formats.has(format)) { + return; + } + const displayType = + format === "sourcebundle" + ? state.sourcebundleType + : (FORMAT_TO_TYPE[format] ?? format); + let objects: { debugId: string }[]; + try { + objects = parseDebugFile(await readFile(path)).objects; + } catch { + return; + } + for (const obj of objects) { + const matched = matchRemaining(state, obj.debugId); + if (!matched) { + continue; + } + state.matches.push({ type: displayType, id: matched, path }); + // A breakpad file is reported but does not satisfy the request: the id + // stays "missing" (a breakpad symbol is not the real debug file). + if (format === "breakpad") { + state.breakpadFound.add(matched); + } else { + satisfy(state, matched); + } + } +} + +/** Resolve a search root to the list of files to inspect. */ +async function* walkPath(path: string): AsyncGenerator<{ + absolutePath: string; + size: number; +}> { + const abs = resolve(path); + const info = await stat(abs).catch(() => null); + if (!info) { + return; + } + if (info.isFile()) { + yield { absolutePath: abs, size: info.size }; + return; + } + if (!info.isDirectory()) { + return; + } + yield* walkFiles({ + cwd: abs, + hidden: true, + followSymlinks: false, + respectGitignore: false, + alwaysSkipDirs: [], + maxFileSize: Number.POSITIVE_INFINITY, + classifyBinary: false, + }); +} + +/** + * Search `paths` for debug files matching the requested ids. + * + * Object formats are detected by a cheap header peek and only fully parsed when + * wanted; ProGuard mappings are matched by computing their UUID. The search + * stops early once every id is located (breakpad-only matches never satisfy an + * id, mirroring the legacy CLI). + */ +export async function findDebugFiles(opts: FindOptions): Promise { + const wantedTypes = + opts.types && opts.types.length > 0 ? opts.types : FIND_DIF_TYPES; + const state: SearchState = { + remaining: new Set(opts.ids.map(normalizeDebugId)), + breakpadFound: new Set(), + formats: new Set( + wantedTypes + .map((t) => TYPE_TO_FORMAT[t.toLowerCase()]) + .filter((f): f is string => Boolean(f)) + ), + sourcebundleType: sourcebundleDisplayType(wantedTypes), + wantProguard: wantedTypes.some((t) => t.toLowerCase() === "proguard"), + matches: [], + }; + + const seen = new Set(); + for (const path of opts.paths) { + const abs = resolve(path); + if (seen.has(abs)) { + continue; + } + seen.add(abs); + for await (const entry of walkPath(path)) { + if (state.remaining.size === 0) { + break; + } + opts.onProgress?.(state.matches.length, entry.absolutePath); + await tryProguard(entry.absolutePath, entry.size, state); + await tryObject(entry.absolutePath, entry.size, state); + } + if (state.remaining.size === 0) { + break; + } + } + + // Breakpad-only matches are reported but still counted as missing. + const missingIds = new Set([...state.remaining, ...state.breakpadFound]); + const missing: MissingId[] = [...missingIds].map((id) => ({ + id, + hint: idHint(id), + })); + return { matches: state.matches, missing }; +} diff --git a/test/commands/debug-files/find.test.ts b/test/commands/debug-files/find.test.ts new file mode 100644 index 0000000000..ddf5751682 --- /dev/null +++ b/test/commands/debug-files/find.test.ts @@ -0,0 +1,109 @@ +/** + * Tests for `sentry debug-files find`. + * + * Drives the full app router with a deterministic Breakpad symbol fixture (no + * committed binaries), covering flag wiring, JSON output, the exit code, and + * the breakpad "reported-but-still-missing" behaviour. + */ + +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { run } from "@stricli/core"; +import { afterEach, beforeEach, describe, expect, test } from "vitest"; +import { app } from "../../../src/app.js"; +import type { SentryContext } from "../../../src/context.js"; +import { useTestConfigDir } from "../../helpers.js"; + +useTestConfigDir("debug-files-find-"); + +let tempDir: string; + +beforeEach(async () => { + tempDir = await mkdtemp(join(tmpdir(), "df-find-test-")); +}); +afterEach(async () => { + await rm(tempDir, { recursive: true, force: true }); +}); + +const BREAKPAD_FIXTURE = [ + "MODULE Linux x86_64 0F13A5DA412AFBF7C8662048F3294F3D0 example", + "INFO CODE_ID DAA5130F2A41F7FBC8662048F3294F3D439CA7FF", + "FUNC 1000 10 0 main", + "1000 10 42 1", +].join("\n"); + +const BREAKPAD_ID = "0f13a5da-412a-fbf7-c866-2048f3294f3d"; + +async function runFind( + args: string[] +): Promise<{ output: string; exitCode: number | undefined }> { + let output = ""; + const mockContext: SentryContext = { + process: { ...process, exitCode: undefined } as typeof process, + env: process.env, + cwd: process.cwd(), + homeDir: "/tmp", + configDir: "/tmp", + stdout: { + write(data: string | Uint8Array) { + output += + typeof data === "string" ? data : new TextDecoder().decode(data); + return true; + }, + }, + stderr: { write: () => true }, + stdin: process.stdin, + }; + await run(app, ["debug-files", "find", ...args], mockContext); + return { output, exitCode: mockContext.process.exitCode }; +} + +describe("sentry debug-files find", () => { + test("finds a breakpad file but still reports the id as missing (exit 1)", async () => { + await writeFile(join(tempDir, "example.sym"), BREAKPAD_FIXTURE); + + const { output, exitCode } = await runFind([ + BREAKPAD_ID, + "--no-well-known", + "--no-cwd", + "--path", + tempDir, + "--json", + ]); + const parsed = JSON.parse(output); + expect(parsed.matches).toHaveLength(1); + expect(parsed.matches[0]).toMatchObject({ + type: "breakpad", + id: BREAKPAD_ID, + }); + // A breakpad match does not satisfy the request. + expect(parsed.missing.map((m: { id: string }) => m.id)).toContain( + BREAKPAD_ID + ); + expect(exitCode).toBe(1); + }); + + test("exits successfully when there is nothing to find (no ids)", async () => { + const { exitCode } = await runFind(["--no-cwd", "--no-well-known"]); + expect(exitCode ?? 0).toBe(0); + }); + + test("rejects an unknown --type", async () => { + const { exitCode } = await runFind([BREAKPAD_ID, "--type", "bogus"]); + expect(exitCode).not.toBe(0); + }); + + test("exits 1 with a missing hint when nothing matches", async () => { + await writeFile(join(tempDir, "example.sym"), BREAKPAD_FIXTURE); + const { output, exitCode } = await runFind([ + "ffffffff-0000-0000-0000-000000000000", + "--no-well-known", + "--no-cwd", + "-p", + tempDir, + ]); + expect(output).toContain("Missing debug information files"); + expect(exitCode).toBe(1); + }); +}); diff --git a/test/lib/dif/find.test.ts b/test/lib/dif/find.test.ts new file mode 100644 index 0000000000..41f9c97279 --- /dev/null +++ b/test/lib/dif/find.test.ts @@ -0,0 +1,143 @@ +/** + * Tests for `debug-files find` search logic. + * + * Uses the committed PE fixture (a real debug id) and a generated ProGuard + * mapping (deterministic UUID) — no network, no mocks of the parser. + */ + +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, test } from "vitest"; +import { findDebugFiles, idHint } from "../../../src/lib/dif/find.js"; +import { computeProguardUuid } from "../../../src/lib/proguard.js"; + +const FIXTURES = join(process.cwd(), "test/fixtures/dif"); +// The committed PE fixture's embedded debug id (see check output). +const PE_ID = "d8eb7dca-4883-4b10-a1f7-048ea1ea388b-cfb0fc89"; + +const dirs: string[] = []; +afterEach(() => { + while (dirs.length > 0) { + const d = dirs.pop(); + if (d) { + rmSync(d, { recursive: true, force: true }); + } + } +}); + +describe("idHint", () => { + test("classifies ids by shape", () => { + expect(idHint("00000000-0000-6000-0000-000000000000-1")).toBe("likely PDB"); + expect(idHint("00000000-0000-5000-0000-000000000000")).toBe( + "likely Proguard" + ); + expect(idHint("00000000-0000-3000-0000-000000000000")).toBe("likely dSYM"); + expect(idHint("00000000-0000-4000-0000-000000000000")).toBe("unknown"); + expect(idHint("00000000-0000-0000-0000-000000000000")).toBe( + "likely ELF Debug" + ); + }); +}); + +describe("findDebugFiles", () => { + test("locates a PE by its exact debug id", async () => { + const result = await findDebugFiles({ ids: [PE_ID], paths: [FIXTURES] }); + expect(result.missing).toEqual([]); + expect(result.matches).toHaveLength(1); + expect(result.matches[0]).toMatchObject({ type: "pe", id: PE_ID }); + expect(result.matches[0].path).toContain("embedded-ppdb.dll"); + }); + + test("reports an unmatched id as missing with a hint", async () => { + const missingId = "ffffffff-0000-0000-0000-000000000000"; + const result = await findDebugFiles({ + ids: [missingId], + paths: [FIXTURES], + }); + expect(result.matches).toEqual([]); + expect(result.missing).toEqual([ + { id: missingId, hint: "likely ELF Debug" }, + ]); + }); + + test("a type filter that excludes PE finds nothing", async () => { + const result = await findDebugFiles({ + ids: [PE_ID], + types: ["elf"], + paths: [FIXTURES], + }); + expect(result.matches).toEqual([]); + expect(result.missing.map((m) => m.id)).toEqual([PE_ID]); + }); + + test("locates a ProGuard mapping by its computed UUID", async () => { + const dir = mkdtempSync(join(tmpdir(), "find-pg-")); + dirs.push(dir); + const mapping = + "com.example.Foo -> a.a:\n" + + " int field -> a\n" + + " void method() -> a\n"; + const buf = Buffer.from(mapping); + writeFileSync(join(dir, "mapping.txt"), buf); + const uuid = computeProguardUuid(buf); + + const result = await findDebugFiles({ + ids: [uuid], + types: ["proguard"], + paths: [dir], + }); + expect(result.missing).toEqual([]); + expect(result.matches).toHaveLength(1); + expect(result.matches[0]).toMatchObject({ type: "proguard", id: uuid }); + }); + + test("de-duplicates repeated search paths", async () => { + const result = await findDebugFiles({ + ids: [PE_ID], + paths: [FIXTURES, FIXTURES], + }); + expect(result.matches).toHaveLength(1); + }); + + test("a real match after a breakpad clears the id from missing", async () => { + // Construct a breakpad whose debug id equals a ProGuard mapping's UUID, so + // the same id is matched by both a breakpad (does not satisfy) and a real + // ProGuard file (satisfies). The id must not remain "missing". + const dir = mkdtempSync(join(tmpdir(), "find-bp-")); + dirs.push(dir); + const mapping = "com.example.Foo -> a.a:\n int field -> a\n"; + const uuid = computeProguardUuid(Buffer.from(mapping)); + const hex = uuid.replaceAll("-", "").toUpperCase(); + // `a.sym` sorts before `z.txt`, so the breakpad is seen first. + writeFileSync( + join(dir, "a.sym"), + `MODULE Linux x86_64 ${hex}0 example\nFUNC 1000 10 0 main\n` + ); + writeFileSync(join(dir, "z.txt"), mapping); + + const result = await findDebugFiles({ + ids: [uuid], + types: ["breakpad", "proguard"], + paths: [dir], + }); + expect(result.missing).toEqual([]); + expect(result.matches.map((m) => m.type).sort()).toEqual([ + "breakpad", + "proguard", + ]); + }); + + test("labels a jvm-only search as jvm, not sourcebundle", async () => { + // sourcebundle + jvm share a format; the requested type drives the label. + // (No sourcebundle fixture is needed to verify the mapping choice.) + const noneForElf = await findDebugFiles({ + ids: [PE_ID], + types: ["jvm"], + paths: [FIXTURES], + }); + // PE isn't a sourcebundle, so nothing matches — but the search must not throw + // and the jvm type must be accepted. + expect(noneForElf.missing.map((m) => m.id)).toEqual([PE_ID]); + }); +});