Skip to content

Add Scripts helper classes #109

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Aug 5, 2025
Merged
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
266 changes: 145 additions & 121 deletions JetStreamDriver.js
Original file line number Diff line number Diff line change
Expand Up @@ -312,56 +312,6 @@ class Driver {
}
}

runCode(string) {
if (!isInBrowser) {
const scripts = string;
let globalObject;
let realm;
if (isD8) {
realm = Realm.createAllowCrossRealmAccess();
globalObject = Realm.global(realm);
globalObject.loadString = function(s) {
return Realm.eval(realm, s);
};
globalObject.readFile = read;
} else if (isSpiderMonkey) {
globalObject = newGlobal();
globalObject.loadString = globalObject.evaluate;
globalObject.readFile = globalObject.readRelativeToScript;
} else
globalObject = runString("");

globalObject.console = {
log: globalObject.print,
warn: (e) => { print("Warn: " + e); },
error: (e) => { print("Error: " + e); },
debug: (e) => { print("Debug: " + e); },
};

globalObject.self = globalObject;
globalObject.top = {
currentResolve,
currentReject
};

globalObject.performance ??= performance;
for (const script of scripts)
globalObject.loadString(script);

return isD8 ? realm : globalObject;
}

const magic = document.getElementById("magic");
magic.contentDocument.body.textContent = "";
magic.contentDocument.body.innerHTML = "<iframe id=\"magicframe\" frameborder=\"0\">";

const magicFrame = magic.contentDocument.getElementById("magicframe");
magicFrame.contentDocument.open();
magicFrame.contentDocument.write(`<!DOCTYPE html><head><title>benchmark payload</title></head><body>\n${string}</body></html>`);

return magicFrame;
}

