Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions file.go
Original file line number Diff line number Diff line change
Expand Up @@ -2012,6 +2012,19 @@ func (rd _GGUFTensorInfoReader) Read() (ti GGUFTensorInfo, err error) {
}
}

// Refuse shapes whose size overflows uint64, which would make Elements or Bytes panic.
tt, _ := ti.Type.Trait()
elements := uint64(1)
for _, d := range ti.Dimensions {
var hi uint64
if hi, elements = bits.Mul64(elements, d); hi != 0 {
return ti, fmt.Errorf("invalid dimensions: %v (size overflows uint64)", ti.Dimensions)
}
Comment thread
jpatel2005 marked this conversation as resolved.
Resolved
}
if hi, _ := bits.Mul64(elements, tt.TypeSize); hi != 0 {
return ti, fmt.Errorf("invalid dimensions: %v (size overflows uint64)", ti.Dimensions)
}
Comment thread
jpatel2005 marked this conversation as resolved.
Resolved

ti.Offset, err = rd.ReadUint64()
if err != nil {
return ti, fmt.Errorf("read offset: %w", err)
Expand Down
27 changes: 27 additions & 0 deletions file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,33 @@ func TestBytesOverflowPanics(t *testing.T) {
_ = ti.Bytes()
}

func TestTensorInfoReaderRejectsOverflowingShapes(t *testing.T) {
cases := []struct {
name string
dims []uint64
}{
{"elements overflow", []uint64{1 << 32, 1 << 32}},
{"bytes overflow", []uint64{1 << 62, 1}},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
var buf bytes.Buffer
bo := binary.LittleEndian
_ = binary.Write(&buf, bo, uint64(1)) // name length
buf.WriteByte('x')
_ = binary.Write(&buf, bo, uint32(len(c.dims)))
_ = binary.Write(&buf, bo, c.dims)
_ = binary.Write(&buf, bo, uint32(GGMLTypeF32))
_ = binary.Write(&buf, bo, uint64(0)) // offset

rd := _GGUFTensorInfoReader{_GGUFReader: _GGUFReader{v: GGUFVersionV3, bo: bo, f: bytes.NewReader(buf.Bytes())}}
if _, err := rd.Read(); err == nil {
t.Fatalf("expected error for dimensions %v", c.dims)
}
})
}
}

func TestElementsAndBytesValid(t *testing.T) {
ti := GGUFTensorInfo{
Name: "ok",
Expand Down
Loading