Skip to content

Installs fine, runs out of RAM: balancing a Java Card applet suite on the J3R452

Monoid is a set of Java Card applets I work on. Identity holds the card identity, the Secret PIN and the Bundle; Monoid manages keys, data and the Access PIN; Security Key implements FIDO2; an OTP applet that computes TOTP codes came later. The last three share one library package, and they call each other through a Shareable Interface. The suite had already passed its full flow on a D321 card. Moved to a J3R452 (D600), with all four CAP files byte-for-byte identical, LOAD and INSTALL succeeded — and the first Hello came back with an internal error. A diagnostic build named the cause: SystemException.NO_TRANSIENT_SPACE, raised while checking whether a PIN had been set.

This post is what the following rounds of debugging taught me: how Java Card accounts for RAM, why “a power cycle clears RAM” and “there’s plenty left when the command ends” are both unreliable intuitions, which buffers moved to persistent memory, and what it cost when the wrong things moved.

Every RAM figure here comes from a read-only probe command that calls JCSystem.getAvailableMemory for MEMORY_TYPE_TRANSIENT_RESET and MEMORY_TYPE_TRANSIENT_DESELECT, written as RESET/DESELECT, for example 519/512 B. The probe allocates nothing and never requests object deletion. It reports what is free at the moment of the call, not a peak.

The two readings must not be added together. On the D321 card, allocating four 256 B arrays — CLEAR_ON_RESET, CLEAR_ON_DESELECT or global (JCSystem.makeGlobalArray) — and then reclaiming them restores 1024 B in both readings, plus 64 B of persistent memory. On this card the two views look at the same pool of RAM, and each transient array also costs about 16 B of persistent memory. The specification does not require this; it is measured behaviour.

Timings are complete command times measured on the host through PC/SC, including GET RESPONSE continuations and excluding host-side signature verification and logging. The D321 card ran on an ACR1552 contactless reader and the J3R452 on an ACR39U contact reader, so absolute timings across the two cards are not comparable.

In the benchmarks, a J3R452 cleaned down to its platform packages has about 4.6 KB of transient memory available. That is the budget for the whole card, not a per-applet allowance. On the cards measured, a transient array that an applet allocates in its constructor holds its share from installation onward, whether or not the applet is selected.

A later test put a number on it. On the same J3R452, with the test layout installed next to an earlier deployment of Monoid, the starting reading was 273/336 B; after the old Identity, Monoid and Security Key were deleted, it was 1417/1408 B. When the card first failed, it carried the vendor’s packages and that older deployment in addition to the four test packages.

LOAD and INSTALL only prove that the code and the constructor allocations fit. Objects created on demand at run time, and buffers allocated halfway through a command, are never exercised by installation.

RAM you allocate does not come back by itself

Section titled “RAM you allocate does not come back by itself”

Java Card does not promise automatic garbage collection. new, makeTransientByteArray and makeGlobalArray all allocate. Once an object is unreachable, its space returns only when the runtime runs object deletion, and that happens only after the applet calls JCSystem.requestObjectDeletion(). In the specification’s words the call merely logs a request; the runtime must schedule deletion before the next invocation of Applet.process().

A common intuition is that a power cycle wipes RAM. To check it, I ran the same experiment on the D321 card for four kinds of array: allocate four 256 B arrays and drop the references, without requesting deletion; reselect; then cycle the RF field for real twice (field off for 2 seconds, then on).

A real power cycle needs evidence. A PC/SC disconnect and reconnect, or a fresh SELECT, is not a power cycle. Before each cycle the applet wrote A5 into a RESET array and 5A into a DESELECT array, and after power-up the RESET marker had to read 00 for the cycle to count. A reselect-only control keeps A5 and clears 5A, so the two events can be told apart. Across the four groups there were 33 power cycles, each with that proof.

Results:

Array kind References dropped, no request, two power cycles Next APDU after a deletion request
CLEAR_ON_RESET space not recovered +1024 B in both RAM readings, +64 B persistent
CLEAR_ON_DESELECT space not recovered same
global space not recovered same
persistent space not recovered +1088 B persistent, RAM readings unchanged

A second control kept the reference. A RESET array was written with 6D; after a power cycle its content read 00, but its space was still taken, and requesting deletion did not free it either, because it was still reachable. A power cycle clears contents, not allocations.

