Skip to content

Fix SonarQube AutoCloseable findings for borrowed CF references - #3298

Merged
dbwiddis merged 2 commits into
oshi:masterfrom
dbwiddis:fix/sonarqube-autocloseable-findings
May 24, 2026
Merged

dbwiddis merged 2 commits into
oshi:masterfrom
dbwiddis:fix/sonarqube-autocloseable-findings

Conversation

@dbwiddis

@dbwiddis dbwiddis commented May 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Resolves 45 SonarQube blocker findings introduced when CFTypeRef was made AutoCloseable in #3292.

Background

PR #3292 correctly made CFTypeRef implement AutoCloseable, enabling try-with-resources for owned CoreFoundation objects. This uncovered real memory leaks and established clear ownership semantics. However, it also caused SonarQube to flag every place where a CFTypeRef subclass is instantiated without being closed — including borrowed references that must NOT be released.

Why these are false positives

CoreFoundation uses reference-counted memory management with two ownership patterns:

  • Owned references (from Create/Copy functions) — caller owns the reference and must call CFRelease. These should use try-with-resources. ✓
  • Borrowed references (from Get functions like CFDictionaryGetValue, CFArrayGetValueAtIndex, IOReportChannelGetGroup) — caller does NOT own the reference and must NOT call CFRelease. Closing these would decrement the ref count on objects still owned by their parent containers, causing use-after-free or double-free bugs.

SonarQube cannot distinguish between these two patterns. It sees new CFStringRef(segment) and flags it as an unclosed resource regardless of whether the segment is owned or borrowed.

Fix strategies

Three patterns are used depending on the context:

1. Static value-extraction methods (majority of fixes)

For the common pattern of wrapping a borrowed segment just to extract a value:

// Before — SonarQube flags unclosed CFStringRef
new CFStringRef(groupSeg).stringValue()

// After — no AutoCloseable created
CFStringRef.stringValue(groupSeg)

Added static methods to CFStringRef, CFNumberRef, CFBooleanRef, CFArrayRef, and CFDictionaryRef that operate directly on MemorySegment without creating an AutoCloseable wrapper.

2. Move owned refs directly into try-with-resources

For owned references (DASessionRef, DADiskRef) that had a gap between creation and the try block:

// Before — SonarQube flags potential leak between create and try
DASessionRef session = DASessionRef.create(alloc);
if (session.isNull()) { return; }
try (session) { ... }

// After — no gap
try (DASessionRef session = DASessionRef.create(alloc)) {
    if (session.isNull()) { return; }
    ...
}

3. @SuppressWarnings for framework-consumed references

For references with complex ownership semantics that cannot be expressed through code structure:

  • CFAllocatorRef from CFAllocatorGetDefault() — a borrowed singleton that must never be released
  • CFMutableDictionaryRef passed to IOServiceGetMatchingServices() — IOKit consumes (releases) the matching dictionary on the caller's behalf
@SuppressWarnings("resource") // consumed by getMatchingServices
CFMutableDictionaryRef matchingDict = ...

Summary by CodeRabbit

  • Refactor

    • Optimized internal memory access patterns across macOS and Windows implementations to reduce object allocations and improve performance.
  • Chores

    • Enhanced resource cleanup and lifetime management throughout native library interactions to improve stability and prevent resource leaks.

Review Change Stack

dbwiddis added 2 commits May 24, 2026 02:10
Add try/finally blocks to ensure native resources are released even when
exceptions occur:

- WindowsInternetProtocolStatsJNA: Wrap Memory buf in try/finally in all
  4 connection query methods. Also fixes missing buf.close() in
  queryUDPv6Connections() which leaked on every call. Gate table parsing
  on ERROR_SUCCESS to avoid parsing buf on API failures.
- WindowsDisplayJNA: Wrap hDevInfo and registry key in try/finally.
- WindowsPowerSourceJNA: Wrap hdev (SetupDi handle) in try/finally.
- MacHWDiskStoreJNA: Wrap DASession and CFStringRef releases in
  try/finally. Move try to start immediately after session null-check
  so mapCFKeys() failure cannot leak the session.
- HkeyUserData: Wrap registry key usage in try/finally.
- SessionWtsData: Wrap WTSFreeMemory calls in try/finally for both
  the session info buffer and individual query buffers. Guard
  WTSQuerySessionInformation calls by checking return value and null
  pointer before dereferencing.
- ProcessWtsData: Wrap WTSFreeMemoryEx in try/finally.

