github.com/kubeshark/ebpf@v0.9.2/btf/strings_test.go (about) 1 package btf 2 3 import ( 4 "bytes" 5 "strings" 6 "testing" 7 ) 8 9 func TestStringTable(t *testing.T) { 10 const in = "\x00one\x00two\x00" 11 const splitIn = "three\x00four\x00" 12 13 st, err := readStringTable(strings.NewReader(in), nil) 14 if err != nil { 15 t.Fatal(err) 16 } 17 18 var buf bytes.Buffer 19 if err := st.Marshal(&buf); err != nil { 20 t.Fatal("Can't marshal string table:", err) 21 } 22 23 if !bytes.Equal([]byte(in), buf.Bytes()) { 24 t.Error("String table doesn't match input") 25 } 26 27 // Parse string table of split BTF 28 split, err := readStringTable(strings.NewReader(splitIn), st) 29 if err != nil { 30 t.Fatal(err) 31 } 32 33 testcases := []struct { 34 offset uint32 35 want string 36 }{ 37 {0, ""}, 38 {1, "one"}, 39 {5, "two"}, 40 {9, "three"}, 41 {15, "four"}, 42 } 43 44 for _, tc := range testcases { 45 have, err := split.Lookup(tc.offset) 46 if err != nil { 47 t.Errorf("Offset %d: %s", tc.offset, err) 48 continue 49 } 50 51 if have != tc.want { 52 t.Errorf("Offset %d: want %s but have %s", tc.offset, tc.want, have) 53 } 54 } 55 56 if _, err := st.Lookup(2); err == nil { 57 t.Error("No error when using offset pointing into middle of string") 58 } 59 60 // Make sure we reject bogus tables 61 _, err = readStringTable(strings.NewReader("\x00one"), nil) 62 if err == nil { 63 t.Fatal("Accepted non-terminated string") 64 } 65 66 _, err = readStringTable(strings.NewReader("one\x00"), nil) 67 if err == nil { 68 t.Fatal("Accepted non-empty first item") 69 } 70 } 71 72 func newStringTable(strings ...string) *stringTable { 73 offsets := make([]uint32, len(strings)) 74 75 var offset uint32 76 for i, str := range strings { 77 offsets[i] = offset 78 offset += uint32(len(str)) + 1 // account for NUL 79 } 80 81 return &stringTable{nil, offsets, strings} 82 }