Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: remove unsafe pkg usage from util.mempool #15428

Merged
merged 2 commits into from
Dec 16, 2024
Merged
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
20 changes: 6 additions & 14 deletions pkg/util/mempool/pool.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,20 @@
package mempool

import (
"errors"
"fmt"
"sync"
"time"
"unsafe"

"github.com/dustin/go-humanize"
"github.com/prometheus/client_golang/prometheus"
)

var (
errSlabExhausted = errors.New("slab exhausted")

reasonSizeExceeded = "size-exceeded"
reasonSlabExhausted = "slab-exhausted"
reasonSizeExceeded = "size-exceeded"
)

type slab struct {
buffer chan unsafe.Pointer
buffer chan []byte
size, count int
once sync.Once
metrics *metrics
Expand All @@ -39,11 +34,10 @@ func newSlab(bufferSize, bufferCount int, m *metrics) *slab {
}

func (s *slab) init() {
s.buffer = make(chan unsafe.Pointer, s.count)
s.buffer = make(chan []byte, s.count)
for i := 0; i < s.count; i++ {
buf := make([]byte, 0, s.size)
ptr := unsafe.Pointer(unsafe.SliceData(buf)) //#nosec G103 -- Simple arena allocator implementation, does not appear to allow for any unsafe operations.
s.buffer <- ptr
s.buffer <- buf
}
s.metrics.availableBuffersPerSlab.WithLabelValues(s.name).Set(float64(s.count))
}
Expand All @@ -54,8 +48,7 @@ func (s *slab) get(size int) ([]byte, error) {

waitStart := time.Now()
// wait for available buffer on channel
ptr := <-s.buffer
buf := unsafe.Slice((*byte)(ptr), s.size) //#nosec G103 -- Simple arena allocator implementation, does not appear to allow for any unsafe operations.
buf := <-s.buffer
s.metrics.waitDuration.WithLabelValues(s.name).Observe(time.Since(waitStart).Seconds())

return buf[:size], nil
Expand All @@ -67,9 +60,8 @@ func (s *slab) put(buf []byte) {
panic("slab is not initialized")
}

ptr := unsafe.Pointer(unsafe.SliceData(buf)) //#nosec G103 -- Simple arena allocator implementation, does not appear to allow for any unsafe operations.
// Note that memory is NOT zero'd on return, but since all allocations are of defined widths and we only ever then read a record of exactly that width into the allocation, it will always be overwritten before use and can't leak.
s.buffer <- ptr
s.buffer <- buf
}

// MemPool is an Allocator implementation that uses a fixed size memory pool
Expand Down
Loading