Repository navigation
Migrate MacHWDiskStoreFFM to AutoCloseable try-with-resources - #3296
Conversation
|
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 (2)
📜 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)
🧰 Additional context used🧠 Learnings (1)📚 Learning: 2026-04-06T04:45:47.644ZApplied to files:
🔇 Additional comments (5)
📝 WalkthroughWalkthroughRefactors 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. ChangesTry-with-resources refactor for FFM native wrapper objects
JNA DiskArbitration session cleanup
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 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 #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
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:
|
There was a problem hiding this comment.
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 winRelease
cfKeyMapon thesession.isNull()return path.Lines 244-246 return before the
finallyat Lines 335-339 runs, so everyCFStringRefcreated bymapCFKeys()leaks whenDASessionRef.create(alloc)fails. Move the key-map cleanup to an outerfinallythat 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 winClose each
IORegistryEntryfromnext()with try-with-resources to prevent leaks on exceptions.
InserviceIterator/iterloops, the entry (sdService/media) is onlyrelease()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 eachnext()result in its owntry (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
📒 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 winClose native
CFStringRefkeys indetectDiskType()
CFStringRef.createCFString("Device Characteristics")andCFStringRef.createCFString("Medium Type")create native-backedCFStringRefinstances 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(); ... } - } + } + }
2518837 to
0e2e5e5
Compare
There was a problem hiding this comment.
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 winClose the temporary
CFStringReflookup keys here.
CFStringRef.createCFString("Device Characteristics")andCFStringRef.createCFString("Medium Type")both allocate native CF objects, but this path never releases them. SincedetectDiskType()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 winUse try-with-resources for
parentas well.Because this module now targets Java 25, the effectively-final
parentvariable can be wrapped directly intry (parent)even when it may benull. 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
📒 Files selected for processing (2)
oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.javaoshi-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!
0e2e5e5 to
f862491
Compare
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.javaoshi-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
f862491 to
a73b1e1
Compare
There was a problem hiding this comment.
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 winScope
sessionbeforemapCFKeys()can fail.
sessionis not inside try-with-resources until Line 69. IfmapCFKeys()throws on Line 68, thecatch (Throwable)path returnsfalseand leaks the nativeDASessionRef. MovemapCFKeys()insidetry (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
📒 Files selected for processing (2)
oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.javaoshi-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)
a73b1e1 to
b2642be
Compare
🎉 Final boss of the NativeHandle/AutoCloseable migration series!
Replace 15 of 18 manual
finallyblocks with try-with-resources across all four methods inMacHWDiskStoreFFM.Pre-existing bugs found and fixed
The migration and subsequent review uncovered several native resource management bugs:
FFM side:
cfKeyMapentries leaked ingetDisks()whensession.isNull()— moved release to outer finallyIORegistryEntryleaked in iterator loops on exception — wrapped withtry (IORegistryEntry current = entry)CFStringRefkeys leaked indetectDiskType()—createCFString()calls never releasedJNA side (same file, same bugs):
cfKeyMapentries leaked ingetDisks()when session is null — added outer try/finallyDASessionRefleaked on exception — wrapped in try/finallysdServicein serial lookup loop —release()called twice per iteration when serial was nullMigration 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-resourcesparent.release()—getParentEntry()can return Java null (NPE in try-with-resources)Migration series complete 🏆
PRs #3290 → #3291 → #3292 → #3293 → #3294 → #3296
Summary by CodeRabbit