strings.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package btf
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io"
  7. )
  8. type stringTable []byte
  9. func readStringTable(r io.Reader) (stringTable, error) {
  10. contents, err := io.ReadAll(r)
  11. if err != nil {
  12. return nil, fmt.Errorf("can't read string table: %v", err)
  13. }
  14. if len(contents) < 1 {
  15. return nil, errors.New("string table is empty")
  16. }
  17. if contents[0] != '\x00' {
  18. return nil, errors.New("first item in string table is non-empty")
  19. }
  20. if contents[len(contents)-1] != '\x00' {
  21. return nil, errors.New("string table isn't null terminated")
  22. }
  23. return stringTable(contents), nil
  24. }
  25. func (st stringTable) Lookup(offset uint32) (string, error) {
  26. if int64(offset) > int64(^uint(0)>>1) {
  27. return "", fmt.Errorf("offset %d overflows int", offset)
  28. }
  29. pos := int(offset)
  30. if pos >= len(st) {
  31. return "", fmt.Errorf("offset %d is out of bounds", offset)
  32. }
  33. if pos > 0 && st[pos-1] != '\x00' {
  34. return "", fmt.Errorf("offset %d isn't start of a string", offset)
  35. }
  36. str := st[pos:]
  37. end := bytes.IndexByte(str, '\x00')
  38. if end == -1 {
  39. return "", fmt.Errorf("offset %d isn't null terminated", offset)
  40. }
  41. return string(str[:end]), nil
  42. }