One observation remains unexplained: the first empty power cycle after installation moved the readings from 1681/1776 B to 1470/1552 B, and they were stable after that. Its source was not located, so it was isolated and kept out of the table above.

What happens with no deletion requests at all? I built a variant with all 21 requestObjectDeletion() calls disabled. The sixth command of initialization failed with NO_TRANSIENT_SPACE, with RAM readings down to 12/0 B. The unmodified build, on the same card, completed 512 replacements and 128 delete-and-recreate cycles with stable readings.

Allocations also pile up within a single command. Monoid’s SetGrant runs several groups of security checks, three rounds each, and every round re-obtained Identity’s Shareable reference and with it a 32 B global copy of a token — 24 copies by the end of the command. Obtaining the reference once per group and reusing it (all three comparison rounds still run) brought that down to 8. Each copy is tiny, but none of them is returned before the command ends.

A deletion request has a cost. On the D321 card I compared the same warmed-up FIDO getAssertion with no request, and with a request in a finally block after the call that sends the response. Twenty ABBA/BAAB-interleaved pairs:

Mode Samples Assertion mean Following GetInfo mean
no request 40 245.8 ms 34.08 ms
request after sending 40 305.3 ms 34.08 ms
request before sending 8 303.9 ms 34.12 ms

The paired difference averaged 59.5 ms (median 58.6 ms, range 55.8–64.4 ms). The GetInfo that followed did not slow down at all: the cost did not move to the next command, it landed on this response.

Putting the request after the send call does not help, and the APDU interface explains why. setOutgoingAndSend explicitly allows the actual transmission to wait until process() returns, and sendBytes / sendBytesLong may send the last piece of data together with the status word. An applet cannot flush the status word and keep running, and it gets no callback when the response has been delivered. The specification only requires deletion to happen before the next process(); when exactly is up to the runtime, and on this card the cost was paid before the client had the complete response.

In the end I accepted the roughly 60 ms: every complete CTAP command requests deletion when it finishes, instead of maintaining state just to know whether a command left garbage behind. Pure request chunks and GET RESPONSE continuations make no extra request.

Back to the J3R452. The four CAP files were byte-for-byte identical to the ones that passed the full flow on the D321, installation succeeded, and the first Hello of initialization returned Monoid’s CBOR error code INTERNAL (the status word was still 9000).

A diagnostic build with exception tracing located it: Hello threw SystemException with reason 2, NO_TRANSIENT_SPACE, while checking whether the Secret PIN had been set. Readings were 403/432 B before that Hello and 226/256 B after it failed. An immediate second Hello succeeded. Looking only at the second one, you would conclude the card is fine. When testing a cold start, the first failure is the result; warming up must not be allowed to paper over it.

Setting the Secret PIN failed the same way, with reason 2. The full layout could not even finish initialization.

Removing the test Security Key left Identity, Monoid and the library. Readings rose to 519/512 B, and PIN setup plus reads and writes of 64 B items passed. Then creating a 600 B item returned INTERNAL again, and a non-empty List and the first Ed25519 signature failed as well. With more than 500 bytes free at the end of each command, why would a 600 B request not fit?

The answer is in the middle of the command. The 600 B Create encodes to 666 B, sent in chunks of 255, 255 and 156 B. I inserted a read-only probe between chunks; it does not end the command, clear the transport state or request deletion:

Sampled Original RESET/DESELECT Changed RESET/DESELECT
before Create 519/512 B 519/512 B
after chunk 1 263/256 B 519/512 B
after chunk 2 7/0 B 519/512 B
after the last chunk 519/512 B 519/512 B

The original receive buffer used transient arrays for its first 512 B, so after two chunks only 7/0 B of RAM was left. The last chunk failed, the end-of-command deletion ran, and the readings were back at 519/512 B. Sampling only before and after the command would never show those 512 B. That run had no exception tracing, so the exact exception on the last chunk was not confirmed, but once those 512 B were changed the same request succeeded.

The change: a single complete short APDU still borrows the APDU buffer directly; a chunked request allocates a 256 B persistent array per chunk, only when needed.

byte[] chunk = (byte[]) chunks[chunkIndex];
if (chunk == null) {
chunk = new byte[CHUNK_LENGTH]; // 256 B, persistent, allocated on first use
chunks[chunkIndex] = chunk;
}
Util.arrayCopyNonAtomic(input, offset, chunk, chunkOffset, chunkLength);

