Debian Codegraph @

btf/dedup.go

raw symbols SCIP
1 package btf
2
3 import (
4 "errors"
5 "fmt"
6 "hash/maphash"
7 "slices"
8 )
9
10 // deduper deduplicates BTF types by finding all types in a Type graph that are
11 // Equivalent and replaces them with a single instance.
12 //
13 // See doc comments in types.go to understand the various ways in which Types
14 // can relate to each other and how they are compared for equality. We separate
15 // Identity (same memory location), Equivalence (same shape/layout), and
16 // Compatibility (CO-RE compatible) to be explicit about intent.
17 //
18 // This deduper opportunistically uses a combination of Identity and Equivalence
19 // to find types that can be deduplicated.
20 type deduper struct {
21 visited map[Type]struct{}
22 hashCache map[hashCacheKey]uint64
23
24 // Set of types that have been deduplicated.
25 done map[Type]Type
26
27 // Map of hash to types with that hash.
28 hashed map[uint64][]Type
29 eqCache map[typKey]bool
30
31 seed maphash.Seed
32 }
33
34 func newDeduper() *deduper {
35 return &deduper{
36 make(map[Type]struct{}),
37 make(map[hashCacheKey]uint64),
38 make(map[Type]Type),
39 make(map[uint64][]Type),
40 make(map[typKey]bool),
41 maphash.MakeSeed(),
42 }
43 }
44
45 func (d *deduper) deduplicate(t Type) (Type, error) {
46 // If we have already attempted to deduplicate this exact type, return the
47 // result.
48 if done, ok := d.done[t]; ok {
49 return done, nil
50 }
51
52 // Visit the subtree, if a type has children, attempt to replace it with a
53 // deduplicated version of those children.
54 for t := range postorder(t, d.visited) {
55 for c := range children(t) {
56 var err error
57 *c, err = d.hashInsert(*c)
58 if err != nil {
59 return nil, err
60 }
61 }
62 }
63
64 // Finally, deduplicate the root type itself.
65 return d.hashInsert(t)
66 }
67
68 // hashInsert attempts to deduplicate t by hashing it and comparing against
69 // other types with the same hash. Returns the Type to be used as the common
70 // substitute at this position in the graph.
71 func (d *deduper) hashInsert(t Type) (Type, error) {
72 // If we have deduplicated this type before, return the result of that
73 // deduplication.
74 if done, ok := d.done[t]; ok {
75 return done, nil
76 }
77
78 // Compute the hash of this type. Types with the same hash are candidates for
79 // deduplication.
80 hash, err := d.hash(t, -1)
81 if err != nil {
82 return nil, err
83 }
84
85 // A hash collision is possible, so we need to compare against all candidates
86 // with the same hash.
87 for _, candidate := range d.hashed[hash] {
88 // Pre-size the visited slice, experimentation on VMLinux shows a capacity
89 // of 16 to give the best performance.
90 const visitedCapacity = 16
91 err := d.typesEquivalent(candidate, t, make([]Type, 0, visitedCapacity))
92 if errors.Is(err, errNotEquivalent) {
93 continue
94 }
95 if err != nil {
96 return nil, err
97 }
98
99 // Found a Type that's both Equivalent and hashes to the same value, choose
100 // it as the deduplicated version.
101 d.done[t] = candidate
102
103 return candidate, nil
104 }
105
106 d.hashed[hash] = append(d.hashed[hash], t)
107
108 return t, nil
109 }
110
111 // The hash of a Type is the same given its pointer and depth budget.
112 type hashCacheKey struct {
113 t Type
114 depthBudget int
115 }
116
117 // hash computes a hash for t. The produced hash is the same for Types which
118 // are similar. The hash can collide such that two different Types may produce
119 // the same hash, so equivalence must be checked explicitly. It will recurse
120 // into children. The initial call should use a depthBudget of -1.
121 func (d *deduper) hash(t Type, depthBudget int) (uint64, error) {
122 if depthBudget == 0 {
123 return 0, nil
124 }
125
126 h := &maphash.Hash{}
127 h.SetSeed(d.seed)
128
129 switch t := t.(type) {
130 case *Void:
131 maphash.WriteComparable(h, kindUnknown)
132
133 case *Int:
134 maphash.WriteComparable(h, kindInt)
135 maphash.WriteComparable(h, *t)
136
137 case *Pointer:
138 maphash.WriteComparable(h, kindPointer)
139 // If the depth budget is positive, decrement it every time we follow a
140 // pointer.
141 if depthBudget > 0 {
142 depthBudget--
143 }
144
145 // If this is the first time we are following a pointer, set the depth
146 // budget. This limits amount of recursion we do when hashing pointers that
147 // form cycles. This is cheaper than tracking visited types and works
148 // because hash collisions are allowed.
149 if depthBudget < 0 {
150 depthBudget = 1
151
152 // Double pointers are common in C. However, with a depth budget of 1, all
153 // double pointers would hash the same, causing a performance issue when
154 // checking equivalence. So we give double pointers a bit more budget.
155 if _, ok := t.Target.(*Pointer); ok {
156 depthBudget = 2
157 }
158 }
159 sub, err := d.hash(t.Target, depthBudget)
160 if err != nil {
161 return 0, err
162 }
163 maphash.WriteComparable(h, sub)
164
165 case *Array:
166 maphash.WriteComparable(h, kindArray)
167 maphash.WriteComparable(h, t.Nelems)
168 sub, err := d.hash(t.Index, depthBudget)
169 if err != nil {
170 return 0, err
171 }
172 maphash.WriteComparable(h, sub)
173 _, err = d.hash(t.Type, depthBudget)
174 if err != nil {
175 return 0, err
176 }
177 maphash.WriteComparable(h, sub)
178
179 case *Struct, *Union:
180 // Check the cache to avoid recomputing the hash for this type and depth
181 // budget.
182 key := hashCacheKey{t, depthBudget}
183 if cached, ok := d.hashCache[key]; ok {
184 return cached, nil
185 }
186
187 var members []Member
188 switch t := t.(type) {
189 case *Struct:
190 maphash.WriteComparable(h, kindStruct)
191 maphash.WriteComparable(h, t.Name)
192 maphash.WriteComparable(h, t.Size)
193 members = t.Members
194
195 case *Union:
196 maphash.WriteComparable(h, kindUnion)
197 maphash.WriteComparable(h, t.Name)
198 maphash.WriteComparable(h, t.Size)
199 members = t.Members
200 }
201
202 maphash.WriteComparable(h, len(members))
203 for _, m := range members {
204 maphash.WriteComparable(h, m.Name)
205 maphash.WriteComparable(h, m.Offset)
206 sub, err := d.hash(m.Type, depthBudget)
207 if err != nil {
208 return 0, err
209 }
210 maphash.WriteComparable(h, sub)
211 }
212
213 sum := h.Sum64()
214 d.hashCache[key] = sum
215 return sum, nil
216
217 case *Enum:
218 maphash.WriteComparable(h, kindEnum)
219 maphash.WriteComparable(h, t.Name)
220 maphash.WriteComparable(h, t.Size)
221 maphash.WriteComparable(h, t.Signed)
222 for _, v := range t.Values {
223 maphash.WriteComparable(h, v)
224 }
225
226 case *Fwd:
227 maphash.WriteComparable(h, kindForward)
228 maphash.WriteComparable(h, *t)
229
230 case *Typedef:
231 maphash.WriteComparable(h, kindTypedef)
232 maphash.WriteComparable(h, t.Name)
233 sub, err := d.hash(t.Type, depthBudget)
234 if err != nil {
235 return 0, err
236 }
237 maphash.WriteComparable(h, sub)
238
239 case *Volatile:
240 maphash.WriteComparable(h, kindVolatile)
241 sub, err := d.hash(t.Type, depthBudget)
242 if err != nil {
243 return 0, err
244 }
245 maphash.WriteComparable(h, sub)
246
247 case *Const:
248 maphash.WriteComparable(h, kindConst)
249 sub, err := d.hash(t.Type, depthBudget)
250 if err != nil {
251 return 0, err
252 }
253 maphash.WriteComparable(h, sub)
254
255 case *Restrict:
256 maphash.WriteComparable(h, kindRestrict)
257 sub, err := d.hash(t.Type, depthBudget)
258 if err != nil {
259 return 0, err
260 }
261 maphash.WriteComparable(h, sub)
262
263 case *Func:
264 maphash.WriteComparable(h, kindFunc)
265 maphash.WriteComparable(h, t.Name)
266 sub, err := d.hash(t.Type, depthBudget)
267 if err != nil {
268 return 0, err
269 }
270 maphash.WriteComparable(h, sub)
271
272 case *FuncProto:
273 // It turns out that pointers to function prototypes are common in C code,
274 // function pointers. Function prototypes frequently have similar patterns
275 // of [ptr, ptr] -> int, or [ptr, ptr, ptr] -> int. Causing frequent hash
276 // collisions, for the default depth budget of 1. So allow one additional
277 // level of pointers when we encounter a function prototype.
278 if depthBudget >= 0 {
279 depthBudget++
280 }
281
282 maphash.WriteComparable(h, kindFuncProto)
283 for _, p := range t.Params {
284 maphash.WriteComparable(h, p.Name)
285 sub, err := d.hash(p.Type, depthBudget)
286 if err != nil {
287 return 0, err
288 }
289 maphash.WriteComparable(h, sub)
290 }
291 sub, err := d.hash(t.Return, depthBudget)
292 if err != nil {
293 return 0, err
294 }
295 maphash.WriteComparable(h, sub)
296
297 case *Var:
298 maphash.WriteComparable(h, kindVar)
299 maphash.WriteComparable(h, t.Name)
300 maphash.WriteComparable(h, t.Linkage)
301 sub, err := d.hash(t.Type, depthBudget)
302 if err != nil {
303 return 0, err
304 }
305 maphash.WriteComparable(h, sub)
306
307 case *Datasec:
308 maphash.WriteComparable(h, kindDatasec)
309 maphash.WriteComparable(h, t.Name)
310 for _, v := range t.Vars {
311 maphash.WriteComparable(h, v.Offset)
312 maphash.WriteComparable(h, v.Size)
313 sub, err := d.hash(v.Type, depthBudget)
314 if err != nil {
315 return 0, err
316 }
317 maphash.WriteComparable(h, sub)
318 }
319
320 case *declTag:
321 maphash.WriteComparable(h, kindDeclTag)
322 maphash.WriteComparable(h, t.Value)
323 maphash.WriteComparable(h, t.Index)
324 sub, err := d.hash(t.Type, depthBudget)
325 if err != nil {
326 return 0, err
327 }
328 maphash.WriteComparable(h, sub)
329
330 case *TypeTag:
331 maphash.WriteComparable(h, kindTypeTag)
332 maphash.WriteComparable(h, t.Value)
333 sub, err := d.hash(t.Type, depthBudget)
334 if err != nil {
335 return 0, err
336 }
337 maphash.WriteComparable(h, sub)
338
339 case *Float:
340 maphash.WriteComparable(h, kindFloat)
341 maphash.WriteComparable(h, *t)
342
343 default:
344 return 0, fmt.Errorf("unsupported type for hashing: %T", t)
345 }
346
347 return h.Sum64(), nil
348 }
349
350 type typKey struct {
351 a Type
352 b Type
353 }
354
355 var errNotEquivalent = errors.New("types are not equivalent")
356
357 // typesEquivalent checks if two types are Equivalent.
358 func (d *deduper) typesEquivalent(ta, tb Type, visited []Type) error {
359 // Fast path: if Types are Identical, they are also Equivalent.
360 if ta == tb {
361 return nil
362 }
363
364 switch a := ta.(type) {
365 case *Void:
366 if _, ok := tb.(*Void); ok {
367 return nil
368 }
369 return errNotEquivalent
370
371 case *Int:
372 b, ok := tb.(*Int)
373 if !ok {
374 return errNotEquivalent
375 }
376 if a.Name != b.Name || a.Size != b.Size || a.Encoding != b.Encoding {
377 return errNotEquivalent
378 }
379 return nil
380
381 case *Enum:
382 b, ok := tb.(*Enum)
383 if !ok {
384 return errNotEquivalent
385 }
386 if a.Name != b.Name || len(a.Values) != len(b.Values) {
387 return errNotEquivalent
388 }
389 for i := range a.Values {
390 if a.Values[i].Name != b.Values[i].Name || a.Values[i].Value != b.Values[i].Value {
391 return errNotEquivalent
392 }
393 }
394 return nil
395
396 case *Fwd:
397 b, ok := tb.(*Fwd)
398 if !ok {
399 return errNotEquivalent
400 }
401 if a.Name != b.Name || a.Kind != b.Kind {
402 return errNotEquivalent
403 }
404 return nil
405
406 case *Float:
407 b, ok := tb.(*Float)
408 if !ok {
409 return errNotEquivalent
410 }
411 if a.Name != b.Name || a.Size != b.Size {
412 return errNotEquivalent
413 }
414 return nil
415
416 case *Array:
417 b, ok := tb.(*Array)
418 if !ok {
419 return errNotEquivalent
420 }
421
422 if a.Nelems != b.Nelems {
423 return errNotEquivalent
424 }
425 if err := d.typesEquivalent(a.Index, b.Index, visited); err != nil {
426 return err
427 }
428 if err := d.typesEquivalent(a.Type, b.Type, visited); err != nil {
429 return err
430 }
431 return nil
432
433 case *Pointer:
434 b, ok := tb.(*Pointer)
435 if !ok {
436 return errNotEquivalent
437 }
438
439 // Detect cycles by tracking visited types. Assume types are Equivalent if
440 // we have already visited this type in the current Equivalence check.
441 if slices.Contains(visited, ta) {
442 return nil
443 }
444 visited = append(visited, ta)
445
446 return d.typesEquivalent(a.Target, b.Target, visited)
447
448 case *Struct, *Union:
449 // Use a cache to avoid recomputation. We only do this for composite types
450 // since they are where types fan out the most. For other types, the
451 // overhead of the lookup and update outweighs performance benefits.
452 cacheKey := typKey{a: ta, b: tb}
453 if equal, ok := d.eqCache[cacheKey]; ok {
454 if equal {
455 return nil
456 }
457 return errNotEquivalent
458 }
459
460 compErr := d.compositeEquivalent(ta, tb, visited)
461 d.eqCache[cacheKey] = compErr == nil
462
463 return compErr
464
465 case *Typedef:
466 b, ok := tb.(*Typedef)
467 if !ok {
468 return errNotEquivalent
469 }
470 if a.Name != b.Name {
471 return errNotEquivalent
472 }
473 return d.typesEquivalent(a.Type, b.Type, visited)
474
475 case *Volatile:
476 b, ok := tb.(*Volatile)
477 if !ok {
478 return errNotEquivalent
479 }
480 return d.typesEquivalent(a.Type, b.Type, visited)
481
482 case *Const:
483 b, ok := tb.(*Const)
484 if !ok {
485 return errNotEquivalent
486 }
487 return d.typesEquivalent(a.Type, b.Type, visited)
488
489 case *Restrict:
490 b, ok := tb.(*Restrict)
491 if !ok {
492 return errNotEquivalent
493 }
494 return d.typesEquivalent(a.Type, b.Type, visited)
495
496 case *Func:
497 b, ok := tb.(*Func)
498 if !ok {
499 return errNotEquivalent
500 }
501 if a.Name != b.Name {
502 return errNotEquivalent
503 }
504 return d.typesEquivalent(a.Type, b.Type, visited)
505
506 case *FuncProto:
507 b, ok := tb.(*FuncProto)
508 if !ok {
509 return errNotEquivalent
510 }
511
512 if err := d.typesEquivalent(a.Return, b.Return, visited); err != nil {
513 return err
514 }
515 if len(a.Params) != len(b.Params) {
516 return errNotEquivalent
517 }
518 for i := range a.Params {
519 if a.Params[i].Name != b.Params[i].Name {
520 return errNotEquivalent
521 }
522 if err := d.typesEquivalent(a.Params[i].Type, b.Params[i].Type, visited); err != nil {
523 return err
524 }
525 }
526 return nil
527
528 case *Var:
529 b, ok := tb.(*Var)
530 if !ok {
531 return errNotEquivalent
532 }
533 if a.Name != b.Name {
534 return errNotEquivalent
535 }
536 if err := d.typesEquivalent(a.Type, b.Type, visited); err != nil {
537 return err
538 }
539 if a.Linkage != b.Linkage {
540 return errNotEquivalent
541 }
542 return nil
543
544 case *Datasec:
545 b, ok := tb.(*Datasec)
546 if !ok {
547 return errNotEquivalent
548 }
549 if a.Name != b.Name || len(a.Vars) != len(b.Vars) {
550 return errNotEquivalent
551 }
552 for i := range a.Vars {
553 if a.Vars[i].Offset != b.Vars[i].Offset ||
554 a.Vars[i].Size != b.Vars[i].Size {
555 return errNotEquivalent
556 }
557
558 if err := d.typesEquivalent(a.Vars[i].Type, b.Vars[i].Type, visited); err != nil {
559 return err
560 }
561 }
562 return nil
563
564 case *declTag:
565 b, ok := tb.(*declTag)
566 if !ok {
567 return errNotEquivalent
568 }
569 if a.Value != b.Value || a.Index != b.Index {
570 return errNotEquivalent
571 }
572 return d.typesEquivalent(a.Type, b.Type, visited)
573
574 case *TypeTag:
575 b, ok := tb.(*TypeTag)
576 if !ok {
577 return errNotEquivalent
578 }
579 if a.Value != b.Value {
580 return errNotEquivalent
581 }
582 if err := d.typesEquivalent(a.Type, b.Type, visited); err != nil {
583 return err
584 }
585 return nil
586
587 default:
588 return fmt.Errorf("unsupported type for equivalence: %T", a)
589 }
590 }
591
592 // compositeEquivalent checks if two composite types (Struct or Union) are
593 // Equivalent.
594 func (d *deduper) compositeEquivalent(at, bt Type, visited []Type) error {
595 var ma, mb []Member
596 switch a := at.(type) {
597 case *Struct:
598 b, ok := bt.(*Struct)
599 if !ok {
600 return errNotEquivalent
601 }
602
603 if a.Name != b.Name || a.Size != b.Size || len(a.Members) != len(b.Members) {
604 return errNotEquivalent
605 }
606 ma = a.Members
607 mb = b.Members
608
609 case *Union:
610 b, ok := bt.(*Union)
611 if !ok {
612 return errNotEquivalent
613 }
614
615 if a.Name != b.Name || a.Size != b.Size || len(a.Members) != len(b.Members) {
616 return errNotEquivalent
617 }
618 ma = a.Members
619 mb = b.Members
620 }
621
622 for i := range ma {
623 if ma[i].Name != mb[i].Name || ma[i].Offset != mb[i].Offset {
624 return errNotEquivalent
625 }
626
627 if err := d.typesEquivalent(ma[i].Type, mb[i].Type, visited); err != nil {
628 return err
629 }
630 }
631
632 return nil
633 }