Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
29 changes: 18 additions & 11 deletions core/src/main/java/com/alibaba/fastjson2/JSONReaderJSONB.java
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,8 @@ public Map<String, Object> readObject() {
len = valueType - BC_ARRAY_FIX_MIN;
}

checkArrayLen(len, offset, end);
Comment on lines 436 to +439

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] This guard sits one line below the unchecked bytes[offset] read of the array's length-type byte, so a payload truncated exactly at a BC_ARRAY header still escapes as a raw ArrayIndexOutOfBoundsException — the guard never executes for that input shape. Failure scenario: probe-verified at this commit — JSONB.parseObject(new byte[]{(byte) 0xA6, 0x4A, 0x6B, (byte) 0xA4}) throws ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4 at readObject:396 with no guard frame in the stack; JSONB.parse(new byte[]{(byte) 0xA4}) and JSONB.parseArray(new byte[]{(byte) 0xA4, 0x01, (byte) 0xA4}) AIOOBE inside readLength:197. The control probe (the declared-length overflow payload) throws JSONException through the full checkArrayLen → checkLength → throwLengthOutOfRange chain, so the guard works for its claimed case but is unreachable one byte shorter; the same class applies at the sibling inline sites (~930 readAny, ~1103 readArray). The throwing reads are pre-existing (byte-identical at the merge base) and truncation AIOOBEs exist reader-wide for every unchecked marker, so this is scoped as an adjacent follow-up — but the three sites this PR guards still leak raw AIOOBE one line above their new guards.

Suggested fix: reject before the length-type byte read — most leverage is one offset >= end check inside readLength() itself (covers the readAny/readArray callers), plus one before bytes[offset] at readObject:396 (Int32Num fast path, never calls readLength()); can land with the truncated-fix-array follow-up above since the fix shape is shared.

— qwen3.8-max via Qwen Code /review (v0.21.11)