The FFM equivalents of these files already handle resource cleanup
correctly (via Arena try-with-resources or NativeHandle). These fixes
bring the JNA module to parity.
Add static value-extraction methods to CFStringRef, CFNumberRef,
CFBooleanRef, CFArrayRef, and CFDictionaryRef for use with borrowed
(non-owned) CoreFoundation segments that must not be released.

Migrate all call sites that wrap borrowed segments solely for value
extraction. For owned references with gaps before try-with-resources,
move creation directly into the try declaration. For framework-consumed
references (IOKit matching dictionaries), add @SuppressWarnings with
explanatory comments.

Resolves 45 SonarQube blocker findings introduced when CFTypeRef was
made AutoCloseable in #3292.
@coderabbitai

coderabbitai Bot commented May 24, 2026 •

Copy link
Copy Markdown
Contributor

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: 35301c02-f1e9-4a32-86b3-d5aa5ebc2f0d

📥 Commits

Reviewing files that changed from the base of the PR and between 6fa5662 and c42fea8.

📒 Files selected for processing (16)
  • oshi-core-ffm/src/main/java/oshi/driver/mac/IOReportClientFFM.java
  • oshi-core-ffm/src/main/java/oshi/driver/mac/WindowInfoFFM.java
  • oshi-core-ffm/src/main/java/oshi/ffm/mac/CoreFoundation.java
  • oshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/CFUtilFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacNetworkIfFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/mac/MacFileSystemFFM.java
  • oshi-core/src/main/java/oshi/driver/windows/registry/HkeyUserData.java
  • oshi-core/src/main/java/oshi/driver/windows/registry/ProcessWtsData.java
  • oshi-core/src/main/java/oshi/driver/windows/registry/SessionWtsData.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsDisplayJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java
  • oshi-core/src/main/java/oshi/software/os/windows/WindowsInternetProtocolStatsJNA.java
📜 Recent review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2026-04-06T04:45:47.644Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3121
File: oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java:53-53
Timestamp: 2026-04-06T04:45:47.644Z
Learning: In the oshi/oshi project, only interfaces and classes in the root packages `oshi`, `oshi.hardware`, and `oshi.software.os` are considered the public API. Code in subpackages that represent specific implementations/platforms (e.g., `oshi.software.os.linux`, `oshi.hardware.platform.linux`, and similar subpackages) is implementation detail. When reviewing, do not treat changes to classes in these platform-specific subpackages as public API breaks (for example: making `LinuxOperatingSystem` abstract, narrowing constructor visibility, or adding/removing abstract methods should not be flagged as breaking public API).

Applied to files:

  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsDisplayJNA.java
  • oshi-core/src/main/java/oshi/software/os/windows/WindowsInternetProtocolStatsJNA.java
📚 Learning: 2026-04-08T00:58:07.212Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3125
File: oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java:131-133
Timestamp: 2026-04-08T00:58:07.212Z
Learning: Do not flag `getPowerSources()` as incorrect when it returns a singleton list that wraps `getPowerSource("System Battery")` and/or short-circuits the enumeration after the first eligible battery pack in the Windows power source JNA/FFM implementations. This is intentional for longstanding JNA behavior; a refactor to support zero-or-more batteries is planned later, so the current single-battery behavior should be treated as by-design rather than a bug.

Applied to files:

  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java
🔇 Additional comments (18)
oshi-core-ffm/src/main/java/oshi/ffm/mac/CoreFoundation.java (1)

215-234: LGTM!

Also applies to: 256-275, 381-392, 418-429, 444-457, 538-550, 667-698

oshi-core-ffm/src/main/java/oshi/driver/mac/IOReportClientFFM.java (1)

253-259: LGTM!

Also applies to: 264-265, 269-270, 281-288, 293-299, 308-308

oshi-core-ffm/src/main/java/oshi/driver/mac/WindowInfoFFM.java (1)

91-93: LGTM!

Also applies to: 98-100, 103-103, 118-121

oshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/CFUtilFFM.java (1)

42-42: LGTM!

oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacNetworkIfFFM.java (1)

55-55: LGTM!

Also applies to: 58-58

oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java (1)

111-111: LGTM!

Also applies to: 118-118, 139-139, 146-146, 184-184, 246-246

oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java (1)

62-77: LGTM!

Also applies to: 119-133, 136-143, 162-167, 176-178, 254-259, 291-294, 301-302, 306-313, 412-416

oshi-core/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreJNA.java (1)

68-80: LGTM!

oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.java (2)

187-188: LGTM!


