Skip to content

Fix WrongMethodTypeException in BStrFFM.free void invokeExact (#3422) - #3424

Merged
dbwiddis merged 3 commits into
oshi:masterfrom
dbwiddis:fix-bstr-free-invokeexact
Jul 1, 2026
Merged

dbwiddis merged 3 commits into
oshi:masterfrom
dbwiddis:fix-bstr-free-invokeexact

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Jul 1, 2026 •

Copy link
Copy Markdown
Member

Problem

Fixes #3422. On the Windows FFM path, BStrFFM.free throws at runtime:

java.lang.invoke.WrongMethodTypeException: handle's method type (MemorySegment)void but found (MemorySegment)Object
	at oshi.ffm.platform.windows.com.BStrFFM.lambda$free$0(BStrFFM.java:72)

SysFreeString is a void downcall (handle type (MemorySegment)void). MethodHandle.invokeExact is signature-polymorphic and infers its return type from the call site. In an expression-bodied lambda passed to the void-returning runOrLog(ThrowingRunnable), javac infers Object rather than void, so the call site's (MemorySegment)Object mismatches the handle and throws. It's caught and logged at DEBUG by runOrLog, so it doesn't crash — but the BSTR is never freed, leaking memory on every WMI query.

Regression note

This is a regression of #3302 (which fixed #3301). #3302 fixed this exact line with a block lambda. It was not lost in the later FFM package move (#3356 preserved it); it was re-broken by 1d0cb9cf97 "Collapse single-statement block lambdas to expression form (S1602)", a Sonar mechanical sweep that collapsed () -> { invokeExact(); } back to () -> invokeExact() — reintroducing the footgun. S1602 (and its autofix) will do this again to any such line.

Fix

  • Convert back to a block lambda so invokeExact is in a statement context where its return type is correctly inferred as void, with a comment marking why the block form matters.
  • Add VoidInvokeExactSourceTest, a source-policy test that scans oshi-core-ffm main sources for the expression-lambda form and fails with the offending file:line. Because the runtime WrongMethodTypeException only fires on the native platform and is swallowed by runOrLog, no ordinary unit test can observe it — the source scan runs on every build (incl. non-Windows CI) and is the guard against the next S1602-style collapse. Verified it fails on the pre-fix form and passes on the fix.

I scanned the whole oshi-core-ffm tree — BStrFFM.free was the only remaining reintroduction (sibling methods pin the type with casts; Ole32FFM uses a ::invokeExact method reference where the void SAM pins it).

Pre-commit gate (spotless, checkstyle, install, forbiddenapis, javadoc) passes on oshi-core-ffm.

Summary by CodeRabbit

  • Bug Fixes

    • Fixed an issue that could trigger a WrongMethodTypeException when releasing Windows WMI BSTR strings, improving stability on affected systems.
  • Tests

    • Added a safeguard test to catch similar low-level invocation regressions before release.

SysFreeString is a void downcall, so its handle type is (MemorySegment)void.
MethodHandle.invokeExact is signature-polymorphic and infers its return type
from the call site; in an expression lambda passed to the void-returning
runOrLog(ThrowingRunnable), javac infers Object instead of void, so the call
site's (MemorySegment)Object does not match the handle and throws
WrongMethodTypeException at runtime (swallowed at DEBUG, leaking the BSTR).

Convert to a block lambda so invokeExact is in a statement context and its
return type is inferred as void. This reinstates the fix from #3302, which was
lost when the FFM code moved from oshi.ffm.windows.com to
oshi.ffm.platform.windows.com; a comment now marks why the block form matters.

Fixes #3422
@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: de1f4a27-f8e6-4085-b8da-85252b78a4de

📥 Commits

Reviewing files that changed from the base of the PR and between 977a8f2 and 8555a9b.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • oshi-core-ffm/src/main/java/oshi/ffm/platform/windows/com/BStrFFM.java
  • oshi-core-ffm/src/test/java/oshi/ffm/VoidInvokeExactSourceTest.java
✅ Files skipped from review due to trivial changes (1)
  • CHANGELOG.md
🚧 Files skipped from review as they are similar to previous changes (2)
  • oshi-core-ffm/src/main/java/oshi/ffm/platform/windows/com/BStrFFM.java
  • oshi-core-ffm/src/test/java/oshi/ffm/VoidInvokeExactSourceTest.java
📜 Recent review details
⏰ Context from checks skipped due to timeout. (14)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)
  • GitHub Check: Test JDK 26, windows-latest
  • GitHub Check: Test JDK 26, macos-latest
  • GitHub Check: Test JDK 25, FreeBSD (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 26, ubuntu-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)

