Skip to content

Commit

Permalink
save
Browse files Browse the repository at this point in the history
  • Loading branch information
petar-dambovaliev committed Sep 30, 2024
1 parent e9c9b87 commit 8b4d3a8
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 4 deletions.
2 changes: 1 addition & 1 deletion gno.land/cmd/gnoland/testdata/alloc_array.txtar
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@ package alloc
var buffer interface{}

func DoAlloc() {
var arr [1_000_000_000]byte
var arr [1_000_000_000_000_000]byte
buffer = arr
}
2 changes: 1 addition & 1 deletion gno.land/cmd/gnoland/testdata/alloc_byte_slice.txtar
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@ package alloc
var buffer []byte

func DoAlloc() {
buffer := make([]byte, 1_000_000_000)
buffer := make([]byte, 1_000_000_000_000)
buffer[1] = 'a'
}
2 changes: 1 addition & 1 deletion gno.land/cmd/gnoland/testdata/alloc_slice.txtar
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@ package alloc
var buffer []int

func DoAlloc() {
buffer := make([]int, 1_000_000_0)
buffer := make([]int, 1_000_000_000_000)
buffer[1] = 1
}
14 changes: 13 additions & 1 deletion gnovm/pkg/gnolang/alloc.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package gnolang

import (
"reflect"
"runtime"
)

// Keeps track of in-memory allocations.
Expand Down Expand Up @@ -115,7 +116,9 @@ func (alloc *Allocator) Allocate(size int64) {
if alloc.heap != nil {
deleted := alloc.heap.MarkAndSweep()
alloc.DeallocDeleted(deleted)
if alloc.detonate && alloc.bytes > alloc.maxBytes {

ca := canAllocate(size)
if (alloc.detonate || ca) && alloc.bytes > alloc.maxBytes {
panic("allocation limit exceeded")

Check warning on line 122 in gnovm/pkg/gnolang/alloc.go

View check run for this annotation

Codecov / codecov/patch

gnovm/pkg/gnolang/alloc.go#L122

Added line #L122 was not covered by tests
}
alloc.detonate = alloc.bytes > alloc.maxBytes
Expand Down Expand Up @@ -323,6 +326,15 @@ func (alloc *Allocator) NewDataArray(n int) *ArrayValue {
}
}

func canAllocate(size int64) bool {
var memStats runtime.MemStats
runtime.ReadMemStats(&memStats)

availableMemory := memStats.HeapIdle - memStats.HeapReleased

return uint64(size) < availableMemory
}

func (alloc *Allocator) NewArrayFromData(data []byte) *ArrayValue {
av := alloc.NewDataArray(len(data))
copy(av.Data, data)
Expand Down

0 comments on commit 8b4d3a8

Please sign in to comment.