[Libguestfs] [PATCH libnbd] golang: aio_buffer.go: Explicit panic() on invalid usage

Nir Soffer nsoffer at redhat.com
Thu Jun 9 17:10:53 UTC 2022


Previously we depended on the behavior on common platforms to panic when
trying to use a nil pointer, but Richard reported that it segfault on
RISC-V. Avoid the undocumented assumptions and panic explicitly with a
useful panic message.

Signed-off-by: Nir Soffer <nsoffer at redhat.com>
---
 golang/aio_buffer.go | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/golang/aio_buffer.go b/golang/aio_buffer.go
index 52ea54de..325dbc98 100644
--- a/golang/aio_buffer.go
+++ b/golang/aio_buffer.go
@@ -65,28 +65,37 @@ func (b *AioBuffer) Free() {
 	if b.P != nil {
 		C.free(b.P)
 		b.P = nil
 	}
 }
 
 // Bytes copies the underlying C array to Go allocated memory and return a
 // slice. Modifying the returned slice does not modify the underlying buffer
 // backing array.
 func (b *AioBuffer) Bytes() []byte {
+	if b.P == nil {
+		panic("Using AioBuffer after Free()")
+	}
 	return C.GoBytes(b.P, C.int(b.Size))
 }
 
 // Slice creates a slice backed by the underlying C array. The slice can be
 // used to access or modify the contents of the underlying array. The slice
 // must not be used after caling Free().
 func (b *AioBuffer) Slice() []byte {
+	if b.P == nil {
+		panic("Using AioBuffer after Free()")
+	}
 	// See https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices
 	// TODO: Use unsafe.Slice() when we require Go 1.17.
 	return (*[1<<30]byte)(b.P)[:b.Size:b.Size]
 }
 
 // Get returns a pointer to a byte in the underlying C array. The pointer can
 // be used to modify the underlying array. The pointer must not be used after
 // calling Free().
 func (b *AioBuffer) Get(i uint) *byte {
+	if b.P == nil {
+		panic("Using AioBuffer after Free()")
+	}
 	return (*byte)(unsafe.Pointer(uintptr(b.P) + uintptr(i)))
 }
-- 
2.36.1



More information about the Libguestfs mailing list