From fdafa897045a2147cdc0f7c62e5741035cb22e66 Mon Sep 17 00:00:00 2001 From: Nassim Boutekedjiret Date: Wed, 18 Nov 2026 13:52:19 +0100 Subject: [PATCH 1/3] Issue #85: Free the native memory of WMI queries without waiting for the garbage collector Property values are read into a native VARIANT buffer freed right after the conversion, instead of a JNA VARIANT structure that allocates a native block for each pointer field of its union on every creation and read. Scalar values are converted straight from the buffer, exactly as before; arrays, objects and unexpected types still go through the JNA structure. IEnumWbemClassObject::Next reuses two native buffers for all the records. One Win32_Process query (534 rows) left 151,372 native blocks to the garbage collector, and now leaves 9. Co-Authored-By: Claude Opus 5.5 --- .../wmi/wbem/WmiCimTypeHandler.java | 236 ++++++++++++++---- .../metricshub/wmi/wbem/WmiWbemServices.java | 94 +++---- .../wmi/wbem/WmiCimTypeHandlerTest.java | 102 ++++++++ .../wmi/wbem/WmiWbemServicesTest.java | 86 +++++++ 4 files changed, 428 insertions(+), 90 deletions(-) diff --git a/src/main/java/org/metricshub/wmi/wbem/WmiCimTypeHandler.java b/src/main/java/org/metricshub/wmi/wbem/WmiCimTypeHandler.java index d3c53a3..ece723d 100644 --- a/src/main/java/org/metricshub/wmi/wbem/WmiCimTypeHandler.java +++ b/src/main/java/org/metricshub/wmi/wbem/WmiCimTypeHandler.java @@ -20,6 +20,9 @@ * ╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱ */ +import com.sun.jna.Memory; +import com.sun.jna.Native; +import com.sun.jna.Pointer; import com.sun.jna.platform.win32.COM.COMUtils; import com.sun.jna.platform.win32.COM.IUnknown; import com.sun.jna.platform.win32.COM.Unknown; @@ -27,11 +30,13 @@ import com.sun.jna.platform.win32.COM.Wbemcli.IWbemClassObject; import com.sun.jna.platform.win32.Guid.REFIID; import com.sun.jna.platform.win32.OaIdl.SAFEARRAY; -import com.sun.jna.platform.win32.OleAuto; -import com.sun.jna.platform.win32.Variant.VARIANT.ByReference; +import com.sun.jna.platform.win32.Variant; +import com.sun.jna.platform.win32.Variant.VARIANT; import com.sun.jna.platform.win32.WinNT.HRESULT; -import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.PointerByReference; +import com.sun.jna.win32.StdCallLibrary; +import com.sun.jna.win32.W32APIOptions; +import java.nio.charset.StandardCharsets; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collections; @@ -56,29 +61,29 @@ private WmiCimTypeHandler() {} /** * Map of functions that convert WBEM types to Java corresponding class/type */ - private static final Map> CIMTYPE_TO_CONVERTER_MAP; + private static final Map> CIMTYPE_TO_CONVERTER_MAP; static { - final Map> map = new HashMap<>(); + final Map> map = new HashMap<>(); map.put(Wbemcli.CIM_EMPTY, value -> null); - map.put(Wbemcli.CIM_BOOLEAN, ByReference::booleanValue); + map.put(Wbemcli.CIM_BOOLEAN, VARIANT::booleanValue); - map.put(Wbemcli.CIM_UINT8, ByReference::byteValue); - map.put(Wbemcli.CIM_UINT16, ByReference::intValue); + map.put(Wbemcli.CIM_UINT8, VARIANT::byteValue); + map.put(Wbemcli.CIM_UINT16, VARIANT::intValue); map.put(Wbemcli.CIM_UINT32, WmiCimTypeHandler::convertCimUint32); - map.put(Wbemcli.CIM_UINT64, ByReference::stringValue); - map.put(Wbemcli.CIM_SINT8, ByReference::shortValue); - map.put(Wbemcli.CIM_SINT16, ByReference::shortValue); - map.put(Wbemcli.CIM_SINT32, ByReference::intValue); - map.put(Wbemcli.CIM_SINT64, ByReference::stringValue); + map.put(Wbemcli.CIM_UINT64, VARIANT::stringValue); + map.put(Wbemcli.CIM_SINT8, VARIANT::shortValue); + map.put(Wbemcli.CIM_SINT16, VARIANT::shortValue); + map.put(Wbemcli.CIM_SINT32, VARIANT::intValue); + map.put(Wbemcli.CIM_SINT64, VARIANT::stringValue); - map.put(Wbemcli.CIM_REAL32, ByReference::floatValue); - map.put(Wbemcli.CIM_REAL64, ByReference::doubleValue); + map.put(Wbemcli.CIM_REAL32, VARIANT::floatValue); + map.put(Wbemcli.CIM_REAL64, VARIANT::doubleValue); - map.put(Wbemcli.CIM_CHAR16, ByReference::shortValue); - map.put(Wbemcli.CIM_STRING, ByReference::stringValue); + map.put(Wbemcli.CIM_CHAR16, VARIANT::shortValue); + map.put(Wbemcli.CIM_STRING, VARIANT::stringValue); map.put(Wbemcli.CIM_REFERENCE, WmiCimTypeHandler::convertCimReference); map.put(Wbemcli.CIM_DATETIME, WmiCimTypeHandler::convertCimDateTime); @@ -89,7 +94,27 @@ private WmiCimTypeHandler() {} private static final String CIM_OBJECT_LABEL = "CIM_OBJECT"; /** - * Convert a ByReference value holding a CIM_UINT32 (i.e. an unsigned int on 32 bits). + * IWbemClassObject::Get is the 5th method of the IWbemClassObject vtable + */ + private static final int WBEM_CLASS_OBJECT_GET_VTABLE_ID = 4; + + /** + * Size of a native VARIANT (16 bytes on 32-bit, 24 bytes on 64-bit) + */ + private static final long VARIANT_SIZE = new VARIANT().size(); + + /** + * Offset of the value in a native VARIANT (after vt and 3 reserved WORDs) + */ + private static final long VARIANT_VALUE_OFFSET = 8; + + /** + * Returned by {@link #convertScalar} when the value is not a scalar it can convert + */ + static final Object NOT_SCALAR = new Object(); + + /** + * Convert a VARIANT value holding a CIM_UINT32 (i.e. an unsigned int on 32 bits). *