📝 Walkthrough

Walkthrough

BStrFFM.free now calls SysFreeString.invokeExact(bstr) inside a block lambda, a new test scans for similar expression-bodied invokeExact usage in runOrLog helpers, and the changelog notes the fix.

Changes

FFM void invokeExact fix

Layer / File(s) Summary
Statement lambda and source scan
oshi-core-ffm/src/main/java/oshi/ffm/platform/windows/com/BStrFFM.java, oshi-core-ffm/src/test/java/oshi/ffm/VoidInvokeExactSourceTest.java, CHANGELOG.md
BStrFFM.free switches SysFreeString.invokeExact(bstr) to a statement inside a block lambda, the new test fails if similar expression-bodied invokeExact usages appear under src/main/java, and the changelog records the fix.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

  • oshi/oshi#3302: Fixes the same BStrFFM.free invokeExact void-vs-object issue with the block-lambda change.

Poem

A bunny saw a lambda flip,
No more type mismatch on the trip.
One free call now hops just right,
And tests keep future voids in sight. 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the BStrFFM.free WrongMethodTypeException fix.
Linked Issues check ✅ Passed The PR fixes the BStrFFM.free failure in #3422 and adds a guard test that prevents the same void invokeExact regression from recurring, covering #3301's class of issue.
Out of Scope Changes check ✅ Passed The changelog update and source-policy test support the reported fix and regression prevention, with no unrelated changes evident.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Jul 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 75.15%. Comparing base (6537ec3) to head (8555a9b).
⚠️ Report is 6 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3424      +/-   ##
============================================
- Coverage     75.20%   75.15%   -0.05%     
  Complexity       76       76              
============================================
  Files           580      580              
  Lines         21589    21589              
  Branches       3583     3583              
