Skip to content

Migrate MacHWDiskStoreFFM to AutoCloseable try-with-resources - #3296

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:migrate-mac-hwdiskstore
May 24, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:migrate-mac-hwdiskstore

Conversation

@dbwiddis

@dbwiddis dbwiddis commented May 24, 2026 •

Copy link
Copy Markdown
Member

🎉 Final boss of the NativeHandle/AutoCloseable migration series!

Replace 15 of 18 manual finally blocks with try-with-resources across all four methods in MacHWDiskStoreFFM.

Pre-existing bugs found and fixed

The migration and subsequent review uncovered several native resource management bugs:

FFM side:

  • cfKeyMap entries leaked in getDisks() when session.isNull() — moved release to outer finally
  • IORegistryEntry leaked in iterator loops on exception — wrapped with try (IORegistryEntry current = entry)
  • CFStringRef keys leaked in detectDiskType() — createCFString() calls never released

JNA side (same file, same bugs):

  • cfKeyMap entries leaked in getDisks() when session is null — added outer try/finally
  • DASessionRef leaked on exception — wrapped in try/finally
  • Double-release of sdService in serial lookup loop — release() called twice per iteration when serial was null

Migration details

  • updateAttributes() — try (session)
  • updateDiskStats() — try (driveListIter), try (drive), try (properties), try (driveProps), try (serviceIterator), try (DADiskRef), try (CFDictionaryRef), try (IORegistryEntry current)
  • getDisks() — try (session), try (iter), try (IORegistryEntry current), try (DADiskRef), try (CFDictionaryRef), try (modelNameRef), try (serviceIterator)
  • detectDiskType() — try (iter), try (media), try (driver), try (device), try (props), try (CFStringRef keys)

Remaining 2 finally blocks

  • cfKeyMap.values() iteration release — can't express map iteration as try-with-resources
  • Conditional parent.release() — getParentEntry() can return Java null (NPE in try-with-resources)

Migration series complete 🏆

PRs #3290 → #3291 → #3292 → #3293 → #3294 → #3296

Summary by CodeRabbit

  • Refactor
    • Simplified macOS disk discovery by centralizing resource lifecycle management, improving reliability of disk enumeration.
  • Bug Fixes
    • More robust error handling and logging during disk detection and metadata collection to reduce leaks and ensure consistent size, model, and serial reporting.

Review Change Stack

@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: 6535b12b-f613-4944-9ad9-2bfad8fb2da3

📥 Commits

Reviewing files that changed from the base of the PR and between a73b1e1 and b2642be.

📒 Files selected for processing (2)
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreJNA.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 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 21, macos-latest
  • 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)
🧰 Additional context used
🧠 Learnings (1)
📚 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
🔇 Additional comments (5)
oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java (4)

68-77: LGTM!


95-100: LGTM!

Also applies to: 111-111, 153-153, 180-220


253-257: LGTM!

Also applies to: 260-270, 288-299, 314-347


377-419: LGTM!

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

243-351: LGTM!


📝 Walkthrough

Walkthrough

Refactors macOS disk code to use try-with-resources for FFM wrapper lifecycles in updateAttributes, updateDiskStats, getDisks, and detectDiskType; and adds guaranteed cfKeyMap CFTypeRef release via try/finally in the JNA getDisks path.

Changes

Try-with-resources refactor for FFM native wrapper objects

Layer / File(s) Summary
Session resource wrapping in updateAttributes
oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java
DASessionRef is now managed by try-with-resources instead of manual session.release(); cfKeyMap values still released in an outer finally.
Drive iteration and nested property dictionary management in updateDiskStats
oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java
IOIterator/IORegistryEntry drive enumeration, device/drive CFDictionaryRef properties, and partition-service iteration are scoped with try-with-resources; existing partition-list error logging preserved.
Disk enumeration and metadata extraction in getDisks
oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java
Wraps DASessionRef, media iterator/registry entries, per-disk DADiskRef and CFDictionaryRef, temporary CFStringRef model matching, and serial-resolution service iterator with try-with-resources; consolidates catch/finally cleanup for cfKeyMap.
IOKit registry traversal and disk classification in detectDiskType
oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java
Converts registry traversal (iterators, registry entries, property dictionaries) to try-with-resources and removes explicit nested finally releases; classification logic unchanged.