* Unfortunately, there seems to be a bug in either JNA or Wbemcli library which stores * CIM_UINT32 values as VT_I4 (signed integer). As a result, it's converted to a signed @@ -100,18 +125,18 @@ private WmiCimTypeHandler() {} * @param cimUint32Value a CIM_UINT32 value... potentially (and wrongly) stored as a VT_I4 * @return always a positive long */ - private static long convertCimUint32(final ByReference cimUint32Value) { + private static long convertCimUint32(final VARIANT cimUint32Value) { return Integer.toUnsignedLong(cimUint32Value.intValue()); } /** - * Convert a ByReference value holding a CIM_DATETIME (i.e. a string in the form + * Convert a VARIANT value holding a CIM_DATETIME (i.e. a string in the form * of yyyymmddHHMMSS.mmmmmmsUUU, or ddddddddHHMMSS.mmmmmm:000 * for an interval) to an OffsetDateTime or a Duration object - * @param value ByReference value with a CIM_DATETIME string + * @param value VARIANT value with a CIM_DATETIME string * @return OffsetDateTime instance, or Duration instance for an interval */ - static Object convertCimDateTime(final ByReference value) { + static Object convertCimDateTime(final VARIANT value) { return Utils.convertCimDateTimeOrInterval(value.stringValue()); } @@ -120,7 +145,7 @@ static Object convertCimDateTime(final ByReference value) { * @param value CIM_REFERENCE * @return a proper String */ - static String convertCimReference(final ByReference value) { + static String convertCimReference(final VARIANT value) { return WmiCimTypeHandler.convertCimReference(value.stringValue()); } @@ -150,7 +175,7 @@ static String convertCimReference(final String reference) { * (example: DriveInfo.Name) */ static Map convertSafeArray( - final ByReference array, + final VARIANT array, final int cimType, final Entry> property ) { @@ -242,7 +267,7 @@ static Map convertSafeArray( * The key is the property as defined in the select request. * (example: DriveInfo.Name) */ - static Map convertCimObject(final ByReference value, final Entry> property) { + static Map convertCimObject(final VARIANT value, final Entry> property) { final Optional maybeClassObject = getUnknownWbemClassObject(value.getValue()); if (!maybeClassObject.isPresent()) { return property @@ -334,7 +359,7 @@ static Optional getUnknownWbemClassObject(final Object value) /** * Convert the specified CIM value into a Java Object depending on its CIM type. - * @param value CIM value (ByReference) + * @param value CIM value (VARIANT) * @param cimType CIM Type * @param property The Property to retrieve. An Entry with the property name * as the key and a set of sub properties to retrieve if exists. @@ -344,7 +369,7 @@ static Optional getUnknownWbemClassObject(final Object value) * (example: DriveInfo.Name) */ static Map convert( - final ByReference value, + final VARIANT value, final int cimType, final Entry> property ) { @@ -392,35 +417,154 @@ public static Map getPropertyValue( } } + /** + * Reads the property into a native VARIANT buffer that is freed as soon as the value is converted. + *

