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

Richard W.M. Jones rjones at redhat.com
Thu Jun 9 17:44:30 UTC 2022


On Thu, Jun 09, 2022 at 08:10:53PM +0300, Nir Soffer wrote:
> 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>

I tested this on RISC-V and it fixes the tests, so I pushed it, thanks.

BTW this doesn't fix the cgocheck=2 problem, I still have to disable
that line in run.in (on RISC-V).

Rich.

>  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

-- 
Richard Jones, Virtualization Group, Red Hat http://people.redhat.com/~rjones
Read my programming and virtualization blog: http://rwmj.wordpress.com
Fedora Windows cross-compiler. Compile Windows programs, test, and
build Windows installers. Over 100 libraries supported.
http://fedoraproject.org/wiki/MinGW


More information about the Libguestfs mailing list