With the change, RAM stayed at 519/512 B through all three chunks, the first two chunks took 544 B of persistent memory instead (256 B plus 16 B each), and Create succeeded. The cost was 6.6 ms over those two chunks (177.8 → 184.5 ms).

With receiving fixed, the first Get of the same item failed. The response side has the same shape: a streamed response allocated a 512 B transient window (a 256 B chunk plus a 256 B maximum output unit). That failure was not traced either; after the window also became an on-demand persistent array, the 600 B response went out in pieces of 256, 256 and 97 B, RAM stayed at 519/512 B throughout, and persistent usage rose by 548 B temporarily and recovered after the last piece. Reads and writes of 600 B and 1536 B items, and List, all passed.

Receiving and responding need to be checked separately. Fix one and the other still fails on the same item.

With chunked I/O fixed, the full four-package layout still failed on its first Hello. Tracing again showed 29/48 B of RAM left near the failure. In the standalone layout, the Ed25519 signature failed while allocating a 32 B transient response array, with 23/16 B left. Private key expansion and the public key computation had already finished, so this was not an algorithm incompatibility; the last few bytes of RAM were simply missing.

What remained was to go through the transient allocations one by one and reclassify them by a single rule:

  • Private data that is rarely written goes to persistent memory. Signature results, public keys, expanded private keys, input that has been read, metadata, credential working data, intermediate derivation results, algorithm contexts.
  • State whose lifetime carries security meaning stays in RAM. Whether an authorization is valid, cursors, session state — these must clear themselves on reset or deselect.
  • Scratch space for hot arithmetic stays in RAM. Big-number arithmetic and the Ed25519 and BIP340 working areas are rewritten over and over in every operation.
  • Global arrays that must cross applet boundaries stay.

Some of the specific changes: the 128 B pad for software HMAC-SHA512 is now created on demand by one shared engine and reused; Identity reuses a single 64 B HMAC pad; BIP32 keeps only the 32 B parent private key it needs; the 65 B uncompressed point that precedes a compressed public key no longer occupies RAM each time; two AES keys became persistent key objects; and when a Bundle response is passed from Identity to Monoid, the destination is already the APDU buffer, so it is written there directly through the Shareable call, removing an intermediate global array.

Two of the traps along the way were not about RAM, and they deserve a mention:

  • KeyBuilder lengths are in bits. A 64 B key for native HMAC-SHA512 has to be built as 512 bits. Getting this wrong made the derivation path throw CryptoException with reason 1 (ILLEGAL_VALUE), which is easy to lump in with the memory errors surrounding it. The same unit error once had the benchmark report the D600 card as having no HMAC (see the methodology).
  • A failed response does not mean nothing happened. Once, creating a Bundle, the client received INTERNAL, and the trace showed NO_TRANSIENT_SPACE before the complete response went out — yet a read-only Hello showed the Bundle had been created. The state had been committed before the response. After a failure like that, read the state before deciding to retry.

The final version completed the whole flow in a single installation of all four packages: cold initialization; 6 FIDO registrations and 43 assertions; 28 Ed25519 and 22 EC/BIP340 signatures, every one verified independently on the host; reads and writes of 64/600/1536 B items; creating and joining a three-member Bundle (the other two members were software peers on the host, not physical cards); then signing again and resetting again. No package was removed along the way to free memory, and the applications already on the card were left alone. After the communication resources were initialized, RAM readings held at 771/784 B — still a boundary reading, not a peak.

Persistent memory is not free. In the benchmark, a RAM read or write takes about 90 µs and a persistent read about the same, but changing one persistent byte takes about 2.9 ms and a 64 B arrayCopy about 3.3 ms, most of it page programming. Data written once per command barely notices the move. A working area rewritten inside a loop pays thirty times more.

The first version of the OTP applet ran straight into this. On the D321 card its software HMAC kept the pad in a persistent array and rewrote it byte by byte, and each code’s dynamic truncation also rewrote a 4 B persistent working area. Computing 16 accounts with 3 time windows each, 48 codes, took 25.25 seconds. Each HMAC rewrites over a hundred pad bytes one at a time; at roughly 2.9 ms per byte that is a few tenths of a second, and the first version needed 1.4–2.4 seconds for one account’s 3 codes, so the magnitude fits. That is only an order-of-magnitude check, not a separate measurement.

