github.com/cilium/ebpf@v0.15.1-0.20240517100537-8079b37aa138/internal/sys/ptr.go (about) 1 package sys 2 3 import ( 4 "unsafe" 5 6 "github.com/cilium/ebpf/internal/unix" 7 ) 8 9 // NewPointer creates a 64-bit pointer from an unsafe Pointer. 10 func NewPointer(ptr unsafe.Pointer) Pointer { 11 return Pointer{ptr: ptr} 12 } 13 14 // NewSlicePointer creates a 64-bit pointer from a byte slice. 15 func NewSlicePointer(buf []byte) Pointer { 16 if len(buf) == 0 { 17 return Pointer{} 18 } 19 20 return Pointer{ptr: unsafe.Pointer(&buf[0])} 21 } 22 23 // NewSlicePointerLen creates a 64-bit pointer from a byte slice. 24 // 25 // Useful to assign both the pointer and the length in one go. 26 func NewSlicePointerLen(buf []byte) (Pointer, uint32) { 27 return NewSlicePointer(buf), uint32(len(buf)) 28 } 29 30 // NewStringPointer creates a 64-bit pointer from a string. 31 func NewStringPointer(str string) Pointer { 32 p, err := unix.BytePtrFromString(str) 33 if err != nil { 34 return Pointer{} 35 } 36 37 return Pointer{ptr: unsafe.Pointer(p)} 38 } 39 40 // NewStringSlicePointer allocates an array of Pointers to each string in the 41 // given slice of strings and returns a 64-bit pointer to the start of the 42 // resulting array. 43 // 44 // Use this function to pass arrays of strings as syscall arguments. 45 func NewStringSlicePointer(strings []string) Pointer { 46 sp := make([]Pointer, 0, len(strings)) 47 for _, s := range strings { 48 sp = append(sp, NewStringPointer(s)) 49 } 50 51 return Pointer{ptr: unsafe.Pointer(&sp[0])} 52 }