Limits and safety¶
Running someone else's script means it might not stop. This page is about that.
Stop a script that will not return¶
KiteJs(Rhino) { instructionBudget = 5_000_000 }.use { js ->
js.evaluate("while (true) {}") // throws JsEngineError
}
The engine counts interpreter instructions. When one call passes the budget it gives up and
throws JsEngineError. Each call gets the budget again, so a long session is not punished for
what an earlier call did. A call here is evaluate, runMicrotasks, or a call into a
JsFunction from Kotlin, and its budget covers the Promise reactions it queues as well: a chain
of reactions that each queue the next is stopped like a loop is.
When the engine stops a script, the reactions it left queued are dropped with it, so the abandoned work does not carry on in the next call. V8 does the same when it terminates a script during its own microtask checkpoint.
There is no right number for every case. Measure your own scripts and leave room:
| Script | Roughly |
|---|---|
| An arithmetic expression | under 1,000 |
| A loop over a hundred items with a callback | tens of thousands |
| Parsing and transforming a large JSON document | millions |
Zero, the default, means no limit.
Stop it on your own signal¶
val deadline = TimeSource.Monotonic.markNow() + 2.seconds
KiteJs(Rhino) { interruptWhen = { deadline.hasPassedNow() } }.use { js ->
js.evaluate(untrustedScript)
}
The hook is asked from inside the running script every hundred thousand instructions or so, Promise reactions included. Answer true and the script stops, dropping the reactions it left queued, as the budget does. Setting the hook turns the check on even with no budget.
Use this for a deadline, a stop button, or a cancelled coroutine. asyncKiteJs uses it for
exactly that, and it chains: whatever you set is still asked.
Take away what a sandbox does not need¶
KiteJs(Rhino) {
safeBuiltins = true // leaves out the built-ins a sandbox does not want
sealBuiltins = true // a script cannot replace Array.prototype.push
console = null // no console at all
}
Sealing matters more than it sounds. Without it, one script can redefine Array.prototype.push
and the next script in the same engine gets the redefined one.
Memory¶
On QuickJS, set memoryLimit and a script that outgrows it ends the call with a
JsEngineError, even when the script tries to catch it, and the engine stays usable:
Rhino has no memory budget. A script that builds an ever larger array will exhaust the heap, and the engine cannot stop it. If that is a real risk for you, use QuickJS, or run the engine in a process or a worker you can kill.
Weak collections on Rhino are the one place memory behaves differently by target:
| Target | WeakMap and WeakSet |
|---|---|
| JVM, Android, iOS, macOS, Linux, Windows | An entry is released when its key is collected, even when the value refers back to the key |
| JavaScript | Same, on any runtime with WeakRef, which is every current one |
| WebAssembly | An entry is released with its key, but a dropped map stays reachable from its live keys |
Entries are stored on their keys rather than in the map, which is why a value that points back
at its key, such as cache.set(node, { node }), does not keep the key alive. Upstream Rhino keeps
such entries for as long as the map lives. The other side of that layout is that a map you drop
while its keys live on leaves its entry on each key until the key is next used as a WeakMap or
WeakSet key, or is collected itself.
No script can tell the difference, because a WeakMap has no iteration and no size. The cost on
WebAssembly is memory, not behaviour. WeakRef.isWeakSupported answers false there if your host
code needs to know.
A script's WeakRef and FinalizationRegistry follow the same rule. Where the target releases
weak keys, deref() answers undefined once the target is collected, and the registry's cleanup
callback runs when the engine next drains its job queue. Collection is never promised, so a script
must not depend on either. On WebAssembly a target is never released.
Speed¶
Both engines interpret. QuickJS, being C, ran between 3 and 12 times faster than Rhino on the JVM across loops, string building, property writes, recursion and sorting; the rest of this section is about Rhino.
Rhino interprets. It does not compile to bytecode or machine code, because iOS does not allow that and the port keeps one behaviour everywhere.
Measured against Mozilla Rhino's own interpreter on the JVM, KiteJS runs the same scripts about 1.0 to 2.0 times slower depending on the work: parsing is at parity, array and JSON methods are within 20 percent, and a tight arithmetic loop is about twice as slow.
For scripting a document, evaluating a rule, or transforming data, that is not the part of your program you will be waiting on. For a numeric inner loop over millions of iterations, write it in Kotlin and bind it.
One engine per thread¶
An engine belongs to the thread that opened it. On Rhino, opening a second engine on that same
thread throws a JsEngineError that says so, rather than quietly sharing the first one's state.
QuickJS keeps each engine's state apart, so one thread can hold several of its engines.
Each thread has its own slot, so two threads can hold two engines at once, and neither sees the other's global scope. A program that runs several documents gives each document a thread.
Only that thread can use or close the engine. From another thread, evaluate, close and the
rest throw JsEngineError and leave the engine as it was.
The objects, arrays and functions an engine hands out belong to it in the same way. They work
while the engine is open and on its thread, they throw JsEngineError once it is closed or from
another thread, before any script can run, and they cannot be handed to a different engine.
Numbers, strings, booleans, BigInts, null and undefined are copies and work anywhere. A handle's
toString() never throws: where its engine cannot be used it prints the object's class.
JavaScript and WebAssembly run one thread, so there Rhino holds one engine at a time and QuickJS holds
as many as you open. JsEngine.oneEnginePerThread says which kind an engine is.
Use asyncKiteJs when you want the calls serialised for you on a thread of its own.
Errors from a script cannot break the engine¶
A script that throws leaves the engine usable. So does one that runs out of budget.
KiteJs(Rhino) { instructionBudget = 100_000 }.use { js ->
runCatching { js.evaluate("for (;;) {}") }
js.evaluate("1 + 2").asInt() // 3, the engine is fine
}
Global state the script already changed is still changed. If you need a clean slate, build a new engine.