prepareToRun() {
this.benchmarks.sort((a, b) => a.plan.name.toLowerCase() < b.plan.name.toLowerCase() ? 1 : -1);

Expand Down Expand Up @@ -578,6 +528,140 @@ const BenchmarkState = Object.freeze({
DONE: "DONE"
})


class Scripts {
constructor() {
this.scripts = [];
this.add(`
const isInBrowser = ${isInBrowser};
const isD8 = ${isD8};
if (typeof performance.mark === 'undefined') {
performance.mark = function(name) { return { name }};
}
if (typeof performance.measure === 'undefined') {
performance.measure = function() {};
}
`);
}

run() {
throw new Error("Subclasses need to implement this");
}

add(text) {
throw new Error("Subclasses need to implement this");
}

addWithURL(url) {
throw new Error("addWithURL not supported");
}

addDeterministicRandom() {
this.add(`(() => {
const initialSeed = 49734321;
let seed = initialSeed;

Math.random = () => {
// Robert Jenkins' 32 bit integer hash function.
seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffff_ffff;
seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffff_ffff;
seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffff_ffff;
seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffff_ffff;
seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffff_ffff;
seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffff_ffff;
// Note that Math.random should return a value that is
// greater than or equal to 0 and less than 1. Here, we
// cast to uint32 first then divided by 2^32 for double.
return (seed >>> 0) / 0x1_0000_0000;
};

Math.random.__resetSeed = () => {
seed = initialSeed;
};
})();`);
}
}

class ShellScripts extends Scripts {
run() {
let globalObject;
let realm;
if (isD8) {
realm = Realm.createAllowCrossRealmAccess();
globalObject = Realm.global(realm);
globalObject.loadString = function(s) {
return Realm.eval(realm, s);
};
globalObject.readFile = read;
} else if (isSpiderMonkey) {
globalObject = newGlobal();
globalObject.loadString = globalObject.evaluate;
globalObject.readFile = globalObject.readRelativeToScript;
} else
globalObject = runString("");

globalObject.console = {
log: globalObject.print,
warn: (e) => { print("Warn: " + e); },
error: (e) => { print("Error: " + e); },
debug: (e) => { print("Debug: " + e); },
};

globalObject.self = globalObject;
globalObject.top = {
currentResolve,
currentReject
};

globalObject.performance ??= performance;
for (const script of this.scripts)
globalObject.loadString(script);

return isD8 ? realm : globalObject;
}

add(text) {
this.scripts.push(text);
}

addWithURL(url) {
assert(false, "Should not reach here in CLI");
}
}

class BrowserScripts extends Scripts {
constructor() {
super();
this.add("window.onerror = top.currentReject;");
}

run() {
const string = this.scripts.join("\n");
const magic = document.getElementById("magic");
magic.contentDocument.body.textContent = "";
magic.contentDocument.body.innerHTML = `<iframe id="magicframe" frameborder="0">`;

const magicFrame = magic.contentDocument.getElementById("magicframe");
magicFrame.contentDocument.open();
magicFrame.contentDocument.write(`<!DOCTYPE html>
<head>
<title>benchmark payload</title>
</head>
<body>${string}</body>
</html>`);
return magicFrame;
}


add(text) {
this.scripts.push(`<script>${text}</script>`);
}

addWithURL(url) {
this.scripts.push(`<script src="${url}"></script>`);
}
}

class Benchmark {
constructor(plan)
{
Expand Down Expand Up @@ -682,98 +766,38 @@ class Benchmark {
if (this.isDone)
throw new Error(`Cannot run Benchmark ${this.name} twice`);
this._state = BenchmarkState.PREPARE;
let code;
if (isInBrowser)
code = "";
else
code = [];

const addScript = (text) => {
if (isInBrowser)
code += `<script>${text}</script>`;
else
code.push(text);
};

const addScriptWithURL = (url) => {
if (isInBrowser)
code += `<script src="${url}"></script>`;
else
assert(false, "Should not reach here in CLI");
};

addScript(`
const isInBrowser = ${isInBrowser};
const isD8 = ${isD8};
if (typeof performance.mark === 'undefined') {
performance.mark = function(name) { return { name }};
}
if (typeof performance.measure === 'undefined') {
performance.measure = function() {};
}
`);
const scripts = isInBrowser ? new BrowserScripts() : new ShellScripts();

if (!!this.plan.deterministicRandom) {
addScript(`
(() => {
const initialSeed = 49734321;
let seed = initialSeed;

Math.random = () => {
// Robert Jenkins' 32 bit integer hash function.
seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffff_ffff;
seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffff_ffff;
seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffff_ffff;
seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffff_ffff;
seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffff_ffff;
seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffff_ffff;
// Note that Math.random should return a value that is
// greater than or equal to 0 and less than 1. Here, we
// cast to uint32 first then divided by 2^32 for double.
return (seed >>> 0) / 0x1_0000_0000;
};

Math.random.__resetSeed = () => {
seed = initialSeed;
};
})();
`);
}
if (!!this.plan.deterministicRandom)
scripts.addDeterministicRandom()

if (this.plan.preload) {
let str = "";
let preloadCode = "";
for (let [ variableName, blobURLOrPath ] of this.preloads)
str += `const ${variableName} = "${blobURLOrPath}";\n`;
addScript(str);
preloadCode += `const ${variableName} = "${blobURLOrPath}";\n`;
scripts.add(preloadCode);
}

const prerunCode = this.prerunCode;
if (prerunCode)
addScript(prerunCode);
scripts.add(prerunCode);

if (!isInBrowser) {
assert(this.scripts && this.scripts.length === this.plan.files.length);

for (const text of this.scripts)
addScript(text);
scripts.add(text);
} else {
const cache = JetStream.blobDataCache;
for (const file of this.plan.files)
addScriptWithURL(cache[file].blobURL);
scripts.addWithURL(cache[file].blobURL);
}

const promise = new Promise((resolve, reject) => {
currentResolve = resolve;
currentReject = reject;
});

if (isInBrowser) {
code = `
<script> window.onerror = top.currentReject; </script>
${code}
`;
}
addScript(this.runnerCode);
scripts.add(this.runnerCode);

performance.mark(this.name);
this.startTime = performance.now();
Expand All @@ -784,7 +808,7 @@ class Benchmark {
let magicFrame;
try {
this._state = BenchmarkState.RUNNING;
magicFrame = JetStream.runCode(code);
magicFrame = scripts.run();
} catch(e) {
this._state = BenchmarkState.ERROR;
console.log("Error in runCode: ", e);
Expand Down
Loading