Skip to content

Migrate nested handle patterns to NativeHandle (Windows + Linux) - #3291

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:migrate-nested-native-handles
May 23, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:migrate-nested-native-handles

Conversation

@dbwiddis

@dbwiddis dbwiddis commented May 23, 2026 •

Copy link
Copy Markdown
Member

Replace manual try/finally blocks with NativeHandle try-with-resources for nested native handle lifecycle management. This is PR 2 of 3 in the NativeHandle migration series (#3290 introduced the class).

Linux (udev handles)

  • LinuxCentralProcessorFFM (3 methods: topology, current freq, max freq)
  • LinuxHWDiskStoreFFM
  • LinuxLogicalVolumeGroupFFM
  • LinuxNetworkIFFFM
  • LinuxPowerSourceFFM
  • LinuxUsbDeviceFFM

Windows

  • WindowsBluetoothDeviceFFM (radio find + device find handles)
  • WindowsDisplayFFM (SetupDi + registry key handles; extracted queryEdidFromKey helper)
  • WindowsPowerSourceFFM (SetupDi + battery handles)
  • WindowsOSProcessFFM (process + token handles)

Summary

  • 11 files changed, net -56 lines
  • All nested finally blocks replaced with NativeHandle try-with-resources
  • PR 3 will cover macOS (IOObject/CFTypeRef → AutoCloseable)

Summary by CodeRabbit

  • Refactor

    • Improved native resource management across platform-specific hardware and OS modules for better reliability and cleaner code handling.
  • Chores

    • Updated project ignore patterns.

Review Change Stack

Replace manual try/finally blocks with NativeHandle try-with-resources
for nested native handle lifecycle management.

Linux (udev):
- LinuxCentralProcessorFFM (3 methods)
- LinuxHWDiskStoreFFM
- LinuxLogicalVolumeGroupFFM
- LinuxNetworkIFFFM
- LinuxPowerSourceFFM
- LinuxUsbDeviceFFM

Windows:
- WindowsBluetoothDeviceFFM (radio + device find handles)
- WindowsDisplayFFM (SetupDi + registry key handles)
- WindowsPowerSourceFFM (SetupDi + battery handles)
- WindowsOSProcessFFM (process + token handles)
@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: cbcca0c2-19f3-4c7b-925b-36b95e442dff

📥 Commits

Reviewing files that changed from the base of the PR and between 47e9f43 and 896bf03.

📒 Files selected for processing (11)
  • .gitignore
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/linux/LinuxCentralProcessorFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/linux/LinuxHWDiskStoreFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/linux/LinuxLogicalVolumeGroupFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/linux/LinuxNetworkIFFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/linux/LinuxUsbDeviceFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsBluetoothDeviceFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsDisplayFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.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). (10)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-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 (5)
📚 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
📚 Learning: 2026-04-05T15:37:16.042Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3117
File: oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxUsbDeviceFFM.java:59-65
Timestamp: 2026-04-05T15:37:16.042Z
Learning: For OSHI Linux USB device implementations, the behavior of `getUsbDevices(boolean tree)` with `tree=false` is intentional: the returned flat list includes controller nodes (it is not meant to exclude them). In code review, do not flag the implementation for including controllers in flat mode; instead, only flag/update documentation/JavaDoc that incorrectly claims controllers are excluded (e.g., Javadoc text like "returns a flat list excluding controllers" should be corrected).

Applied to files:

  • oshi-core-ffm/src/main/java/oshi/hardware/platform/linux/LinuxUsbDeviceFFM.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-ffm/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
🔇 Additional comments (11)
.gitignore (1)

19-19: LGTM!

oshi-core-ffm/src/main/java/oshi/hardware/platform/linux/LinuxCentralProcessorFFM.java (1)

27-27: LGTM!

Also applies to: 87-90, 104-105, 129-129, 131-131, 176-176, 178-178

oshi-core-ffm/src/main/java/oshi/hardware/platform/linux/LinuxHWDiskStoreFFM.java (1)

20-20: LGTM!

Also applies to: 73-73, 75-75, 89-89

oshi-core-ffm/src/main/java/oshi/hardware/platform/linux/LinuxLogicalVolumeGroupFFM.java (1)

24-24: LGTM!

Also applies to: 54-54, 56-56, 70-70

oshi-core-ffm/src/main/java/oshi/hardware/platform/linux/LinuxNetworkIFFFM.java (1)

20-20: LGTM!

Also applies to: 49-49, 52-52

oshi-core-ffm/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java (1)

22-22: LGTM!

Also applies to: 60-60, 62-62, 80-80

oshi-core-ffm/src/main/java/oshi/hardware/platform/linux/LinuxUsbDeviceFFM.java (1)

21-21: LGTM!

Also applies to: 82-82, 84-84, 100-100

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