+ * A JNA {@link VARIANT} structure allocates a native memory block for each pointer field of its union, + * every time it is created or read (about 50 blocks per value), and these blocks are only freed by the + * garbage collector. Scalar values are therefore read straight from the buffer, and the JNA structure + * is only built for arrays, objects and unexpected types. + */ private static Map getPropertyValueFromWbemObject( final IWbemClassObject wbemClassObject, final Entry> property ) { - final ByReference value = new ByReference(); - final IntByReference pType = new IntByReference(); + // The name is null for a (sub-)property that the class does not define: Get() then fails, and the value is null + final String name = property.getKey(); + try ( + Memory variant = new Memory(VARIANT_SIZE); + Memory pType = new Memory(4); + Memory wszName = name == null ? null : new Memory((name.length() + 1L) * Native.WCHAR_SIZE) + ) { + // Initialize value (VT_EMPTY), to make sure *VariantClear()* won't throw an exception + // See https://docs.microsoft.com/en-us/windows/win32/api/wbemcli/nf-wbemcli-iwbemclassobject-get + variant.clear(); + if (wszName != null) { + wszName.setWideString(0, name); + } - // Initialize value, to make sure *VariantClear()* won't throw an exception - // See https://docs.microsoft.com/en-us/windows/win32/api/wbemcli/nf-wbemcli-iwbemclassobject-get - OleAuto.INSTANCE.VariantInit(value); + try { + final HRESULT hResult = (HRESULT) WmiComHelper.comInvokerInvokeNativeObject( + wbemClassObject.getPointer(), + WBEM_CLASS_OBJECT_GET_VTABLE_ID, + new Object[] { wbemClassObject.getPointer(), wszName, 0, variant, pType, null }, + HRESULT.class + ); + if (COMUtils.FAILED(hResult)) { + return Collections.singletonMap(name, null); + } - try { - final HRESULT hResult = wbemClassObject.Get(property.getKey(), 0, value, pType, new IntByReference()); - if (COMUtils.FAILED(hResult)) { - return Collections.singletonMap(property.getKey(), null); - } + // Special case for __PATH + final boolean isPath = "__PATH".equalsIgnoreCase(name); + final int cimType = isPath ? Wbemcli.CIM_REFERENCE : pType.getInt(0); - // Special case for __PATH - if ("__PATH".equalsIgnoreCase(property.getKey())) { - return Collections.singletonMap(property.getKey(), convertCimReference(value)); + final Object value = convertScalar(variant, cimType); + if (value != NOT_SCALAR) { + return Collections.singletonMap(name, value); + } + + final VARIANT jnaVariant = new VARIANT(variant); + return isPath + ? Collections.singletonMap(name, convertCimReference(jnaVariant)) + : convert(jnaVariant, cimType, property); + } finally { + try { + OleAutoPointer.INSTANCE.VariantClear(variant); + } catch (final Throwable t) { + /* Do nothing -- This condition rarely happens, but it does, and there's nothing we can do about it */ + } } + } + } - return convert(value, pType.getValue(), property); - } finally { - try { - OleAuto.INSTANCE.VariantClear(value); - } catch (final Throwable t) { - /* Do nothing -- This condition rarely happens, but it does, and there's nothing we can do about it */ + /** + * Converts the scalar value of a VARIANT, exactly as {@link #convert} does it through the JNA structure. + * + * @param variant Native VARIANT + * @param cimType CIM type of the value + * @return the converted value, or {@link #NOT_SCALAR} when the value must go through {@link #convert} + */ + static Object convertScalar(final Pointer variant, final int cimType) { + final Object value; + switch (variant.getShort(0)) { + case Variant.VT_EMPTY: + case Variant.VT_NULL: + return null; + case Variant.VT_BSTR: + final Pointer bstr = variant.getPointer(VARIANT_VALUE_OFFSET); + if (bstr == null) { + return null; + } + value = new String(bstr.getByteArray(0, bstr.getInt(-4)), StandardCharsets.UTF_16LE); + break; + case Variant.VT_BOOL: + return cimType == Wbemcli.CIM_BOOLEAN ? variant.getShort(VARIANT_VALUE_OFFSET) != 0 : NOT_SCALAR; + case Variant.VT_UI1: + // JNA's BYTE gives the unsigned value as an int, but the signed one as a float or a double + if (cimType == Wbemcli.CIM_REAL32 || cimType == Wbemcli.CIM_REAL64) { + return NOT_SCALAR; + } + value = variant.getByte(VARIANT_VALUE_OFFSET) & 0xFF; + break; + case Variant.VT_I2: + value = variant.getShort(VARIANT_VALUE_OFFSET); + break; + case Variant.VT_I4: + value = variant.getInt(VARIANT_VALUE_OFFSET); + break; + case Variant.VT_R4: + value = variant.getFloat(VARIANT_VALUE_OFFSET); + break; + case Variant.VT_R8: + value = variant.getDouble(VARIANT_VALUE_OFFSET); + break; + default: + return NOT_SCALAR; + } + + if (value instanceof String) { + switch (cimType) { + case Wbemcli.CIM_STRING: + case Wbemcli.CIM_UINT64: + case Wbemcli.CIM_SINT64: + return value; + case Wbemcli.CIM_REFERENCE: + return convertCimReference((String) value); + case Wbemcli.CIM_DATETIME: + return Utils.convertCimDateTimeOrInterval((String) value); + default: + return NOT_SCALAR; } } + + final Number number = (Number) value; + switch (cimType) { + case Wbemcli.CIM_UINT8: + return number.byteValue(); + case Wbemcli.CIM_UINT16: + case Wbemcli.CIM_SINT32: + return number.intValue(); + case Wbemcli.CIM_UINT32: + return Integer.toUnsignedLong(number.intValue()); + case Wbemcli.CIM_SINT8: + case Wbemcli.CIM_SINT16: + case Wbemcli.CIM_CHAR16: + return number.shortValue(); + case Wbemcli.CIM_REAL32: + return number.floatValue(); + case Wbemcli.CIM_REAL64: + return number.doubleValue(); + default: + return NOT_SCALAR; + } + } + + /** + * VariantClear() on a native VARIANT buffer (JNA's OleAuto only accepts its VARIANT structure). + */ + interface OleAutoPointer extends StdCallLibrary { + OleAutoPointer INSTANCE = Native.load("OleAut32", OleAutoPointer.class, W32APIOptions.DEFAULT_OPTIONS); + + HRESULT VariantClear(Pointer pvarg); } } diff --git a/src/main/java/org/metricshub/wmi/wbem/WmiWbemServices.java b/src/main/java/org/metricshub/wmi/wbem/WmiWbemServices.java index 0a9e797..becd5ed 100644 --- a/src/main/java/org/metricshub/wmi/wbem/WmiWbemServices.java +++ b/src/main/java/org/metricshub/wmi/wbem/WmiWbemServices.java @@ -20,6 +20,8 @@ * ╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱ */ +import com.sun.jna.Memory; +import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.WString; import com.sun.jna.platform.win32.COM.COMException; @@ -650,6 +652,7 @@ static String getWmiComErrorMessage(final HRESULT hResult) { private static final int SET_VALUE_FUNCTION_VTABLE_ID_IN_WBEM_CONTEXT_INTERFACE = 8; + private static final int ENUM_WBEM_CLASS_OBJECT_NEXT_VTABLE_ID = 4; private static final int WBEM_SERVICES_GET_OBJECT_VTABLE_ID = 6; private static final int WBEM_SERVICES_EXEC_METHOD_VTABLE_ID = 24; @@ -1020,7 +1023,6 @@ private List> processWqlResult( final long timeout, final Map> properties ) throws TimeoutException, WmiComException, WqlQuerySyntaxException { - final Pointer[] pointersOnWbemClassObject = new Pointer[1]; final List> resultRows = new ArrayList<>(); String[] names = null; Map> normalizedProperties = null; @@ -1029,55 +1031,59 @@ private List> processWqlResult( setProxySecurity(wbemClassObjectQueryResult.getPointer(), authIdent); } - while (wbemClassObjectQueryResult.getPointer() != Pointer.NULL) { - // Get the next record - final HRESULT hResult = wbemClassObjectQueryResult.Next( - (int) timeout, - pointersOnWbemClassObject.length, - pointersOnWbemClassObject, - new IntByReference(0) - ); + // Native buffers reused for each record and freed on return, instead of + // a Pointer[] and an IntByReference per record left to the garbage collector + try (Memory ppObject = new Memory(Native.POINTER_SIZE); Memory puReturned = new Memory(4)) { + while (wbemClassObjectQueryResult.getPointer() != Pointer.NULL) { + // Get the next record + final HRESULT hResult = (HRESULT) WmiComHelper.comInvokerInvokeNativeObject( + wbemClassObjectQueryResult.getPointer(), + ENUM_WBEM_CLASS_OBJECT_NEXT_VTABLE_ID, + new Object[] { wbemClassObjectQueryResult.getPointer(), (int) timeout, 1, ppObject, puReturned }, + HRESULT.class + ); - // Any problem? - if ( - hResult == null || - hResult.intValue() == Wbemcli.WBEM_S_FALSE || - hResult.intValue() == Wbemcli.WBEM_S_NO_MORE_DATA - ) { - return resultRows; - } - if (hResult.intValue() == Wbemcli.WBEM_S_TIMEDOUT) { - throw new TimeoutException("No results after " + timeout + " ms."); - } - if (Integer.toUnsignedLong(hResult.intValue()) == 2147749911L) { - throw new WqlQuerySyntaxException("The query was not syntactically valid."); - } - checkHResult(hResult, "Failed to enumerate results"); + // Any problem? + if ( + hResult == null || + hResult.intValue() == Wbemcli.WBEM_S_FALSE || + hResult.intValue() == Wbemcli.WBEM_S_NO_MORE_DATA + ) { + return resultRows; + } + if (hResult.intValue() == Wbemcli.WBEM_S_TIMEDOUT) { + throw new TimeoutException("No results after " + timeout + " ms."); + } + if (Integer.toUnsignedLong(hResult.intValue()) == 2147749911L) { + throw new WqlQuerySyntaxException("The query was not syntactically valid."); + } + checkHResult(hResult, "Failed to enumerate results"); - // Get the actual WbemClassObject - final IWbemClassObject wbemClassObject = new IWbemClassObject(pointersOnWbemClassObject[0]); + // Get the actual WbemClassObject + final IWbemClassObject wbemClassObject = new IWbemClassObject(ppObject.getPointer(0)); - try { - // Get the list of properties in the first record - // Note: this is done only the first time in this loop - if (names == null) { - try { - names = wbemClassObject.GetNames(null, 0, null); - } catch (final Throwable e) { - names = wbemClassObject.GetNames(null, 0, null); + try { + // Get the list of properties in the first record + // Note: this is done only the first time in this loop + if (names == null) { + try { + names = wbemClassObject.GetNames(null, 0, null); + } catch (final Throwable e) { + names = wbemClassObject.GetNames(null, 0, null); + } } - } - if (normalizedProperties == null) { - normalizedProperties = normalizeProperties(names, properties); - } + if (normalizedProperties == null) { + normalizedProperties = normalizeProperties(names, properties); + } - // Add to the result - final Map values = getPropertiesValues(normalizedProperties, wbemClassObject); - resultRows.add(values); - } finally { - // Free memory for this WBEM object instance - wbemClassObject.Release(); + // Add to the result + final Map values = getPropertiesValues(normalizedProperties, wbemClassObject); + resultRows.add(values); + } finally { + // Free memory for this WBEM object instance + wbemClassObject.Release(); + } } } diff --git a/src/test/java/org/metricshub/wmi/wbem/WmiCimTypeHandlerTest.java b/src/test/java/org/metricshub/wmi/wbem/WmiCimTypeHandlerTest.java index b5c4759..49954fc 100644 --- a/src/test/java/org/metricshub/wmi/wbem/WmiCimTypeHandlerTest.java +++ b/src/test/java/org/metricshub/wmi/wbem/WmiCimTypeHandlerTest.java @@ -5,12 +5,17 @@ import com.sun.jna.platform.win32.COM.Wbemcli; import com.sun.jna.platform.win32.COM.Wbemcli.IWbemClassObject; +import com.sun.jna.platform.win32.OleAuto; +import com.sun.jna.platform.win32.Variant; import com.sun.jna.platform.win32.Variant.VARIANT; import com.sun.jna.platform.win32.Variant.VARIANT.ByReference; +import com.sun.jna.platform.win32.WTypes.BSTR; +import com.sun.jna.platform.win32.WinDef.BYTE; import java.time.Duration; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.*; +import java.util.function.Supplier; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledOnOs; @@ -200,4 +205,101 @@ void testConvertCimObject() { assertEquals(expected, WmiCimTypeHandler.convertCimObject(value, property)); } } + + @Test + void testConvertScalarReturnsWhatConvertReturns() { + final VARIANT vtNull = new VARIANT(); + vtNull.setVarType((short) Variant.VT_NULL); + final List values = Arrays.asList( + new VARIANT(), + vtNull, + new VARIANT(new BSTR()), + new VARIANT(""), + new VARIANT("abc"), + new VARIANT("\\\\HOST\\root\\cimv2:Win32_Process.Handle=\"4\""), + new VARIANT("20261118123456.123456+060"), + new VARIANT("00001485050106.000000:000"), + new VARIANT("18446744073709551615"), + new VARIANT(true), + new VARIANT(false), + new VARIANT(new BYTE(200)), + new VARIANT(new BYTE(5)), + new VARIANT((short) -5), + new VARIANT(Short.MAX_VALUE), + new VARIANT(-1), + new VARIANT(123), + new VARIANT(1.5f), + new VARIANT(-2.25d), + new VARIANT((byte) -3), + new VARIANT('x'), + new VARIANT(1L << 40) + ); + final int[] cimTypes = { + Wbemcli.CIM_EMPTY, + Wbemcli.CIM_SINT8, + Wbemcli.CIM_UINT8, + Wbemcli.CIM_SINT16, + Wbemcli.CIM_UINT16, + Wbemcli.CIM_SINT32, + Wbemcli.CIM_UINT32, + Wbemcli.CIM_SINT64, + Wbemcli.CIM_UINT64, + Wbemcli.CIM_REAL32, + Wbemcli.CIM_REAL64, + Wbemcli.CIM_BOOLEAN, + Wbemcli.CIM_STRING, + Wbemcli.CIM_DATETIME, + Wbemcli.CIM_REFERENCE, + Wbemcli.CIM_CHAR16, + Wbemcli.CIM_OBJECT, + Wbemcli.CIM_FLAG_ARRAY | Wbemcli.CIM_SINT32, + 999 + }; + final Map.Entry> property = new AbstractMap.SimpleEntry<>("p", Collections.emptySet()); + + int converted = 0; + try { + for (final VARIANT value : values) { + value.write(); + for (final int cimType : cimTypes) { + final String context = "vt=" + value.getVarType().intValue() + " cimType=" + cimType; + final Object actual = outcome(() -> WmiCimTypeHandler.convertScalar(value.getPointer(), cimType)); + if (actual == WmiCimTypeHandler.NOT_SCALAR) { + continue; + } + final Object expected = outcome(() -> WmiCimTypeHandler.convert(value, cimType, property).get("p")); + if (expected instanceof Throwable || actual instanceof Throwable) { + // Both paths must fail the same way (the caller retries, then lets the exception go) + assertEquals(String.valueOf(expected), String.valueOf(actual), context); + continue; + } + assertEquals(expected, actual, context); + assertEquals( + expected == null ? null : expected.getClass(), + actual == null ? null : actual.getClass(), + context + ); + converted++; + } + } + } finally { + values.forEach(OleAuto.INSTANCE::VariantClear); + } + + assertTrue(converted > 70, converted + " values converted without the JNA structure"); + final VARIANT minusOne = new VARIANT(-1); + minusOne.write(); + assertEquals(4294967295L, WmiCimTypeHandler.convertScalar(minusOne.getPointer(), Wbemcli.CIM_UINT32)); + } + + /** + * @return the value returned by the supplier, or the exception it threw + */ + private static Object outcome(final Supplier supplier) { + try { + return supplier.get(); + } catch (final Throwable t) { + return t; + } + } } diff --git a/src/test/java/org/metricshub/wmi/wbem/WmiWbemServicesTest.java b/src/test/java/org/metricshub/wmi/wbem/WmiWbemServicesTest.java index 816d147..64d9e4c 100644 --- a/src/test/java/org/metricshub/wmi/wbem/WmiWbemServicesTest.java +++ b/src/test/java/org/metricshub/wmi/wbem/WmiWbemServicesTest.java @@ -2,11 +2,15 @@ import static org.junit.jupiter.api.Assertions.*; +import com.sun.jna.Memory; import com.sun.jna.Pointer; import com.sun.jna.platform.win32.OleAuto; import com.sun.jna.platform.win32.Variant; import com.sun.jna.platform.win32.WinNT.HRESULT; import java.lang.Thread.UncaughtExceptionHandler; +import java.lang.management.GarbageCollectorMXBean; +import java.lang.management.ManagementFactory; +import java.lang.reflect.Field; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.List; @@ -605,4 +609,86 @@ public void uncaughtException(final Thread t, final Throwable e) { assertEquals(threadCount / 2, failureCount.get(), "Exception must have been thrown for each failed query"); assertEquals(threadCount / 2, resultCount.get(), "Each successful query must have returned 1 record"); } + + @Test + @Order(40) + void testQueryLeavesNoNativeMemoryToTheGarbageCollector() throws Exception { + final String query = "SELECT Name, ProcessId, ThreadCount, HandleCount, CreationDate FROM Win32_Process"; + try (WmiWbemServices wmiWbemServices = WmiWbemServices.getInstance("root/cimv2", null, null)) { + // Warm-up: JNA allocates its one-time structures on the first query + wmiWbemServices.executeWql(query, 30000); + + // A garbage collection frees blocks during the query and hides the ones the query left: + // only a query that ran without any garbage collection is measured + for (int attempt = 0; attempt < 5; attempt++) { + drainGarbageCollectedNativeMemory(); + final long collections = garbageCollectionCount(); + final int before = allocatedNativeMemoryCount(); + final List> result = wmiWbemServices.executeWql(query, 30000); + final int leftToGc = allocatedNativeMemoryCount() - before; + if (garbageCollectionCount() != collections) { + continue; + } + + assertTrue(result.size() > 10, "Win32_Process must list the running processes"); + assertTrue( + leftToGc >= 0 && leftToGc < 20, + () -> leftToGc + " JNA Memory blocks left to the garbage collector for " + result.size() + " rows" + ); + return; + } + fail("A garbage collection ran during each of the 5 queries"); + } + } + + @Test + @Order(41) + void testUnknownEmbeddedObjectPropertyIsNull() throws Exception { + try (WmiWbemServices wmiWbemServices = WmiWbemServices.getInstance("root/wmi", null, null)) { + final List> result = wmiWbemServices.executeWql( + "SELECT InstanceName, PerfData.NoSuchProperty FROM MSDiskDriver_Performance", + 30000 + ); + + assertFalse(result.isEmpty(), "MSDiskDriver_Performance must list the disks"); + for (final Map row : result) { + assertNotNull(row.get("InstanceName")); + assertTrue(row.containsKey("PerfData.null"), row::toString); + assertNull(row.get("PerfData.null")); + } + } + } + + /** + * @return the number of native memory blocks allocated by JNA and not freed yet + */ + private static int allocatedNativeMemoryCount() throws ReflectiveOperationException { + final Field field = Memory.class.getDeclaredField("allocatedMemory"); + field.setAccessible(true); + return ((Map) field.get(null)).size(); + } + + /** + * @return the number of garbage collections since the JVM started + */ + private static long garbageCollectionCount() { + return ManagementFactory + .getGarbageCollectorMXBeans() + .stream() + .mapToLong(GarbageCollectorMXBean::getCollectionCount) + .sum(); + } + + /** + * Lets the garbage collector and the JNA cleaner free the blocks that are already unreachable, + * so that they are not freed in the middle of the measured query. + */ + private static void drainGarbageCollectedNativeMemory() throws ReflectiveOperationException, InterruptedException { + System.gc(); + int previous = -1; + for (int i = 0; i < 50 && previous != allocatedNativeMemoryCount(); i++) { + previous = allocatedNativeMemoryCount(); + Thread.sleep(100); + } + } } From 9f47429eb6cb6ef49dfb34f22258ed74f536acf4 Mon Sep 17 00:00:00 2001 From: Nassim Boutekedjiret Date: Wed, 18 Nov 2026 14:46:20 +0100 Subject: [PATCH 2/3] Issue #85: Fix the two Checkstyle violations Call VariantClear through a cached JNA Function instead of a library interface whose method name breaks the naming rule, and remove an unused import. Co-Authored-By: Claude Opus 5.5 --- .../wmi/wbem/WmiCimTypeHandler.java | 22 +++++++++---------- .../metricshub/wmi/wbem/WmiWbemServices.java | 1 - 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/metricshub/wmi/wbem/WmiCimTypeHandler.java b/src/main/java/org/metricshub/wmi/wbem/WmiCimTypeHandler.java index ece723d..cd61dd7 100644 --- a/src/main/java/org/metricshub/wmi/wbem/WmiCimTypeHandler.java +++ b/src/main/java/org/metricshub/wmi/wbem/WmiCimTypeHandler.java @@ -34,8 +34,6 @@ import com.sun.jna.platform.win32.Variant.VARIANT; import com.sun.jna.platform.win32.WinNT.HRESULT; import com.sun.jna.ptr.PointerByReference; -import com.sun.jna.win32.StdCallLibrary; -import com.sun.jna.win32.W32APIOptions; import java.nio.charset.StandardCharsets; import java.util.AbstractMap; import java.util.ArrayList; @@ -108,6 +106,15 @@ private WmiCimTypeHandler() {} */ private static final long VARIANT_VALUE_OFFSET = 8; + /** + * VariantClear() on a native VARIANT buffer (JNA's OleAuto only accepts its VARIANT structure) + */ + private static final com.sun.jna.Function VARIANT_CLEAR = com.sun.jna.Function.getFunction( + "OleAut32", + "VariantClear", + com.sun.jna.Function.ALT_CONVENTION + ); + /** * Returned by {@link #convertScalar} when the value is not a scalar it can convert */ @@ -469,7 +476,7 @@ private static Map getPropertyValueFromWbemObject( : convert(jnaVariant, cimType, property); } finally { try { - OleAutoPointer.INSTANCE.VariantClear(variant); + VARIANT_CLEAR.invokeInt(new Object[] { variant }); } catch (final Throwable t) { /* Do nothing -- This condition rarely happens, but it does, and there's nothing we can do about it */ } @@ -558,13 +565,4 @@ static Object convertScalar(final Pointer variant, final int cimType) { return NOT_SCALAR; } } - - /** - * VariantClear() on a native VARIANT buffer (JNA's OleAuto only accepts its VARIANT structure). - */ - interface OleAutoPointer extends StdCallLibrary { - OleAutoPointer INSTANCE = Native.load("OleAut32", OleAutoPointer.class, W32APIOptions.DEFAULT_OPTIONS); - - HRESULT VariantClear(Pointer pvarg); - } } diff --git a/src/main/java/org/metricshub/wmi/wbem/WmiWbemServices.java b/src/main/java/org/metricshub/wmi/wbem/WmiWbemServices.java index becd5ed..62ae5a3 100644 --- a/src/main/java/org/metricshub/wmi/wbem/WmiWbemServices.java +++ b/src/main/java/org/metricshub/wmi/wbem/WmiWbemServices.java @@ -42,7 +42,6 @@ import com.sun.jna.platform.win32.WTypes; import com.sun.jna.platform.win32.WTypes.BSTR; import com.sun.jna.platform.win32.WinNT.HRESULT; -import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.PointerByReference; import java.nio.charset.Charset; import java.util.ArrayList; From e6de18fcbfd8ba60f9396fb23595eb20c12576a5 Mon Sep 17 00:00:00 2001 From: Nassim Boutekedjiret Date: Thu, 19 Nov 2026 11:28:56 +0100 Subject: [PATCH 3/3] Issue #85: Size the ULONG and CIMTYPE buffers with the JNA type sizes Co-Authored-By: Claude Opus 5.5 --- src/main/java/org/metricshub/wmi/wbem/WmiCimTypeHandler.java | 3 ++- src/main/java/org/metricshub/wmi/wbem/WmiWbemServices.java | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/metricshub/wmi/wbem/WmiCimTypeHandler.java b/src/main/java/org/metricshub/wmi/wbem/WmiCimTypeHandler.java index cd61dd7..53ae60d 100644 --- a/src/main/java/org/metricshub/wmi/wbem/WmiCimTypeHandler.java +++ b/src/main/java/org/metricshub/wmi/wbem/WmiCimTypeHandler.java @@ -32,6 +32,7 @@ import com.sun.jna.platform.win32.OaIdl.SAFEARRAY; import com.sun.jna.platform.win32.Variant; import com.sun.jna.platform.win32.Variant.VARIANT; +import com.sun.jna.platform.win32.WinDef; import com.sun.jna.platform.win32.WinNT.HRESULT; import com.sun.jna.ptr.PointerByReference; import java.nio.charset.StandardCharsets; @@ -440,7 +441,7 @@ private static Map getPropertyValueFromWbemObject( final String name = property.getKey(); try ( Memory variant = new Memory(VARIANT_SIZE); - Memory pType = new Memory(4); + Memory pType = new Memory(WinDef.LONG.SIZE); Memory wszName = name == null ? null : new Memory((name.length() + 1L) * Native.WCHAR_SIZE) ) { // Initialize value (VT_EMPTY), to make sure *VariantClear()* won't throw an exception diff --git a/src/main/java/org/metricshub/wmi/wbem/WmiWbemServices.java b/src/main/java/org/metricshub/wmi/wbem/WmiWbemServices.java index 62ae5a3..03d225e 100644 --- a/src/main/java/org/metricshub/wmi/wbem/WmiWbemServices.java +++ b/src/main/java/org/metricshub/wmi/wbem/WmiWbemServices.java @@ -41,6 +41,7 @@ import com.sun.jna.platform.win32.Variant.VARIANT.ByReference; import com.sun.jna.platform.win32.WTypes; import com.sun.jna.platform.win32.WTypes.BSTR; +import com.sun.jna.platform.win32.WinDef; import com.sun.jna.platform.win32.WinNT.HRESULT; import com.sun.jna.ptr.PointerByReference; import java.nio.charset.Charset; @@ -1032,7 +1033,7 @@ private List> processWqlResult( // Native buffers reused for each record and freed on return, instead of // a Pointer[] and an IntByReference per record left to the garbage collector - try (Memory ppObject = new Memory(Native.POINTER_SIZE); Memory puReturned = new Memory(4)) { + try (Memory ppObject = new Memory(Native.POINTER_SIZE); Memory puReturned = new Memory(WinDef.ULONG.SIZE)) { while (wbemClassObjectQueryResult.getPointer() != Pointer.NULL) { // Get the next record final HRESULT hResult = (HRESULT) WmiComHelper.comInvokerInvokeNativeObject(