============================================
- Hits          16235    16226       -9     
- Misses         3328     3336       +8     
- Partials       2026     2027       +1     
Flag Coverage Δ
freebsd 26.93% <ø> (ø)
linux 31.53% <ø> (+0.01%) ⬆️
macos 31.75% <ø> (-0.05%) ⬇️
openbsd 26.41% <ø> (+<0.01%) ⬆️
solaris 28.46% <ø> (ø)
windows 39.99% <ø> (-0.03%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

The WrongMethodTypeException from a void invokeExact in an expression lambda
only surfaces on the native platform and is swallowed by runOrLog, so no
ordinary unit test can observe it -- and it has already regressed twice when
the FFM code was moved between packages (#3301, #3422).

VoidInvokeExactSourceTest scans oshi-core-ffm's main sources for the
expression-lambda form and fails with the offending file:line, so the
regression is caught on every build (including non-Windows CI). Verified it
fails on the pre-fix form and passes on the block-lambda fix.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
oshi-core-ffm/src/test/java/oshi/ffm/VoidInvokeExactSourceTest.java (1)

41-59: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Regex misses multi-line expression lambdas.

The scan processes each line independently (lines.get(i) matched individually), so the pattern in Line 43 only catches offenders where -> and invokeExact appear on the same line. An expression lambda split across lines, e.g.:

runOrLog(() ->
    SysFreeString.invokeExact(bstr), LOG, "msg");

would not be flagged, even though it reproduces the exact WrongMethodTypeException this test is meant to guard against. Given the stated purpose — catching a regression that has already recurred twice — this is a meaningful blind spot.

Consider joining continuation lines (or matching against the whole file content with Pattern.DOTALL) before scanning, so line-wrapped expression lambdas are also detected.

♻️ Possible approach: scan whole-file content instead of per-line
-                    List<String> lines = Files.readAllLines(p, StandardCharsets.UTF_8);
-                    for (int i = 0; i < lines.size(); i++) {
-                        if (EXPRESSION_LAMBDA_INVOKE_EXACT.matcher(lines.get(i)).find()) {
-                            offenders.add(p + ":" + (i + 1) + "  " + lines.get(i).strip());
-                        }
-                    }
+                    String content = Files.readString(p, StandardCharsets.UTF_8);
+                    Matcher m = EXPRESSION_LAMBDA_INVOKE_EXACT.matcher(content);
+                    while (m.find()) {
+                        int line = (int) content.substring(0, m.start()).chars().filter(c -> c == '\n').count() + 1;
+                        offenders.add(p + ":" + line + "  " + m.group().strip());
+                    }

(pattern would also need Pattern.DOTALL so . / [^{] can span newlines)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@oshi-core-ffm/src/test/java/oshi/ffm/VoidInvokeExactSourceTest.java` around
lines 41 - 59, The source scan in VoidInvokeExactSourceTest only checks each
line separately, so EXPRESSION_LAMBDA_INVOKE_EXACT misses expression lambdas
split across multiple lines. Update noVoidInvokeExactInExpressionLambda to scan
multi-line content instead of lines.get(i), for example by reading each file
into a single string or joining continuation lines and using a DOTALL-capable
pattern. Keep the detection anchored around EXPRESSION_LAMBDA_INVOKE_EXACT and
the per-file loop in noVoidInvokeExactInExpressionLambda so wrapped
runOrLog/runSilently lambdas with invokeExact are still flagged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@oshi-core-ffm/src/test/java/oshi/ffm/VoidInvokeExactSourceTest.java`:
- Around line 41-59: The source scan in VoidInvokeExactSourceTest only checks
each line separately, so EXPRESSION_LAMBDA_INVOKE_EXACT misses expression
lambdas split across multiple lines. Update noVoidInvokeExactInExpressionLambda
to scan multi-line content instead of lines.get(i), for example by reading each
file into a single string or joining continuation lines and using a
DOTALL-capable pattern. Keep the detection anchored around
EXPRESSION_LAMBDA_INVOKE_EXACT and the per-file loop in
noVoidInvokeExactInExpressionLambda so wrapped runOrLog/runSilently lambdas with
invokeExact are still flagged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 35eda9dc-e719-4e32-a4de-26f7a423aef5

📥 Commits

Reviewing files that changed from the base of the PR and between de545fa and 977a8f2.

📒 Files selected for processing (1)
  • oshi-core-ffm/src/test/java/oshi/ffm/VoidInvokeExactSourceTest.java
📜 Review details
⏰ Context from checks skipped due to timeout. (15)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 26, macos-latest
  • GitHub Check: Test JDK 21, ubuntu-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 26, windows-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 26, ubuntu-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
  • GitHub Check: Test JDK 25, FreeBSD (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)
🔇 Additional comments (1)
oshi-core-ffm/src/test/java/oshi/ffm/VoidInvokeExactSourceTest.java (1)

1-40: LGTM!

Also applies to: 60-70

- Add // NOSONAR (java:S1602) on the BStrFFM.free block lambda so a future
  Sonar S1602 sweep can't collapse it back to the expression form that
  reintroduced #3422. It is the only single-statement void invokeExact block
  lambda; the other runOrLog/runSilently blocks are multi-statement, and
  Ole32FFM.CoUninitialize is a safe no-arg method reference.
- VoidInvokeExactSourceTest now scans whole-file content (bounded to a single
  statement with [^{};]*) so an expression lambda wrapped across lines is also
  caught, not just single-line occurrences.
- Add CHANGELOG entry.
@dbwiddis
dbwiddis merged commit 50ca2b6 into oshi:master Jul 1, 2026
31 of 32 checks passed
@dbwiddis
dbwiddis deleted the fix-bstr-free-invokeexact branch July 1, 2026 08:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

FFM free string failed on windows handle's method type ()void but found ()Object on windows when getFileStores with FFM

1 participant