The fix: prefer the native HMAC and fall back to software when the factory reports it unsupported (on this card, at least the native SHA-256 HMAC is unsupported); give the software pad a 128 B RESET array created on demand and reused; and give truncation a 4 B DESELECT array reused for the whole batch. Ordinary input and output stay in persistent memory. Same card, same data:

Calculate First version Changed Change
SHA-1, 1 account, 3 codes 1381.7 ms 462.3 ms −66.5%
SHA-256, 1 account, 3 codes 1489.4 ms 476.3 ms −68.0%
SHA-512, 1 account, 3 codes 2353.1 ms 526.8 ms −77.6%
3 accounts, 9 codes 4858.4 ms 1056.0 ms −78.3%
16 accounts, 48 codes 25251.3 ms 5373.7 ms −78.7%

Both changes were measured together, and the runs did not record which HMAC backend actually executed, so the gain cannot be split between “native HMAC” and “RAM working area”.

On the J3R452 the native HMAC brought a RAM problem of its own. After the SHA-1 and SHA-256 codes had been computed, the first SHA-512 window failed, and the trace showed Signature.getInstance itself throwing NO_TRANSIENT_SPACE, with readings at 500/1232 B. A candidate that caught the exception at the factory and fell back to software computed correct codes, but in the warm state only 262/256 B were left, and the final Hello still failed.

The final implementation does without a native HMAC object altogether. It composes HMAC from the native MessageDigest, with all three algorithms sharing one 128 B RESET pad:

if (block == null) {
block = JCSystem.makeTransientByteArray((short) 128, JCSystem.CLEAR_ON_RESET);
}
Util.arrayFillNonAtomic(block, (short) 0, blockLength, (byte) 0x36);
for (short index = 0; index < keyLength; index++) {
block[index] ^= normalized[index];
}
digest.update(block, (short) 0, blockLength);
digest.doFinal(message, offset, length, result, (short) 0);
for (short index = 0; index < blockLength; index++) {
block[index] ^= (byte) (0x36 ^ 0x5C);
}
digest.update(block, (short) 0, blockLength);
digest.doFinal(result, (short) 0, outputLength, result, (short) 0);

The pad is rewritten byte by byte on every call, so it lives in RAM; the 64 B result is only written whole, twice per call, so it lives in a persistent array. With all three algorithms warmed up, readings held at 562/560 B, about 300 B more than the native-first candidate. On the J3R452 one account’s 3 codes take about 0.66–0.74 seconds, and 16 accounts’ 48 codes about 7.5–7.8 seconds. Those numbers come from a different card, a different reader and a later data model, so don’t compare them with the D321 table above.

  • Cards: the deletion and deletion-cost experiments ran on the D321 card; the layout problems and the final acceptance run were on the J3R452. Their behaviour is the project’s measured baseline, not a guarantee of the specification, and says nothing about models that were never tested.
  • Readings: every RAM figure is what was free at the moment of sampling, not a continuous peak; RESET and DESELECT must not be added.
  • Timings: complete command times on the host, including reader and protocol overhead — not pure on-card computation, and not what a phone user experiences. Sample counts are in each table; some are in single digits.
  • The roughly 60 ms deletion cost comes from one warmed-up single-response assertion. It is not a fixed per-command cost, and a complete sign-in involves several commands, so it can add up.

Looking back, most of these rounds changed not the algorithms but when a piece of memory is allocated, who is using it and when it is given back. A few lessons:

  • A successful install only proves that the constructors fit. Test the first command after a fresh install, and record the first failure instead of warming up past it.
  • End-of-command readings hide what happens in the middle. When a command is suspect, sample inside it.
  • Every object a command allocates stays allocated until deletion is requested — a power cycle does not change that. On this card a request costs about 60 ms, and it lands on the current response.
  • Decide between RAM and persistent memory by write frequency and lifetime semantics, not by size. Data written once can live in persistent memory; a working area rewritten in a loop belongs in RAM.
  • When a response fails, the state may already be committed. Read it before retrying.

The code is at vilicvane/monoid-javacard. The shared receive and send layer is in monoidlib/CBORApduReader.java and CBORApduWriter.java, and the HMAC is in monoid/HMAC.java.