Skip to content
Closed
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
4 changes: 4 additions & 0 deletions .github/workflows/source-lints.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ on:
paths:
- "src/**/*.rs"
- "src/jsc/bindings/**"
- "src/runtime/bake/*.cpp"
- "src/runtime/bake/*.h"
- "scripts/build/**"
- "scripts/glob-sources.ts"
- "scripts/utils.mjs"
Expand All @@ -29,6 +31,8 @@ on:
paths:
- "src/**/*.rs"
- "src/jsc/bindings/**"
- "src/runtime/bake/*.cpp"
- "src/runtime/bake/*.h"
- "scripts/build/**"
- "scripts/glob-sources.ts"
- "scripts/utils.mjs"
Expand Down
4 changes: 2 additions & 2 deletions src/runtime/bake/BakeSourceProvider.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ extern "C" JSC::JSPromise* BakeLoadModuleByKey(GlobalObject* global, JSC::JSStri
return JSC::loadAndEvaluateModule(global, key->getString(global), nullptr, nullptr);
}

extern "C" JSC::EncodedJSValue BakeLoadServerHmrPatch(GlobalObject* global, BunString source) {
extern "C" JSC::EncodedJSValue BakeLoadServerHmrPatch(JSC::JSGlobalObject* global, BunString source) {
JSC::VM&vm = global->vm();
auto scope = DECLARE_THROW_SCOPE(vm);

Expand All @@ -80,7 +80,7 @@ extern "C" JSC::EncodedJSValue BakeLoadServerHmrPatch(GlobalObject* global, BunS
return JSC::JSValue::encode(result);
}

extern "C" JSC::EncodedJSValue BakeLoadServerHmrPatchWithSourceMap(GlobalObject* global, BunString source, const char* sourceMapJSONPtr, size_t sourceMapJSONLength) {
extern "C" JSC::EncodedJSValue BakeLoadServerHmrPatchWithSourceMap(JSC::JSGlobalObject* global, BunString source, const char* sourceMapJSONPtr, size_t sourceMapJSONLength) {
JSC::VM&vm = global->vm();
auto scope = DECLARE_THROW_SCOPE(vm);

Expand Down
111 changes: 111 additions & 0 deletions test/internal/source-lints/bake-global-object-ffi.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { Glob } from "bun";
import { expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import path from "node:path";

// `Bake::GlobalObject` (src/runtime/bake/BakeGlobalObject.h) is the global of a
// `bun build --app` production build: `BakeCreateProdGlobal` is the only thing
// that creates one, and it adds `m_perThreadData` on top of `Zig::GlobalObject`.
// The dev server runs inside the ordinary runtime VM, whose global is a plain
// `Zig::GlobalObject`.
//
// An `extern "C"` entry point in src/runtime/bake/ whose parameter is typed
// `GlobalObject*` (`Bake::GlobalObject*`, since these files sit in
// `namespace Bake`) therefore claims that every caller passes a production
// global. Nothing checks that claim at the boundary: the Rust bindings all spell
// the parameter `&JSGlobalObject`, so a dev-server caller compiles, and the C++
// body reads a `Zig::GlobalObject` as if it were the larger `Bake::GlobalObject`.
//
// Motivating instance: `BakeLoadServerHmrPatch` and
// `BakeLoadServerHmrPatchWithSourceMap` (src/runtime/bake/BakeSourceProvider.cpp)
// took `GlobalObject*` while their only callers were in
// src/runtime/bake/DevServer.rs. Entry points reachable from the dev server take
// `JSC::JSGlobalObject*`, like `BakeLoadInitialServerCode` next to them.
//
// The lint: every bake `extern "C"` function with a `Bake::GlobalObject*`
// parameter may only be bound (`fn Name(..)` in an extern block, `#[link_name]`,
// or a `HOST_EXPORT` marker) from the Rust files listed below, which are the
// ones whose global really is a production global. Recognized C++ shape: one
// `extern "C" <ret> Name(...)` declaration or definition per function, which is
// how every entry point in src/runtime/bake/ is written.

const root = path.resolve(import.meta.dir, "..", "..", "..");
const bakeDir = "src/runtime/bake";

const PRODUCTION_GLOBAL_RUST_FILES = new Set(["src/runtime/bake/production.rs"]);

const EXTERN_C_FUNCTION = /extern\s+"C"\s+[^;{}()]*?\b(\w+)\s*\(/g;
// `GlobalObject*`, `Bake::GlobalObject*` or `::Bake::GlobalObject*` (also by
// reference). The lookbehind rejects `JSC::JSGlobalObject*` and
// `Zig::GlobalObject*`, which every global satisfies.
const BAKE_GLOBAL_PARAM = /(?<![\w:])(?:(?:::)?Bake::)?GlobalObject\s*(?:const\s*)?[*&]/;

function stripLineComments(source: string): string {
// `[ \t]*`, not `\s*`, so blank lines survive and line numbers stay right.
return source.replace(/^[ \t]*\/\/.*$/gm, "");
}

function lineOf(source: string, index: number): number {
return source.slice(0, index).split("\n").length;
}

function* readSources(dir: string, pattern: string): Generator<{ file: string; source: string }> {
for (const rel of new Glob(pattern).scanSync({ cwd: path.join(root, dir) })) {
const file = path.posix.join(dir, rel.replaceAll(path.sep, "/"));
yield { file, source: stripLineComments(readFileSync(path.join(root, file), "utf8")) };
}

Check warning on line 56 in test/internal/source-lints/bake-global-object-ffi.test.ts

View check run for this annotation

Claude / Claude Code Review

HOST_EXPORT arm of RUST_BINDING is dead — stripLineComments removes the markers

The `HOST_EXPORT` arm of `RUST_BINDING` is dead code: `readSources()` unconditionally applies `stripLineComments` (line 55) to Rust sources too, but every `HOST_EXPORT(...)` marker in the repo is a `//` line comment at column 0 (generate-host-exports.ts's own scraper regex requires `^\s*//\s*HOST_EXPORT`), so the markers are stripped before the regex runs. Either skip `stripLineComments` for the `.rs` scan, or drop the `HOST_EXPORT` alternative and its mention in the doc comment at line 27.
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
}

// C++ function name -> where it is declared with a `Bake::GlobalObject*` parameter.
const declaredAt = new Map<string, string[]>();
let scannedCxx = 0;
for (const { file, source } of readSources(bakeDir, "*.{cpp,h}")) {
scannedCxx++;
for (const m of source.matchAll(EXTERN_C_FUNCTION)) {
const paramsStart = m.index + m[0].length;
let depth = 1;
let i = paramsStart;
for (; i < source.length && depth > 0; i++) {
if (source[i] === "(") depth++;
else if (source[i] === ")") depth--;
}
if (!BAKE_GLOBAL_PARAM.test(source.slice(paramsStart, i - 1))) continue;
const name = m[1];
declaredAt.set(name, [...(declaredAt.get(name) ?? []), `${file}:${lineOf(source, m.index)}`]);
}
}

const names = [...declaredAt.keys()].sort();
const offenders: string[] = [];
const boundFromProduction: string[] = [];
if (names.length > 0) {
const alternatives = names.join("|");
const RUST_BINDING = new RegExp(
String.raw`\bfn\s+(${alternatives})\s*\(|\blink_name\s*=\s*"(${alternatives})"|\bHOST_EXPORT\(\s*(${alternatives})\b`,
"g",
);
for (const { file, source } of readSources("src", "**/*.rs")) {
for (const m of source.matchAll(RUST_BINDING)) {
const name = m[1] ?? m[2] ?? m[3];
const entry = `${file}:${lineOf(source, m.index)}: ${name} (takes Bake::GlobalObject* at ${declaredAt.get(name)!.join(", ")})`;
(PRODUCTION_GLOBAL_RUST_FILES.has(file) ? boundFromProduction : offenders).push(entry);
}
}
}
offenders.sort();

test("scans the bake C++ sources", () => {
expect(scannedCxx).toBeGreaterThan(0);
});

test("the pattern still recognizes entry points that take Bake::GlobalObject*", () => {
// If this goes empty, either the last such entry point was retyped (then
// delete this lint) or the declarations no longer match EXTERN_C_FUNCTION.
expect(names).not.toBeEmpty();
// Same for the Rust side of the match: the production build binds these.
expect(boundFromProduction).not.toBeEmpty();
});

test("entry points that take Bake::GlobalObject* are only bound by the production build", () => {
expect(offenders).toEqual([]);
});