192-192: LGTM!

Also applies to: 199-199, 204-204

oshi-core-ffm/src/main/java/oshi/software/os/mac/MacFileSystemFFM.java (2)

84-85: LGTM!


86-90: ⚡ Quick win

Confirm null-safety of DASessionRef/CFTypeRef.close() in try-with-resources

The early return fsList; still exits the try-with-resources and will invoke DASessionRef.close() (via its CFTypeRef superclass). The current evidence only shows DASessionRef extends CFTypeRef and delegates the constructor to super(segment), but it doesn’t show whether CFTypeRef.close() safely handles a NULL/absent MemorySegment (e.g., MemorySegment.NULL). Ensure close() is a no-op (or otherwise safe) for NULL segments, or avoid creating DASessionRef when DASessionCreate(...) produces a NULL segment.

oshi-core/src/main/java/oshi/driver/windows/registry/HkeyUserData.java (1)

54-78: LGTM!

oshi-core/src/main/java/oshi/driver/windows/registry/SessionWtsData.java (1)

59-141: LGTM!

oshi-core/src/main/java/oshi/driver/windows/registry/ProcessWtsData.java (1)

72-89: LGTM!

oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsDisplayJNA.java (1)

70-87: LGTM!

Also applies to: 89-91

oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java (1)

107-297: LGTM!

oshi-core/src/main/java/oshi/software/os/windows/WindowsInternetProtocolStatsJNA.java (1)

115-137: LGTM!

Also applies to: 150-171, 184-204, 217-237


📝 Walkthrough

Walkthrough

This PR introduces "borrowed segment" static helper methods to CoreFoundation wrapper classes (CFNumberRef, CFBooleanRef, CFArrayRef, CFDictionaryRef, CFStringRef) and refactors macOS driver/hardware code to use them instead of constructing wrapper instances. It also tightens Windows resource cleanup in registry, WTS session, and device enumeration code via try/finally patterns.

Changes

FFM and native resource management improvements

Layer / File(s) Summary
CoreFoundation borrowed-segment static helpers
oshi-core-ffm/src/main/java/oshi/ffm/mac/CoreFoundation.java
Adds 7 new static extraction APIs: CFNumberRef.longValue(segment) and intValue(segment) extract numeric values; CFBooleanRef.booleanValue(segment) extracts booleans; CFArrayRef.getCount(segment) and getValueAtIndex(segment, idx) access array elements; CFDictionaryRef.getValue(segment, key) performs dictionary lookups; CFStringRef.stringValue(segment) converts native strings to Java. All include null-safety handling and fallback/default values.
macOS driver and utility refactoring
oshi-core-ffm/src/main/java/oshi/driver/mac/IOReportClientFFM.java, WindowInfoFFM.java, oshi-core-ffm/.../CFUtilFFM.java, MacNetworkIfFFM.java
IOReportClientFFM's energy/channel extraction and WindowInfoFFM's window property parsing now use CFDictionaryRef.getValue/CFArrayRef accessors and CFStringRef.stringValue directly instead of wrapping. CFUtilFFM simplifies string conversion, and MacNetworkIfFFM removes intermediate CFStringRef wrapping in BSD name matching.
macOS hardware and system updates
oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java, MacHWDiskStoreFFM.java, MacHWDiskStoreJNA.java, MacPowerSourceFFM.java, oshi-core-ffm/.../MacFileSystemFFM.java
MacGpuStatsFFM switches GPU stats extraction to static CF helpers. MacHWDiskStoreFFM refactors disk stats/partition discovery to use CFDictionaryRef.getValue and CFNumberRef.longValue directly, and tightens DASessionRef lifecycle via try-with-resources. MacHWDiskStoreJNA, MacPowerSourceFFM, and MacFileSystemFFM add try-with-resources/try-finally for guaranteed cleanup of DiskArbitration and CoreFoundation resources.
Windows resource cleanup via try/finally
oshi-core/src/main/java/oshi/driver/windows/registry/HkeyUserData.java, SessionWtsData.java, ProcessWtsData.java, oshi-core/.../WindowsDisplayJNA.java, WindowsPowerSourceJNA.java, WindowsInternetProtocolStatsJNA.java
Registry key queries (HkeyUserData, SessionWtsData) and process/WTS enumeration (ProcessWtsData) wrap native handle/buffer cleanup in try/finally to guarantee release even on failure. WindowsDisplayJNA, WindowsPowerSourceJNA, and WindowsInternetProtocolStatsJNA refactor buffer allocation/EDID/battery/TCP-UDP queries to use try-with-resources or try/finally, ensuring JNA Memory buffers are closed and device lists destroyed regardless of exception/error conditions.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • oshi/oshi#3163: Adds integration tests validating CoreFoundation wrapper behavior against native symbols, complementing this PR's new borrowed-segment static helper APIs.
  • oshi/oshi#3296: Overlaps directly on MacHWDiskStoreFFM refactoring to try-with-resources and native value extraction, addressing the same disk storage resource lifetime patterns.
  • oshi/oshi#3294: Updates MacFileSystemFFM.getFileStoreMatching to use try-with-resources for DiskArbitration/CoreFoundation resource lifetime, using the same pattern as this PR.

Poem

🐰 Borrowed segments dance with grace,
No wrappers cluttering the place,
Windows cleanup, finally sure,
Resources freed, forever pure! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 45.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 and specifically identifies the primary change: fixing SonarQube findings related to AutoCloseable borrowed CoreFoundation references, which is the main focus across all modified files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 and usage tips.

@codecov

codecov Bot commented May 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 68.27586% with 46 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.52%. Comparing base (f35b3c2) to head (c42fea8).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
...re/os/windows/WindowsInternetProtocolStatsJNA.java 56.36% 12 Missing and 12 partials ⚠️
.../oshi/hardware/platform/mac/MacHWDiskStoreFFM.java 77.14% 4 Missing and 4 partials ⚠️
...ava/oshi/driver/windows/registry/HkeyUserData.java 61.53% 1 Missing and 4 partials ⚠️
...in/java/oshi/software/os/mac/MacFileSystemFFM.java 25.00% 2 Missing and 1 partial ⚠️
...a/oshi/driver/windows/registry/ProcessWtsData.java 80.00% 1 Missing and 1 partial ⚠️
...i/hardware/platform/windows/WindowsDisplayJNA.java 80.00% 0 Missing and 2 partials ⚠️
...m/src/main/java/oshi/driver/mac/WindowInfoFFM.java 90.00% 0 Missing and 1 partial ⚠️
...va/oshi/hardware/platform/mac/MacNetworkIfFFM.java 50.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3298      +/-   ##
============================================
- Coverage     75.54%   75.52%   -0.03%     
  Complexity       76       76              
============================================
  Files           410      410              
  Lines         15807    15814       +7     
  Branches       2539     2546       +7     
============================================
+ Hits          11942    11943       +1     
- Misses         2385     2386       +1     
- Partials       1480     1485       +5     
Flag Coverage Δ
linux 40.14% <0.00%> (+0.02%) ⬆️
macos 40.82% <30.34%> (-0.05%) ⬇️
windows 48.61% <37.93%> (-0.03%) ⬇️

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

☔ View full report in Codecov by Sentry.
📢 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.

@dbwiddis
dbwiddis merged commit 2e28cda into oshi:master May 24, 2026
18 of 19 checks passed
@dbwiddis
dbwiddis deleted the fix/sonarqube-autocloseable-findings branch May 24, 2026 05:21
dbwiddis added a commit that referenced this pull request Aug 3, 2026
The getString/getLong helpers hoisted in #3570 were copied from the JNA
twin verbatim, wrapping the borrowed CFDictionaryGetValue result in
`new CFStringRef(v)` / `new CFNumberRef(v)` just to read a value. In FFM
CFTypeRef is AutoCloseable, so that reintroduces the exact shape #3298
removed when it added the static borrowed-segment accessors and migrated
45 call sites to them. SonarCloud flagged both as S2095 blockers.

Switch to CFStringRef.stringValue(MemorySegment) and
CFNumberRef.longValue(MemorySegment), matching cfPointerToString a few
lines above. There was no leak to fix: these are borrowed references
under the CF Get Rule and must not be released, so actually closing them
as the rule literally suggests would over-release memory OSHI does not
own. The constructors' type-ID check is dropped, which is the tradeoff
the other migrated sites already accepted; a soft "" / 0 fallback via
getOrDefault is preferable here to a ClassCastException escaping
MacDisplayFFM.synthesize.

The JNA CFUtil twin is intentionally left alone: its CFTypeRef is a
PointerType, not AutoCloseable, so the idiom is correct there and it has
no static accessors to switch to.

Verified on macOS (JDK 26): CFUtilFFMTest testGetString/testGetLong run
and pass, and SystemInfoTest still enumerates both the external and the
built-in display, whose synthesize() path calls both methods.
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.

1 participant