Repository navigation
Add more macOS hardware FFM implementations - #3110
Conversation
…aces, displays, power sources, USB devices) - Add MacHardwareAbstractionLayerFFM overriding all 5 hardware methods - Add MacHWDiskStoreFFM using DiskArbitration + IOKit + CoreFoundation - Fix DADiskGetBSDName zero-sized segment bug using ForeignFunctions.getStringFromNativePointer - Fix MacInternetProtocolStatsFFM udp.stats buffer size 1644->84 (actual struct is 104 bytes) - Fix MacInternetProtocolStats (JNA) udp.stats size guard 1644->84, returning zeros on modern macOS - Fix FreeBsdInternetProtocolStats same udp.stats size guard bug - Fix BsdUdpstat record comment: udps_snd6_swcsum offset 89->80
📝 WalkthroughWalkthroughAdds multiple macOS FFM hardware discovery implementations and SystemConfiguration bindings, refactors DiskArbitration symbol lookup and error handling, tightens UDP/IPv6 stats parsing and size guards, and updates HAL classes to surface the new FFM-backed implementations. Changes
Sequence DiagramsequenceDiagram
participant Client as HardwareDiscovery
participant IOReg as IOKit_IORegistry
participant CF as CoreFoundation
participant DA as DiskArbitration
participant Model as JavaModelBuilder
Client->>IOReg: getMatchingServices(serviceName)
IOReg-->>Client: IOIterator
loop each service entry
Client->>IOReg: getRegistryEntry()
Client->>CF: createCFString(key)
IOReg->>CF: createCFProperty(entry, cfKey)
CF-->>Client: CFValue (data/dict/boolean)
alt disk path
Client->>DA: create DADisk (from media or BSD name)
DA-->>Client: DADiskRef or NULL
Client->>DA: DADiskCopyDescription(disk)
DA-->>Client: CFDictionaryRef
end
Client->>Model: extract fields/bytes and instantiate model
Client->>CF: release CF objects
IOReg->>IOReg: release registryEntry
end
Client->>IOReg: release iterator
Model-->>Client: List<Hardware>
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
✨ Simplify code
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✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #3110 +/- ##
==========================================
+ Coverage 67.65% 68.50% +0.85%
==========================================
Files 37 37
Lines 1994 1994
Branches 323 323
==========================================
+ Hits 1349 1366 +17
+ Misses 535 517 -18
- Partials 110 111 +1 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (4)
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceFFM.java (1)
198-200: Consider debug logging for swallowed exceptions.While silently ignoring failures in
getControllerIdByLocationis acceptable (vendor/product IDs fall back to "0000"), adding debug-level logging would aid troubleshooting.💡 Optional: Add debug logging
} catch (Throwable e) { - // Ignore + // Best-effort lookup; failure is non-critical }Or if a logger is added:
} catch (Throwable e) { LOG.debug("Failed to get controller vendor/product ID by location: {}", e.getMessage()); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceFFM.java` around lines 198 - 200, The catch block in getControllerIdByLocation within MacUsbDeviceFFM currently swallows all Throwables; change it to log the exception at debug level instead of ignoring it—either use the existing class logger (LOG.debug(...)) or add a logger to MacUsbDeviceFFM, and include the exception message/stack in the debug log so failures retrieving controller vendor/product IDs are recorded for troubleshooting while preserving the fallback behavior.oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java (3)
402-408: Consider documenting caller's responsibility to release CFStringRefs.The
mapCFKeys()helper createsCFStringRefobjects that must be released by the caller. This is correctly done in bothgetDisks()andupdateAttributes(), but a brief Javadoc would help future maintainers.📝 Add documentation
+ /** + * Creates a map of CFKey to CFStringRef for dictionary lookups. + * Caller is responsible for releasing all values in the returned map. + */ private static Map<CFKey, CFStringRef> mapCFKeys() {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java` around lines 402 - 408, The helper mapCFKeys() creates CFStringRef instances that require explicit release by callers; add a Javadoc to mapCFKeys() stating that it returns a map of CFKey to CFStringRef and that callers (e.g., getDisks() and updateAttributes()) are responsible for calling CFStringRef.release() on the values to avoid leaks. Mention CFKey, CFStringRef, mapCFKeys(), getDisks(), and updateAttributes() in the doc so future maintainers know where releases occur.
260-262: Silent exception swallowing in partition enumeration.This catch block logs "Error building partition list" but doesn't include the exception, making root cause analysis difficult.
🔧 Include exception in log message
} catch (Throwable e) { - LOG.debug("Error building partition list for {}", bsdName); + LOG.debug("Error building partition list for {}", bsdName, e); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java` around lines 260 - 262, The catch block in MacHWDiskStoreFFM that currently reads "catch (Throwable e) { LOG.debug(\"Error building partition list for {}\", bsdName); }" swallows the exception; update this catch to include the throwable in the log call (e.g., pass 'e' as the logger throwable parameter) so the stacktrace is emitted (keep the same message and bsdName variable). Locate the catch(Throwable e) around the partition enumeration code in MacHWDiskStoreFFM and change the LOG.debug invocation to include the exception object.
119-121: Silent failure on unexpected errors.The outer
catch (Throwable e)swallows all exceptions including programming errors (e.g.,NullPointerException,ClassCastException) without logging, making debugging difficult.♻️ Consider logging the exception
} catch (Throwable e) { + LOG.debug("Error updating disk attributes", e); return false; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java` around lines 119 - 121, The catch block in MacHWDiskStoreFFM currently swallows all Throwables (catch (Throwable e)) which hides programming errors; change it to catch (Exception e) (or catch specific checked exceptions used there) and log the exception instead of returning silently—use the class logger (e.g., LOGGER or the existing logging facility in MacHWDiskStoreFFM) to record the exception and a clear message, and let serious Errors propagate rather than catching Throwable.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In
`@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacDisplayFFM.java`:
- Around line 52-75: The child IORegistryEntry stored in propertySource
(obtained via sdService.getChildEntry(childEntryName)) can leak if an exception
occurs before the explicit propertySource.release() call; wrap the logic that
uses propertySource in a nested try/finally (or equivalent) so that if
childEntryName != null you always call propertySource.release() in that finally
regardless of exceptions, while preserving the outer finally that releases
sdService and advances serviceIterator; update the block around propertySource
creation/usage (references: propertySource, sdService, CFDataRef edid,
displays.add(new MacDisplayFFM(bytes))) to ensure propertySource.release() is
executed whenever propertySource was assigned.
In
`@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.java`:
- Around line 194-199: The current calculation in MacPowerSourceFFM that sets
psRemainingCapacityPercent uses currentCapacity / maxCapacity without handling
maxCapacity == 0; update the block where maxCapacityKey is read (the
dict.getValue/getValueIfPresent/CFNumberRef usage) to detect maxCapacity <= 0
and in that case set psRemainingCapacityPercent to 0d (or another sentinel such
as Double.NaN if preferred) instead of performing the division; otherwise
compute psRemainingCapacityPercent = Math.min(1d, currentCapacity / maxCapacity)
as before to avoid Infinity and incorrect 100% readings.
- Around line 84-90: The ManufactureDate bitfield parsing can throw
DateTimeException (e.g., month/day == 0) and crash getPowerSources(); guard the
parsing in the block that reads
smartBattery.getIntegerProperty("ManufactureDate") by validating the extracted
day/month/year (ensure month in 1..12 and day >=1 and <= lengthOfMonth for the
year) or by wrapping LocalDate.of(...) in a try/catch that catches
DateTimeException and leaves psManufactureDate as null; update the code in
MacPowerSourceFFM where temp, day, month, year80 and psManufactureDate are
handled so any invalid ManufactureDate does not propagate and instead results in
a null psManufactureDate.
---
Nitpick comments:
In
`@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java`:
- Around line 402-408: The helper mapCFKeys() creates CFStringRef instances that
require explicit release by callers; add a Javadoc to mapCFKeys() stating that
it returns a map of CFKey to CFStringRef and that callers (e.g., getDisks() and
updateAttributes()) are responsible for calling CFStringRef.release() on the
values to avoid leaks. Mention CFKey, CFStringRef, mapCFKeys(), getDisks(), and
updateAttributes() in the doc so future maintainers know where releases occur.
- Around line 260-262: The catch block in MacHWDiskStoreFFM that currently reads
"catch (Throwable e) { LOG.debug(\"Error building partition list for {}\",
bsdName); }" swallows the exception; update this catch to include the throwable
in the log call (e.g., pass 'e' as the logger throwable parameter) so the
stacktrace is emitted (keep the same message and bsdName variable). Locate the
catch(Throwable e) around the partition enumeration code in MacHWDiskStoreFFM
and change the LOG.debug invocation to include the exception object.
- Around line 119-121: The catch block in MacHWDiskStoreFFM currently swallows
all Throwables (catch (Throwable e)) which hides programming errors; change it
to catch (Exception e) (or catch specific checked exceptions used there) and log
the exception instead of returning silently—use the class logger (e.g., LOGGER
or the existing logging facility in MacHWDiskStoreFFM) to record the exception
and a clear message, and let serious Errors propagate rather than catching
Throwable.
In
`@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceFFM.java`:
- Around line 198-200: The catch block in getControllerIdByLocation within
MacUsbDeviceFFM currently swallows all Throwables; change it to log the
exception at debug level instead of ignoring it—either use the existing class
logger (LOG.debug(...)) or add a logger to MacUsbDeviceFFM, and include the
exception message/stack in the debug log so failures retrieving controller
vendor/product IDs are recorded for troubleshooting while preserving the
fallback behavior.
🪄 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: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: e920ba86-acec-4f40-81e3-29ce9b3eb5f8
📒 Files selected for processing (15)
oshi-core-java25/src/main/java/oshi/ffm/mac/DiskArbitration.javaoshi-core-java25/src/main/java/oshi/ffm/mac/DiskArbitrationFunctions.javaoshi-core-java25/src/main/java/oshi/ffm/mac/IOKit.javaoshi-core-java25/src/main/java/oshi/ffm/mac/SystemConfigurationFunctions.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacDisplayFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacNetworkIFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceFFM.javaoshi-core-java25/src/main/java/oshi/software/os/mac/MacInternetProtocolStatsFFM.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayer.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerJNA.javaoshi-core/src/main/java/oshi/software/os/mac/MacInternetProtocolStats.javaoshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdInternetProtocolStats.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). (5)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Test JDK 25, macos-latest
- GitHub Check: Test JDK 11, windows-latest
- GitHub Check: Test JDK 25, windows-latest
- GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2026-03-29T20:01:06.452Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java11/src/main/java/module-info.java:10-17
Timestamp: 2026-03-29T20:01:06.452Z
Learning: In the oshi project, `oshi-core-java25/src/main/java/module-info.java` intentionally does NOT export `oshi.util.platform.unix.freebsd`, `oshi.util.platform.unix.openbsd`, or `oshi.util.platform.unix.solaris`, because the FFM (Foreign Function & Memory) implementation only supports Windows, macOS, and Linux. This differs from `oshi-core-java11/src/main/java/module-info.java` which exports all Unix platform packages. The asymmetry is by design.
Applied to files:
oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdInternetProtocolStats.javaoshi-core/src/main/java/oshi/software/os/mac/MacInternetProtocolStats.javaoshi-core-java25/src/main/java/oshi/software/os/mac/MacInternetProtocolStatsFFM.javaoshi-core-java25/src/main/java/oshi/ffm/mac/IOKit.javaoshi-core-java25/src/main/java/oshi/ffm/mac/DiskArbitration.javaoshi-core-java25/src/main/java/oshi/ffm/mac/DiskArbitrationFunctions.javaoshi-core-java25/src/main/java/oshi/ffm/mac/SystemConfigurationFunctions.java
📚 Learning: 2026-03-29T20:03:00.830Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java:87-89
Timestamp: 2026-03-29T20:03:00.830Z
Learning: In the OSHI FFM codebase (oshi-core-java25), all PDH/Kernel32/COM wrapper methods in classes like PdhFFM, Kernel32FFM, etc. declare `throws Throwable` solely as a compiler artifact of `MethodHandle.invokeExact`. They are native calls and do not throw Java checked exceptions in practice. The enclosing `getOpenFileDescriptors()` method in PdhUtilFFM already has an outer `catch (Throwable t)` that covers the entire method body including any `finally` blocks, so no exception-masking concern exists for cleanup calls like `PdhCloseQuery` in `finally`.
Applied to files:
oshi-core-java25/src/main/java/oshi/ffm/mac/DiskArbitration.javaoshi-core-java25/src/main/java/oshi/ffm/mac/DiskArbitrationFunctions.java
🔇 Additional comments (17)
oshi-core-java25/src/main/java/oshi/software/os/mac/MacInternetProtocolStatsFFM.java (1)
333-343: LGTM! Correct fix for UDP statistics buffer sizing.The buffer reduction from 1644 to 84 bytes is correct: the highest field
udps_snd6_swcsumis read at offset 80, and with a 4-byte int, 84 bytes is the minimum required. The comment correction from// 89to// 80now accurately reflects the actual read offset.oshi-core/src/main/java/oshi/software/os/mac/MacInternetProtocolStats.java (2)
292-307: LGTM! Size guard fix aligns with FFM implementation.The guard change from
>= 1644to>= 84correctly matches the actual buffer requirements and is consistent with the FFM implementation.Note: The
BsdUdpstatclass inCLibrary.java(context snippet, line 98) still has the comment// 89forudps_snd6_swcsum, but the actual read here is at offset 80. Consider updating that comment to// 80for consistency across the codebase.
210-237: Formatting-only change, no functional impact.The
stateLookupswitch statement reformatting maintains identical TCP state mappings.oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdInternetProtocolStats.java (1)
80-95: LGTM! Consistent UDP stats fix for FreeBSD.The size guard change from
>= 1644to>= 84is correct and consistent with the parallel fix in macOS implementations. Both platforms share the same BSD-derivedudpstatstructure with the highest field at offset 80.oshi-core-java25/src/main/java/oshi/ffm/mac/IOKit.java (1)
359-375: Well-structured addition following existing patterns.The
getBooleanPropertymethod correctly follows the established pattern of other property accessors in this class, including proper NULL checks, CoreFoundation object lifecycle management via try/finally, and consistent exception handling.oshi-core-java25/src/main/java/oshi/ffm/mac/SystemConfigurationFunctions.java (1)
1-50: Clean FFM wrapper implementation.The class follows the established pattern for FFM function wrappers in this codebase: static framework lookup, precomputed MethodHandles via
findOrThrow, and thin public wrappers usinginvokeExact. The function signatures match the macOS SystemConfiguration framework documentation.oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceFFM.java (1)
38-48: Flat list intentionally excludes USB host controllers.When
tree=false, only connected devices are flattened—host controllers are excluded. This is consistent with typical USB enumeration semantics where controllers (xHCI, EHCI) are infrastructure rather than actual USB devices.oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacNetworkIFFM.java (2)
53-83: Correct Core Foundation memory management.The code correctly follows Core Foundation ownership conventions:
SCNetworkInterfaceCopyAllreturns an owned reference → released viacfArray.release()SCNetworkInterfaceGetBSDNameandSCNetworkInterfaceGetLocalizedDisplayNamereturn unowned references (Get rule) → correctly not released
159-177: Field mappings are correct.All
IFdatafields are properly mapped to the corresponding instance variables, matching the expected semantics (O=outbound, I=inbound).oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerFFM.java (1)
36-59: Clean delegation to FFM implementations.The new override methods correctly delegate to the corresponding
Mac*FFMstatic factory methods, maintaining consistency with the JNA counterpart inMacHardwareAbstractionLayerJNA.oshi-core/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerJNA.java (1)
40-63: Symmetric JNA delegation structure.The new override methods mirror the FFM layer structure, delegating to the existing JNA-based
Mac*implementations. This maintains API parity between JNA and FFM backends.oshi-core-java25/src/main/java/oshi/ffm/mac/DiskArbitration.java (2)
42-48: LGTM - Proper error handling for FFM native calls.The try/catch pattern correctly handles the
throws ThrowablefromMethodHandle.invokeExactand returns a NULL-wrapped reference on failure, which callers can check viaisNull(). Based on learnings, these native calls don't throw Java checked exceptions in practice; thethrows Throwableis solely a compiler artifact.
127-132: LGTM - Improved string extraction with proper null handling.Using
ForeignFunctions.getStringFromNativePointer(nameSeg, arena)is cleaner and handles zero-length/null segments appropriately. The confined arena scope ensures proper cleanup.oshi-core/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayer.java (1)
28-53: LGTM - Clean abstraction for JNA/FFM implementations.Converting these five methods to abstract declarations properly separates the HAL interface from JNA/FFM-specific implementations. The class is correctly marked
abstractand the remaining concrete methods (processor, LVG, sound cards, graphics cards, printers) that don't need FFM-specific handling remain unchanged.oshi-core-java25/src/main/java/oshi/ffm/mac/DiskArbitrationFunctions.java (1)
21-30: LGTM - Clean refactor to dedicated symbol lookup.Using a dedicated
SymbolLookupfor the DiskArbitration framework andfindOrThrowfor symbol resolution is cleaner than previous approaches. Thethrows Throwabledeclarations are correct compiler artifacts ofMethodHandle.invokeExact(), and the higher-levelDiskArbitration.javawrappers properly catch these. Based on learnings, these native calls don't throw Java checked exceptions in practice.oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java (2)
283-399: LGTM - Well-structured disk enumeration with proper resource management.The
getDisks()method properly:
- Creates and releases the DA session in a try-finally block
- Releases CF string refs in the finally block
- Releases each disk/media/iterator after use
- Filters out disk images and zero-size disks
- Handles null/empty BSD names gracefully
The nested try-finally pattern ensures resources are cleaned up even on partial failures.
46-53: The thread-safety annotation and field declarations are correct as designed. TheHWDiskStoreinterface explicitly states that the class is "thread safe for the designed use of retrieving the most recent data" and documents that callers must "externally synchronize" when using theupdateAttributes()method. Since this pattern is consistent across all platform implementations (Linux, Windows, FreeBSD, etc.) and matches the existing JNA implementation, the lack ofvolatilefields is intentional and aligns with the documented thread-safety contract. No changes are needed.
…edback TCPv6 negative stats: - getTCPv6Stats() subtracts udp swcsum counters from ip6 totals as an estimate of TCP-only traffic. Now that udpstat returns real values instead of zeros, this subtraction can go negative on some systems. Apply Math.max(0L, ...) consistent with the existing guard in getTCPv4Stats() in both MacInternetProtocolStats (JNA) and MacInternetProtocolStatsFFM (FFM). Review feedback: - MacDisplayFFM: move propertySource.release() into a nested finally block to prevent leaks if an exception occurs before the explicit release call - MacPowerSourceFFM: guard ManufactureDate bitfield parsing against DateTimeException (e.g. month/day == 0 from corrupt data); guard maxCapacity <= 0 to avoid division by zero in psRemainingCapacityPercent - MacHWDiskStoreFFM: include exception in partition list debug log; add Javadoc to mapCFKeys() noting caller release responsibility - MacUsbDeviceFFM: replace silent catch (Throwable) with LOG.debug() including the exception; add Logger field - CHANGELOG.md: add entry for PR #3110
There was a problem hiding this comment.
Actionable comments posted: 7
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In
`@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java`:
- Around line 119-121: The updateAttributes() method in MacHWDiskStoreFFM
currently swallows exceptions with "catch (Throwable e) { return false; }";
change this to log the caught exception (preferably catch Exception rather than
Throwable) and include the exception message/stack in the log before returning
false so failures are visible; follow the pattern used in getDisks() for logging
(use the same logger and log level used there) and ensure the logged message
gives context like "Failed to update disk attributes for [device]" and includes
the exception.
- Around line 188-192: The BSD_UNIT and LEAF lookups from driveProps may return
NULL and are not checked; avoid creating a CFNumberRef from a NULL MemorySegment
and avoid passing a NULL segment into propertyDict.setValue. Before creating
CFNumberRef(bsdUnit) from driveProps.getValue(cfKeyMap.get(CFKey.BSD_UNIT))
validate the returned MemorySegment is non-NULL and only construct CFNumberRef
when present (otherwise skip setting the BSD_UNIT property); likewise check the
MemorySegment returned for CFKey.LEAF and only call propertyDict.setValue(...)
with cfFalseSeg when that segment is non-NULL, ensuring driveProps.getValue,
CFKey.BSD_UNIT, CFKey.LEAF, CFNumberRef and propertyDict.setValue are guarded.
- Around line 333-336: In MacHWDiskStoreFFM, guard against a NULL CF pointer for
DA_MEDIA_SIZE before constructing a CFNumberRef: when retrieving result via
diskInfo.getValue(cfKeyMap.get(CFKey.DA_MEDIA_SIZE)), check if result is null
(or equals MemorySegment.NULL) and only call new CFNumberRef(result).longValue()
if non-null; otherwise set size to a safe default (e.g., 0) so subsequent logic
using size is well-defined.
- Around line 153-164: The block that extracts statistics from properties (calls
to properties.getValue(cfKeyMap.get(CFKey.STATISTICS)) and subsequent
statistics.getValue(...) for CFKey.READ_OPS, READ_BYTES, WRITE_OPS, WRITE_BYTES)
needs NULL guards: check that the initial result for STATISTICS is non-null
before creating CFDictionaryRef statistics, and for each
statistics.getValue(...) verify the returned MemorySegment is non-null before
constructing a CFNumberRef and calling longValue(); only assign this.reads,
this.readBytes, this.writes, this.writeBytes when the corresponding value is
non-null (or else leave/initialize them to 0), mirroring the NULL-check pattern
used for read/write time handling around methods that start at lines 166-172.
In
`@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.java`:
- Line 60: The variable psDesignCapacity in MacPowerSourceFFM (inside class
MacPowerSourceFFM and related to AppleSmartBattery handling) is initialized to 1
which creates a bogus 1 mAh value when AppleSmartBattery is missing; change its
initialization to use the same "unknown" sentinel as the JNA path (0) so that
psDesignCapacity defaults to 0 when unavailable, matching the behavior in
MacPowerSource.java and avoiding a fake capacity value.
- Around line 96-124: In MacPowerSourceFFM, apply the same invalid-value guards
as MacPowerSource when reading smartBattery properties: only assign
psDesignCapacity and psMaxCapacity if the value from
smartBattery.getIntegerProperty("DesignCapacity"/"MaxCapacity") is > 0; only
assign psCurrentCapacity if the value from getIntegerProperty("CurrentCapacity")
is >= 0; only assign psCycleCount if getIntegerProperty("CycleCount") is >= 0;
and only assign psVoltage if getIntegerProperty("Voltage") is > 0; keep
psCapacityUnits assignment as-is. Locate these assignments in MacPowerSourceFFM
(references: psDesignCapacity, psMaxCapacity, psCurrentCapacity, psCycleCount,
psVoltage, smartBattery.getIntegerProperty) and wrap each assignment with the
appropriate conditional checks so FFM matches the JNA behavior.
- Around line 166-221: Allocate native resources (powerSourcesInfo =
IOPSCopyPowerSourcesInfo() and powerSourcesList = IOPSCopyPowerSourcesList(...))
under a cleanup guard: immediately after those calls enter a try/finally block
and move creation of CFArrayRef cfList and CFStringRef keys (nameKey,
isPresentKey, currentCapacityKey, maxCapacityKey) into the try; in the finally
check for non-null/MemorySegment.NULL equivalents and release each
(isPresentKey.release(), nameKey.release(), currentCapacityKey.release(),
maxCapacityKey.release(), cfList.release()) and then call
oshi.ffm.mac.CoreFoundationFunctions.CFRelease(powerSourcesInfo) so that any
exception thrown before/during processing still frees all native CoreFoundation
objects; update MacPowerSourceFFM processing loop (cfList, dict usage) to assume
these resources are present inside the guarded try block.
🪄 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: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 2d4780ec-6c88-473d-ad16-e0eb889c95f4
📒 Files selected for processing (7)
CHANGELOG.mdoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacDisplayFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceFFM.javaoshi-core-java25/src/main/java/oshi/software/os/mac/MacInternetProtocolStatsFFM.javaoshi-core/src/main/java/oshi/software/os/mac/MacInternetProtocolStats.java
✅ Files skipped from review due to trivial changes (1)
- CHANGELOG.md
🚧 Files skipped from review as they are similar to previous changes (2)
- oshi-core/src/main/java/oshi/software/os/mac/MacInternetProtocolStats.java
- oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceFFM.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). (5)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Test JDK 11, windows-latest
- GitHub Check: Analyze (java)
- GitHub Check: Test JDK 25, macos-latest
- GitHub Check: Test JDK 21, macos-latest
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2026-03-29T20:01:06.452Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java11/src/main/java/module-info.java:10-17
Timestamp: 2026-03-29T20:01:06.452Z
Learning: In the oshi project, `oshi-core-java25/src/main/java/module-info.java` intentionally does NOT export `oshi.util.platform.unix.freebsd`, `oshi.util.platform.unix.openbsd`, or `oshi.util.platform.unix.solaris`, because the FFM (Foreign Function & Memory) implementation only supports Windows, macOS, and Linux. This differs from `oshi-core-java11/src/main/java/module-info.java` which exports all Unix platform packages. The asymmetry is by design.
Applied to files:
oshi-core-java25/src/main/java/oshi/software/os/mac/MacInternetProtocolStatsFFM.java
📚 Learning: 2026-03-29T20:03:00.830Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java:87-89
Timestamp: 2026-03-29T20:03:00.830Z
Learning: In the OSHI FFM codebase (oshi-core-java25), all PDH/Kernel32/COM wrapper methods in classes like PdhFFM, Kernel32FFM, etc. declare `throws Throwable` solely as a compiler artifact of `MethodHandle.invokeExact`. They are native calls and do not throw Java checked exceptions in practice. The enclosing `getOpenFileDescriptors()` method in PdhUtilFFM already has an outer `catch (Throwable t)` that covers the entire method body including any `finally` blocks, so no exception-masking concern exists for cleanup calls like `PdhCloseQuery` in `finally`.
Applied to files:
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacDisplayFFM.java
🔇 Additional comments (9)
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacDisplayFFM.java (3)
30-33: Constructor is clean and consistent withAbstractDisplay.Initialization is straightforward and the debug-level log is appropriately low-noise.
35-40: Service aggregation logic is clear and matches the intended discovery paths.Combining both macOS registry patterns here keeps the public entry point simple.
49-83: Resource lifecycle handling looks robust.The nested
try/finallystructure correctly releasesCFDataRef, optional child registry entries, per-iteration services, iterator, and CF string handles.oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java (3)
38-59: LGTM - Clean class structure and initialization.The class follows established OSHI patterns: final class extending
AbstractHWDiskStore, private constructor ensuring controlled instantiation viagetDisks(), and proper initialization of disk statistics during construction.
283-317: LGTM - Proper resource management in disk enumeration.The
IOMediaiteration correctly:
- Uses
Boolean.TRUE.equals(whole)for safe null handling- Releases each
DADiskRefandIORegistryEntryin the loop- Releases the iterator in a
finallyblock
402-438: LGTM - Well-designed key management.The
mapCFKeys()helper withEnumMapprovides type-safe key lookups, and the Javadoc clearly documents the caller's responsibility to release theCFStringRefvalues. TheCFKeyenum cleanly centralizes all property key strings.oshi-core-java25/src/main/java/oshi/software/os/mac/MacInternetProtocolStatsFFM.java (3)
2-2: No review feedback.Metadata-only update.
122-123: Good fix for negative derived TCPv6 counters.This now matches the non-FFM path and prevents transient UDP checksum counters from driving the synthesized IPv6 TCP totals below zero.
333-343: Nice parity fix for the UDP stats layout.The
80-byteudps_snd6_swcsumoffset and84-byte buffer are consistent with the fields read here and with the JNA implementation, so this should resolve the zeroed UDP stats path cleanly.
| CapacityUnits psCapacityUnits = CapacityUnits.RELATIVE; | ||
| int psCurrentCapacity = 0; | ||
| int psMaxCapacity = 1; | ||
| int psDesignCapacity = 1; |
There was a problem hiding this comment.
Use the same unknown sentinel for psDesignCapacity as the JNA path.
Line 60 initializes psDesignCapacity to 1, but oshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSource.java uses 0 for “unavailable”. If AppleSmartBattery is missing, this reports a fake 1 mAh design capacity instead of “unknown”.
Proposed fix
- int psDesignCapacity = 1;
+ int psDesignCapacity = 0;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| int psDesignCapacity = 1; | |
| int psDesignCapacity = 0; |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In
`@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.java`
at line 60, The variable psDesignCapacity in MacPowerSourceFFM (inside class
MacPowerSourceFFM and related to AppleSmartBattery handling) is initialized to 1
which creates a bogus 1 mAh value when AppleSmartBattery is missing; change its
initialization to use the same "unknown" sentinel as the JNA path (0) so that
psDesignCapacity defaults to 0 when unavailable, matching the behavior in
MacPowerSource.java and avoiding a fake capacity value.
| temp = smartBattery.getIntegerProperty("DesignCapacity"); | ||
| if (temp != null) { | ||
| psDesignCapacity = temp; | ||
| } | ||
| temp = smartBattery.getIntegerProperty("MaxCapacity"); | ||
| if (temp != null) { | ||
| psMaxCapacity = temp; | ||
| } | ||
| temp = smartBattery.getIntegerProperty("CurrentCapacity"); | ||
| if (temp != null) { | ||
| psCurrentCapacity = temp; | ||
| } | ||
| psCapacityUnits = CapacityUnits.MAH; | ||
|
|
||
| temp = smartBattery.getIntegerProperty("TimeRemaining"); | ||
| if (temp != null) { | ||
| psTimeRemainingInstant = temp * 60d; | ||
| } | ||
| temp = smartBattery.getIntegerProperty("CycleCount"); | ||
| if (temp != null) { | ||
| psCycleCount = temp; | ||
| } | ||
| temp = smartBattery.getIntegerProperty("Temperature"); | ||
| if (temp != null) { | ||
| psTemperature = temp / 100d; | ||
| } | ||
| temp = smartBattery.getIntegerProperty("Voltage"); | ||
| if (temp != null) { | ||
| psVoltage = temp / 1000d; |
There was a problem hiding this comment.
Keep the same invalid-value guards as MacPowerSource.
The JNA implementation rejects non-positive DesignCapacity, MaxCapacity, and Voltage, plus negative CurrentCapacity and CycleCount. Here those values are copied verbatim, so the FFM path can publish impossible battery metrics and diverge from the existing macOS implementation on the same machine.
Proposed fix
temp = smartBattery.getIntegerProperty("DesignCapacity");
- if (temp != null) {
+ if (temp != null && temp > 0) {
psDesignCapacity = temp;
}
temp = smartBattery.getIntegerProperty("MaxCapacity");
- if (temp != null) {
+ if (temp != null && temp > 0) {
psMaxCapacity = temp;
}
temp = smartBattery.getIntegerProperty("CurrentCapacity");
- if (temp != null) {
+ if (temp != null && temp >= 0) {
psCurrentCapacity = temp;
}
@@
temp = smartBattery.getIntegerProperty("CycleCount");
- if (temp != null) {
+ if (temp != null && temp >= 0) {
psCycleCount = temp;
}
@@
temp = smartBattery.getIntegerProperty("Voltage");
- if (temp != null) {
+ if (temp != null && temp > 0) {
psVoltage = temp / 1000d;
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| temp = smartBattery.getIntegerProperty("DesignCapacity"); | |
| if (temp != null) { | |
| psDesignCapacity = temp; | |
| } | |
| temp = smartBattery.getIntegerProperty("MaxCapacity"); | |
| if (temp != null) { | |
| psMaxCapacity = temp; | |
| } | |
| temp = smartBattery.getIntegerProperty("CurrentCapacity"); | |
| if (temp != null) { | |
| psCurrentCapacity = temp; | |
| } | |
| psCapacityUnits = CapacityUnits.MAH; | |
| temp = smartBattery.getIntegerProperty("TimeRemaining"); | |
| if (temp != null) { | |
| psTimeRemainingInstant = temp * 60d; | |
| } | |
| temp = smartBattery.getIntegerProperty("CycleCount"); | |
| if (temp != null) { | |
| psCycleCount = temp; | |
| } | |
| temp = smartBattery.getIntegerProperty("Temperature"); | |
| if (temp != null) { | |
| psTemperature = temp / 100d; | |
| } | |
| temp = smartBattery.getIntegerProperty("Voltage"); | |
| if (temp != null) { | |
| psVoltage = temp / 1000d; | |
| temp = smartBattery.getIntegerProperty("DesignCapacity"); | |
| if (temp != null && temp > 0) { | |
| psDesignCapacity = temp; | |
| } | |
| temp = smartBattery.getIntegerProperty("MaxCapacity"); | |
| if (temp != null && temp > 0) { | |
| psMaxCapacity = temp; | |
| } | |
| temp = smartBattery.getIntegerProperty("CurrentCapacity"); | |
| if (temp != null && temp >= 0) { | |
| psCurrentCapacity = temp; | |
| } | |
| psCapacityUnits = CapacityUnits.MAH; | |
| temp = smartBattery.getIntegerProperty("TimeRemaining"); | |
| if (temp != null) { | |
| psTimeRemainingInstant = temp * 60d; | |
| } | |
| temp = smartBattery.getIntegerProperty("CycleCount"); | |
| if (temp != null && temp >= 0) { | |
| psCycleCount = temp; | |
| } | |
| temp = smartBattery.getIntegerProperty("Temperature"); | |
| if (temp != null) { | |
| psTemperature = temp / 100d; | |
| } | |
| temp = smartBattery.getIntegerProperty("Voltage"); | |
| if (temp != null && temp > 0) { | |
| psVoltage = temp / 1000d; | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In
`@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.java`
around lines 96 - 124, In MacPowerSourceFFM, apply the same invalid-value guards
as MacPowerSource when reading smartBattery properties: only assign
psDesignCapacity and psMaxCapacity if the value from
smartBattery.getIntegerProperty("DesignCapacity"/"MaxCapacity") is > 0; only
assign psCurrentCapacity if the value from getIntegerProperty("CurrentCapacity")
is >= 0; only assign psCycleCount if getIntegerProperty("CycleCount") is >= 0;
and only assign psVoltage if getIntegerProperty("Voltage") is > 0; keep
psCapacityUnits assignment as-is. Locate these assignments in MacPowerSourceFFM
(references: psDesignCapacity, psMaxCapacity, psCurrentCapacity, psCycleCount,
psVoltage, smartBattery.getIntegerProperty) and wrap each assignment with the
appropriate conditional checks so FFM matches the JNA behavior.
… imports - MacPowerSourceFFM: restructure resource cleanup with null-guarded finally block; declare powerSourcesInfo/cfList/CFStringRef keys before try so they are always released; wrap CFRelease in inner try/catch(Throwable) with explanatory comment to satisfy compiler and checkstyle EmptyCatchBlock rule - MacPowerSourceFFM/MacPowerSource: change psDesignCapacity default from 1 to -1 (consistent unknown sentinel matching psCycleCount/psVoltage); add DateTimeException guard on ManufactureDate bitfield parsing; guard maxCapacity <= 0 before division in psRemainingCapacityPercent - MacHWDiskStoreFFM: null-guard BSD_UNIT/LEAF lookups before CFNumberRef/ CFTypeRef construction; null-guard STATISTICS dict before CFDictionaryRef creation; individually null-guard READ_OPS/READ_BYTES/WRITE_OPS/WRITE_BYTES values; null-guard DA_MEDIA_SIZE before longValue() - MacUsbDeviceFFM: replace inline fully qualified class names with proper imports (CFAllocatorRef, CFMutableDictionaryRef, CoreFoundationFunctions)
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.java (1)
98-131: Missing validation for battery property values diverges from JNA implementation.The JNA implementation in
MacPowerSourcevalidates that certain battery properties are within valid ranges before accepting them (e.g.,DesignCapacity > 0,MaxCapacity > 0,CurrentCapacity >= 0,CycleCount >= 0,Voltage > 0). This FFM implementation accepts any non-null value, which could result in impossible metrics (negative capacities, zero voltages used in calculations, etc.).This was flagged in a previous review but appears unaddressed in both implementations. Consider adding guards for consistency and data validity:
♻️ Proposed validation guards
temp = smartBattery.getIntegerProperty("DesignCapacity"); - if (temp != null) { + if (temp != null && temp > 0) { psDesignCapacity = temp; } temp = smartBattery.getIntegerProperty("MaxCapacity"); - if (temp != null) { + if (temp != null && temp > 0) { psMaxCapacity = temp; } temp = smartBattery.getIntegerProperty("CurrentCapacity"); - if (temp != null) { + if (temp != null && temp >= 0) { psCurrentCapacity = temp; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.java` around lines 98 - 131, MacPowerSourceFFM currently assigns any non-null values from smartBattery.getIntegerProperty to fields (psDesignCapacity, psMaxCapacity, psCurrentCapacity, psCycleCount, psVoltage, etc.) without range checks; add the same validation guards used in the JNA MacPowerSource implementation so only sensible values are accepted: assign psDesignCapacity and psMaxCapacity only if > 0, psCurrentCapacity and psCycleCount only if >= 0, and psVoltage only if > 0 (leave defaults otherwise); update the code paths in MacPowerSourceFFM that read DesignCapacity, MaxCapacity, CurrentCapacity, CycleCount, and Voltage to perform these checks before setting the corresponding ps* fields (psDesignCapacity, psMaxCapacity, psCurrentCapacity, psCycleCount, psVoltage).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In
`@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java`:
- Around line 313-318: The code calls DADiskRef.createFromIOMedia(alloc,
session, media) then immediately uses disk.getBSDName() and disk.release()
without checking for a null reference; update the block that creates DADiskRef
(the variable disk from DADiskRef.createFromIOMedia) to first verify
!disk.isNull() (or disk.isNull() == false) before calling getBSDName() and
release(), and only add to bsdNames when the disk is non-null so you mirror the
null-guard pattern used elsewhere (see updateDiskStats and the check at line
335).
---
Nitpick comments:
In
`@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.java`:
- Around line 98-131: MacPowerSourceFFM currently assigns any non-null values
from smartBattery.getIntegerProperty to fields (psDesignCapacity, psMaxCapacity,
psCurrentCapacity, psCycleCount, psVoltage, etc.) without range checks; add the
same validation guards used in the JNA MacPowerSource implementation so only
sensible values are accepted: assign psDesignCapacity and psMaxCapacity only if
> 0, psCurrentCapacity and psCycleCount only if >= 0, and psVoltage only if > 0
(leave defaults otherwise); update the code paths in MacPowerSourceFFM that read
DesignCapacity, MaxCapacity, CurrentCapacity, CycleCount, and Voltage to perform
these checks before setting the corresponding ps* fields (psDesignCapacity,
psMaxCapacity, psCurrentCapacity, psCycleCount, psVoltage).
🪄 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: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: ee613c9c-eee0-478a-ba55-3fe97667003e
📒 Files selected for processing (4)
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceFFM.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSource.java
✅ Files skipped from review due to trivial changes (1)
- oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceFFM.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). (6)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Test JDK 25, windows-latest
- GitHub Check: Test JDK 25, macos-latest
- GitHub Check: Test JDK 11, windows-latest
- GitHub Check: Test JDK 11, macos-latest
- GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-04-03T02:07:47.621Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3110
File: oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java:119-121
Timestamp: 2026-04-03T02:07:47.621Z
Learning: In OSHI’s Java FFM/API implementation classes (e.g., *FFM.java) that implement/override `updateAttributes()`, preserve the intentional failure-handling pattern: catch `Throwable` and return `false` without logging. `updateAttributes()` is a public API whose contract is to signal failure via the boolean return value, and callers rely on that return value (so emitting logs from this path is not desired and should not be introduced during review unless the method contract changes).
Applied to files:
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java
🔇 Additional comments (15)
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.java (5)
1-48: LGTM: Class structure and constructor.The imports, class definition, and constructor properly delegate to
AbstractPowerSource. The@ThreadSafeannotation is appropriate given the method creates new instances per call.
50-69: LGTM: Default values align with JNA implementation.The sentinel values (
psDesignCapacity = -1,psCycleCount = -1,psVoltage = -1d) now match the JNA implementation and correctly signal "unknown" rather than potentially valid values.
86-96: LGTM: DateTimeException guard properly implemented.The try/catch around
LocalDate.of()handles corrupt bitfields (e.g., month=0 or day=0) gracefully, leavingpsManufactureDateas null rather than crashing the entire enumeration.
168-219: LGTM: Resource cleanup with null guards properly implemented.The resource management pattern correctly:
- Declares variables before the try block so they're accessible in finally
- Uses null guards for each CFStringRef/CFArrayRef before calling release()
- Wraps CFRelease in inner try/catch to handle the declared Throwable
- Releases
powerSourcesInfolast since it ownspowerSourcesList- Guards
maxCapacity <= 0before division at line 208
220-246: LGTM: Exception handling and cleanup follow project patterns.The catch-all
Throwablereturning an empty list aligns with the project's pattern forgetPowerSources()style factory methods. The finally block properly cleans up all native resources in reverse allocation order.oshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSource.java (3)
67-67: LGTM: Sentinel value change is appropriate.Changing
psDesignCapacityfrom1to-1correctly signals "unknown" rather than reporting a misleading 1 mAh capacity whenAppleSmartBatteryis unavailable. This aligns withpsCycleCountwhich also uses-1as its unknown sentinel.
106-110: LGTM: DateTimeException guard prevents enumeration failure.Wrapping
LocalDate.of()in a try/catch handles corrupt bitfields (e.g., month=0) gracefully, leavingpsManufactureDateas null rather than propagating an exception that would fail the entiregetPowerSources()call.
206-207: LGTM: Division guard handles edge case correctly.The
maxCapacity <= 0 ? 0d : ...guard prevents division by zero and avoids reporting misleading 100% capacity (fromMath.min(1d, Infinity)) when battery data is unavailable or corrupted.oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java (7)
39-60: LGTM - Class structure and constructor.The private constructor with factory method pattern (
getDisks()) is clean. CallingupdateDiskStatsduring construction ensures disk statistics are populated immediately.
62-100: LGTM - Getter implementations.Standard getter implementations.
getPartitions()correctly returns the unmodifiable list created inupdateDiskStats.
102-123: LGTM - Resource cleanup and error handling.The
updateAttributes()implementation correctly:
- Checks for null session before proceeding
- Releases all
CFStringRefvalues in the finally block- Returns
falseon failure without logging (per project convention for API methods)Based on learnings:
updateAttributes()is a public API whose contract signals failure via the boolean return value, so silent catch-and-return-false is intentional.
125-290: LGTM - Comprehensive NULL guards and resource cleanup.The
updateDiskStatsmethod has thorough defensive coding:
- All dictionary lookups check for
MemorySegment.NULLbefore creating wrapper objects- All IOKit/CoreFoundation resources are released in appropriate
finallyblocks- The nested try-finally structure ensures cleanup even on exceptions
- Parent entry null-check before release at line 279-281
This addresses all previously flagged concerns about missing NULL checks on
STATISTICS,BSD_UNIT,LEAF, and individual statistic values.
338-399: LGTM - Disk enumeration and filtering.The disk enumeration logic:
- Properly checks
disk.isNull()at line 335 (contrast with issue above)- Includes NULL guard for
DA_MEDIA_SIZEat lines 345-347- Correctly filters out "Disk Image" models and disks with invalid sizes
- Handles missing serial numbers gracefully with empty string fallback
401-410: LGTM - Factory method error handling.The
getDisks()static factory appropriately:
- Logs errors at ERROR level (unlike the API method
updateAttributeswhich returns boolean)- Releases all
CFStringRefvalues fromcfKeyMapin the finally block- Returns the accumulated
diskList(potentially partial) rather than empty list on late failures
413-449: LGTM - Helper method and enum design.The
mapCFKeys()method andCFKeyenum provide a clean abstraction for managing CoreFoundation string keys:
EnumMapis the correct collection type for enum keys- The Javadoc clearly documents the caller's responsibility to release values
- All keys used throughout the class are centralized in the enum
Mirror the null-guard pattern used for createFromBSDName: only call getBSDName() and release() when the DADiskRef is non-null, and only add to bsdNames when the disk reference is valid.
There was a problem hiding this comment.
🧹 Nitpick comments (2)
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java (2)
42-54: Thread safety: mutable fields lack visibility guarantees.The class is annotated
@ThreadSafe, but the mutable fields (reads,readBytes,writes,writeBytes,transferTime,timeStamp,partitionList) are notvolatileand are updated/read without synchronization. IfupdateAttributes()is called concurrently with getters, callers may observe stale or partially-updated values.Consider marking these fields
volatileto ensure visibility across threads, or document that the class is thread-safe only for construction followed by single-threaded access.♻️ Proposed fix to add volatile modifiers
- private long reads = 0L; - private long readBytes = 0L; - private long writes = 0L; - private long writeBytes = 0L; - private long currentQueueLength = 0L; - private long transferTime = 0L; - private long timeStamp = 0L; - private List<HWPartition> partitionList; + private volatile long reads = 0L; + private volatile long readBytes = 0L; + private volatile long writes = 0L; + private volatile long writeBytes = 0L; + private volatile long currentQueueLength = 0L; + private volatile long transferTime = 0L; + private volatile long timeStamp = 0L; + private volatile List<HWPartition> partitionList;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java` around lines 42 - 54, The class MacHWDiskStoreFFM is annotated `@ThreadSafe` but its mutable fields (reads, readBytes, writes, writeBytes, currentQueueLength, transferTime, timeStamp, partitionList) lack visibility guarantees; make these fields volatile (e.g., declare reads, readBytes, writes, writeBytes, currentQueueLength, transferTime, timeStamp as volatile long and partitionList as volatile List<HWPartition>) so reads in the various getters and updates in updateAttributes() see consistent values across threads, or alternatively add proper synchronization around updateAttributes() and the getters—prefer the volatile field change for minimal invasive fix.
51-51:currentQueueLengthis never updated.The field is initialized to
0Land never modified anywhere in this class, sogetCurrentQueueLength()always returns0. If macOS doesn't expose this metric via IOKit, consider adding a brief comment to document this limitation for maintainability.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java` at line 51, The field currentQueueLength in class MacHWDiskStoreFFM is initialized to 0L and never updated so getCurrentQueueLength() always returns 0; either implement reading/updating this metric from IOKit in the methods that poll disk stats (e.g., within the update/poll routine that fills readBytes/writeBytes) and set currentQueueLength accordingly, or if macOS does not expose this value, add a clear inline comment above the currentQueueLength field and update getCurrentQueueLength()’s Javadoc to state explicitly that this metric is unavailable on macOS and always returns 0 to aid future maintainability.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In
`@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java`:
- Around line 42-54: The class MacHWDiskStoreFFM is annotated `@ThreadSafe` but
its mutable fields (reads, readBytes, writes, writeBytes, currentQueueLength,
transferTime, timeStamp, partitionList) lack visibility guarantees; make these
fields volatile (e.g., declare reads, readBytes, writes, writeBytes,
currentQueueLength, transferTime, timeStamp as volatile long and partitionList
as volatile List<HWPartition>) so reads in the various getters and updates in
updateAttributes() see consistent values across threads, or alternatively add
proper synchronization around updateAttributes() and the getters—prefer the
volatile field change for minimal invasive fix.
- Line 51: The field currentQueueLength in class MacHWDiskStoreFFM is
initialized to 0L and never updated so getCurrentQueueLength() always returns 0;
either implement reading/updating this metric from IOKit in the methods that
poll disk stats (e.g., within the update/poll routine that fills
readBytes/writeBytes) and set currentQueueLength accordingly, or if macOS does
not expose this value, add a clear inline comment above the currentQueueLength
field and update getCurrentQueueLength()’s Javadoc to state explicitly that this
metric is unavailable on macOS and always returns 0 to aid future
maintainability.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 96a91355-5b52-4e6b-8e7d-433149a48766
📒 Files selected for processing (1)
oshi-core-java25/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). (7)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Test JDK 21, macos-latest
- GitHub Check: Test JDK 25, macos-latest
- GitHub Check: Test JDK 11, windows-latest
- GitHub Check: Test JDK 25, windows-latest
- GitHub Check: Test JDK 11, macos-latest
- GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-04-03T02:07:47.621Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3110
File: oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java:119-121
Timestamp: 2026-04-03T02:07:47.621Z
Learning: In OSHI’s Java FFM/API implementation classes (e.g., *FFM.java) that implement/override `updateAttributes()`, preserve the intentional failure-handling pattern: catch `Throwable` and return `false` without logging. `updateAttributes()` is a public API whose contract is to signal failure via the boolean return value, and callers rely on that return value (so emitting logs from this path is not desired and should not be introduced during review unless the method contract changes).
Applied to files:
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java
🔇 Additional comments (3)
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java (3)
125-290: Well-structured resource management with proper NULL guards.The nested try-finally blocks ensure native resources (IOIterator, IORegistryEntry, CFDictionaryRef) are properly released. The NULL checks for STATISTICS and its sub-values (lines 155-184), as well as BSD_UNIT and LEAF (lines 209-214), correctly guard against missing dictionary keys.
292-413: Good defensive coding with comprehensive null-safety checks.The
getDisks()method properly guards against null DASessionRef (line 300), null DADiskRef (lines 314, 337), null CFDictionaryRef (line 342), and null MemorySegment for media size (line 347). Resources are consistently released in finally blocks, and the catch block at line 409-411 logs enumeration errors appropriately.
415-451: Clear documentation of memory management responsibility.The Javadoc properly documents that callers must release the CFStringRef values to avoid native memory leaks. The CFKey enum provides a clean, type-safe mapping to the various IOKit and CoreFoundation key names.
Summary
This PR adds FFM (Foreign Function & Memory) implementations for all five macOS hardware subsystems in oshi-core-java25, completing the hardware layer for the FFM backend. It also fixes a pre-existing bug in oshi-core where UDP statistics returned all zeros on modern macOS and FreeBSD.
Hardware FFM Implementations
MacHWDiskStoreFFM— disk enumeration via DiskArbitration + IOKit + CoreFoundationMacNetworkIFFM— network interfaces via SystemConfigurationMacDisplayFFM— display information via CoreGraphics/IOKitMacPowerSourceFFM— power sources via IOKitMacUsbDeviceFFM— USB device tree via IOKitMacHardwareAbstractionLayerFFM— wires all five into the FFM HALOutput was validated by running SystemInfoTest (JNA) and SystemInfoFFMTest (FFM) side-by-side. All hardware sections match structurally; only expected volatile differences (memory usage, CPU load, live connection counts) remain.
Bug Fixes
UDP stats size guard too strict (
MacInternetProtocolStats,FreeBsdInternetProtocolStats,MacInternetProtocolStatsFFM)queryUdpstatmethod guarded withm.size() >= 1644, but net.inet.udp.stats returns only 104 bytes on modern macOS. This caused all UDP statistics to silently return zero. The highest offset actually read is 80 (udps_snd6_swcsum), so the guard is corrected to >= 84. The same bug existed identically inFreeBsdInternetProtocolStats. The FFM implementation's oversized 1644-byte allocation is similarly reduced to 84, consistent with how the other stat buffers (tcp, ip, ip6) are handled.Summary by CodeRabbit
New Features
Bug Fixes
Refactor
Chores