28-28: LGTM!

Also applies to: 72-73, 76-76, 121-121

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

20-20: LGTM!

Also applies to: 60-60, 76-79, 88-110

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

53-53: LGTM!

Also applies to: 134-134, 167-167

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

127-128: LGTM!

Also applies to: 132-132, 138-138, 193-194, 196-199, 219-220, 222-225, 295-297, 301-301, 314-314, 327-327, 337-337, 341-341, 348-348


📝 Walkthrough

Walkthrough

This PR refactors native resource management across multiple Linux and Windows FFM (Foreign Function Memory) classes to consistently use NativeHandle try-with-resources wrappers instead of manual try/finally unref and close patterns. The refactoring spans CPU topology/frequency queries, disk/LVM/network/power/USB enumeration, Bluetooth device discovery, display EDID registry handling, and process information queries, with no changes to public API signatures or external behavior.

Changes

Native Handle Lifecycle Management Refactor

Layer / File(s) Summary
Linux CPU topology and frequency via udev
oshi-core-ffm/src/main/java/oshi/hardware/platform/linux/LinuxCentralProcessorFFM.java
LinuxCentralProcessorFFM wraps udev context and enumerate handles in nested try-with-resources blocks for topology enumeration and replaces manual try/finally unref logic in queryCurrentFreqFromUdev and queryMaxFreqFromUdev, including per-device handle management for property reads.
Linux hardware enumeration via udev
oshi-core-ffm/src/main/java/oshi/hardware/platform/linux/LinuxHWDiskStoreFFM.java, LinuxLogicalVolumeGroupFFM.java, LinuxNetworkIFFFM.java, LinuxPowerSourceFFM.java, LinuxUsbDeviceFFM.java
Five Linux FFM classes adopt NativeHandle wrapping for udev enumeration and per-device handle lifetimes during disk store, LVM, network interface, power source, and USB device discovery, removing nested explicit finally unref blocks.
Windows Bluetooth device enumeration
oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsBluetoothDeviceFFM.java
Radio and device enumeration handles are wrapped in NativeHandle try-with-resources blocks, eliminating manual BluetoothFindRadioClose, BluetoothFindDeviceClose, and CloseHandle finally calls.
Windows display device and registry EDID handling
oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsDisplayFFM.java
Device-info and registry key handles are wrapped via NativeHandle try-with-resources; EDID registry value retrieval is extracted into a queryEdidFromKey(...) helper that performs sizing and read in one method.
Windows power source device and battery enumeration
oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
SetupAPI device-info and battery handles are wrapped in NativeHandle try-with-resources, removing manual SetupDiDestroyDeviceInfoList and battery CloseHandle finally blocks.
Windows OS process information queries
oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
Process and token handle lifetimes in updateAttributes, queryUserInfo, queryGroupInfo, and queryCwdCommandlineEnvironment are managed via NativeHandle try-with-resources; handle references inside scopes use h.get() accessor.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • oshi/oshi#3290: Introduces oshi.ffm.NativeHandle class and migrates initial FFM handle management patterns that this PR builds upon across more classes.
  • oshi/oshi#3126: Also refactors WindowsOSProcessFFM native handle management for process/token/CWD/command-line queries.
  • oshi/oshi#3120: Both PRs refactor LinuxCentralProcessorFFM udev-based CPU topology and frequency code paths.

🐰 Native handles hop along the path so free,
No more unref dances, resources wild and free,
Try-with-resources wrap them tight,
Cleanup scopes do their magic right! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.76% 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 summarizes the main change: migrating nested handle patterns to NativeHandle across Windows and Linux platforms.
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 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.60%. Comparing base (47e9f43) to head (896bf03).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...i/hardware/platform/windows/WindowsDisplayFFM.java 63.63% 5 Missing and 3 partials ⚠️
.../oshi/software/os/windows/WindowsOSProcessFFM.java 69.56% 0 Missing and 7 partials ⚠️
...re/platform/windows/WindowsBluetoothDeviceFFM.java 0.00% 3 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3291      +/-   ##
============================================
- Coverage     75.68%   75.60%   -0.08%     
  Complexity       76       76              
============================================
  Files           410      410              
  Lines         15814    15812       -2     
  Branches       2518     2524       +6     
============================================
- Hits          11969    11955      -14     
- Misses         2379     2386       +7     
- Partials       1466     1471       +5     
Flag Coverage Δ
linux 40.10% <23.80%> (+<0.01%) ⬆️
macos 40.94% <0.00%> (-0.01%) ⬇️
windows 48.62% <47.61%> (-0.08%) ⬇️

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 4777faa into oshi:master May 23, 2026
19 of 20 checks passed
@dbwiddis
dbwiddis deleted the migrate-nested-native-handles branch May 23, 2026 21:50
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