Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
62 changes: 60 additions & 2 deletions src/jsc/bindings/CodeCoverage.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
#include "root.h"
#include "ZigSourceProvider.h"
#include <JavaScriptCore/CodeBlock.h>
#include <JavaScriptCore/ControlFlowProfiler.h>
#include <JavaScriptCore/FunctionExecutable.h>
#include <JavaScriptCore/Heap.h>
#include <JavaScriptCore/HeapInlines.h>
#include <JavaScriptCore/UnlinkedFunctionExecutable.h>
#include <wtf/HashSet.h>
#include <wtf/ScopedLambda.h>

using namespace JSC;

Expand All @@ -24,15 +31,66 @@ extern "C" bool CodeCoverage__withBlocksAndFunctions(

size_t functionStartOffset = basicBlocks.size();

// Classify function byte-offset ranges reachable from this source as synthetic
// vs. same-source, so we can drop only the synthetic ones from the range list.
//
// JSC emits a synthetic default class constructor for `class Foo extends Bar() {}`
// (and plain `class Foo {}`) by linking a *separate* builtin SourceProvider —
// `(function (...args) { super(...args); })` or `(function () { })`. But
// `CodeBlock::finishCreation` files the constructor's `unlinkedFunctionStart`
// and `unlinkedFunctionEnd` under the OWNER's sourceID, so those offsets — which
// live in the synthetic provider — end up looking like real function ranges in
// the user's source. Coverage then reports bogus "uncovered" bytes that straddle
// whatever user code happens to sit at those offsets. See issue #29691.
//
// The synthetic case is identifiable because `functionExecutable->sourceID()`
// resolves to the synthetic provider's ID (via `linkedSourceCode`), not the
// owner's. But a real user function CAN have offsets that numerically collide
// with a synthetic constructor's `[1, N)` range (e.g. a user file starting with
// `!function(){}` where the function begins at offset 1). So also collect
// same-source ranges and skip only when a range is synthetic and NOT also
// present in the same-source set.
HashSet<std::pair<unsigned, unsigned>> syntheticFunctionRanges;
HashSet<std::pair<unsigned, unsigned>> sameSourceFunctionRanges;
vm.heap.forEachCodeBlock([&](CodeBlock* codeBlock) {
auto* owner = codeBlock->ownerExecutable();
if (!owner || owner->sourceID() != sourceID)
return;

auto collect = [&](FunctionExecutable* fnExec) {
if (!fnExec)
return;
auto* unlinked = fnExec->unlinkedExecutable();
if (!unlinked)
return;
std::pair<unsigned, unsigned> range { unlinked->unlinkedFunctionStart(), unlinked->unlinkedFunctionEnd() };
if (fnExec->sourceID() == sourceID)
sameSourceFunctionRanges.add(range);
else
syntheticFunctionRanges.add(range);
};

for (const auto& fn : codeBlock->functionDecls())
collect(fn.get());
for (int i = 0, count = static_cast<int>(codeBlock->numberOfFunctionExprs()); i < count; ++i)
collect(codeBlock->functionExpr(i));
});

const Vector<std::tuple<bool, unsigned, unsigned>>& functionRanges = vm.functionHasExecutedCache()->getFunctionRanges(sourceID);

basicBlocks.reserveCapacity(functionRanges.size() + basicBlocks.size());

for (const auto& functionRange : functionRanges) {
unsigned start = std::get<1>(functionRange);
unsigned end = std::get<2>(functionRange);
std::pair<unsigned, unsigned> key { start, end };
if (syntheticFunctionRanges.contains(key) && !sameSourceFunctionRanges.contains(key))
continue;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

BasicBlockRange range;
range.m_hasExecuted = std::get<0>(functionRange);
range.m_startOffset = static_cast<int>(std::get<1>(functionRange));
range.m_endOffset = static_cast<int>(std::get<2>(functionRange));
range.m_startOffset = static_cast<int>(start);
range.m_endOffset = static_cast<int>(end);
range.m_executionCount = range.m_hasExecuted
? 1
: 0; // This is a hack. We don't actually count this.
Expand Down
34 changes: 26 additions & 8 deletions src/sourcemap_jsc/CodeCoverage.zig
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,15 @@ pub const ByteRangeMapping = struct {
}
}

// Snapshot of lines marked executed by statement blocks above. Statement
// coverage is authoritative for line coverage — a never-called function's
// declaration line still ran as a statement, and JSC's synthetic default
// class constructor ranges get filed under the user's sourceID with
// offsets into a completely different (synthetic) source, so they must
// not unset lines that real statements already covered. Issue #29691.
var stmt_lines_which_have_executed = bun.handleOom(lines_which_have_executed.clone(allocator));
defer stmt_lines_which_have_executed.deinit(allocator);

for (function_blocks, 0..) |function, i| {
if (function.endOffset < 0 or function.startOffset < 0) continue; // does not map to anything

Expand All @@ -508,14 +517,16 @@ pub const ByteRangeMapping = struct {

const did_fn_execute = function.executionCount > 0 or function.hasExecuted;

// only mark the lines as executable if the function has not executed
// functions that have executed have non-executable lines in them and thats fine.
// Mark executable lines for a function that did not execute — but
// preserve hits recorded by statement blocks.
if (!did_fn_execute) {
const end = @min(max_line, line_count);
@memset(line_hits_slice[min_line..end], 0);
for (min_line..end) |line| {
executable_lines.set(line);
lines_which_have_executed.unset(line);
if (!stmt_lines_which_have_executed.isSet(line)) {
lines_which_have_executed.unset(line);
line_hits_slice[line] = 0;
}
}
}

Expand Down Expand Up @@ -587,6 +598,11 @@ pub const ByteRangeMapping = struct {
}
}

// Snapshot of lines marked executed by statement blocks above. See the
// same comment in the no-sourcemap branch for rationale. Issue #29691.
var stmt_lines_which_have_executed = bun.handleOom(lines_which_have_executed.clone(allocator));
defer stmt_lines_which_have_executed.deinit(allocator);

for (function_blocks, 0..) |function, i| {
if (function.endOffset < 0 or function.startOffset < 0) continue; // does not map to anything

Expand Down Expand Up @@ -624,14 +640,16 @@ pub const ByteRangeMapping = struct {

const did_fn_execute = function.executionCount > 0 or function.hasExecuted;

// only mark the lines as executable if the function has not executed
// functions that have executed have non-executable lines in them and thats fine.
// Mark executable lines for a function that did not execute — but
// preserve hits recorded by statement blocks.
if (!did_fn_execute) {
const end = @min(max_line, line_count);
for (min_line..end) |line| {
executable_lines.set(line);
lines_which_have_executed.unset(line);
line_hits_slice[line] = 0;
if (!stmt_lines_which_have_executed.isSet(line)) {
lines_which_have_executed.unset(line);
line_hits_slice[line] = 0;
}
}
}

Expand Down
6 changes: 3 additions & 3 deletions test/cli/test/__snapshots__/coverage.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ exports[`lcov coverage reporter: lcov-coverage-reporter-output 1`] = `
"TN:
SF:demo1.ts
FNF:1
FNH:0
FNH:1
DA:2,19
DA:3,16
DA:4,1
Expand All @@ -18,11 +18,11 @@ FNH:1
DA:2,28
DA:4,11
DA:6,9
DA:9,0
DA:9,5
DA:10,0
DA:11,1
DA:14,9
LF:7
LH:5
LH:6
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
end_of_record"
`;
73 changes: 63 additions & 10 deletions test/cli/test/coverage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,18 @@ import { bunEnv, bunExe, normalizeBunSnapshot, tempDirWithFiles } from "harness"
import { readFileSync } from "node:fs";
import path from "path";

// Debug/ASAN builds print "WARNING: ASAN interferes with JSC signal handlers; …"
// to stderr on every JS-executing process launch — emitted via std::call_once
// in Options.cpp, so at most once per subprocess. It leaks into snapshot tests
// that capture stderr. Strip it before snapshotting so debug-ASAN CI lanes
// match the release snapshot.
function stripAsanWarning(s: string): string {
return s
.split("\n")
.filter(line => !line.startsWith("WARNING: ASAN interferes"))
.join("\n");
}

test("coverage crash", () => {
const dir = tempDirWithFiles("cov", {
"demo.test.ts": `class Y {
Expand Down Expand Up @@ -57,6 +69,47 @@ export class Y {
);
});

// https://github.com/oven-sh/bun/issues/29691
//
// `class Foo extends Something() {}` has no user-written constructor, so JSC
// synthesizes one from `(function (...args) { super(...args); })`. JSC also
// records that synthetic function in its control-flow profiler indexed by the
// USER's source ID, even though the offsets it records live in the synthetic
// source. Coverage then reported the 37-byte range `[1, 38)` straddling the
// import line and the class declaration line as an uncovered "function" —
// marking line 1 (the import) as `DA:1,0` even though the module loaded.
test("derived class with no explicit constructor (issue #29691)", () => {
const dir = tempDirWithFiles("cov-29691", {
"dep.ts": `export const Base = () => class {};\n`,
"subject.ts": `import { Base } from "./dep";
export class Derived extends Base() {}
`,
"subject.test.ts": `import { expect, test } from "bun:test";
import { Derived } from "./subject";
test("loads the class", () => {
expect(Derived.name).toBe("Derived");
});
`,
});
const result = Bun.spawnSync([bunExe(), "test", "--coverage", "--coverage-reporter", "lcov"], {
cwd: dir,
env: bunEnv,
stdio: [null, null, "pipe"],
});
expect(result.exitCode).toBe(0);
expect(result.signalCode).toBeUndefined();

const lcov = readFileSync(path.join(dir, "coverage", "lcov.info"), "utf-8");

// subject.ts should not report the import on line 1 as uncovered (DA:1,0),
// and should not count the synthetic default constructor as a function.
const subjectRecord = lcov.split("end_of_record").find(r => r.includes("SF:subject.ts"))!;
expect(subjectRecord).toContain("FNF:1");
expect(subjectRecord).toContain("FNH:1");
expect(subjectRecord).toMatch(/DA:2,[1-9]\d*/); // class declaration line was evaluated (non-zero hits)
expect(subjectRecord).not.toContain("DA:1,0"); // import line is not bogusly marked unexecuted
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});
Comment on lines +81 to +111

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.

🧹 Nitpick | 🔵 Trivial

Consider adding a collision-specific regression for the new same-source guard.

This repro locks down the original synthetic-constructor bug, but it still doesn't exercise the new synthetic && !same_source branch in CodeCoverage.cpp. A tiny fixture where a real user function shares the synthetic constructor's raw (start, end) offsets would protect the collision fix directly.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/cli/test/coverage.test.ts` around lines 69 - 99, Add a new, small
regression test that specifically triggers the synthetic && !same_source branch
in CodeCoverage.cpp by creating a real (non-synthetic) user function that
deliberately shares the synthetic constructor's raw (start,end) offsets so the
same-source guard collision is exercised; mirror the existing "derived class
with no explicit constructor" test pattern (test/cli/test/coverage.test.ts) but
add a fixture file that defines a user function with the same raw offsets as the
synthetic constructor and assert coverage records show both entries handled
correctly (so the new branch is executed and prevents the collision regression).


test("coverage excludes node_modules directory", () => {
const dir = tempDirWithFiles("cov", {
"node_modules/pi/index.js": `
Expand Down Expand Up @@ -117,7 +170,7 @@ test("should call both functions", () => {
stdio: [null, null, "pipe"],
});

let stderr = result.stderr.toString("utf-8");
let stderr = stripAsanWarning(result.stderr.toString("utf-8"));
// Normalize output for cross-platform consistency
stderr = normalizeBunSnapshot(stderr, dir);

Expand Down Expand Up @@ -182,7 +235,7 @@ test("should call only some functions", () => {
stdio: [null, null, "pipe"],
});

let stderr = result.stderr.toString("utf-8");
let stderr = stripAsanWarning(result.stderr.toString("utf-8"));
// Normalize output for cross-platform consistency
stderr = normalizeBunSnapshot(stderr, dir);

Expand All @@ -192,8 +245,8 @@ test("should call only some functions", () => {
---------------|---------|---------|-------------------
File | % Funcs | % Lines | Uncovered Line #s
---------------|---------|---------|-------------------
All files | 75.00 | 83.33 |
include-me.ts | 50.00 | 66.67 |
All files | 75.00 | 100.00 |
include-me.ts | 50.00 | 100.00 |
test.test.ts | 100.00 | 100.00 |
---------------|---------|---------|-------------------

Expand Down Expand Up @@ -247,7 +300,7 @@ test("should call all functions", () => {
stdio: [null, null, "pipe"],
});

let stderr = result.stderr.toString("utf-8");
let stderr = stripAsanWarning(result.stderr.toString("utf-8"));
// Normalize output for cross-platform consistency
stderr = normalizeBunSnapshot(stderr, dir);

Expand Down Expand Up @@ -314,7 +367,7 @@ test("should call all functions", () => {
stdio: [null, null, "pipe"],
});

let stderr = result.stderr.toString("utf-8");
let stderr = stripAsanWarning(result.stderr.toString("utf-8"));
// Normalize output for cross-platform consistency
stderr = normalizeBunSnapshot(stderr, dir);

Expand Down Expand Up @@ -432,7 +485,7 @@ test("should pass", () => {
stdio: [null, null, "pipe"],
});

let stderr = result.stderr.toString("utf-8");
let stderr = stripAsanWarning(result.stderr.toString("utf-8"));
// Normalize error output for cross-platform consistency
stderr = normalizeBunSnapshot(stderr, dir);

Expand Down Expand Up @@ -471,7 +524,7 @@ test("should pass", () => {
stdio: [null, null, "pipe"],
});

let stderr = result.stderr.toString("utf-8");
let stderr = stripAsanWarning(result.stderr.toString("utf-8"));
// Normalize error output for cross-platform consistency
stderr = normalizeBunSnapshot(stderr, dir);

Expand Down Expand Up @@ -516,7 +569,7 @@ test("should call function", () => {
stdio: [null, null, "pipe"],
});

let stderr = result.stderr.toString("utf-8");
let stderr = stripAsanWarning(result.stderr.toString("utf-8"));
// Normalize output for cross-platform consistency
stderr = normalizeBunSnapshot(stderr, dir);

Expand Down Expand Up @@ -569,7 +622,7 @@ test("should call function", () => {
stdio: [null, null, "pipe"],
});

let stderr = result.stderr.toString("utf-8");
let stderr = stripAsanWarning(result.stderr.toString("utf-8"));
// Normalize output for cross-platform consistency
stderr = normalizeBunSnapshot(stderr, dir);

Expand Down
Loading