if (len == 0) {
if ((features & Feature.UseNativeObject.mask) != 0) {
value = new ArrayList<>();
Expand Down Expand Up @@ -695,9 +697,7 @@ public Object readAny() {
}
case BC_BINARY: {
int len = readLength();
if (len < 0 || len > end - offset) {
throw new JSONException("BC_BINARY length out of range: " + len);
}
checkLength(len, offset, end, "BC_BINARY length");
byte[] binary = Arrays.copyOfRange(this.bytes, offset, offset + len);
offset += len;
return binary;
Expand Down Expand Up @@ -927,6 +927,8 @@ public Object readAny() {
? readLength()
: type - BC_ARRAY_FIX_MIN;

checkArrayLen(len, offset, end);
Comment on lines 956 to +959

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] No test exercises a truncated BC_ARRAY_FIX payload against the new inline checkArrayLen — the fix-length sub-branch of this ternary is guarded but unpinned at all three inline sites. Failure scenario: probe-verified at this commit — JSONB.parse(new byte[]{(byte) 0x9B, 0x01}) throws JSONException: array length out of range at offset 1/2: 7, available: 1 through the new guard (nothing in Issue7669 covers it), while JSONB.parseObject(new byte[]{(byte) 0x9B, 0x01}, int[].class) throws ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2, because startArray()'s fix branch (~1436-1439) returns type - BC_ARRAY_FIX_MIN with no check — the exact JSONException-vs-AIOOBE asymmetry testArrayDeclaredLengthNotAtBufferEnd pins as wrong on the guarded paths. If a future change narrows this guard into the type == BC_ARRAY arm (a plausible "optimization" — fix lengths are ≤ 15 and cannot OOM), the rejection silently reverts to AIOOBE and no test notices.

Suggested fix — pin the inline-site rejection:

assertThrows(JSONException.class, () -> JSONB.parse(new byte[]{(byte) 0x9B, 0x01}));

and extend checkArrayLen into startArray()'s fix branch so the typed path rejects with JSONException too.

— qwen3.8-max via Qwen Code /review (v0.21.11)


if (len == 0) {
if ((context.features & Feature.UseNativeObject.mask) != 0) {
return new ArrayList<>();
Expand Down Expand Up @@ -1098,6 +1100,8 @@ public List readArray() {
? readLength()
: valueType - BC_ARRAY_FIX_MIN;

checkArrayLen(len, offset, end);

if (len == 0) {
if ((context.features & Feature.UseNativeObject.mask) != 0) {
value = new ArrayList<>();
Expand Down Expand Up @@ -1461,13 +1465,20 @@ static void checkArrayLen(int len, int offset, int end) {
// `label` identifies the context in the error message (e.g. "array length",
// "BC_BIGINT length"). A declared length larger than the remaining buffer is
// malformed input and must be rejected before any pre-allocation.
// Hot/cold split (AGENTS.md MaxInlineSize gate): keep the two comparisons
// small enough to inline on every BC_ARRAY header decode; the exception
// message StringBuilder chain lives in the cold throw helper.
static void checkLength(int len, int offset, int end, String label) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] checkLength compiles to 76 bytes at the project's Java 8 source/target (measured: javac -source 8 -target 8 + javap; the pom pins maven.compiler.source/target=8 with no <release>), over double the 35-byte -XX:MaxInlineSize gate AGENTS.md asks hot-path methods to stay under, because the exception-message StringBuilder chain (~64 of the 76 bytes) lives in the same method as the two comparisons. It is called from five sites, three of them hot JSONB decode paths (readAny/readObject/readArray — once per decoded BC_ARRAY header). Note checkBigintLen shrank 52→10 bytes precisely by delegating. — Failure scenario: at 76 bytes, inlining relies on FreqInlineSize (325) plus per-site call-frequency profiling; in the interpreter and C1 tiers during warmup, and at any site whose profile stays cool, every array-length validation pays a real static call plus stack frame instead of ~9 bytes of inlined comparisons.

Fix — hot/cold split, leaving the guard at ~15–20 bytes:

static void checkLength(int len, int offset, int end, String label) {
    if (len < 0 || len > end - offset) {
        throwLengthOutOfRange(len, offset, end, label);
    }
}

static void throwLengthOutOfRange(int len, int offset, int end, String label) {
    throw new JSONException(
            label + " out of range at offset " + offset + "/" + end + ": " + len + ", available: " + (end - offset));
}

— qwen3.8-max via Qwen Code /review (v0.21.10)

if (len < 0 || len > end - offset) {
throw new JSONException(
label + " out of range at offset " + offset + "/" + end + ": " + len + ", available: " + (end - offset));
throwLengthOutOfRange(len, offset, end, label);
}
}
Comment on lines +1463 to +1467

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] The declared-length pre-allocation OOM class this PR closes for BC_ARRAY/BC_BINARY/BC_BIGINT survives at the string decode sites: string lengths read via readLength() are never checked against end - offset before allocation — readAny()'s BC_STR_ASCII branch (~968), BC_STR_UTF8 (~608, new byte[strlen << 1]), BC_STR_UTF16LE/BE (~648/663), the JDK8 path via JDKUtils.latin1StringJDK8 (new char[strlen]), readString() (~2864-2920) and readFieldName() (~3113-3188). Failure scenario: probe-verified at this commit — JSONB.parse(new byte[]{0x79, 0x48, 0x0F, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}) under -Xmx128m dies with OutOfMemoryError: Java heap space in ~95 ms: a 6-byte input declaring 268,435,455 string bytes (one under readLength()'s own 256 MB cap, which it passes) exhausts the heap; the UTF8 variant allocates strlen << 1 (~512 MB) and the JDK8 latin1 path char[strlen] (~512 MB). The allocating lines are pre-existing and untouched here — the hole is identically exploitable at the merge base — so this is filed as the next increment of the #7669 series rather than a blocker for this PR: same class, same fix shape.

Suggested fix:

checkLength(strlen, offset, end, "string length");

immediately after each strlen = readLength() at the readAny/readString/readFieldName sites, before any allocation — a declared string byte-length larger than the remaining buffer is malformed by the same invariant (rejects nothing well-formed).

— qwen3.8-max via Qwen Code /review (v0.21.11)


static void throwLengthOutOfRange(int len, int offset, int end, String label) {
throw new JSONException(
label + " out of range at offset " + offset + "/" + end + ": " + len + ", available: " + (end - offset));
}

public String error(byte type) {
StringBuilder buf = new StringBuilder();

Expand Down Expand Up @@ -3730,9 +3741,7 @@ public byte[] readBinary() {
}

int len = readLength();
if (len < 0 || len > end - offset) {
throw new JSONException("BC_BINARY length out of range: " + len);
}
checkLength(len, offset, end, "BC_BINARY length");
byte[] bytes = new byte[len];
System.arraycopy(this.bytes, offset, bytes, 0, len);
offset += len;
Expand Down Expand Up @@ -4504,9 +4513,7 @@ private BigInteger readBigInteger0(byte type) {
}
case BC_BINARY: {
int len = readInt32Value();
if (len < 0 || len > end - offset) {
throw new JSONException("BC_BINARY length out of range: " + len);
}
checkLength(len, offset, end, "BC_BINARY length");
byte[] buf = new byte[len];
System.arraycopy(this.bytes, offset, buf, 0, len);
offset += len;
Expand Down
86 changes: 86 additions & 0 deletions core/src/test/java/com/alibaba/fastjson2/issues/Issue7669.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@
import org.junit.jupiter.api.Test;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

@Tag("regression")
@Tag("jsonb")
Expand Down Expand Up @@ -189,4 +192,87 @@ public void testArrayDeclaredLengthNotAtBufferEnd() {
assertThrows(JSONException.class,
() -> JSONB.parseObject(NESTED_ARRAY_BAD_LEN, int[][].class));
}

// --- R2-1: the same declared-length pre-allocation OOM class, but through the
// untyped/nested BC_ARRAY decode paths that never call startArray():
// readAny() (default branch), readObject() (map-value branch), readArray()
// (element branch). They read the length via readLength() and pre-allocate
// new JSONArray(len)/new ArrayList(len) with no remaining-buffer check.
// This change folds the same checkLength guard into those three inline sites.

// 0xA4 = BC_ARRAY, 0x48 = BC_INT32, 0x0FFFFFFF = 268,435,455 elements
static final byte[] UNTYPED_ARRAY_MAX_LEN = {
(byte) 0xA4,
(byte) 0x48,
(byte) 0x0F, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF
};

/**
* Corrupt the first BC_ARRAY (0xA4) + BC_INT32 (0x48) length field found in
* the payload to a huge value, so the declared length vastly exceeds the
* remaining buffer. Used to exercise the untyped/nested readLength() sites.
*/
private static void corruptFirstArrayLength(byte[] bytes) {
for (int i = 0; i + 5 < bytes.length; i++) {
if ((bytes[i] & 0xFF) == 0xA4) { // BC_ARRAY
// Rewrite the array's leading byte as BC_INT32 (0x48) so the inline
// readLength() site treats it as a 4-byte length-type, then overwrite
// those 4 bytes with 0x0FFFFFFF (268,435,455) — far larger than the
// remaining buffer — to exercise the checkLength guard placed at the
// inline readLength() decode site (readObject() map-value branch).
// The corrupt target is the inner array value, not the (BC_OBJECT)
// root, because the root is never encoded as BC_ARRAY.
bytes[i + 1] = (byte) 0x48; // BC_INT32
bytes[i + 2] = (byte) 0x0F;
bytes[i + 3] = (byte) 0xFF;
bytes[i + 4] = (byte) 0xFF;
bytes[i + 5] = (byte) 0xFF;
return;
}
}
throw new IllegalStateException("BC_ARRAY not found in payload");
}

@Test
public void testUntypedArrayDeclaredLengthOOM_readAny() {
// JSONB.parse with no target type dispatches to readAny(); its BC_ARRAY
// branch reads the length via readLength() and pre-allocates
// new JSONArray(len) — now guarded by checkLength. Pin the guard's own
// message: without the guard a downstream "readAny overflow" JSONException
// would also satisfy a type-only assertion, letting the fix rot silently.
JSONException ex = assertThrows(JSONException.class, () -> JSONB.parse(UNTYPED_ARRAY_MAX_LEN));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] Every new test asserts rejection of malformed input; none asserts acceptance of VALID input through the three inline guard sites (readObject/readAny/readArray). testArrayValidPayloadStillWorks pins the exact-fit boundary (len == end - offset) only via the startArray() typed path. Failure scenario: probe-verified — exact-fit {0xA4, 0x01, 0x00} is accepted as [0] at this commit, and replacing checkArrayLen at the readAny site with a hand-rolled len < 0 || len >= end - offset off-by-one false-rejects it while ALL existing tests in this file — including the message-pinning assertion below — stay green: a future strictness off-by-one would silently break valid exact-fit arrays.

Suggested fix: add acceptance round-trips through the three inline sites asserting values — JSONB.parse on an encoded exact-fit array, JSONB.parseObject(bytes) on a map with a valid array value, JSONB.parseArray on a valid nested array. (Exact fit is reachable at the readAny/readArray sites only; at the readObject site the trailing BC_OBJECT_END byte keeps remaining = len + 1, so pin it with a near-boundary payload there.)

— qwen3.8-max via Qwen Code /review (v0.21.11)

assertTrue(ex.getMessage().contains("array length out of range"));
}

@Test
public void testUntypedArrayDeclaredLengthOOM_readObject() {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] This test never exercises the readObject() map-value BC_ARRAY guard (JSONReaderJSONB.java:407). JSONB.parseObject(bytes, Object.class) dispatches through readAny() (the Object.class shortcut), so the corrupted array is rejected by the readAny guard at line 932 — the same site the _readAny test already covers. A bytecode-verified deletion probe confirmed it: removing the line-407 guard leaves this test green, so the readObject() guard ships with zero regression coverage. — Failure scenario: a future refactor that drops the checkLength at line 407 revives the declared-length pre-allocation OOM (~1 GB new JSONArray from a 6-byte payload) on readObject()'s map-value path (reachable via the untyped JSONB.parseObject(bytes) overload) while this suite stays green.

Fix — route through readObject() via the untyped overload:

assertThrows(JSONException.class, () -> JSONB.parseObject(bytes));

(keep the Object.class variant too if desired, and update the "readObject() takes the map-value BC_ARRAY branch" comment, which describes the opposite of what happens)

— qwen3.8-max via Qwen Code /review (v0.21.10)

// A map whose value is an int[] (32 elems -> BC_ARRAY + BC_INT32 length).
// Corrupt the declared length, then parse via the untyped overload:
// JSONB.parseObject(bytes, Object.class) short-circuits through readAny()
// (the Object.class fast path) and would NOT exercise the readObject()
// map-value guard at JSONReaderJSONB.java:407 — the untyped overload does.
Map<String, Object> m = new HashMap<>();
m.put("k", new int[32]);
byte[] bytes = JSONB.toBytes(m);
corruptFirstArrayLength(bytes);
JSONException ex = assertThrows(JSONException.class, () -> JSONB.parseObject(bytes));
assertTrue(ex.getMessage().contains("array length out of range"));
}

@Test
public void testUntypedArrayDeclaredLengthOOM_readArray() {
// Top-level JSONB.parseArray dispatches to readArray(); a nested element
// that is itself a BC_ARRAY must have its declared length (read via the
// inline readLength() at the element branch, line ~1099) rejected by
// checkLength.
// 0xA4 = BC_ARRAY (outer, 1 element), 0x01 = outer declared length,
// 0xA4 = BC_ARRAY (inner element), 0x48 = BC_INT32 length-type,
// 0x0FFFFFFF = declares 268,435,455 inner elements (exceeds buffer).
byte[] bytes = {
(byte) 0xA4, 0x01,
(byte) 0xA4, (byte) 0x48,
(byte) 0x0F, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF
};
assertThrows(JSONException.class, () -> JSONB.parseArray(bytes));
}
}
Loading