Skip to content

Commit 460d2e4

Browse files
authored
Merge pull request #7936 from alibaba/fix/jsonb-null-string-capacity
fix: reserve the BC_NULL byte for null strings in JSONB capacity
2 parents 35111f3 + 22d75ef commit 460d2e4

2 files changed

Lines changed: 145 additions & 1 deletion

File tree

‎core/src/main/java/com/alibaba/fastjson2/JSONB.java‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2831,7 +2831,10 @@ static int int64Capacity(Collection<Long> values) {
28312831
*/
28322832
static int stringCapacity(String str) {
28332833
if (str == null) {
2834-
return 0;
2834+
// writeString emits one BC_NULL byte for null. The ASM direct-write group reserves
2835+
// capacity up front and then stores without bounds checks, so reserving 0 here lets
2836+
// an Unsafe store write past the buffer end. See issue #7927.
2837+
return 1;
28352838
}
28362839

28372840
int strlen = str.length();
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
package com.alibaba.fastjson2;
2+
3+
import com.alibaba.fastjson2.writer.ObjectWriter;
4+
import org.junit.jupiter.api.Test;
5+
6+
import java.util.Arrays;
7+
8+
import static org.junit.jupiter.api.Assertions.assertEquals;
9+
import static org.junit.jupiter.api.Assertions.assertTrue;
10+
11+
/**
12+
* The ASM JSONB writer reserves a whole field group's capacity up front
13+
* ({@code ensureCapacity(offset + minCapacity)}) and then writes the fields straight into the
14+
* byte array with no further bounds checks, using Unsafe stores for the field names and for
15+
* the multi-byte numeric forms. Every capacity helper therefore has to be an upper bound on
16+
* what the matching write helper actually emits.
17+
*
18+
* <p>{@code JSONB.IO.stringCapacity(null)} returned 0 while {@code JSONB.IO.writeString} emits
19+
* one {@code BC_NULL} byte for null, so each null String field under-reserved the group by one
20+
* byte whenever nulls were written. Depending on which store crossed the end of the buffer the
21+
* result was either an ArrayIndexOutOfBoundsException or - when the crossing store was an
22+
* Unsafe {@code putShortUnaligned}/{@code putLongUnaligned} - a silent one-byte write into the
23+
* neighboring heap object. Overwriting a mark word that way surfaces later as a SIGSEGV inside
24+
* GC, which is how issue #7927 presented.
25+
*
26+
* <p>The capacity contract is pinned directly rather than only through a bean, because whether
27+
* a given bean overflows depends on unrelated over-reservation elsewhere in the same group
28+
* absorbing the shortfall.
29+
*/
30+
public class JSONBNullStringCapacityTest {
31+
/**
32+
* writeString(null) is a single BC_NULL byte, so the capacity reserved for it must not be 0.
33+
*/
34+
@Test
35+
public void nullStringCapacityMatchesWhatIsWritten() {
36+
byte[] buf = new byte[16];
37+
int end = JSONB.IO.writeString(buf, 0, (String) null);
38+
assertEquals(1, end, "writeString(null) emits exactly one byte");
39+
assertEquals(JSONB.Constants.BC_NULL, buf[0]);
40+
assertTrue(JSONB.IO.stringCapacity((String) null) >= end,
41+
"stringCapacity(null) must cover the BC_NULL byte that writeString emits");
42+
}
43+
44+
/**
45+
* The general invariant: for every value, reserved capacity >= bytes actually written.
46+
* Null is the case that regressed; the rest guard the surrounding length boundaries.
47+
*/
48+
@Test
49+
public void capacityCoversWrittenBytesForAllStringShapes() {
50+
String[] values = {
51+
null, "", "J", "ab",
52+
rep('x', 46), rep('x', 47), rep('x', 48), rep('x', 200), rep('x', 2047), rep('x', 2048),
53+
"\u4e2d", "\u4e2d\u6587abc", rep('\u4e2d', 50)
54+
};
55+
byte[] buf = new byte[1 << 16];
56+
for (String s : values) {
57+
int written = JSONB.IO.writeString(buf, 0, s);
58+
int reserved = JSONB.IO.stringCapacity(s);
59+
assertTrue(reserved >= written,
60+
"under-reserved for " + (s == null ? "null" : "String(len=" + s.length() + ")")
61+
+ ": reserved=" + reserved + " written=" + written);
62+
}
63+
}
64+
65+
/**
66+
* Null elements of a String collection/array are summed through the same helper, so they
67+
* under-reserved the enclosing frame by one byte each as well. Enough nulls are used to
68+
* exhaust the fixed headroom these two overloads add, which would otherwise mask the
69+
* shortfall and let the assertion pass on the broken code.
70+
*/
71+
@Test
72+
public void nullElementsInStringContainersAreCovered() {
73+
String[] withNulls = new String[18];
74+
Arrays.fill(withNulls, null);
75+
withNulls[0] = "J";
76+
withNulls[17] = rep('x', 47);
77+
78+
byte[] buf = new byte[1 << 16];
79+
int written = JSONB.IO.writeString(buf, 0, withNulls, 0);
80+
assertTrue(JSONB.IO.stringCapacity(withNulls) >= written,
81+
"String[] with null elements under-reserved: reserved="
82+
+ JSONB.IO.stringCapacity(withNulls) + " written=" + written);
83+
84+
written = JSONB.IO.writeString(buf, 0, Arrays.asList(withNulls), 0);
85+
assertTrue(JSONB.IO.stringCapacity(Arrays.asList(withNulls)) >= written,
86+
"Collection<String> with null elements under-reserved: reserved="
87+
+ JSONB.IO.stringCapacity(Arrays.asList(withNulls)) + " written=" + written);
88+
}
89+
90+
/**
91+
* End-to-end through the generated ASM writer. Starting from a 1-byte buffer makes
92+
* ensureCapacity size the array to exactly the computed minimum (1.5x growth cannot cover
93+
* it), so a one-byte shortfall has nowhere to hide.
94+
*
95+
* <p>Five null Strings under-reserve by 5 while the int 74 over-reserves by 3 (fieldCapacity
96+
* reserves 5, its two-byte form writes 2), leaving the group 2 bytes short: capacity 19 for
97+
* 21 bytes of output. The int is emitted by a bare Unsafe putShortUnaligned at indices 18-19,
98+
* so before the fix its low byte 0x4A landed at index 19 - past the end - without any
99+
* exception, and the bounds-checked closing marker then threw at index 20. An exception
100+
* naming index 20 rather than 19 is what proves the store at 19 went unchecked. Asserting
101+
* both that the call succeeds and that off never exceeds the buffer covers that silent case.
102+
*/
103+
@Test
104+
public void asmDirectGroupStaysInsideTheBuffer() {
105+
NullsAndInt bean = new NullsAndInt();
106+
ObjectWriter objectWriter = JSONFactory.getDefaultObjectWriterProvider()
107+
.getObjectWriter(NullsAndInt.class, NullsAndInt.class, 0);
108+
109+
JSONWriterJSONB writer = new JSONWriterJSONB(
110+
JSONFactory.createWriteContext(JSONWriter.Feature.WriteNulls), null);
111+
writer.bytes = new byte[1];
112+
writer.off = 0;
113+
objectWriter.writeJSONB(writer, bean, null, null, JSONWriter.Feature.WriteNulls.mask);
114+
assertTrue(writer.off <= writer.bytes.length,
115+
"wrote past the buffer end: off=" + writer.off + " capacity=" + writer.bytes.length);
116+
// the group must have been sized to its computed minimum, otherwise the default buffer
117+
// would absorb the shortfall and this test would pass without exercising the bug
118+
assertTrue(writer.bytes.length < 128,
119+
"capacity amplifier did not engage, capacity=" + writer.bytes.length);
120+
121+
// and the encoding still round-trips
122+
byte[] encoded = Arrays.copyOf(writer.bytes, writer.off);
123+
NullsAndInt decoded = JSONB.parseObject(encoded, NullsAndInt.class);
124+
assertEquals(74, decoded.v);
125+
}
126+
127+
private static String rep(char c, int n) {
128+
char[] chars = new char[n];
129+
Arrays.fill(chars, c);
130+
return new String(chars);
131+
}
132+
133+
public static class NullsAndInt {
134+
public String a;
135+
public String b;
136+
public String c;
137+
public String d;
138+
public String e;
139+
public int v = 74;
140+
}
141+
}

0 commit comments

Comments
 (0)