Skip to content

Commit 0213343

Browse files
committed
remove allocs for map lookup ENOENT error
Fixes #1516 Signed-off-by: Bryce Kahle <bryce.kahle@datadoghq.com>
1 parent fbb9ed8 commit 0213343

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

map.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@ var (
2828
ErrIterationAborted = errors.New("iteration aborted")
2929
ErrMapIncompatible = errors.New("map spec is incompatible with existing map")
3030
errMapNoBTFValue = errors.New("map spec does not contain a BTF Value")
31+
32+
// pre-allocating these errors here since they may get called in hot code paths
33+
// and cause unnecessary memory allocations
34+
errMapLookupKeyNotExist = fmt.Errorf("lookup: %w", sysErrKeyNotExist)
3135
)
3236

3337
// MapOptions control loading a map into the kernel.
@@ -695,7 +699,7 @@ func (m *Map) lookup(key interface{}, valueOut sys.Pointer, flags MapLookupFlags
695699
}
696700

697701
if err = sys.MapLookupElem(&attr); err != nil {
698-
return fmt.Errorf("lookup: %w", wrapMapError(err))
702+
return wrapMapLookupError(err)
699703
}
700704
return nil
701705
}

map_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,13 @@ func TestMapLookupKeyTooSmall(t *testing.T) {
245245
qt.Assert(t, qt.IsNotNil(m.Lookup(uint32(0), &small)))
246246
}
247247

248+
func TestMapLookupKeyNotFoundAllocations(t *testing.T) {
249+
allocs := testing.AllocsPerRun(5, func() {
250+
_ = wrapMapLookupError(unix.ENOENT)
251+
})
252+
qt.Assert(t, qt.Equals(allocs, float64(0)))
253+
}
254+
248255
func TestBatchAPIMapDelete(t *testing.T) {
249256
if err := haveBatchAPI(); err != nil {
250257
t.Skipf("batch api not available: %v", err)

syscalls.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,13 @@ var haveNoPreallocMaps = internal.NewFeatureTest("prealloc maps", "4.6", func()
145145
return nil
146146
})
147147

148+
func wrapMapLookupError(err error) error {
149+
if errors.Is(err, unix.ENOENT) {
150+
return errMapLookupKeyNotExist
151+
}
152+
return fmt.Errorf("lookup: %w", wrapMapError(err))
153+
}
154+
148155
func wrapMapError(err error) error {
149156
if err == nil {
150157
return nil

0 commit comments

Comments
 (0)