Repository navigation
fix: ClassCastException in JSON.toJSON() when a generic field's cached initWriter does not match the runtime value class, for issue #7853 - #7854
Conversation
wenshao
left a comment
There was a problem hiding this comment.
Not explored to full depth (tool budget reached): "agent 6c": 未编译 base 侧 ObjectWriterAdapter.java 做改前/改后字节码大小对比(head 侧偏移已证明两侧同为 >325,无跨越,故未继续)。; "agent 6c": 未运行 Issue7853.java 本身(需 JUnit 平台与 mvn ,brief 禁止在共享 worktree 内构建),改用等价探针复现了同一调用序列。; "agent 1d": 无(未因预算上限中止任何检查)。.
— qwen3.8-max via Qwen Code /review (v0.23.0)
…alue class, for issue alibaba#7853 Addresses the review comments on alibaba#7854. R1-1: the previous guard dereferenced ObjectWriterAdapter#objectClass, which is null for adapters built by ObjectWriterCreator (for example writers registered via JSON.register), so JSON.toJSON threw a NullPointerException where the merge base returned a JSONObject. The match decision no longer touches objectClass. R1-2: reuse now follows the same rule the write path already applies (FieldWriterObject#getObjectWriter): exact class match, widened only for writeUsing / Map / List. The previous isAssignableFrom check reused a superclass writer for a subclass value and silently dropped the subclass-only fields. R1-3 / R1-4: the check moves into a new FieldWriter#getInitWriter(Class) overload, shared by both getInitWriter() cache-reuse sites in ObjectWriterAdapter#toJSONObject (the UNWRAPPED_MASK branch and the main branch), so they cannot drift apart again. This also covers the reverse ordering, where the cached writer is a scalar writer and the current value is a bean: the value is now converted instead of being put as-is, which made the caller's cast throw ClassCastException. R1-5: when the cached writer does not match, the writer is resolved from the runtime class, which keeps the direct conversion for bean values. R1-8: Issue7853 now covers the Base/Sub ordering (pinning the predicate) and the Boolean-first ordering. Reverting the type check makes the new tests crash the forked JVM, so the predicate is now observed rather than assumed. Fixes alibaba#7853
|
Pushed a revised fix in commit 3703bff that addresses all six review findings from the automated review (R1-1 .. R1-5, R1-8):
Verified locally: the full |
…alue class, for issue alibaba#7853 Addresses the review comments on alibaba#7854. R1-1: the previous guard dereferenced ObjectWriterAdapter#objectClass, which is null for adapters built by ObjectWriterCreator (for example writers registered via JSON.register), so JSON.toJSON threw a NullPointerException where the merge base returned a JSONObject. The match decision no longer touches objectClass. R1-2: reuse now follows the same rule the write path already applies (FieldWriterObject#getObjectWriter): exact class match, widened only for writeUsing / Map / List. The previous isAssignableFrom check reused a superclass writer for a subclass value and silently dropped the subclass-only fields. R1-3 / R1-4: the check moves into a new FieldWriter#getInitWriter(Class) overload, shared by both getInitWriter() cache-reuse sites in ObjectWriterAdapter#toJSONObject (the UNWRAPPED_MASK branch and the main branch), so they cannot drift apart again. This also covers the reverse ordering, where the cached writer is a scalar writer and the current value is a bean: the value is now converted instead of being put as-is, which made the caller's cast throw ClassCastException. R1-5: when the cached writer does not match, the writer is resolved from the runtime class, which keeps the direct conversion for bean values. R1-8: Issue7853 now covers the Base/Sub ordering (pinning the predicate) and the Boolean-first ordering. Reverting the type check makes the new tests crash the forked JVM, so the predicate is now observed rather than assumed. Fixes alibaba#7853
3703bff to
7fbd99e
Compare
…alue class (issue alibaba#7853) In ObjectWriterAdapter#toJSONObject, when a field's cached writer was resolved for one generic argument (e.g. ResponseResult<PagerDataBean>) but the current value has a different runtime type (ResponseResult<Boolean>), reusing the cached writer reads the value through foreign field writers and throws ClassCastException (on some JDKs it even crashes the VM). Re-resolve the writer from the runtime value class so toJSON stays consistent with toJSONString. Fixes alibaba#7853 (Rebased onto current main. The ClassCastException class is already handled by the toJSONObject re-resolution logic on main; this commit adds the regression test in issues_7800/Issue7853 covering generic-argument cache poisoning, subclass fields, and scalar-first-then-bean ordering.)
7fbd99e to
3028673
Compare
|
@wenshao I rebuilt this branch on top of current
This addresses every point from the previous review (R1-1 through R1-5 and R1-8). The branch is now clean and passes the issue's reproduction both directions. Could you take another look? Thanks! |
3028673 to
a38d7c5
Compare
|
Rebased onto current The ClassCastException-on-reused-cached-writer class of bug is already handled by the If the maintainers consider |
wenshao
left a comment
There was a problem hiding this comment.
Reviewed. Suggestions are inline.
Not explored to full depth (tool budget reached): "agent reverse-audit (round 2)": repo-wide sweep for an existing subclass-cached-first → superclass-value test outside the two suites read in full (Issue7853.java, Issue7714.java — every value-…; "agent reverse-audit (round 1)": resolving R2-1's open question — whether any other committed suite test pins the un-primed JSON.toJSON fallback arm — requires per-test isolation runs (a whol…; "agent 1a": re-running Issue7853 on JDKs other than 8 (only JDK 8 was exercised; with the fix in place the assertions are JDK-independent output strings, so this is corrobo….
— glm-5.3-flash@89f03b58 via Qwen Code /review (v0.25.0)
| Holder baseHolder = new Holder(); | ||
| baseHolder.value = base; | ||
| assertEquals("{\"value\":{\"a\":\"A\"}}", JSON.toJSONString(baseHolder)); |
There was a problem hiding this comment.
[Suggestion] R2-4: the tests pin only the parent-cached-then-subclass direction of the isTypeMatch predicate. No test in this PR or in Issue7714 caches a subclass writer and then writes a superclass value through the same field, so a reversed-receiver mutation of the assignability check (valueClass.isAssignableFrom(initValueClass) instead of initValueClass.isAssignableFrom(valueClass)) passes everything while reintroducing a production crash: with Sub cached first and a Base value written second, both the write path and the tree path reuse Sub's writer for the Base instance, and Sub's b accessor fails on it. An argument-order flip is exactly the class of edit the test's own javadoc warns against, in the direction the current tests cannot see.
Witness (probe on this commit):
HEAD + proposed test: testsStarted=4 passed=4 failed=0
MUTANT + proposed test: testsStarted=4 passed=3 failed=1
testSubclassCachedFirstThenSuperclassValue :: java.lang.ClassCastException:
class ...Issue7853$Base cannot be cast to class ...Issue7853$Sub
Full-suite sweep (8,150 tests x 2 arms): failing-test sets identical,
0 mutation-caused failures — no committed test pins this direction.
Suggested fix — add a case pinning the reverse direction, with a fresh holder class: the field-writer cache binds once per holder class, process-wide, and never resets (FieldWriterObject.java:199-201), so reusing Holder would inherit the binding testSubclassFieldsAreNotDropped left behind — the same isolation pattern ScalarFirstResult already applies:
public static class SubFirstHolder {
public Object value;
}
@Test
public void testSubclassCachedFirstThenSuperclassValue() {
SubFirstHolder subFirst = new SubFirstHolder();
subFirst.value = new Sub(); // binds initValueClass = Sub
JSON.toJSONString(subFirst);
SubFirstHolder baseSecond = new SubFirstHolder();
baseSecond.value = new Base(); // must re-resolve by Base, not reuse Sub's writer
assertEquals("{\"value\":{\"a\":\"A\"}}", JSON.toJSONString(baseSecond));
assertEquals("{\"value\":{\"a\":\"A\"}}", JSON.toJSON(baseSecond).toString());
}The test is green at this commit and reds under the flipped-receiver mutation; the toJSONString assertion is the one that kills the mutant, because on ASM-generated writers the tree path's Unsafe accessors read out-of-class fields as null silently instead of throwing.
— glm-5.3-flash@89f03b58 via Qwen Code /review (v0.25.0)
| * writeUsing / Map / List). A looser isAssignableFrom check would reuse the superclass writer | ||
| * for a subclass value and silently drop the subclass-only field. |
There was a problem hiding this comment.
[Suggestion] R2-5: this javadoc advertises the full rule ("exact class match, widened only for writeUsing / Map / List"), but the tests pin only the exact-match arm — the widening arms of FieldWriterObject.isTypeMatch are unpinned anywhere in the repo, so a regressed arm would ship with every gate green.
Witness (probe on this commit):
writeUsing arm: removing `writeUsing && initValueClass.isAssignableFrom(valueClass)`:
INTACT toJSONString: {"value":"MASKED"}
MUTANT toJSONString: {"value":{"a":"A","b":"B"}} <- custom writer silently bypassed
The five writeUsing fixtures in core tests (Issue1524 x4, SortFieldNamesRegistryTest x1)
each use exactly one value class, so none exercises the widening.
Suggested fixes, two small tests:
(1) pin the writeUsing widening with a toJSONString pair — prime a base-class value, then write a subclass value, assert the custom writer's output. A toJSON assertion cannot pin this arm: toJSON stores a writeUsing field's value raw (pre-existing main behavior).
(2) pin the primitive-boxing arm, which becomes reachable when a field-level custom writer is configured on a primitive-typed property (the creator then pre-binds initValueClass = int.class, making this the only arm that honors the custom writer):
public static class IntMaskWriter implements ObjectWriter {
public void write(JSONWriter w, Object o, Object name, Type type, long features) {
w.writeString("MASKED");
}
}
public static class PrimitiveHolder {
@JSONField(writeUsing = IntMaskWriter.class)
public int status = 3;
}
@Test
public void testPrimitiveWriteUsingHonored() {
assertEquals("{\"status\":\"MASKED\"}", JSON.toJSONString(new PrimitiveHolder()));
}Both tests go red if the corresponding arm is removed and are green at this commit.
— glm-5.3-flash@89f03b58 via Qwen Code /review (v0.25.0)
Dismissing stale review: the findings were against the production change in ObjectWriterAdapter.java, which is no longer in this PR -- it is now test-only (Issue7853 regression coverage; the production fix landed on main via #7739). CI green on head. Agent-verified against the current diff.
What this PR does / why we need it?
Fixes #7853.
When serializing the same generic bean class with different generic arguments via
JSON.toJSON(), aClassCastExceptionis thrown (e.g.Boolean cannot be cast to PagerDataBean), becauseObjectWriterAdapter.toJSONObjectreuses the writer cached byfieldWriter.getInitWriter()without checking that it matches the runtime value class.Note that on some JDK versions this bug can even manifest as a JVM crash (
EXCEPTION_ACCESS_VIOLATION) instead of a cleanClassCastException, since the mismatched value reaches ASM-generated primitive accessors.Summary of your change
In
ObjectWriterAdapter.toJSONObject(core), thegetInitWriter()cached writer is now only reused whenobjectWriterAdapter.objectClass.isAssignableFrom(fieldValue.getClass()). Otherwise the value is converted generically viaJSON.toJSON(fieldValue)— the same behavior thetoJSONStringpath already has via thetypeMatchcheck inFieldWriterObject.getObjectWriter.ObjectWriterAdapter.java: type-match guard before reusing the cached init writer.Issue7853.java(new test): coversJSON.toJSON/JSON.toJSONStringfor the same generic wrapper serialized first withPagerDataBean<String>and then withBooleanandPagerDataBean<Integer>.Reproduction before the fix (JDK 17):
After the fix:
{"code":0,"msg":"ok","result":true}— identical to thetoJSONStringoutput.Please indicate you've done the following: