Repository navigation
Fix SonarQube AutoCloseable findings for borrowed CF references - #3298
Conversation
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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (16)
📜 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)
🧰 Additional context used🧠 Learnings (2)📚 Learning: 2026-04-06T04:45:47.644ZApplied to files:
📚 Learning: 2026-04-08T00:58:07.212ZApplied to files:
🔇 Additional comments (18)
📝 WalkthroughWalkthroughThis PR introduces "borrowed segment" static helper methods to CoreFoundation wrapper classes ( ChangesFFM and native resource management improvements
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
Codecov Report❌ Patch coverage is 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
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.
Summary
Resolves 45 SonarQube blocker findings introduced when
CFTypeRefwas madeAutoCloseablein #3292.Background
PR #3292 correctly made
CFTypeRefimplementAutoCloseable, 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 aCFTypeRefsubclass 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:
Create/Copyfunctions) — caller owns the reference and must callCFRelease. These should use try-with-resources. ✓Getfunctions likeCFDictionaryGetValue,CFArrayGetValueAtIndex,IOReportChannelGetGroup) — caller does NOT own the reference and must NOT callCFRelease. 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:
Added static methods to
CFStringRef,CFNumberRef,CFBooleanRef,CFArrayRef, andCFDictionaryRefthat operate directly onMemorySegmentwithout creating anAutoCloseablewrapper.2. Move owned refs directly into try-with-resources
For owned references (DASessionRef, DADiskRef) that had a gap between creation and the try block:
3. @SuppressWarnings for framework-consumed references
For references with complex ownership semantics that cannot be expressed through code structure:
CFAllocatorReffromCFAllocatorGetDefault()— a borrowed singleton that must never be releasedCFMutableDictionaryRefpassed toIOServiceGetMatchingServices()— IOKit consumes (releases) the matching dictionary on the caller's behalfSummary by CodeRabbit
Refactor
Chores