JNA DiskArbitration session cleanup

Layer / File(s) Summary
getDisks() session try/finally and cfKeyMap release
oshi-core/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreJNA.java
Main session and disk enumeration wrapped in a try, with a finally block that releases all CFTypeRef values in cfKeyMap to ensure keys are freed even on early return when the DiskArbitration session is null.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • oshi/oshi#3231: Prior changes touching disk-type detection and related macOS disk enumeration logic used by these methods.
  • oshi/oshi#3292: Earlier AutoCloseable-based macOS call-site migration that this try-with-resources refactor follows.

Poem

🐰 I hopped through native handles with care,

Closed sessions and keys in the open air,
No more finally nests tangled and deep,
Now try-with-resources tucks them to sleep,
Disk scans hum softly — tidy and fair.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.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 accurately describes the primary change: migrating MacHWDiskStoreFFM to use try-with-resources, which is the core focus of the PR across multiple methods.
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 73.46939% with 39 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.50%. Comparing base (443360e) to head (b2642be).

Files with missing lines Patch % Lines
.../oshi/hardware/platform/mac/MacHWDiskStoreJNA.java 67.16% 12 Missing and 10 partials ⚠️
.../oshi/hardware/platform/mac/MacHWDiskStoreFFM.java 78.75% 5 Missing and 12 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3296      +/-   ##
============================================
- Coverage     75.74%   75.50%   -0.24%     
  Complexity       76       76              
============================================
  Files           410      410              
  Lines         15800    15807       +7     
  Branches       2528     2539      +11     
============================================
- Hits          11967    11935      -32     
- Misses         2370     2387      +17     
- Partials       1463     1485      +22     
Flag Coverage Δ
linux 40.12% <0.00%> (-0.04%) ⬇️
macos 40.86% <73.46%> (-0.05%) ⬇️
windows 48.61% <0.00%> (-0.20%) ⬇️

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.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java (2)

241-248: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Release cfKeyMap on the session.isNull() return path.

Lines 244-246 return before the finally at Lines 335-339 runs, so every CFStringRef created by mapCFKeys() leaks when DASessionRef.create(alloc) fails. Move the key-map cleanup to an outer finally that wraps the whole method body.

Also applies to: 335-339

🤖 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/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java`
around lines 241 - 248, The CFStringRef entries in cfKeyMap returned by
mapCFKeys() are leaked if DASessionRef.create(alloc) fails because the current
cleanup lives in an inner finally block; update the method so that the cfKeyMap
cleanup (release of each CFStringRef) is performed in an outer finally that
always runs before any early returns (e.g., when session.isNull() triggers a
return). Specifically, ensure cfKeyMap is created before attempting
DASessionRef.create(alloc) and move the release logic that currently runs in the
inner finally into a finally that wraps the entire method body so mapCFKeys()
entries are released on all exit paths; reference symbols: cfKeyMap,
mapCFKeys(), CFStringRef, DASessionRef.create(...), session.isNull().

177-217: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Close each IORegistryEntry from next() with try-with-resources to prevent leaks on exceptions.
In serviceIterator/iter loops, the entry (sdService / media) is only release()d at the bottom of the iteration; if any property lookup or disk/HWPartition construction throws before that point, the native entry won’t be closed. Wrap each next() result in its own try (entry) block.

Applies to: 177-217, 252-268, 308-317.

Example pattern
- IORegistryEntry sdService = serviceIterator.next();
- while (sdService != null) {
-     ...
-     sdService.release();
-     sdService = serviceIterator.next();
- }
+ IORegistryEntry sdService;
+ while ((sdService = serviceIterator.next()) != null) {
+     try (sdService) {
+         ...
+     }
+ }
🤖 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/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java`
around lines 177 - 217, The IORegistryEntry instances returned by
serviceIterator.next() (sdService) must be closed via try-with-resources to
avoid native leaks if an exception occurs before the explicit release(); update
the loop in MacHWDiskStoreFFM (the serviceIterator/sdService loop) to obtain the
entry into a local variable and wrap its lifetime in a try (IORegistryEntry
sdService = serviceIterator.next()) { ... } so all property lookups
(getStringProperty/getLongProperty/getIntegerProperty),
DADiskRef.createFromBSDName usage, and HWPartition construction happen inside
that resource block and remove the manual sdService.release(); apply the same
pattern to the other iterator loops mentioned (iter/media) so each next() result
is auto-closed on exception.
🤖 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.

