ptr.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package sys
  2. import (
  3. "unsafe"
  4. "github.com/cilium/ebpf/internal/unix"
  5. )
  6. // NewPointer creates a 64-bit pointer from an unsafe Pointer.
  7. func NewPointer(ptr unsafe.Pointer) Pointer {
  8. return Pointer{ptr: ptr}
  9. }
  10. // NewSlicePointer creates a 64-bit pointer from a byte slice.
  11. func NewSlicePointer(buf []byte) Pointer {
  12. if len(buf) == 0 {
  13. return Pointer{}
  14. }
  15. return Pointer{ptr: unsafe.Pointer(&buf[0])}
  16. }
  17. // NewSlicePointerLen creates a 64-bit pointer from a byte slice.
  18. //
  19. // Useful to assign both the pointer and the length in one go.
  20. func NewSlicePointerLen(buf []byte) (Pointer, uint32) {
  21. return NewSlicePointer(buf), uint32(len(buf))
  22. }
  23. // NewStringPointer creates a 64-bit pointer from a string.
  24. func NewStringPointer(str string) Pointer {
  25. p, err := unix.BytePtrFromString(str)
  26. if err != nil {
  27. return Pointer{}
  28. }
  29. return Pointer{ptr: unsafe.Pointer(p)}
  30. }
  31. // NewStringSlicePointer allocates an array of Pointers to each string in the
  32. // given slice of strings and returns a 64-bit pointer to the start of the
  33. // resulting array.
  34. //
  35. // Use this function to pass arrays of strings as syscall arguments.
  36. func NewStringSlicePointer(strings []string) Pointer {
  37. sp := make([]Pointer, 0, len(strings))
  38. for _, s := range strings {
  39. sp = append(sp, NewStringPointer(s))
  40. }
  41. return Pointer{ptr: unsafe.Pointer(&sp[0])}
  42. }