[libvirt] [libvirt-java] [PATCH] Fix wrapping of native size_t data type

Eric Blake eblake at redhat.com
Wed May 8 15:42:52 UTC 2013


On 04/24/2013 07:43 AM, Claudio Bley wrote:
> Libvirt function parameters having type (pointer to) size_t were
> wrapped via JNA using int, long or even NativeLong. Alas, none of
> these is actually correct as the size of size_t may be the same as the
> size of either (unsigned) int, long or even long long on different
> platforms.
> 
> JNA provides the size of a native size_t to us, so using this
> information we define and use class SizeT and class SizeTByReference for
> wrapping a native size_t and size_t*, respectively.
> 
> Signed-off-by: Claudio Bley <cbley at av-test.de>
> ---

> +public final class SizeT extends IntegerType {
> +    public SizeT() { this(0); }
> +    public SizeT(long value) {
> +        /* N.B. A three argument constructor is supported starting with
> +         * JNA version 3.4.1.
> +         *
> +         * The third argument determines whether this class represents
> +         * an unsigned integer type. When extracting a value into a
> +         * larger-sized container (e.g. 4 byte native type into Java
> +         * long), the value is properly converted as unsigned.
> +         *
> +         * TODO: Use this constructor once we require JNA >= 3.4.1
> +         */
> +        // super(Native.SIZE_T_SIZE, value, true);
> +        super(Native.SIZE_T_SIZE, value);

Can't you enforce proper expansion yourself, something like:

super(Native.SIZE_T_SIZE,
      Native.SIZE_T_SIZE == 4 ? value & 0xffffffffL : value);

That way, even on a 32-bit platform, if a caller passes in a size_t
value of 0x80000000, but it gets sign-extended in conversion to Java
long, you undo the sign extension and leave things with a positive value
even without relying on the 3-argument superconstructor.   Then again,
it probably won't ever matter - if you have a 32-bit size_t, you are
probably on a 32-bit platform where it is impossible to address that
much memory in one object anyways, so it is unlikely that bug-free code
will ever be passing a size_t value that large.  If we argue that a
large value is already buggy, and that we would eventually reject it as
an error anyways, then it shouldn't matter if it accidentally gets sign
extended into an even larger invalid value.

Other than that, this patch looks okay to me.

-- 
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 621 bytes
Desc: OpenPGP digital signature
URL: <http://listman.redhat.com/archives/libvir-list/attachments/20130508/f96db3f8/attachment-0001.sig>


More information about the libvir-list mailing list