Skip to content

Make IOObject and CFTypeRef AutoCloseable, migrate macOS call sites - #3292

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:migrate-macos-autocloseable
May 23, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:migrate-macos-autocloseable

Conversation

@dbwiddis

@dbwiddis dbwiddis commented May 23, 2026 •

Copy link
Copy Markdown
Member

Make IOObject and CFTypeRef implement AutoCloseable (delegating to their existing release() methods), enabling try-with-resources for IOKit and CoreFoundation object lifecycle management. This is PR 3 in the NativeHandle/AutoCloseable series (#3290, #3291).

Infrastructure

  • IOKit.IOObject now implements AutoCloseable with close() → release()
  • CoreFoundation.CFTypeRef now implements AutoCloseable with close() → release()

Migrated call sites (11 files)

  • IOKitProviderFFM, MacDisplayFFM, MacFirmwareFFM, MacGpuStatsFFM
  • MacNetworkIfFFM, MacUsbDeviceFFM, MacOSProcessFFM
  • IOReportClientFFM, WindowInfoFFM

Remaining for follow-up

Complex patterns not addressed in this PR:

  • MacHWDiskStoreFFM — deeply nested with conditional releases and reassigned variables
  • MacSensorsFFM — smcClose(int) not AutoCloseable
  • MacPowerSourceFFM, MacFileSystemFFM — multi-release with null checks
  • IOKit.java — releaseCFObjects() multi-release helper
  • IOReportClientFFM — raw cfRelease with null checks
  • MacNetworkParamsFFM — freeaddrinfo (not a release pattern)

Summary by CodeRabbit

  • Refactor
    • Improved resource and lifecycle handling across macOS platform modules, enhancing stability and reliability by switching to deterministic automatic cleanup for system resources.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 23, 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: ef380d65-f2c4-4f13-8146-bc81ccb9cfda

📥 Commits

Reviewing files that changed from the base of the PR and between 132e079 and 466ad76.

📒 Files selected for processing (12)
  • .gitignore
  • 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/mac/IOKit.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/IOKitProviderFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacDisplayFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacFirmwareFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacNetworkIfFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.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: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
  • GitHub Check: Codacy Static Code Analysis
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: 2026-04-14T23:28:14.505Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3160
File: oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxSensorsTest.java:34-40
Timestamp: 2026-04-14T23:28:14.505Z
Learning: In oshi/oshi, treat `vcgencmd` as a Raspberry Pi–only dependency. For tests that set `isPi=true` and exercise `LinuxSensors.queryCpuTemperatureFromVcGenCmd()` (and related paths) expecting deterministic `0`/empty results when `vcgencmd` is unavailable, do not mark the assertions as potentially flaky due to CI/x86/amd64 environment differences—these tests are intended to be stable for non-Pi hosts.

Applied to files:

  • .gitignore
📚 Learning: 2026-04-15T04:56:15.707Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3163
File: oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java:97-103
Timestamp: 2026-04-15T04:56:15.707Z
Learning: In oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java, assertions that verify exact CFGetRetainCount deltas (+1 after retain and -1 after release) should be treated as intentional and reliable for freshly created, uniquely owned CoreFoundation objects (e.g., CFStringRef created via CFStringRef.createCFString). If the test creates the object and holds sole ownership, do not flag these CFGetRetainCount checks as flaky; the Apple guidance about avoiding CFGetRetainCount is intended for shared/framework-managed objects rather than exclusively owned unit-test objects.

Applied to files:

  • .gitignore
📚 Learning: 2026-04-18T23:21:41.153Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3173
File: oshi-common/src/main/java/oshi/driver/common/windows/wmi/Win32LogicalDisk.java:44-46
Timestamp: 2026-04-18T23:21:41.153Z
Learning: In `oshi-common/src/main/java/oshi/driver/common/windows/wmi/Win32LogicalDisk.java`, within `Win32LogicalDisk.buildWmiClassNameWithWhere`, the `nameToMatch` value is produced by OSHI’s prior WMI query results (i.e., controlled/non-user input). Therefore, during review do not flag the lack of additional WQL escaping for backslashes (`\`) or single quotes (`'`) in the `nameToMatch` handling; treat only the existing double-quote escaping as required/intentional (per maintainer confirmation).

Applied to files:

  • .gitignore
🔇 Additional comments (12)
oshi-core-ffm/src/main/java/oshi/ffm/mac/CoreFoundation.java (1)

91-91: LGTM!

Also applies to: 146-149

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

56-56: LGTM!

Also applies to: 78-81

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

29-31: LGTM!

Also applies to: 48-53

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

262-263: LGTM!

Also applies to: 292-293

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

67-67: LGTM!

Also applies to: 77-83

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

61-66: LGTM!

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

34-42: LGTM!

Also applies to: 45-53, 59-66, 72-73

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

106-109: LGTM!

Also applies to: 115-116, 132-137, 143-144, 179-182, 235-244

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

49-49: LGTM!

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

148-148: LGTM!

Also applies to: 177-177

oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java (1)

118-122: LGTM!

.gitignore (1)

20-20: LGTM!


📝 Walkthrough

Walkthrough

This PR refactors FFM resource management across the oshi macOS driver layer. Base classes CFTypeRef and IOObject now implement AutoCloseable, enabling try-with-resources throughout. Multiple macOS FFM files are updated to use try-with-resources blocks for CoreFoundation and IOKit references, replacing manual try/finally cleanup patterns.

Changes

FFM Try-with-Resources Resource Management

Layer / File(s) Summary
AutoCloseable Foundation Layer
oshi-core-ffm/src/main/java/oshi/ffm/mac/CoreFoundation.java, oshi-core-ffm/src/main/java/oshi/ffm/mac/IOKit.java
CFTypeRef and IOObject now implement AutoCloseable with close() methods that delegate to existing release(), enabling try-with-resources syntax for all dependent code.
IOKit Generic Provider Pattern
oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/IOKitProviderFFM.java
withMatchingService and forEachMatchingServiceUntil wrap IORegistryEntry and IOIterator in try-with-resources blocks, ensuring deterministic cleanup even on early visitor returns.
Driver and Utility Resource Management
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/hardware/platform/mac/MacDisplayFFM.java, oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacFirmwareFFM.java, oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java, oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacNetworkIfFFM.java, oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceFFM.java, oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java, .gitignore
IOReportClientFFM, WindowInfoFFM, MacDisplayFFM, MacFirmwareFFM, MacGpuStatsFFM, MacNetworkIfFFM, MacUsbDeviceFFM, and MacOSProcessFFM convert manual try/finally release() calls to try-with-resources for CoreFoundation references (CFStringRef, CFArrayRef, CFDataRef, CFMutableDictionaryRef) and IOKit resources (IOIterator, IORegistryEntry). Property extraction, enumeration loops, and early-return logic remain functionally unchanged. The .gitignore adds an ignore for .kiro/.

🐰 With AutoCloseable now in place,
Resources close themselves with grace,
No finally block in sight,
Just try-with-resources, clean and tight!


Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% 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 accurately describes the main changes: making IOObject and CFTypeRef AutoCloseable and migrating call sites to use this pattern.
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 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 71.42857% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.57%. Comparing base (4777faa) to head (466ad76).

Files with missing lines Patch % Lines
...ava/oshi/hardware/platform/mac/MacFirmwareFFM.java 60.00% 4 Missing ⚠️
...a/oshi/hardware/platform/mac/IOKitProviderFFM.java 75.00% 0 Missing and 1 partial ⚠️
...java/oshi/hardware/platform/mac/MacDisplayFFM.java 0.00% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3292      +/-   ##
============================================
- Coverage     75.77%   75.57%   -0.20%     
  Complexity       76       76              
============================================
  Files           410      410              
  Lines         15812    15810       -2     
  Branches       2524     2528       +4     
============================================
- Hits          11981    11949      -32     
- Misses         2369     2386      +17     
- Partials       1462     1475      +13     
Flag Coverage Δ
linux 40.12% <0.00%> (-0.03%) ⬇️
macos 40.91% <71.42%> (-0.05%) ⬇️
windows 48.62% <0.00%> (-0.14%) ⬇️

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.

Make IOObject and CFTypeRef implement AutoCloseable (delegating to
their existing release() methods), enabling try-with-resources for
IOKit and CoreFoundation object lifecycle management.

Migrated call sites:
- IOKitProviderFFM
- MacDisplayFFM
- MacFirmwareFFM
- MacGpuStatsFFM
- MacNetworkIfFFM
- MacUsbDeviceFFM
- MacOSProcessFFM
- IOReportClientFFM
- WindowInfoFFM

Remaining for follow-up (complex patterns):
- MacHWDiskStoreFFM (deeply nested, conditional releases)
- MacSensorsFFM (smcClose takes int, not AutoCloseable)
- MacPowerSourceFFM (multi-release with null checks)
- MacFileSystemFFM (conditional releases)
- IOKit.java (releaseCFObjects multi-release helper)
- IOReportClientFFM (raw cfRelease with null checks)
- MacNetworkParamsFFM (freeaddrinfo)
- WhoFFM, MacCentralProcessorFFM, MacDisplayFFM (partial)
@dbwiddis
dbwiddis force-pushed the migrate-macos-autocloseable branch from 132e079 to 466ad76 Compare May 23, 2026 23:07
@dbwiddis
dbwiddis merged commit 3889424 into oshi:master May 23, 2026
19 checks passed
@dbwiddis
dbwiddis deleted the migrate-macos-autocloseable branch May 23, 2026 23:22
dbwiddis added a commit that referenced this pull request May 24, 2026
* Fix native resource leaks in JNA module

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.

* Fix SonarQube AutoCloseable findings for borrowed CF references

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.
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