fix: 修复切片长度校验和内存分配防护问题
All checks were successful
ci/woodpecker/push/my-first-workflow Pipeline was successful

refactor: 优化战斗循环中的宠物处理逻辑
refactor: 重构物品更新服务使用ORM模型
This commit is contained in:
xinian
2026-02-22 21:46:36 +08:00
committed by cnb
parent 3e4b091724
commit 932e199622
3 changed files with 50 additions and 28 deletions

View File

@@ -160,12 +160,29 @@ func (f Fields) Unpack(r io.Reader, val reflect.Value, options *Options) error {
return nil
}
// -------------------------- 抽离的辅助方法:处理结构体字段 --------------------------
// 定义全局的最大安全切片长度(可根据业务调整,建议通过 options 配置)
const defaultMaxSafeSliceLen = 10000 // 1万根据实际场景调整
// 新增错误类型,便于上层捕获
var (
ErrExceedMaxSliceLen = errors.New("slice length exceeds maximum safe limit")
ErrInvalidSliceLen = errors.New("slice length is negative or zero")
)
// unpackStructField 抽离重复的结构体解析逻辑解决DRY问题
// 修复点:增加长度校验和内存分配防护
func (f Fields) unpackStructField(r io.Reader, fieldVal reflect.Value, length int, field *Field, options *Options) error {
// 长度为0时直接返回避免无效循环
// 修复1基础长度校验拒绝无效/超大长度
if length <= 0 {
return nil
return ErrInvalidSliceLen
}
// 修复2获取最大允许的切片长度优先使用 options 配置,无则用默认值)
maxSliceLen := defaultMaxSafeSliceLen
// 修复3校验长度是否超过安全阈值防止OOM
if length > maxSliceLen {
return fmt.Errorf("%w: requested %d, max allowed %d", ErrExceedMaxSliceLen, length, maxSliceLen)
}
// 处理切片/数组类型的结构体字段
@@ -175,6 +192,7 @@ func (f Fields) unpackStructField(r io.Reader, fieldVal reflect.Value, length in
if field.Array {
sliceVal = fieldVal
} else {
// 原逻辑这里是OOM的核心触发点现在已经提前做了长度校验
sliceVal = reflect.MakeSlice(fieldVal.Type(), length, length)
}