From ba96d53bad35f7466073f14cb3d89d09383e1a2d Mon Sep 17 00:00:00 2001 From: Marcono1234 Date: Mon, 25 Oct 2021 21:14:41 +0200 Subject: [PATCH] Fix missing bounds checks for JsonTreeReader.getPath() (#2001) There are situations where the stack of JsonTreeReader contains a JsonArray or JsonObject without a subsequent Iterator, for example after calling peek() or nextName(). When JsonTreeReader.getPath() is called afterwards it therefore must not assume that a JsonArray or JsonObject is always followed by an Iterator. The only reason why this never caused an ArrayIndexOutOfBoundsException in the past is because the stack has an even default size (32) so it would just have read the next `null`. However, if the stack had for example the default size 31, a user created a JsonTreeReader for 16 JSON arrays nested inside each other, then called 15 times beginArray(), followed by peek() and getPath() the exception would occur. --- .../java/com/google/gson/internal/bind/JsonTreeReader.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gson/src/main/java/com/google/gson/internal/bind/JsonTreeReader.java b/gson/src/main/java/com/google/gson/internal/bind/JsonTreeReader.java index ac659335..0954fb33 100644 --- a/gson/src/main/java/com/google/gson/internal/bind/JsonTreeReader.java +++ b/gson/src/main/java/com/google/gson/internal/bind/JsonTreeReader.java @@ -308,11 +308,11 @@ public final class JsonTreeReader extends JsonReader { StringBuilder result = new StringBuilder().append('$'); for (int i = 0; i < stackSize; i++) { if (stack[i] instanceof JsonArray) { - if (stack[++i] instanceof Iterator) { + if (++i < stackSize && stack[i] instanceof Iterator) { result.append('[').append(pathIndices[i]).append(']'); } } else if (stack[i] instanceof JsonObject) { - if (stack[++i] instanceof Iterator) { + if (++i < stackSize && stack[i] instanceof Iterator) { result.append('.'); if (pathNames[i] != null) { result.append(pathNames[i]);