github.com/DataDog/datadog-agent/pkg/security/secl@v0.55.0-devel.0.20240517055856-10c4965fea94/utils/pprof.go (about) 1 // Unless explicitly stated otherwise all files in this repository are licensed 2 // under the Apache License Version 2.0. 3 // This product includes software developed at Datadog (https://www.datadoghq.com/). 4 // Copyright 2016-present Datadog, Inc. 5 6 // Package utils groups multiple utils function that can be used by the secl package 7 package utils 8 9 import ( 10 "errors" 11 "unsafe" 12 ) 13 14 // LabelSet represents an abstracted set of labels that can be used to call PprofDoWithoutContext 15 type LabelSet struct { 16 inner *map[string]string 17 } 18 19 // NewLabelSet returns a new LabelSet based on the labels provided as a pair number of arguments (key, value, key value ....) 20 func NewLabelSet(labels ...string) (LabelSet, error) { 21 if len(labels)%2 != 0 { 22 return LabelSet{}, errors.New("non-pair label set values") 23 } 24 25 set := make(map[string]string) 26 for i := 0; i+1 < len(labels); i += 2 { 27 set[labels[i]] = labels[i+1] 28 } 29 30 return LabelSet{ 31 inner: &set, 32 }, nil 33 } 34 35 type labelMap map[string]string 36 37 //go:linkname runtimeSetProfLabel runtime/pprof.runtime_setProfLabel 38 func runtimeSetProfLabel(labels unsafe.Pointer) 39 40 //go:linkname runtimeGetProfLabel runtime/pprof.runtime_getProfLabel 41 func runtimeGetProfLabel() unsafe.Pointer 42 43 func setGoroutineLabels(labels *labelMap) { 44 runtimeSetProfLabel(unsafe.Pointer(labels)) 45 } 46 47 func getGoroutineLabels() *labelMap { 48 return (*labelMap)(runtimeGetProfLabel()) 49 } 50 51 // PprofDoWithoutContext does the same thing as https://pkg.go.dev/runtime/pprof#Do, but without the allocation resulting 52 // from the usage of context values. This function also directly takes a map of labels, instead of incuring allocations 53 // when converting from one format (LabelSet) to the other (map). 54 func PprofDoWithoutContext(labelSet LabelSet, f func()) { 55 previousLabels := getGoroutineLabels() 56 defer setGoroutineLabels(previousLabels) 57 58 setGoroutineLabels((*labelMap)(labelSet.inner)) 59 f() 60 }