Debian Codegraph @

internal/sysenc/marshal.go

raw symbols SCIP
1 package sysenc
2
3 import (
4 "encoding"
5 "encoding/binary"
6 "errors"
7 "fmt"
8 "reflect"
9 "slices"
10 "unsafe"
11
12 "github.com/cilium/ebpf/internal"
13 )
14
15 // Marshal turns data into a byte slice using the system's native endianness.
16 //
17 // If possible, avoids allocations by directly using the backing memory
18 // of data. This means that the variable must not be modified for the lifetime
19 // of the returned [Buffer].
20 //
21 // Returns an error if the data can't be turned into a byte slice according to
22 // the behaviour of [binary.Write].
23 func Marshal(data any, size int) (Buffer, error) {
24 if data == nil {
25 return Buffer{}, errors.New("can't marshal a nil value")
26 }
27
28 var buf []byte
29 var err error
30 switch value := data.(type) {
31 case encoding.BinaryMarshaler:
32 buf, err = value.MarshalBinary()
33 case string:
34 buf = unsafe.Slice(unsafe.StringData(value), len(value))
35 case []byte:
36 buf = value
37 case int16:
38 buf = internal.NativeEndian.AppendUint16(make([]byte, 0, 2), uint16(value))
39 case uint16:
40 buf = internal.NativeEndian.AppendUint16(make([]byte, 0, 2), value)
41 case int32:
42 buf = internal.NativeEndian.AppendUint32(make([]byte, 0, 4), uint32(value))
43 case uint32:
44 buf = internal.NativeEndian.AppendUint32(make([]byte, 0, 4), value)
45 case int64:
46 buf = internal.NativeEndian.AppendUint64(make([]byte, 0, 8), uint64(value))
47 case uint64:
48 buf = internal.NativeEndian.AppendUint64(make([]byte, 0, 8), value)
49 default:
50 if buf := unsafeBackingMemory(data); len(buf) == size {
51 return newBuffer(buf), nil
52 }
53
54 buf, err = binary.Append(nil, internal.NativeEndian, value)
55 }
56 if err != nil {
57 return Buffer{}, err
58 }
59
60 if len(buf) != size {
61 return Buffer{}, fmt.Errorf("%T doesn't marshal to %d bytes", data, size)
62 }
63
64 return newBuffer(buf), nil
65 }
66
67 // Unmarshal a byte slice in the system's native endianness into data.
68 //
69 // Returns an error if buf can't be unmarshalled according to the behaviour
70 // of [binary.Decode].
71 func Unmarshal(data any, buf []byte) error {
72 switch value := data.(type) {
73 case encoding.BinaryUnmarshaler:
74 return value.UnmarshalBinary(buf)
75
76 case *string:
77 *value = string(buf)
78 return nil
79
80 case *[]byte:
81 // Backwards compat: unmarshaling into a slice replaces the whole slice.
82 *value = slices.Clone(buf)
83 return nil
84
85 default:
86 if dataBuf := unsafeBackingMemory(data); len(dataBuf) == len(buf) {
87 copy(dataBuf, buf)
88 return nil
89 }
90
91 n, err := binary.Decode(buf, internal.NativeEndian, value)
92 if err != nil {
93 return err
94 }
95
96 if n != len(buf) {
97 return fmt.Errorf("unmarshaling %T doesn't consume all data", data)
98 }
99
100 return nil
101 }
102 }
103
104 // unsafeBackingMemory returns the backing memory of data if it can be used
105 // instead of calling into package binary.
106 //
107 // Returns nil if the value is not a pointer or a slice, or if it contains
108 // padding or unexported fields.
109 func unsafeBackingMemory(data any) []byte {
110 if data == nil {
111 return nil
112 }
113
114 value := reflect.ValueOf(data)
115 var valueSize int
116 switch value.Kind() {
117 case reflect.Pointer:
118 if value.IsNil() {
119 return nil
120 }
121
122 if elemType := value.Type().Elem(); elemType.Kind() != reflect.Slice {
123 valueSize = int(elemType.Size())
124 break
125 }
126
127 // We're dealing with a pointer to a slice. Dereference and
128 // handle it like a regular slice.
129 value = value.Elem()
130 fallthrough
131
132 case reflect.Slice:
133 valueSize = int(value.Type().Elem().Size()) * value.Len()
134
135 default:
136 // Prevent Value.UnsafePointer from panicking.
137 return nil
138 }
139
140 // Some nil pointer types currently crash binary.Size. Call it after our own
141 // code so that the panic isn't reachable.
142 // See https://github.com/golang/go/issues/60892
143 if size := binary.Size(data); size == -1 || size != valueSize {
144 // The type contains padding or unsupported types.
145 return nil
146 }
147
148 if hasUnexportedFields(reflect.TypeOf(data)) {
149 return nil
150 }
151
152 // Reinterpret the pointer as a byte slice. This violates the unsafe.Pointer
153 // rules because it's very unlikely that the source data has "an equivalent
154 // memory layout". However, we can make it safe-ish because of the
155 // following reasons:
156 // - There is no alignment mismatch since we cast to a type with an
157 // alignment of 1.
158 // - There are no pointers in the source type so we don't upset the GC.
159 // - The length is verified at runtime.
160 return unsafe.Slice((*byte)(value.UnsafePointer()), valueSize)
161 }