Skip to content

Commit 8ca22fe

Browse files
authored
Merge pull request #7796 from 1919chichi/fix/issue-7795-shared-empty-collection-ref
fix: exclude JVM-singleton empty collections from raw $ref path tracking
2 parents 4c6e1c0 + 4609730 commit 8ca22fe

2 files changed

Lines changed: 216 additions & 11 deletions

File tree

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

Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -291,14 +291,24 @@ public final String setPath(FieldWriter fieldWriter, Object object) {
291291
}
292292

293293
/**
294-
* Sets the path for the specified object using the provided field writer without reference detection.
295-
* This method is used for reference detection during serialization.
294+
* Sets the path for the specified object using the provided field writer, without checking the
295+
* {@link Feature#ReferenceDetection} feature flag - callers (typically the ASM-generated writers)
296+
* are expected to have checked it already.
297+
* <p>
298+
* The class-level exclusion of {@link ObjectWriterProvider#isNotReferenceDetect(Class)} is still
299+
* enforced here, and a null object is ignored, so that this method stays symmetric with
300+
* {@link #popPath0(Object)}: whatever is not pushed here is not popped there.
296301
*
297302
* @param fieldWriter the field writer to use for path generation
298303
* @param object the object to set the path for
299-
* @return the previous path as a string, or null if no previous path exists
304+
* @return the previous path as a string, or null if no previous path exists, the object is null,
305+
* or the object's class is excluded from reference detection
300306
*/
301307
public final String setPath0(FieldWriter fieldWriter, Object object) {
308+
if (object == null || ObjectWriterProvider.isNotReferenceDetect(object.getClass())) {
309+
return null;
310+
}
311+
302312
this.path = this.path == Path.ROOT
303313
? fieldWriter.getRootParentPath()
304314
: fieldWriter.getPath(path);
@@ -368,15 +378,20 @@ public final String setPath(int index, Object object) {
368378
}
369379

370380
/**
371-
* Sets the path for the specified object at the given index without reference detection.
372-
* This method is used for reference detection during serialization of array elements.
381+
* Sets the path for the specified object at the given index, without checking the
382+
* {@link Feature#ReferenceDetection} feature flag - callers are expected to have checked it already.
383+
* <p>
384+
* The class-level exclusion of {@link ObjectWriterProvider#isNotReferenceDetect(Class)} is still
385+
* enforced here, and a null object is ignored, so that this method stays symmetric with
386+
* {@link #popPath0(Object)}: whatever is not pushed here is not popped there.
373387
*
374388
* @param index the index to set the path for
375389
* @param object the object to set the path for
376-
* @return the previous path as a string, or null if no previous path exists
390+
* @return the previous path as a string, or null if no previous path exists, the object is null,
391+
* or the object's class is excluded from reference detection
377392
*/
378393
public final String setPath0(int index, Object object) {
379-
if (path == null) {
394+
if (path == null || object == null || ObjectWriterProvider.isNotReferenceDetect(object.getClass())) {
380395
return null;
381396
}
382397
this.path = index == 0
@@ -416,16 +431,22 @@ public final void popPath(Object object) {
416431
}
417432

418433
/**
419-
* Removes the path for the specified object without reference detection.
420-
* This method is used to clean up path information during serialization.
434+
* Removes the path for the specified object, without checking the
435+
* {@link Feature#ReferenceDetection} feature flag on the caller's behalf beyond the writer-level
436+
* feature mask.
437+
* <p>
438+
* It applies exactly the same exclusions as {@link #setPath0(FieldWriter, Object)} /
439+
* {@link #setPath0(int, Object)} - a null object and any class rejected by
440+
* {@link ObjectWriterProvider#isNotReferenceDetect(Class)} are ignored - so a value that was never
441+
* pushed is never popped.
421442
*
422443
* @param object the object to remove the path for
423444
*/
424445
public final void popPath0(Object object) {
425446
if (this.path == null
426447
|| (context.features & MASK_REFERENCE_DETECTION) == 0
427-
|| object == Collections.EMPTY_LIST
428-
|| object == Collections.EMPTY_SET
448+
|| object == null
449+
|| ObjectWriterProvider.isNotReferenceDetect(object.getClass())
429450
) {
430451
return;
431452
}
Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
package com.alibaba.fastjson2.issues_7000;
2+
3+
import com.alibaba.fastjson2.JSON;
4+
import com.alibaba.fastjson2.JSONB;
5+
import com.alibaba.fastjson2.JSONFactory;
6+
import com.alibaba.fastjson2.JSONWriter;
7+
import com.alibaba.fastjson2.TypeReference;
8+
import com.alibaba.fastjson2.writer.FieldWriter;
9+
import org.junit.jupiter.api.Test;
10+
11+
import java.util.Collections;
12+
import java.util.LinkedHashMap;
13+
import java.util.List;
14+
import java.util.Map;
15+
import java.util.Set;
16+
17+
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
18+
import static org.junit.jupiter.api.Assertions.assertEquals;
19+
import static org.junit.jupiter.api.Assertions.assertFalse;
20+
import static org.junit.jupiter.api.Assertions.assertNull;
21+
import static org.junit.jupiter.api.Assertions.assertTrue;
22+
23+
/**
24+
* {@link Collections#emptySet()}/{@link Collections#emptyList()}/{@link Collections#emptyMap()} are
25+
* JVM-wide singletons, so {@link com.alibaba.fastjson2.writer.ObjectWriterProvider#isNotReferenceDetect(Class)}
26+
* excludes them from reference tracking. But the ASM-generated bean field writers
27+
* (see {@code ObjectWriterCreatorASM}) call the raw {@code JSONWriter.setPath0}/{@code popPath0}
28+
* directly for non-{@code Object}-declared fields, bypassing that exclusion on the push side, while
29+
* {@code popPath0} only special-cased the two singletons by identity on the pop side. That push/pop
30+
* asymmetry left {@code JSONWriter.path} one level too deep after writing a shared empty collection,
31+
* corrupting every path computed afterwards and producing a bogus {@code $ref} for the next occurrence.
32+
*/
33+
public class Issue7795 {
34+
public static class Model {
35+
private Set<Integer> ids;
36+
private Map<String, Integer> counts;
37+
38+
public Model() {
39+
}
40+
41+
public Model(Set<Integer> ids) {
42+
this.ids = ids;
43+
}
44+
45+
public Model(Map<String, Integer> counts) {
46+
this.counts = counts;
47+
}
48+
49+
public Set<Integer> getIds() {
50+
return ids;
51+
}
52+
53+
public void setIds(Set<Integer> ids) {
54+
this.ids = ids;
55+
}
56+
57+
public Map<String, Integer> getCounts() {
58+
return counts;
59+
}
60+
61+
public void setCounts(Map<String, Integer> counts) {
62+
this.counts = counts;
63+
}
64+
}
65+
66+
@Test
67+
public void testSharedEmptySetAcrossMapEntries() {
68+
Set<Integer> sharedEmptySet = Collections.emptySet();
69+
70+
Map<Integer, Model> sourceModels = new LinkedHashMap<>();
71+
sourceModels.put(1001, new Model(sharedEmptySet));
72+
sourceModels.put(1002, new Model(sharedEmptySet));
73+
74+
String json = JSON.toJSONString(sourceModels, JSONWriter.Feature.ReferenceDetection);
75+
assertFalse(json.contains("$ref"), "shared empty collections must not be turned into $ref: " + json);
76+
77+
Map<Integer, Model> parsed = JSON.parseObject(json, new TypeReference<Map<Integer, Model>>() {
78+
});
79+
assertEquals(Collections.emptySet(), parsed.get(1001).getIds());
80+
assertEquals(Collections.emptySet(), parsed.get(1002).getIds());
81+
}
82+
83+
@Test
84+
public void testSharedEmptyMapAcrossMapEntries() {
85+
Map<String, Integer> sharedEmptyMap = Collections.emptyMap();
86+
87+
Map<Integer, Model> sourceModels = new LinkedHashMap<>();
88+
sourceModels.put(1001, new Model(sharedEmptyMap));
89+
sourceModels.put(1002, new Model(sharedEmptyMap));
90+
91+
String json = JSON.toJSONString(sourceModels, JSONWriter.Feature.ReferenceDetection);
92+
assertFalse(json.contains("$ref"), "shared empty collections must not be turned into $ref: " + json);
93+
94+
Map<Integer, Model> parsed = JSON.parseObject(json, new TypeReference<Map<Integer, Model>>() {
95+
});
96+
assertEquals(Collections.emptyMap(), parsed.get(1001).getCounts());
97+
assertEquals(Collections.emptyMap(), parsed.get(1002).getCounts());
98+
}
99+
100+
/**
101+
* {@code ObjectWriterImplList.writeJSONB} is the only other caller of the raw
102+
* {@code setPath0(int, Object)} overload, and its own {@code refDetect} pre-check already
103+
* excludes singleton classes before ever reaching it - so no current caller can trip this
104+
* overload unguarded. It is fixed anyway for defense-in-depth, since it is a {@code public}
105+
* method on {@code JSONWriter} with the same "raw path-tracking" contract as the
106+
* {@code FieldWriter} overload that caused this issue. Exercise that contract directly.
107+
*/
108+
@Test
109+
public void testSetPath0IntOverloadExcludesSingletons() {
110+
JSONWriter jsonWriter = JSONWriter.of(JSONWriter.Feature.ReferenceDetection);
111+
jsonWriter.setRootObject(new Object());
112+
113+
Set<Integer> sharedEmptySet = Collections.emptySet();
114+
115+
assertNull(jsonWriter.setPath0(0, sharedEmptySet));
116+
jsonWriter.popPath0(sharedEmptySet);
117+
118+
assertNull(jsonWriter.setPath0(1, sharedEmptySet),
119+
"a JVM-wide singleton must never be resolved to a $ref, even via the raw overload");
120+
jsonWriter.popPath0(sharedEmptySet);
121+
}
122+
123+
public static class NullFieldBean {
124+
public List<String> aItems;
125+
public Model b;
126+
public Model c;
127+
}
128+
129+
/**
130+
* The raw path methods accepted a null value before the singleton exclusion was centralized here,
131+
* and the ASM-generated writers rely on it: for a null collection field the codegen skips
132+
* {@code setPath0} (there is an explicit {@code ifnull} before it) but still emits the trailing
133+
* {@code popPath0(fieldValue)}. Classifying the value by {@code object.getClass()} without a null
134+
* guard therefore throws on a perfectly ordinary bean. Removing either {@code object == null}
135+
* guard must make this test fail.
136+
*/
137+
@Test
138+
public void testRawPathMethodsAcceptNull() {
139+
JSONWriter jsonWriter = JSONWriter.of(JSONWriter.Feature.ReferenceDetection);
140+
jsonWriter.setRootObject(new Object());
141+
// initialize JSONWriter.path, otherwise the null checks are masked by the path == null guard
142+
jsonWriter.setPath(0, new Object());
143+
144+
FieldWriter fieldWriter = JSONFactory.getDefaultObjectWriterProvider()
145+
.getObjectWriter(Model.class)
146+
.getFieldWriter("ids");
147+
148+
assertDoesNotThrow(() -> {
149+
assertNull(jsonWriter.setPath0(fieldWriter, null));
150+
assertNull(jsonWriter.setPath0(1, null));
151+
jsonWriter.popPath0(null);
152+
});
153+
}
154+
155+
/**
156+
* End-to-end counterpart of {@link #testRawPathMethodsAcceptNull}: a bean with a null collection
157+
* field written as JSONB with {@code ReferenceDetection} + {@code WriteNulls} goes through exactly
158+
* the codegen shape described above. It also pins the resulting {@code $ref}: because the null
159+
* field is never pushed, it must not be popped either, so the path of the following fields must
160+
* still carry the enclosing map key.
161+
*/
162+
@Test
163+
public void testNullCollectionFieldDoesNotCorruptPath() {
164+
Model shared = new Model(Collections.<Integer>emptySet());
165+
NullFieldBean bean = new NullFieldBean();
166+
bean.b = shared;
167+
bean.c = shared;
168+
169+
Map<String, NullFieldBean> root = new LinkedHashMap<>();
170+
root.put("k", bean);
171+
172+
byte[] jsonbBytes = assertDoesNotThrow(() -> JSONB.toBytes(
173+
root,
174+
JSONWriter.Feature.ReferenceDetection,
175+
JSONWriter.Feature.WriteNulls));
176+
177+
String jsonb = JSONB.toJSONString(jsonbBytes).replaceAll("[\\s]", "");
178+
String json = JSON.toJSONString(root, JSONWriter.Feature.ReferenceDetection, JSONWriter.Feature.WriteNulls);
179+
180+
String expected = "\"c\":{\"$ref\":\"$.k.b\"}";
181+
assertTrue(json.contains(expected), json);
182+
assertTrue(jsonb.contains(expected), jsonb);
183+
}
184+
}

0 commit comments

Comments
 (0)