Outside diff comments:
In
`@oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java`:
- Around line 241-248: The CFStringRef entries in cfKeyMap returned by
mapCFKeys() are leaked if DASessionRef.create(alloc) fails because the current
cleanup lives in an inner finally block; update the method so that the cfKeyMap
cleanup (release of each CFStringRef) is performed in an outer finally that
always runs before any early returns (e.g., when session.isNull() triggers a
return). Specifically, ensure cfKeyMap is created before attempting
DASessionRef.create(alloc) and move the release logic that currently runs in the
inner finally into a finally that wraps the entire method body so mapCFKeys()
entries are released on all exit paths; reference symbols: cfKeyMap,
mapCFKeys(), CFStringRef, DASessionRef.create(...), session.isNull().
- Around line 177-217: The IORegistryEntry instances returned by
serviceIterator.next() (sdService) must be closed via try-with-resources to
avoid native leaks if an exception occurs before the explicit release(); update
the loop in MacHWDiskStoreFFM (the serviceIterator/sdService loop) to obtain the
entry into a local variable and wrap its lifetime in a try (IORegistryEntry
sdService = serviceIterator.next()) { ... } so all property lookups
(getStringProperty/getLongProperty/getIntegerProperty),
DADiskRef.createFromBSDName usage, and HWPartition construction happen inside
that resource block and remove the manual sdService.release(); apply the same
pattern to the other iterator loops mentioned (iter/media) so each next() result
is auto-closed on exception.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: be2037ed-ce46-47da-8f83-5df256ba8456

📥 Commits

Reviewing files that changed from the base of the PR and between 443360e and 2518837.

📒 Files selected for processing (1)
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java
📜 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). (13)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: Analyze (java)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🔇 Additional comments (1)
oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java (1)

390-398: ⚡ Quick win

Close native CFStringRef keys in detectDiskType()

CFStringRef.createCFString("Device Characteristics") and CFStringRef.createCFString("Medium Type") create native-backed CFStringRef instances that aren’t closed in this code path. Wrap them in try-with-resources (or reuse cached keys) around the lookups.

Possible fix
- MemorySegment charSeg = props
-         .getValue(CFStringRef.createCFString("Device Characteristics"));
- if (!charSeg.equals(MemorySegment.NULL)) {
-     CFDictionaryRef chars = new CFDictionaryRef(charSeg);
-     MemorySegment typeSeg = chars
-             .getValue(CFStringRef.createCFString("Medium Type"));
+ try (CFStringRef deviceCharacteristicsKey = CFStringRef.createCFString("Device Characteristics");
+         CFStringRef mediumTypeKey = CFStringRef.createCFString("Medium Type")) {
+     MemorySegment charSeg = props.getValue(deviceCharacteristicsKey);
+     if (!charSeg.equals(MemorySegment.NULL)) {
+         CFDictionaryRef chars = new CFDictionaryRef(charSeg);
+         MemorySegment typeSeg = chars.getValue(mediumTypeKey);
          if (!typeSeg.equals(MemorySegment.NULL)) {
              String type = new CFStringRef(typeSeg).stringValue();
              ...
          }
- }
+     }
+ }

@dbwiddis
dbwiddis force-pushed the migrate-mac-hwdiskstore branch from 2518837 to 0e2e5e5 Compare May 24, 2026 00:53

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java (1)

394-400: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Close the temporary CFStringRef lookup keys here.

