Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/runtime/bake/dev_server/source_map_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -674,7 +674,8 @@ impl SourceMapStore {
match source_map::mapping::parse(
&vlq_bytes,
None,
i32::try_from(entry.paths.len()).expect("int cast"),
// Source 0 is the HMR runtime, so `paths[i]` is source `i + 1`.
i32::try_from(entry.paths.len() + 1).expect("int cast"),
Default::default(),
) {
Err(fail) => {
Expand Down
4 changes: 0 additions & 4 deletions src/sourcemap/Mapping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -383,10 +383,6 @@ impl Lookup {
}
}

if index >= source_map.external_source_names.len() {
return None;
}

let name: &[u8] = &source_map.external_source_names[index];

let mut buf = bun_paths::path_buffer_pool::get();
Expand Down
2 changes: 1 addition & 1 deletion src/sourcemap/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -951,7 +951,7 @@ pub(crate) fn parse_json(source: &[u8], hint: ParseUrlResultHint) -> crate::Resu
let mut map_data = match mapping::parse(
mappings_vlq,
None,
i32::MAX,
i32::try_from(sources_paths.items().len()).unwrap_or(i32::MAX),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 (optional) Users running a prebuilt // @ bun file whose map has one segment past sources now lose remapping for every frame in that file, with a warn: line, where main remapped the in-range frames. src/sourcemap/lib.rs:954 passes sources.len() to mapping::parse, and Mapping.rs:582 refuses the whole map on the first out-of-range index, so get_source_map_impl returns None at lib.rs:552 and SavedSourceMap.rs:329 drops the entry for good. Node leaves only the bad frame unmapped. Fix: match node per frame: let parse keep the map and have Lookup::display_source_url_if_needed/get_source_code return None for an out-of-range source_index (the guard this PR deletes at Mapping.rs:386), or at least keep accepting sources: [] maps.

Why this was flagged

Trigger: any JSON map reachable through parse_json (lib.rs:447 inline, :468 dev-server provider, :493 registered, :538 <file>.map on disk) in which at least one 4- or 5-field segment names an index >= sources.length, or whose sources is [] while mappings carries 4-field segments. On the base commit parse_json passed i32::MAX (lib.rs:954 old), the map parsed, in-range frames were remapped to their original file and only the bad frame printed a mixed position. After this change Mapping.rs:582 returns InvalidSourceIndexValue for the first bad segment, lib.rs:545-552 warns Could not decode sourcemap in '<file>': InvalidSourceIndexValue and returns None, and SavedSourceMap.rs:329-338 removes the entry so the file is never retried: every stack trace, Bun.inspect(error) preview, and bun test --coverage lookup for that file stays at built positions for the life of the process. A per-frame guard (the one deleted at Mapping.rs:386, plus the kept one at Mapping.rs:321) would reject only the bad frame as node does.

Verification: src/sourcemap/lib.rs:954 now passes i32::try_from(sources_paths.items().len()).unwrap_or(i32::MAX) where the base passed i32::MAX. src/sourcemap/Mapping.rs:582-589 returns Err(ParseFail { err: InvalidSourceIndexValue }) on the first out-of-range index, and src/jsc/SavedSourceMap.rs:327-333 removes the table entry, so no frame in that file is remapped for the rest of the process.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changed. The guard you suggest is what main does today, and it is the cause of the mixed frame. display_source_url_if_needed returns None for an index past the names (Mapping.rs:321). The three remap sites in VirtualMachine.rs then keep the built URL and still copy the original line and column. That prints entry.js:5:3.

A verdict for each frame needs more than that guard. Every reader of a lookup has to treat the mapping as absent: the three remap sites, coverage, and the content pick in parse_json. Or the decoder has to mark the row. Both add a branch to each lookup, for every map.

The whole-map refusal is what this decoder already does for a negative source index, a negative line or column, and a bad VLQ. new module.SourceMap passes its real count to the same decoder and throws.

Reach: 0 of 542 bun-built maps from npm packages have such a row, and 0 of 192 maps from bun build. 2 of 8,111 .map files in the checkout have one. Both are invalid-map fixtures of the tc39 suite.

For sources: [] with 4-field mappings, every frame of that file is a mixed frame on main. Node leaves those frames unmapped. With this PR they are unmapped too, with one warning.

The cost is the first Downsides bullet: the in-range frames of such a map are no longer remapped. I leave this thread open so that a maintainer can decide.

mapping::ParseOptions {
allow_names: matches!(
hint,
Expand Down
131 changes: 130 additions & 1 deletion test/bake/dev/html.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// HTML tests are tests relating to HTML files themselves.
import { expect } from "bun:test";
import { devTest, emptyHtmlFile } from "../bake-harness";
import { basename } from "node:path";
import { Dev, devTest, emptyHtmlFile } from "../bake-harness";

devTest("html file is watched", {
files: {
Expand Down Expand Up @@ -463,6 +464,134 @@ devTest("error report endpoint blanks stray non-text bytes in reported frames",
await dev.fetch("/").expect.toInclude("<h1>Frame Bytes</h1>");
},
});

// Posts frames to /_bun/report_error and returns the frames of the reply. Both use: i32 line, i32 column,
// string32 function name, string32 file name. The request starts with string32 error name, string32 message,
// string32 browser url and a u32 frame count. The reply starts with a u32 frame count.
async function reportErrorFrames(
dev: Dev,
frames: { line: number; column: number; functionName: string; file: string }[],
) {
function i32(n: number) {
const b = Buffer.alloc(4);
b.writeInt32LE(n, 0);
return b;
}
function str32(s: string) {
const bytes = Buffer.from(s, "utf8");
return Buffer.concat([i32(bytes.length), bytes]);
}
const body = Buffer.concat([
str32("Error"),
str32("remap-message"),
str32(dev.baseUrl + "/"),
i32(frames.length),
...frames.flatMap(frame => [i32(frame.line), i32(frame.column), str32(frame.functionName), str32(frame.file)]),
]);
const res = await dev.fetch("/_bun/report_error", { method: "POST", body });
const reply = Buffer.from(await res.arrayBuffer());
expect(res.status).toBe(200);

let at = 0;
const readInt = () => ((at += 4), reply.readInt32LE(at - 4));
const readString = () => {
const length = readInt();
return reply.toString("utf8", at, (at += length));
};
return Array.from({ length: readInt() }, () => ({
line: readInt(),
column: readInt(),
functionName: readString(),
// Relative to the project root, or absolute on Windows.
file: basename(readString()),
}));
}

// The one-based line and column of `marker` in `script`.
function positionOf(script: string, marker: string) {
const offset = script.indexOf(marker);
expect(offset).toBeGreaterThan(0);
const lineStart = script.lastIndexOf("\n", offset) + 1;
return { line: script.slice(0, lineStart).split("\n").length, column: offset - lineStart + 1 };
}

devTest("error report endpoint remaps a frame in every file of the client bundle", {
files: {
"index.html": emptyHtmlFile({
scripts: ["/index.ts"],
body: "<h1>Remap</h1>",
}),
"index.ts": `
import { other } from "./other";
console.log("index-frame-marker", other());
`,
"other.ts": `
// The marker is on line 3.
export function other() {
return "other-frame-marker";
}
`,
},
async test(dev) {
const page = await dev.fetch("/").text();
const [scriptPath] = page.match(/\/_bun\/client\/index-[0-9a-f]{16}\.js/) ?? [];
const script = await dev.fetch(scriptPath).text();
const file = dev.baseUrl + scriptPath;

const frames = await reportErrorFrames(dev, [
{ ...positionOf(script, "index-frame-marker"), functionName: "inIndex", file },
{ ...positionOf(script, "other-frame-marker"), functionName: "inOther", file },
]);
expect(frames).toEqual([
{ line: 2, column: 'console.log("'.length, functionName: "inIndex", file: "index.ts" },
{ line: 3, column: ' return "'.length, functionName: "inOther", file: "other.ts" },
]);
},
});

devTest("error report endpoint remaps a frame in a hot update chunk", {
files: {
"index.html": emptyHtmlFile({
scripts: ["/index.ts"],
}),
"index.ts": `
import { other } from "./other";
console.log("index " + other());
import.meta.hot.accept();
`,
"other.ts": `
export function other() {
return "first";
}
import.meta.hot.accept();
`,
},
async test(dev) {
await using c = await dev.client("/", { storeHotChunks: true });
await dev.write(
"other.ts",
`
console.log("updated");
export function other() {
return "chunk-frame-marker";
}
import.meta.hot.accept();
`,
);
const chunk = await c.getMostRecentHmrChunk();
const [, id] = chunk.match(/\n\/\/# sourceMappingURL=\S*?([0-9a-f]{16})\.js\.map/) ?? [];

const frames = await reportErrorFrames(dev, [
{
...positionOf(chunk, "chunk-frame-marker"),
functionName: "inChunk",
file: `${dev.baseUrl}/_bun/client/hmr-${id}.js`,
},
]);
expect(frames).toEqual([{ line: 3, column: ' return "'.length, functionName: "inChunk", file: "other.ts" }]);
await c.expectMessage("index first", "updated");
},
});
devTest("client script route returns 404 when the route bundle index is out of range", {
files: {
"index.html": emptyHtmlFile({ scripts: ["/script.ts"] }),
Expand Down
118 changes: 118 additions & 0 deletions test/js/bun/sourcemap/negative-vlq-mapping.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,3 +169,121 @@ describe.concurrent("sourcemap: negative VLQ delta in mappings is rejected, not
expect(exitCode).toBe(0);
});
});

// A segment that names a source the map does not have. ";;EAIE" maps generated
// 3:3 to original 5:3 of source 0. ";;ECIE" maps it to source 1.
describe.concurrent("sourcemap: a source index past `sources` is rejected", () => {
const map = { version: 3, sources: ["original.ts"], sourcesContent: [null], names: [], mappings: ";;ECIE" };
const maps = {
"last-source": { ...map, sources: ["other.ts", "original.ts"], sourcesContent: [null, null] },
"past-end": map,
"no-sources": { ...map, sources: [], sourcesContent: [], mappings: ";;EAIE" },
// Long enough for the SIMD decoder, which leaves the last segment of any input to the scalar loop.
"past-end-at-tail": { ...map, mappings: ";;EAIE" + Buffer.alloc(5 * 46, ",CAAC").toString() + ",CCAA" },
// ",CCAA" names source 1 and ",CDAA" goes back to source 0. The SIMD decoder has to refuse it mid-input.
"past-end-mid-input": {
...map,
mappings:
";;EAIE" + Buffer.alloc(5 * 20, ",CAAC").toString() + ",CCAA,CDAA" + Buffer.alloc(5 * 20, ",CAAC").toString(),
},
// The same with two-character VLQs, which take another path in the SIMD decoder.
"past-end-mid-input-wide": {
...map,
mappings:
";;EAIE" +
Buffer.alloc(7 * 20, ",gBAAgB").toString() +
",CCAA,CDAA" +
Buffer.alloc(7 * 20, ",gBAAgB").toString(),
},
};
const throwsOnLine3 = `// @bun\nexport function t() {\n throw new Error("SI");\n}\n`;
const files: Record<string, string> = {
"main.js": `
for (const file of process.argv.slice(2)) {
const { t } = await import("./" + file);
for (let i = 0; i < 2; i++) {
try {
t();
} catch (e) {
console.log(file + ": " + e.stack.split("\\n")[1].trim());
}
}
}
`,
};
for (const [name, map] of Object.entries(maps)) {
const json = JSON.stringify(map);
files[`${name}.js`] = throwsOnLine3 + `//# sourceMappingURL=${name}.js.map\n`;
files[`${name}.js.map`] = json;
files[`${name}.inline.js`] = throwsOnLine3 + `//# sourceMappingURL=data:application/json;base64,${btoa(json)}\n`;
}
const remapped = ["last-source.js", "last-source.inline.js"];
const refused = Object.keys(maps)
.filter(name => name !== "last-source")
.flatMap(name => [`${name}.js`, `${name}.inline.js`]);

for (const [decoder, env] of [
["SIMD", {}],
["scalar", { BUN_FEATURE_FLAG_DISABLE_SIMD_SOURCEMAP: "1" }],
] as const) {
test(`${decoder} decoder: one warning for each file, and its frames keep their built position`, async () => {
using dir = tempDir("source-index-past-end", files);
await using proc = Bun.spawn({
cmd: [bunExe(), "main.js", ...remapped, ...refused],
env: { ...bunEnv, ...env },
cwd: String(dir),
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
const clean = (text: string) => text.replaceAll(String(dir), "<dir>").replaceAll("\\", "/");
const twice = (line: string) => line + line;
expect({ stdout: clean(stdout), stderr: clean(stderr) }).toEqual({
stdout:
remapped.map(file => twice(`${file}: at t (<dir>/original.ts:5:3)\n`)).join("") +
refused.map(file => twice(`${file}: at t (<dir>/${file}:3:18)\n`)).join(""),
stderr: refused
.map(file => `warn: Could not decode sourcemap in '<dir>/${file}': InvalidSourceIndexValue\n`)
.join(""),
});
expect(exitCode).toBe(0);
});
}

test("a throw in the last source of a `bun build --sourcemap=external` bundle is remapped", async () => {
using dir = tempDir("source-index-last-of-bundle", {
"first.ts": `export function first() {}\n`,
"second.ts": `export function second() {}\n`,
"entry.ts":
`import { first } from "./first";\n` +
`import { second } from "./second";\n` +
`first();\n` +
`second();\n` +
`function last() {\n` +
` throw new Error("SI");\n` +
`}\n` +
`last();\n`,
});
const build = await Bun.build({
entrypoints: [join(String(dir), "entry.ts")],
outdir: join(String(dir), "out"),
target: "bun",
sourcemap: "external",
});
expect(build.success).toBe(true);
const { sources } = await Bun.file(join(String(dir), "out", "entry.js.map")).json();
expect(sources).toEqual(["../first.ts", "../second.ts", "../entry.ts"]);

await using proc = Bun.spawn({
cmd: [bunExe(), join("out", "entry.js")],
env: bunEnv,
cwd: String(dir),
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stderr).toContain(`at last (${join(String(dir), "entry.ts")}:6:9)`);
expect(stdout).toBe("");
expect(exitCode).toBe(1);
});
});
Loading