Debian Codegraph @

internal/sys/ptr.go

raw symbols SCIP
1 package sys
2
3 import (
4 "unsafe"
5
6 "github.com/cilium/ebpf/internal/unix"
7 )
8
9 // UnsafePointer creates a 64-bit pointer from an unsafe Pointer.
10 func UnsafePointer(ptr unsafe.Pointer) Pointer {
11 return Pointer{ptr: ptr}
12 }
13
14 // UnsafeSlicePointer creates an untyped [Pointer] from a slice.
15 func UnsafeSlicePointer[T comparable](buf []T) Pointer {
16 if len(buf) == 0 {
17 return Pointer{}
18 }
19
20 return Pointer{ptr: unsafe.Pointer(unsafe.SliceData(buf))}
21 }
22
23 // TypedPointer points to typed memory.
24 //
25 // It is like a *T except that it accounts for the BPF syscall interface.
26 type TypedPointer[T any] struct {
27 _ [0]*T // prevent TypedPointer[a] to be convertible to TypedPointer[b]
28 ptr Pointer
29 }
30
31 func (p TypedPointer[T]) IsNil() bool {
32 return p.ptr.ptr == nil
33 }
34
35 // SlicePointer creates a [TypedPointer] from a slice.
36 func SlicePointer[T comparable](s []T) TypedPointer[T] {
37 return TypedPointer[T]{ptr: UnsafeSlicePointer(s)}
38 }
39
40 // StringPointer points to a null-terminated string.
41 type StringPointer struct {
42 _ [0]string
43 ptr Pointer
44 }
45
46 // NewStringPointer creates a [StringPointer] from a string.
47 func NewStringPointer(str string) StringPointer {
48 slice, err := unix.ByteSliceFromString(str)
49 if err != nil {
50 return StringPointer{}
51 }
52
53 return StringPointer{ptr: Pointer{ptr: unsafe.Pointer(&slice[0])}}
54 }
55
56 // StringSlicePointer points to a slice of [StringPointer].
57 type StringSlicePointer struct {
58 _ [0][]string
59 ptr Pointer
60 }
61
62 // NewStringSlicePointer allocates an array of Pointers to each string in the
63 // given slice of strings and returns a 64-bit pointer to the start of the
64 // resulting array.
65 //
66 // Use this function to pass arrays of strings as syscall arguments.
67 func NewStringSlicePointer(strings []string) StringSlicePointer {
68 sp := make([]StringPointer, 0, len(strings))
69 for _, s := range strings {
70 sp = append(sp, NewStringPointer(s))
71 }
72
73 return StringSlicePointer{ptr: Pointer{ptr: unsafe.Pointer(&sp[0])}}
74 }