CFStringRef.createCFString("Device Characteristics") and CFStringRef.createCFString("Medium Type") both allocate native CF objects, but this path never releases them. Since detectDiskType() runs during disk enumeration, that leaves a small native leak on every probe.

🛠️ Proposed fix
-                                    try (CFDictionaryRef props = new CFDictionaryRef(propsSeg)) {
-                                        MemorySegment charSeg = props
-                                                .getValue(CFStringRef.createCFString("Device Characteristics"));
+                                    try (CFDictionaryRef props = new CFDictionaryRef(propsSeg);
+                                            CFStringRef deviceCharacteristicsKey = CFStringRef
+                                                    .createCFString("Device Characteristics");
+                                            CFStringRef mediumTypeKey = CFStringRef.createCFString("Medium Type")) {
+                                        MemorySegment charSeg = props.getValue(deviceCharacteristicsKey);
                                         if (!charSeg.equals(MemorySegment.NULL)) {
                                             CFDictionaryRef chars = new CFDictionaryRef(charSeg);
-                                            MemorySegment typeSeg = chars
-                                                    .getValue(CFStringRef.createCFString("Medium Type"));
+                                            MemorySegment typeSeg = chars.getValue(mediumTypeKey);
                                             if (!typeSeg.equals(MemorySegment.NULL)) {
                                                 String type = new CFStringRef(typeSeg).stringValue();
                                                 if (type != null) {
🤖 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/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java`
around lines 394 - 400, In MacHWDiskStoreFFM.detectDiskType(), the
CFStringRef.createCFString(...) calls used as lookup keys ("Device
Characteristics" and "Medium Type") are allocated but never freed; to fix,
assign each CFStringRef returned by CFStringRef.createCFString(...) to a local
variable and ensure you close them (preferably via try-with-resources) after use
around the MemorySegment lookups (the variables used when calling
props.getValue(...) and chars.getValue(...)); this removes the native leak while
preserving the existing props/CFDictionaryRef/CFDictionaryRef(chars)
try-with-resources structure.
🧹 Nitpick comments (1)
oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java (1)

102-105: ⚡ Quick win

Use try-with-resources for parent as well.

Because this module now targets Java 25, the effectively-final parent variable can be wrapped directly in try (parent) even when it may be null. That removes the last bespoke close path in this method and keeps the migration consistent.

♻️ Proposed refactor
-                IORegistryEntry parent = drive.getParentEntry("IOService");
-                try {
+                IORegistryEntry parent = drive.getParentEntry("IOService");
+                try (parent) {
                     if (parent != null && (parent.conformsTo("IOBlockStorageDriver")
                             || parent.conformsTo("AppleAPFSContainerScheme"))) {
                         MemorySegment propertiesSeg = parent.createCFProperties();
                         if (!propertiesSeg.equals(MemorySegment.NULL)) {
                             try (CFDictionaryRef properties = new CFDictionaryRef(propertiesSeg)) {
@@
                     } else {
                         LOG.debug("Unable to find block storage driver properties for {}", bsdName);
                     }
 
                     // Partitions
                     List<HWPartition> partitions = new ArrayList<>();
@@
-                } finally {
-                    if (parent != null) {
-                        parent.release();
-                    }
                 }

Also applies to: 228-231

🤖 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/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java`
around lines 102 - 105, The code obtains an IORegistryEntry named parent via
drive.getParentEntry("IOService") and later manually closes it; update the
method to use try-with-resources for parent (taking advantage of Java 25
allowing a possibly-null effectively-final resource variable) so parent is
declared and then used in a try (parent) { ... } block around the conformsTo
checks and any use of parent, removing the bespoke close logic; apply the same
change to the other occurrence where parent is used (the block referenced around
the second parent usage), ensuring IORegistryEntry is closed automatically.
🤖 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.

Inline comments:
In `@oshi-core/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreJNA.java`:
- Around line 309-319: In MacHWDiskStoreJNA's serial lookup loop,
sdService.release() is called twice per iteration (once before checking serial
and again when serial is null); change the logic so each IORegistryEntry
(sdService) is released exactly once: retrieve sdService from
serviceIterator.next(), get the "Serial Number" into serial, then call
sdService.release() once and only after that decide whether to break (if serial
!= null) or continue the loop (sdService = serviceIterator.next()); ensure you
remove the extra release call so no double-release occurs.
- Around line 243-341: The code opens a DiskArbitration session via
DA.DASessionCreate (DASessionRef session) but only calls session.release() at
the end, which leaks the native session on early returns or exceptions; modify
the method to ensure DASessionRef is always released by wrapping the logic after
DA.DASessionCreate(...) in a try/finally (or try-with-resources equivalent) so
that session.release() is invoked in the finally block, keeping existing early
returns (e.g., when session == null or when returning Collections.emptyList())
intact by returning after creating/validating session and placing all subsequent
code inside the try, and reference DA.DASessionCreate, session, and
session.release() when making the change.

---

Outside diff comments:
In
`@oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java`:
- Around line 394-400: In MacHWDiskStoreFFM.detectDiskType(), the
CFStringRef.createCFString(...) calls used as lookup keys ("Device
Characteristics" and "Medium Type") are allocated but never freed; to fix,
assign each CFStringRef returned by CFStringRef.createCFString(...) to a local
variable and ensure you close them (preferably via try-with-resources) after use
around the MemorySegment lookups (the variables used when calling
props.getValue(...) and chars.getValue(...)); this removes the native leak while
preserving the existing props/CFDictionaryRef/CFDictionaryRef(chars)
try-with-resources structure.

---

Nitpick comments:
In
`@oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java`:
- Around line 102-105: The code obtains an IORegistryEntry named parent via
drive.getParentEntry("IOService") and later manually closes it; update the
method to use try-with-resources for parent (taking advantage of Java 25
allowing a possibly-null effectively-final resource variable) so parent is
declared and then used in a try (parent) { ... } block around the conformsTo
checks and any use of parent, removing the bespoke close logic; apply the same
change to the other occurrence where parent is used (the block referenced around
the second parent usage), ensuring IORegistryEntry is closed automatically.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: d4078610-c6c9-4ca0-ae27-1a3c2749da0d

📥 Commits

Reviewing files that changed from the base of the PR and between 2518837 and 0e2e5e5.

📒 Files selected for processing (2)
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreJNA.java
📜 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). (12)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 21, macos-latest
  • 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)
  • GitHub Check: Codacy Static Code Analysis
🧰 Additional context used
🧠 Learnings (1)
📚 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
🔇 Additional comments (1)
oshi-core/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreJNA.java (1)

342-345: LGTM!

@dbwiddis
dbwiddis force-pushed the migrate-mac-hwdiskstore branch from 0e2e5e5 to f862491 Compare May 24, 2026 01:01

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

Actionable comments posted: 1

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

Inline comments:
In `@oshi-core/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreJNA.java`:
- Around line 260-263: Guard against a NULL DADiskRef returned by
DADiskCreateFromIOMedia: after calling DADiskCreateFromIOMedia(session, media)
check if the returned DADiskRef (variable disk) is non-null before calling
DA.DADiskGetBSDName(disk) and disk.release(); if disk is NULL simply skip adding
to bsdNames (and optionally log or continue), ensuring no dereference or release
is attempted on a null reference.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 4c76f047-c8d8-4ffe-a5ee-ba26e98afaf6

📥 Commits

Reviewing files that changed from the base of the PR and between 0e2e5e5 and f862491.

📒 Files selected for processing (2)
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreJNA.java
📜 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). (12)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 11, macos-latest
  • 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 (1)
📚 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
🔇 Additional comments (5)
oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java (4)

69-75: LGTM!


92-97: LGTM!

Also applies to: 108-109, 150-151, 177-181, 186-190


250-257: LGTM!

Also applies to: 260-262, 285-287, 296-297, 311-315, 342-345


374-375: LGTM!

Also applies to: 379-380, 388-389, 391-392, 394-396, 400-402

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

243-259: LGTM!

Also applies to: 264-345

@dbwiddis
dbwiddis force-pushed the migrate-mac-hwdiskstore branch from f862491 to a73b1e1 Compare May 24, 2026 01:09

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java (1)

62-69: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Scope session before mapCFKeys() can fail.

session is not inside try-with-resources until Line 69. If mapCFKeys() throws on Line 68, the catch (Throwable) path returns false and leaks the native DASessionRef. Move mapCFKeys() inside try (session) or build the key map before opening the session.

♻️ Suggested change
         try {
             CFAllocatorRef alloc = new CFAllocatorRef(CoreFoundationFunctions.CFAllocatorGetDefault());
             DASessionRef session = DASessionRef.create(alloc);
             if (session.isNull()) {
                 LOG.error("Unable to open session to DiskArbitration framework.");
                 return false;
             }
-            Map<CFKey, CFStringRef> cfKeyMap = mapCFKeys();
             try (session) {
-                return updateDiskStats(session, FsstatFFM.queryPartitionToMountMap(), cfKeyMap);
-            } finally {
-                for (CFStringRef value : cfKeyMap.values()) {
-                    value.release();
+                Map<CFKey, CFStringRef> cfKeyMap = mapCFKeys();
+                try {
+                    return updateDiskStats(session, FsstatFFM.queryPartitionToMountMap(), cfKeyMap);
+                } finally {
+                    for (CFStringRef value : cfKeyMap.values()) {
+                        value.release();
+                    }
                 }
             }
         } catch (Throwable e) {
             return false;
         }
🤖 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/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java`
around lines 62 - 69, The native DASessionRef may leak if mapCFKeys() throws
before session is in the try-with-resources; after creating alloc and session
(CFAllocatorRef alloc, DASessionRef session), immediately check
session.isNull(), then enter try (session) and call mapCFKeys() inside that try
block (i.e., move the mapCFKeys() invocation into the try-with-resources that
owns DASessionRef) so any exception during mapCFKeys() will close the native
session; update surrounding error handling to preserve the existing return false
behavior.
🤖 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.

Outside diff comments:
In
`@oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java`:
- Around line 62-69: The native DASessionRef may leak if mapCFKeys() throws
before session is in the try-with-resources; after creating alloc and session
(CFAllocatorRef alloc, DASessionRef session), immediately check
session.isNull(), then enter try (session) and call mapCFKeys() inside that try
block (i.e., move the mapCFKeys() invocation into the try-with-resources that
owns DASessionRef) so any exception during mapCFKeys() will close the native
session; update surrounding error handling to preserve the existing return false
behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: d5d864b5-cbd6-46d0-9b70-0608b775fc94

📥 Commits

Reviewing files that changed from the base of the PR and between f862491 and a73b1e1.

📒 Files selected for processing (2)
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreJNA.java
📜 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). (11)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Analyze (java)
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🧰 Additional context used
🧠 Learnings (1)
📚 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
🔇 Additional comments (4)
oshi-core/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreJNA.java (4)

243-249: LGTM!


260-267: LGTM!


315-326: LGTM!


344-351: LGTM!

Replace 15 of 18 manual finally blocks with try-with-resources across
all four methods: updateAttributes(), updateDiskStats(), getDisks(),
and detectDiskType().

Additional fixes found during migration:
- Fix cfKeyMap leak in getDisks() when session creation fails (both
  JNA and FFM) — cfKeyMap entries were not released on early return
- Fix IORegistryEntry leak in iterator loops — entries now wrapped in
  try (IORegistryEntry current = entry) to ensure release on exception

Remaining 3 finally blocks are legitimate patterns:
- cfKeyMap.values() iteration release (2 occurrences)
- Conditional parent.release() with null check (1 occurrence)
@dbwiddis
dbwiddis force-pushed the migrate-mac-hwdiskstore branch from a73b1e1 to b2642be Compare May 24, 2026 01:16
@dbwiddis
dbwiddis merged commit f35b3c2 into oshi:master May 24, 2026
19 checks passed
@dbwiddis
dbwiddis deleted the migrate-mac-hwdiskstore branch May 26, 2026 16:18
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