Cryptography is a funny thing. Alice and Bob spend years inventing protocols so that Eve cannot make sense of anything, when all they really need is to agree on whose turn it is to take out the trash.
Naturally, Opera has supported cryptography since time immemorial. Without it you cannot establish a secure connection or verify a certificate. You cannot check the integrity of your own files or protect the passwords saved in Wand.
In Opera’s source code, cryptography was the job of the modules/libcrypto module, separate from the libcrypto code that ships with OpenSSL. The reasoning behind the split is very much in Opera’s spirit: general cryptographic operations were kept apart from the big secure-connection module libssl, so that they could be used where the whole TLS stack is not needed. The module provided interfaces for the MD5, SHA-1 and SHA-256 cryptographic hashes (with HMAC on top of them—a way to verify a message’s authenticity with a shared secret key), and for AES, 3DES and RC4. Pseudorandom data came from the OpRandomGenerator object, based on a cipher from the SNOW family and fed with entropy from the environment.
We have tweaked a few things in there, but that did not change the essence. For the Web Cryptography API, this module is not enough.
What is that?
A JavaScript application may need cryptography. Even a reliable random value, even computing SHA-256, is already cryptography. Developers had to write these algorithms themselves or pull in third-party libraries. Terribly awkward and wasteful, since the browser already has much of this. All that is needed is a way to ask the browser for a ready-made function.
The first public working draft of the Web Cryptography API appeared on September 13, 2012, and it became a W3C Recommendation only a little over four years later. Adoption was not instant either: there were experimental variants, prefixes and incompatible details of behavior. The standard went through revisions, extensions and the like—but today the Web Crypto API is stable and supported by every browser.
So what is the problem, you might ask? The browser can already do almost everything; all you need is to drill a little hole between the layers. And this is where we plunge into the abyss of “yes, but…”
Yes, we can drill a hole, but that hole must not lead into the internal security system. If JS could read, say, private keys, it would be a disaster.
Yes, but if JS asks for a computation that takes thirty seconds, the browser will freeze.
Yes, but a page can request several thousand operations at once, and their queue will eat up memory before the first of them is even picked up.
Yes, but permission to use a crypto key does not necessarily mean permission to read it.
There will be plenty of such “buts.” So, as usual, it is worth looking at how the “neighbors” do it.
In Chromium, the crypto duties are split between Blink and the Web Crypto component. Blink checks the algorithm name and converts the data it is given into a form native code understands; the job goes to a worker pool, where BoringSSL (a library descended from OpenSSL) executes it and returns the result to Blink. The developers deliberately accepted the overhead of handing jobs off so that cryptography would not hold up page processing.
Firefox uses NSS, its own long-established cryptographic infrastructure. The source code shows the general scheme well: prepare the request, send the heavy part off to background execution, then return to the original thread and resolve the Promise. When the call comes from a web worker, the environment has to be kept alive separately until the result arrives, or the result may come back to “nowhere.”
On Apple platforms, WebKit relies on the system’s cryptographic facilities. The original implementation used CommonCrypto; newer code uses CryptoKit. WebKit ports can also work through OpenSSL or libgcrypt. The exact set of mechanisms changes with the platform, but the principle stays the same: the web interface sits on top of ready-made external cryptographic implementations.
So every major browser keeps its cryptography in a library. Whether the library is its own or borrowed does not change the essence.
This separation lets the cryptographic algorithms be fixed and updated on their own. The library can use CPU-specific optimizations and go through its own testing; the browser is responsible for key permissions, request lifetimes and delivering the response.
For Otium, the natural choice is OpenSSL. The library already ships with it, it is cross-platform and proven. Writing all the cryptography ourselves would mean once again dragging in and maintaining hundreds of thousands of lines of code. It is not worth it.
Time to drill.
The resulting architecture has three layers. The web layer parses the arguments, works out which algorithm the page is asking for and prepares the Promise. CryptoExecutor accepts the prepared work, accounts for resources, checks permissions, queues the tasks and arranges for their completion. Adapters call OpenSSL, directly or indirectly, knowing nothing about documents or JavaScript.
A simplified diagram:
A script Promise “promises” that the program will get an answer someday. Right away, in three seconds, or by Christmas. There are many scripts, but the browser has only one JavaScript execution thread.
With “fast” algorithms such as hashing, you can keep it simple (well, not quite simple, but I am deliberately leaving out the boring technical details and sticking to the essence): lazily create an executor, compute, hand the result to its owner. There is no real need to worry about reconciling state or cancellation here—it is quicker to wait for completion than to interrupt the work.
It is another story when the work takes a long time and has intermediate states. PBKDF2, for example, performs many iterations by design, to make brute-forcing passwords harder. You need to be able to stop the computation, save its state and hand control to the next consumer in line. And, of course, to cancel execution if it is no longer needed.
Opera had already solved this kind of problem in RSA key generation, by turning a linear computation into a state machine. The approach is repeated wherever it fits: PBKDF2 and HKDF are built as resumable sequences of standard operations on OpenSSL’s HMAC and hashes. Driving the sequence and saving intermediate states is transparent to the calling script—for the script, it is a single operation.
This works well where a computation splits more or less naturally into manageable steps. But what about the calls that do not want to be split?
Key generation, validation of imported components and other asymmetric operations can disappear “inside” OpenSSL for a long time. If this were “our” code, we could turn it into a state machine too, or come up with something else. With someone else’s library, that is not an option. For some functions OpenSSL provides callbacks that let you get the status or cancel the computation, but that is not a universal solution.
There is another problem, too. Suppose a script has sent the library a call that takes time, and the user, tired of waiting, closes the tab or even the whole browser. You could wait for the computation to finish—but then the time it takes to close depends on work nobody needs anymore. You could stop delivering the result and leave the computation running in the background, but it will go on occupying memory and library state. You could forcibly stop the thread inside the browser, but it may be holding the allocator lock or be in the middle of modifying a shared structure. Killing the thread does not roll those actions back or free the resources it holds. In a shared address space, the consequences land on the rest of the program.
The universal solution is an external helper process, a separate program standing between the browser and the library. The helper offers the browser a simple, fixed set of calls: create an RSA key, validate imported components, sign a message, verify a signature, perform an elliptic-curve operation and so on. Each of these calls maps to an OpenSSL call.
Such a process can be terminated as a whole at any moment. If the cryptography crashes, only the helper goes down, and Otium, having detected the crash, cleanly returns an error.
The helper process is launched on demand and can stay in memory to handle later requests. On Windows it talks to Otium over a private bidirectional named pipe; on Linux, over a pair of local Unix sockets created in advance.
Simplifying the logic in one place has to be paid for with complexity in another. The browser has to:
This logic now lives in the CryptoHelperBroker component, which runs on top of the OpWorkerThread abstraction.
The helper carries a different share of the complexity. It has to know when and how to cancel an operation properly (even if the response is no longer needed, the OS may still be holding read and write buffers), and what to do about duplicate requests or a crash of the browser instance that made the call. This logic differs between Windows and Linux, and even between their versions. So for now the helper requires Windows 10+ (only there are the necessary process-group controls available through a Job Object) and, on Linux, kernel 5.4+ (for working with pidfd descriptors). If these conditions are not met (or are forbidden by system policy), the helper will not work, and every request to it will return an error.
If you have been reading the previous parts carefully, you may remember OpComponentManager. It is a partly ready infrastructure with message channels that supports inter-process communication. The idea is exactly the same, yet CryptoHelperBroker does not build on OpComponentManager. Why?
Because cryptographic operations need extra guarantees that OpComponentManager does not provide. It is geared more toward passing messages between parts of the browser, whereas what was needed here was managing the executor itself: create it under OS control, stop it safely in the middle of a computation and make sure no unfinished accesses to its memory remain after it stops. In short, the existing model cannot manage the lifecycle of a child process on Windows/Linux the way this requires.
We could teach OpComponentManager to do that—but then we would have to dive into that subsystem as well, multiplying the complexity. It makes more sense to write specialized code and refactor later, once the final list of requirements is clear.
As usual, I will share one unusual case where cryptography meets JavaScript.
There is a handy thing called JWK. Its specification is rather convoluted, but in practice it is a JSON object that can contain cryptographic keys, secrets, public data and instructions for reading them. Everything to do with keys belongs to the cryptographic subsystem. Everything to do with JSON is Carakan’s. So whose responsibility is a corrupted object? And whose concern is a broken key inside a valid object? Fine, that can be sorted out.
Or here is another task: Web Crypto can encrypt one key with another and later unwrap it. The process needs a JSON parser. Carakan has one, and Carakan’s environment obviously already exists—it is the one that called Web Crypto. But that environment cannot be used, because in a JavaScript context the page has access to, it can replace JSON.parse and dump the decrypted data to the console.
So for these functions alone, a new, clean Carakan environment is needed. Creating one every time is expensive and wasteful.
Both problems are solved in one go: the first time it is needed, a separate Carakan environment is created that web pages cannot reach, and it stays around for reuse.
This worked well until I got to load testing—a scenario processing hundreds and thousands of different JWKs showed something suspiciously like a memory leak, and the garbage collector did not help at all.
It turned out that, as an optimization, Carakan keeps information about object shapes, that is, about the sets and layout of their properties. The information piles up, and from the outside it looks like a classic memory leak.
I had to add reset logic: the internal environment is restarted every 128 parses, or once the total size of parsed JWKs exceeds 65,536 UTF-16 code units.
The result so far: Otium now has the SubtleCrypto interface. A web application can ask the browser to compute a hash, encrypt data, verify a signature or create a key. A key can be passed to a web worker and saved to IndexedDB, to be used after a restart.
The implementation is not quite complete yet—1.1% of WPT tests still fail, for a number of reasons. In some places the tests diverge from the standard, in others OpenSSL’s algorithms behave slightly differently, and elsewhere something is missing in the engine itself. There is room left for optimization, but the crypto.subtle “hole” works just fine.
There is a difference between modern JS technically working and the browser being actually usable. Some sites really did start working. Some refused to work because of APIs the browser lacks. But most of them worked with errors, and every last one of them was slow and sluggish.
Both problems were expected. At the previous stage, the engine aimed only at passing the formal tests, which, for all their thoroughness, cannot cover every possible situation. Still less are they meant for measuring execution speed. And let me remind you once again that a JIT for the new specifications is still missing—I will talk about its role below.
I settled on three test suites:
Kraken 1.1 is Mozilla’s suite, in which JavaScript processes audio and images, parses JSON and performs cryptographic computations. Fourteen tests in all. Among them, for example, is an image blur: the program reads array elements over and over, computes and writes out the result. A very handy workload for seeing how much these simple actions cost the engine.
Octane 2.0 started out as a test suite for V8. It includes a Game Boy emulator, the Box2D physics engine, PDF processing, zlib compression, the TypeScript compiler and other fairly serious programs. It also takes into account some of the latency related to compilation and memory. Octane is no longer maintained or developed, but it is perfectly good for checks at the current stage.
JetStream 2.0 adds more modern JavaScript, large programs and work with the browser environment. Among other things, it includes WebAssembly, which we have to ignore for now. Newer versions of JetStream are still beyond Otium.
All three suites can be installed locally and give stable, comparable results. Speaking of which:
I remember perfectly well how, when Chrome appeared, every browser suddenly started caring about speed, even though until then the main arguments had been about rendering quality and interface conveniences, plugin support and user CSS… Being quicker than IE, which ruled the market back then, was not hard—while it was still loading, you had time to drink your coffee over the morning news.
(I could not resist a moment of the classics)
That does not mean browsers did not care how fast they were; the topic just was not the main one. Chrome kicked the door in on that sleepy scene, and that is when the race began. Fans of Chrome, Firefox and Opera flooded forums with benchmark results; every point ahead was a reason to declare their favorite browser the best, and every point behind spoiled the mood.
I miss the days when your favorite browser trailing by 1% in a benchmark was the biggest problem in the world.
I am sure nobody has done that for the last ten years. All browsers have become fast enough, and computers powerful enough, for everything to run smoothly and responsively. Edge cases like running on outdated hardware interest few people. So I have a great excuse to find out where things stand before optimization—and what comes out after.
For this I took Octane 2.0 and ran Otium 2026.10.03, Chrome 155.0.8059.84 and Firefox 158.0 in two modes, with the JIT enabled and without it.
| Otium | Otium jitless | Chrome | Chrome jitless | Firefox | Firefox jitless |
|---|---|---|---|---|---|
| 6721 | 2003 | 124217 | 10376 | 69530 | 7984 |
The absolute numbers do not matter here, since they will be different on every computer. What interests us is the ratio between them, and it is very telling. In every case the JIT speeds things up several times over, and for Chrome by an order of magnitude. Chrome’s gap is downright astonishing—it gives you an idea of how good the JIT in V8 is; in fact, it is several tightly coupled subsystems of mind-boggling complexity.
Firefox is almost half as fast, but… I am sure you would never have noticed. This speed is enough; most of the time goes to networking, parsing, style composition and painting anyway.
And now the sad part: Otium is in a sorry state. Even with its JIT, it is slower than Firefox without one.
But this is only the starting point.
To understand what can be sped up, you first need to understand how Carakan executes a program. It translates JavaScript text into bytecode—a sequence of simple commands for its virtual machine. The interpreter reads the next command, works out what needs to be done, executes it and moves on to the next one. “Take a value,” “add,” “compare,” “jump to the start of the loop”—roughly at that level.
Frequently executed sections of a program can be translated straight into machine code. That is exactly what a JIT compiler does: it watches execution, uses information about the types it encounters and builds code directly for the processor. This is especially effective for repetitive code, which can be compiled once. How effective this mechanism can be in principle, if you pour twenty years of effort by a team of top-class engineers into it, is shown in the table just above.
But a JIT is an add-on. An important one, even a necessary one. But underneath it there has to be a solid interpreter. The JIT’s correctness will be checked against its results, and the interpreter will run whatever the JIT does not understand yet.
That is where we will start.
Predictably, I ran into silly, obvious bugs—plenty of them, none surprising and none worth a story. Instead, I would first like to talk about a problem that was not obvious at all, and all the more interesting for it.
Kraken has an image-blur test, and the console jsshell ran it one and a half times faster than the browser build. The gap is too large to blame on anything outside Carakan. The test’s code and data are identical.
Tracing pointed to the global variable cache: Carakan gathers all the global variables it finds into a single store, ES_Code::GlobalCache, so that it does not have to look up their location in memory every time. But in one case the cache hit and in the other it did not, and a million “misses” add up to a noticeable delay.
The difference turned out to be in how the program was fed in. The console runner loaded the data separately and then the test code, roughly like this:
var pixels = [/* image data */];
and after it:
function blur() {
// Lots of accesses to pixels.
}
blur();
The browser version ran them as a single script:
var pixels = [/* image data */];
function blur() {
// The same accesses to pixels.
}
blur();
In the first case, the first script had time to run and create pixels by the time the second one was loaded. The engine found the variable, filled the cache, and the accesses inside blur() used the location already in place.
In the second case, the global variable pixels had not been created yet. blur() looked up its location in the code every time.
This explains the consequences but says nothing about the cause. Surely the cache should be filled lazily, on the first access to the data?
Yes, but that is not how it worked here. ES_Code::GlobalCache turned out to be not so much a cache as a table, filled once by a special preparatory pass, ES_Code::OptimizeGlobalAccessors(). The cache is never refilled after that, so the order of calls matters.
In one of the engine changes, back during the ES2015 implementation (the standard brought in new rules for creating global variables), this order changed. The regression went unnoticed because at the time there was nothing to notice it with.
Another Kraken test revealed an equally interesting problem: in the console runner, a cryptographic computation ran slower with the JIT than without it. In the browser, this did not happen.
Profiling turned up a clue: the interpreter path needed 16 MiB of memory, the JIT path 900 MiB. Why does the JIT need so much memory? To store compiled machine code, obviously.
For some reason the JIT was compiling the same function thousands of times and dutifully storing the finished code. The reason was found fairly quickly: tail calls.
Let’s look at the code:
"use strict";
function wrapper(x) {
return calculate(x);
}
After calculate(x), the wrapper function has nothing left to do but pass the result on to its caller. So its stack frame can be removed before entering calculate, and in ES2015 this behavior is a requirement.
Let’s expand the example:
"use strict";
function calculate(x) {
var sum = 0;
for (var i = 0; i < 1000; ++i) {
sum += x + i; // Hot loop
}
return sum;
}
function wrapper(x) {
return calculate(x); // Tail call.
}
for (var n = 0; n < 10000; ++n) {
wrapper(n); // Repeat the whole story many times.
}
In Carakan, a tail call always hands calculate to the interpreter, because the JIT does not support PTC. The interpreter starts executing the loop inside calculate, and on one of the iterations the heuristic that sends code to the JIT fires. The JIT successfully compiles the loop, and from then on it runs fast.
On the next call to wrapper, it all repeats: calculate lands in the interpreter again. The code has a baked-in assumption that if a function has been sent to the interpreter, no machine code has been created for it yet—and that was true until Carakan got tail calls. The interpreter requested compilation again, and the JIT obediently carried it out.
But why did not this happen in the browser?
Because the standard requires tail calls only in strict mode. Strict mode is turned on by the "use strict" directive, which has to be in a particular place, usually at the start of the script. In the browser run, the test data came before this directive, so strict mode was not turned on, and neither were tail calls.
There were several possible ways to fix this kind of situation.
— Forbid recompilation, since calculate already has machine code. But then there is a mismatch between what was compiled for PTC (the loop in calculate already partly executed by the interpreter) and for the normal path (the loop not yet started), while the JIT would treat the prepared machine code as suitable for any call. At worst, something other than what was expected gets executed; at best, the compiled code is thrown away and execution falls back entirely to slow interpretation.
— Prepare entry points into all loops in advance. Compile loops to machine code so that the interpreter can jump straight into the right iteration. A speedup for one specific situation at the cost of making the whole mechanism more complex.
— Send the tail call straight into the ready machine code. Now this is the right solution. With it, calculate never reaches the interpreter at all; the problem is that getting the JIT to work with PTC is really hard, and for now that has been put off.
The interim solution is to store the loop entry address and its position in the bytecode in the compiled block. A fairly small intervention that removes the problem until the JIT gets its big overhaul.
While optimizing, I got to thinking: we have pseudothreads that switch between pseudostacks. Otium can create as many of these pseudothreads as it likes, and when there are many of them, even a single CPU cycle of delay on each switch… okay, a single cycle won’t be noticeable, but it is still worth checking, for peace of mind.
I wrote a test that makes Carakan create lots of parallel executors, and measured the speed and the number of switches. My worries about speed were unfounded: the switching machine code is written so tightly that I could not think of a single way to make it any faster. But a problem turned up next door: the engine was making tens of millions of idle switches.
And all those switches looked identical: execution “jumps out” of the pseudothread to the main stack, runs a few do-nothing instructions and jumps back. To understand the cause, I had to figure out that “do-nothing” code.
Yes, it was the garbage collector again.
The engine can decide it is time to take out the trash based on various rules, the most obvious of which is going over the memory limit. The garbage collector always runs on the main thread with the system stack, and when the GC trigger fires, Carakan returns control from the pseudothread.
However, the engine’s internal C++ code sometimes temporarily handles objects in a way that keeps the collector from accounting for all those references correctly: for example, while a structure is still being created or rebuilt. Garbage collection is forbidden for the duration of such operations. Without going into details, the test created exactly that situation.
Carakan requested a GC, and the pseudostacks switched to the system stack. The check for whether garbage collection was allowed ran (that very “do-nothing” code), and control returned to the pseudothread. A single such switch is nothing, a speck of dust. A million of them is a significant delay even on modern processors. Moving the check into the collection request got rid of the idle switches.
Kraken’s audio test builds a table of sine values. When execution in the interpreter and in the JIT was compared, four numbers out of 2048 turned out to be different: 0.16491312048996992 versus 0.1649131204899699.
Floating-point numbers are stored approximately, so a discrepancy in the 17th decimal place is not exactly critical, but it is curious. The same computation, on the same machine—so why does the result depend on whether the JIT is on?
Well, it’s all quite simple. The interpreter called the math library, while the JIT used the x87 FSIN instruction. This processor instruction appeared back in Intel’s 80387 math coprocessors, and it computes the sine approximately. Other trigonometric functions were computed the same way (and so were logarithms and some forms of exponentiation).
You might think this is the price of speed and you can live with it. But these instructions have other documented quirks as well; in particular, they only work correctly within certain ranges of input values. The instruction simply returns the original number if it is too large. After compilation, Math.sin(1e19) returned 1e19, that is, a sine greater than one.
But here is the truly unexpected part: even within the valid ranges, FSIN turned out to be a third slower than the library call! Why, I do not know; that could be a separate investigation, and its results could yield a heuristic for when to compute trigonometry in software and when on the processor. I am not sure I will get to it; for now, all the affected math has been switched to library functions.
Every time I have to run tests in six build configurations, I ask myself whether it is worth it. Can the same code really behave differently?
Take the int type: signed, 32-bit, integer. The minimum value of a variable of this type is -2147483648. The maximum is 2147483647 (the difference comes from the need to store zero). So in C++ you can multiply any int value by -1 except -2147483648—+2147483648 simply does not exist, and such an operation leads to undefined behavior.
For the test where this came to light, GCC built code that crashed the program, but only in the release configuration. In every other case, the overflow happened to give the expected result by chance. Only one build out of six showed the problem; a build with UBSan helped find and fix several more cases like it.
This is far from everything that was touched during optimization. Separate fast paths were written for basic arithmetic, the JIT’s internal diagnostics were optimized, speed-boosting compiler flags were chosen, and a lot more was done. Here is what came out on Octane 2.0:
| Otium | Otium jitless | Otium optimized | Otium jitless optimized | Chrome | Chrome jitless | Firefox | Firefox jitless |
|---|---|---|---|---|---|---|---|
| 6721 | 2003 | 14845 | 3657 | 124217 | 10376 | 69530 | 7984 |
More than a twofold gain! Other measurements showed a steady speedup of ~26% to ~110%, depending on the OS and how the browser was launched.
It might seem that the interpreter is still relatively slow—half as fast as Firefox’s and a third as fast as Chrome’s.
First, we have not hit the limit yet. Access to environments, caching, string handling, data layout and the built-in algorithms themselves can all be improved. The API calls and DOM manipulations that JS performs were not touched at all in this round of optimization—and they can cause delays too. I have literally only skimmed the surface, while the Firefox and Chrome code has been optimized for decades.
Second, neither Chrome nor Firefox is limited to a single thread; they move everything they can (like that same garbage collector) into separate parallel executors. Otium cannot do that yet.
By my estimate, most of the remaining problems with sites working come down to the DOM. Missing properties and interfaces, events that do not work right, a whole pile of places still to be sorted out. Without that, even the most capable and fastest JavaScript is useless. It is a huge amount of work, and with my resources it will take months.
This is the stage where Otium needs contributors. If you are interested in the project, subscribe to the Telegram channel and share links to this series. Let’s make Opera great again!