危机再度降临!Fastjson新Bug曝光

294 阅读1分钟

前提背景

公司最近线上又出现 OOM 了没想道这次是 fastjson,之前就被他搞过一次了,还来?

Bug 描述:外部接口返回一个 JSON 字符串,要将字符串转成 List 数组,在转换的过程中出现了 OOM

依赖信息 fastjson 2.0.7

<dependency>  
    <groupId>com.alibaba</groupId>  
    <artifactId>fastjson</artifactId>  
    <version>2.0.7</version>  
</dependency>

错误点

返回的字符串缺少右括号 "]" 导致死循环直到OOM

String json = "[19,20,21";  

示例代码

@Test  
public void fasJsonBug() {  
    String json = "[19,20,21";  
    List<Integer> list = new ArrayList<>();  
    try {  
        list = JSONArray.parseArray(json, Integer.class);  
    }catch (Exception e){  
        log.error("fasJson error",e);  
    }  
  
}

错误信息

截屏2024-02-05 14.36.30.png

错误分析

执行流程

截屏2024-02-05 14.54.31.png

JSON. class

parseArray方法

image.png

JSONReader. Class

read方法

image.png

ObjestReaderImplList.class

readObject方法

罪魁祸首就出在这,用 while 循环找 "]" 如果找不到就会一直循环下去,直到内存溢出

image.png

while(!jsonReader.nextIfMatch(']')) {  
    Object item;  
    if (this.itemObjectReader != null) {  
        item = this.itemObjectReader.readObject(jsonReader, 0L);  
    } else {  
        if (this.itemType != String.class) {  
            throw new JSONException(jsonReader.info("TODO : " + this.itemType));  
        }  
  
        item = jsonReader.readString();  
    }  
  
    ((Collection)list).add(item);  
    if (jsonReader.nextIfMatch(',')) {  
    }  
}

现在我们已经考虑要换别的依赖了

更多有趣的内容请关注我的公众号 程序员林中酒