From 31c4e1cf522f532fafd3d3ae6cec8ceeed8bc059 Mon Sep 17 00:00:00 2001 From: Paul Cacheux Date: Thu, 21 Apr 2022 19:57:43 +0200 Subject: [PATCH] btf: guess the number of raw types --- internal/btf/btf.go | 2 +- internal/btf/btf_types.go | 13 ++++++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/internal/btf/btf.go b/internal/btf/btf.go index aa4492019..85237540b 100644 --- a/internal/btf/btf.go +++ b/internal/btf/btf.go @@ -461,7 +461,7 @@ func parseBTF(btf io.ReaderAt, bo binary.ByteOrder) ([]rawType, stringTable, err } buf.Reset(io.NewSectionReader(btf, header.typeStart(), int64(header.TypeLen))) - rawTypes, err := readTypes(buf, bo) + rawTypes, err := readTypes(buf, bo, header.TypeLen) if err != nil { return nil, nil, fmt.Errorf("can't read types: %w", err) } diff --git a/internal/btf/btf_types.go b/internal/btf/btf_types.go index d98c73ca5..948dd91e1 100644 --- a/internal/btf/btf_types.go +++ b/internal/btf/btf_types.go @@ -226,11 +226,14 @@ type btfParam struct { Type TypeID } -func readTypes(r io.Reader, bo binary.ByteOrder) ([]rawType, error) { - var ( - header btfType - types []rawType - ) +func readTypes(r io.Reader, bo binary.ByteOrder, typeLen uint32) ([]rawType, error) { + var header btfType + // because of the interleaving between types and struct members it is difficult to + // precompute the numbers of raw types this will parse + // this "guess" is a good first estimation + sizeOfbtfType := uintptr(binary.Size(btfType{})) + tyMaxCount := uintptr(typeLen) / sizeOfbtfType / 2 + types := make([]rawType, 0, tyMaxCount) for id := TypeID(1); ; id++ { if err := binary.Read(r, bo, &header); err == io.EOF {