Repository navigation
Migrate macOS IOKit/SMC hardware to FFM - #3109
Conversation
…irmware, Sensors - Add MacComputerSystemFFM, MacBaseboardFFM, MacFirmwareFFM, MacSensorsFFM - Add SmcUtilFFM replacing JNA SmcUtil/IOConnect for SMC sensor reads - Add IOServiceOpen, IOServiceClose, IOConnectCallStructMethod to IOKitFunctions - Add SMC struct layouts (SMC_KEY_DATA, SMC_VAL) to MacSystem - Add host_processor_info, getloadavg to MacSystemFunctions - Wire FFM implementations into MacHardwareAbstractionLayerFFM - Move createComputerSystem/createSensors defaults from abstract base to MacHardwareAbstractionLayerJNA - Fix IOKitFunctions/CoreFoundationFunctions to load frameworks explicitly via frameworkLookup() - Add ForeignFunctions.frameworkLookup() with /System/Library/Frameworks and /Library/Frameworks fallback using LIBRARY_ARENA
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
✅ Files skipped from review due to trivial changes (3)
📜 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). (5)
📝 WalkthroughWalkthroughAdds macOS FFM support: framework lookup API, framework-scoped CoreFoundation/IOKit symbol resolution, new IOKit downcalls, SMC FFM structs/utilities, FFM-based hardware and sensors implementations, and HAL routing updates between FFM and JNA variants. Changes
Sequence Diagram(s)sequenceDiagram
participant App as Application
participant Sensors as MacSensorsFFM
participant SmcUtil as SmcUtilFFM
participant IOKit as IOKitFunctions
participant SMC as AppleSMC
App->>Sensors: queryCpuTemperature()
Sensors->>SmcUtil: smcOpen()
SmcUtil->>IOKit: IOServiceMatching("AppleSMC") / IOServiceGetMatchingService
IOKit->>SMC: locate service
IOKit-->>SmcUtil: service ref
SmcUtil->>IOKit: IOServiceOpen(service)
IOKit-->>SmcUtil: connection handle
Sensors->>SmcUtil: smcGetFirstFloat(conn, keys...)
SmcUtil->>SmcUtil: smcGetKeyInfo (cache or IOConnectKeyInfo)
SmcUtil->>IOKit: IOConnectCallStructMethod(conn, selector, inStruct, outStruct)
IOKit->>SMC: SMC read request
SMC-->>IOKit: raw bytes
IOKit-->>SmcUtil: raw bytes
SmcUtil->>Sensors: parsed double
Sensors-->>App: temperature value
Sensors->>SmcUtil: smcClose(conn)
SmcUtil->>IOKit: IOServiceClose(connection)
IOKit-->>SmcUtil: closed
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 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
Warning Tools execution failed with the following error: Failed to run tools: 13 INTERNAL: Received RST_STREAM with code 2 (Internal server error) 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 #3109 +/- ##
==========================================
+ Coverage 67.35% 68.50% +1.15%
==========================================
Files 37 37
Lines 1994 1994
Branches 323 323
==========================================
+ Hits 1343 1366 +23
+ Misses 541 516 -25
- Partials 110 112 +2 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
oshi-core-java25/src/main/java/oshi/util/platform/mac/SmcUtilFFM.java (1)
103-104: Prefer SLF4J parameterized logging overString.format.Using
String.formatincurs formatting cost even when the log level is disabled. SLF4J's parameterized logging defers formatting.♻️ Suggested fix
- LOG.error( - String.format(Locale.ROOT, "Unable to open connection to AppleSMC service. Error: 0x%08x", result)); + LOG.error("Unable to open connection to AppleSMC service. Error: 0x{}", String.format("%08x", result));Note: Since SLF4J doesn't support hex formatting directly,
String.formatis still needed for the hex conversion, but this is a minor optimization.🤖 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/util/platform/mac/SmcUtilFFM.java` around lines 103 - 104, Replace the direct String.format call inside the LOG.error invocation so SLF4J does the message assembly; compute the hex string for result (e.g., String hex = String.format(Locale.ROOT, "0x%08x", result)) and then call LOG.error("Unable to open connection to AppleSMC service. Error: {}", hex). Update the usage in SmcUtilFFM where LOG and result are referenced to avoid formatting when the log level is disabled.oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacFirmwareFFM.java (1)
62-128: Consider wrappingplatformExpertin try-finally for exception safety.If an exception occurs during IODeviceTree traversal (e.g., in
entry.getByteArrayProperty()),platformExpert.release()on line 127 would be skipped, leaking the IOKit reference. Since this method is memoized and called once, the impact is minimal, but a try-finally would be more robust.♻️ Suggested improvement
IORegistryEntry platformExpert = IOKitUtilFFM.getMatchingService("IOPlatformExpertDevice"); if (platformExpert != null) { - IOIterator iter = platformExpert.getChildIterator("IODeviceTree"); - if (iter != null) { - // ... traversal code ... - iter.release(); + try { + IOIterator iter = platformExpert.getChildIterator("IODeviceTree"); + if (iter != null) { + try { + // ... traversal code ... + } finally { + iter.release(); + } + } + // ... fallback property reads ... + } finally { + platformExpert.release(); } - // ... fallback property reads ... - platformExpert.release(); }🤖 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/MacFirmwareFFM.java` around lines 62 - 128, Wrap the IORegistryEntry platformExpert usage in a try-finally inside MacFirmwareFFM so platformExpert.release() always runs; move traversal code (using IOIterator iter and IORegistryEntry entry) into the try block and call platformExpert.release() in the finally block, and ensure any created iter.release() and entry.release() calls are also protected (null-check before release) so no IOKit references are leaked on exceptions.
🤖 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/ffm/mac/IOKitFunctions.java`:
- Around line 277-284: Change the FFM binding for IOServiceClose to use a 32-bit
integer parameter: update the MethodHandle creation to use
FunctionDescriptor.of(JAVA_INT, JAVA_INT) (instead of ADDRESS) and change the
Java wrapper signature to public static int IOServiceClose(int connect) throws
Throwable, calling IOServiceClose.invokeExact(connect). Then update callers
(e.g., SmcUtilFFM.smcOpen) to extract the 32-bit port value from the returned
MemorySegment (read the int/mach_port_t value) and pass that int into
IOServiceClose rather than passing the MemorySegment itself. Ensure all
references to IOServiceClose use the new int parameter type.
In
`@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.java`:
- Around line 24-27: The field numFans in class MacSensorsFFM is accessed
non-atomically under the `@ThreadSafe` class (notably in queryFanSpeeds()), which
can cause a benign race during memoization expiry; make numFans volatile to
ensure visibility across threads and eliminate the check-then-act race. Update
the declaration of numFans in MacSensorsFFM to be volatile so reads/writes from
queryFanSpeeds() and any other accessors are properly synchronized with the
AbstractSensors memoization behavior.
---
Nitpick comments:
In
`@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacFirmwareFFM.java`:
- Around line 62-128: Wrap the IORegistryEntry platformExpert usage in a
try-finally inside MacFirmwareFFM so platformExpert.release() always runs; move
traversal code (using IOIterator iter and IORegistryEntry entry) into the try
block and call platformExpert.release() in the finally block, and ensure any
created iter.release() and entry.release() calls are also protected (null-check
before release) so no IOKit references are leaked on exceptions.
In `@oshi-core-java25/src/main/java/oshi/util/platform/mac/SmcUtilFFM.java`:
- Around line 103-104: Replace the direct String.format call inside the
LOG.error invocation so SLF4J does the message assembly; compute the hex string
for result (e.g., String hex = String.format(Locale.ROOT, "0x%08x", result)) and
then call LOG.error("Unable to open connection to AppleSMC service. Error: {}",
hex). Update the usage in SmcUtilFFM where LOG and result are referenced to
avoid formatting when the log level is disabled.
🪄 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: b5c12cee-ddd8-4dd8-93ed-b07d802e7beb
📒 Files selected for processing (13)
oshi-core-java25/src/main/java/oshi/ffm/ForeignFunctions.javaoshi-core-java25/src/main/java/oshi/ffm/mac/CoreFoundationFunctions.javaoshi-core-java25/src/main/java/oshi/ffm/mac/IOKitFunctions.javaoshi-core-java25/src/main/java/oshi/ffm/mac/MacSystem.javaoshi-core-java25/src/main/java/oshi/ffm/mac/MacSystemFunctions.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacBaseboardFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacComputerSystemFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacFirmwareFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.javaoshi-core-java25/src/main/java/oshi/util/platform/mac/SmcUtilFFM.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayer.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerJNA.java
💤 Files with no reviewable changes (1)
- oshi-core/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayer.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 11, windows-latest
- GitHub Check: Test JDK 21, windows-latest
- GitHub Check: Test JDK 25, windows-latest
- GitHub Check: Test JDK 11, macos-latest
- GitHub Check: Test JDK 25, macos-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-java25/src/main/java/oshi/ffm/ForeignFunctions.javaoshi-core-java25/src/main/java/oshi/ffm/mac/CoreFoundationFunctions.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacBaseboardFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacComputerSystemFFM.javaoshi-core-java25/src/main/java/oshi/util/platform/mac/SmcUtilFFM.javaoshi-core-java25/src/main/java/oshi/ffm/mac/IOKitFunctions.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/MacSystemFunctions.javaoshi-core-java25/src/main/java/oshi/ffm/mac/IOKitFunctions.java
🔇 Additional comments (16)
oshi-core/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerJNA.java (1)
19-27: LGTM!Clean implementation of the factory method pattern. Moving
createComputerSystem()andcreateSensors()from the abstract parent class to the JNA-specific implementation allows the FFM counterpart to override with its own implementations.oshi-core-java25/src/main/java/oshi/ffm/ForeignFunctions.java (1)
33-61: Well-designed framework lookup implementation.The search path priority (system frameworks first, then third-party) and the standard macOS framework bundle path format (
Name.framework/Name) are correct. UsingLIBRARY_ARENA(backed byArena.ofAuto()) appropriately ties the framework lifecycle to the classloader.oshi-core-java25/src/main/java/oshi/ffm/mac/CoreFoundationFunctions.java (1)
22-30: Good refactoring to framework-scoped symbol lookup.Using a dedicated
CF_LIBRARYlookup scoped toCoreFoundation.frameworkis cleaner and more explicit than relying on the process-wideSYMBOL_LOOKUP. The private constructor correctly prevents instantiation of this utility class.oshi-core-java25/src/main/java/oshi/ffm/mac/MacSystemFunctions.java (1)
246-269: Correct FFM bindings forhost_processor_infoandgetloadavg.Both signatures match their native counterparts. Using
CAPTURE_CALL_STATEforhost_processor_infois appropriate since Mach kernel calls may set errno. Thegetloadavgbinding correctly usesADDRESSfor thedouble[]parameter andJAVA_INTfor return/nelem.oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacBaseboardFFM.java (1)
49-87: Implementation correctly mirrors the JNA counterpart.The property keys (
board-id,model-number,mlb-serial-number,IOPlatformSerialNumber) and fallback logic matchMacBaseboard.javaexactly. The string normalization (UTF-8 decode, trim, NUL removal) properly handles native byte arrays, andplatformExpert.release()ensures the IOKit resource is freed.oshi-core-java25/src/main/java/oshi/ffm/mac/IOKitFunctions.java (1)
286-298:IOConnectCallStructMethodbinding looks correct.The
size_tparameters are correctly mapped toJAVA_LONGfor 64-bit macOS. TheoutputStructCntis a pointer tosize_t(in-out parameter), soADDRESSis appropriate.oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerFFM.java (1)
19-27: LGTM!The FFM factory methods correctly return
MacComputerSystemFFMandMacSensorsFFM, mirroring the JNA counterpart's structure while providing FFM-backed implementations.oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacComputerSystemFFM.java (1)
61-85: Code implementation is sound and consistent with the JNA counterpart.The
platformExpert()method correctly queriesIOPlatformExpertDevicefor system properties using identical property keys as the JNA implementation ("manufacturer", "model", "IOPlatformSerialNumber", "IOPlatformUUID"). String normalization (UTF-8 decode, trim, NUL removal) is properly applied, the IOKit resource is released correctly, and factory methods are properly wired to FFM implementations.oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.java (1)
29-81: Implementation follows established patterns and correctly manages SMC resources.The try-finally pattern ensures
smcClose()is always called, and the fallback logic for temperature/voltage keys matches the JNA implementation. The memoization inAbstractSensors(300ms default TTL from context) prevents excessive SMC connection churn.oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacFirmwareFFM.java (1)
136-138: LGTM:toUtf8helper correctly handles null-terminated strings.The combination of UTF-8 decoding, trim, and null-character removal properly handles the byte arrays returned from IOKit properties.
oshi-core-java25/src/main/java/oshi/util/platform/mac/SmcUtilFFM.java (4)
85-112: Resource management insmcOpenis correct.The
smcService.release()is properly placed in afinallyblock, ensuring the IOService reference is released regardless of success or failure. The null/error checks are comprehensive.
138-160: Float parsing handles multiple SMC data types correctly.The implementation properly handles:
SP78: signed 7.8 fixed-point formatFPE2: fixed-point with 2-bit exponent viaParseUtil.byteArrayToFloatFLT: IEEE 754 little-endian float
231-250: Thread-safe key info caching withConcurrentHashMap.The caching pattern is correct: check cache first, then populate on miss. Since
ConcurrentHashMap.get()andput()are atomic, and duplicate puts would store identical values, no additional synchronization is needed.
252-259:⚠️ Potential issue | 🟡 MinorUnused
arenaparameter insmcCallmethod signature at line 231.The
smcCallmethod creates its own confinedArenabut ignores thearenaparameter passed from the caller. Looking at the call site insmcGetKeyInfo(line 242), anarenais passed but never used.Either remove the parameter from the method signature or use the passed arena instead of creating a new one.
♻️ Suggested fix (remove parameter)
The parameter appears to be unused at both call sites (lines 222 and 242). If the caller's arena should be used:
- private static int smcCall(MemorySegment conn, int index, MemorySegment input, MemorySegment output) - throws Throwable { - try (Arena arena = Arena.ofConfined()) { - MemorySegment outputSize = arena.allocate(JAVA_LONG); + private static int smcCall(MemorySegment conn, int index, MemorySegment input, MemorySegment output, Arena arena) + throws Throwable { + MemorySegment outputSize = arena.allocate(JAVA_LONG); outputSize.set(JAVA_LONG, 0, SMC_KEY_DATA.byteSize()); return IOConnectCallStructMethod(conn, index, input, SMC_KEY_DATA.byteSize(), output, outputSize); - } }Or remove the parameter from callers if the nested arena is intentional.
> Likely an incorrect or invalid review comment.oshi-core-java25/src/main/java/oshi/ffm/mac/MacSystem.java (2)
492-504: SMC_VAL layout is correct and matches JNA structure size.The FFM
SMC_VALlayout (52 bytes) explicitly specifies padding that JNA applies implicitly via native struct alignment. The JNASMCValhas field orderbyte[5] key,int dataSize,byte[5] dataType,byte[32] bytes. On macOS, JNA automatically pads 3 bytes afterkey[5]to aligndataSizeto a 4-byte boundary, and 3 bytes afterdataType[5]for alignment, totaling 52 bytes. Both implementations match.
439-490: The structure size calculations are correct and match JNA's natural alignment.All FFM structure byte sizes match their JNA counterparts exactly:
SMC_KEY_DATA_KEY_INFO: 12 bytes (the padding(3) correctly accounts for int struct alignment)SMC_KEY_DATA: 80 bytes (all nested fields and padding align correctly)SMC_VAL: 52 bytes (padding afterkey[5]anddataType[5]is correct for int alignment)The explicit padding in the FFM layouts properly reflects JNA's natural alignment rules. These definitions will work correctly with
IOConnectCallStructMethod.
io_connect_t is natural_t (unsigned int, 32-bit) not a pointer.
JNA's IOConnect extends PointerType was a JNA abstraction convenience,
not a reflection of the wire type.
- IOServiceClose: FunctionDescriptor ADDRESS -> JAVA_INT
- IOConnectCallStructMethod: first param ADDRESS -> JAVA_INT
- SmcUtilFFM: smcOpen() allocates JAVA_INT slot, returns int (0=failure);
all conn parameters changed from MemorySegment to int
- MacSensorsFFM: conn MemorySegment -> int, null checks -> conn == 0
Also fix nitpicks from code review:
- MacFirmwareFFM: wrap platformExpert/iter/entry in try-finally
to guarantee IOKit resource release on exceptions
- SmcUtilFFM: use SLF4J lazy {} formatting instead of eager String.format
- MacSensorsFFM: make numFans volatile for visibility under @threadsafe
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacFirmwareFFM.java (1)
145-147: Consider stopping at first NUL for stricter parity with JNA.The JNA
Native.toString()stops at the first NUL byte. This implementation removes all NUL characters, which works for properly-formed C strings but behaves differently if the byte array contains data after a NUL terminator.Optional defensive fix
private static String toUtf8(byte[] data) { - return new String(data, StandardCharsets.UTF_8).trim().replace("\0", ""); + int end = 0; + while (end < data.length && data[end] != 0) { + end++; + } + return new String(data, 0, end, StandardCharsets.UTF_8).trim(); }🤖 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/MacFirmwareFFM.java` around lines 145 - 147, The toUtf8(byte[] data) helper currently removes all NULs instead of stopping at the first NUL like JNA's Native.toString(), causing different behavior when bytes exist after a NUL terminator; update toUtf8 to find the first 0 byte (NUL) in the input and construct the String only from data[0..nulIndex) using StandardCharsets.UTF_8, then trim the result so it matches JNA semantics while preserving existing trimming behavior.
🤖 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/MacSensorsFFM.java`:
- Around line 52-57: The code in MacSensorsFFM reads the volatile field
this.numFans twice (for array allocation and loop bound), which can race and
cause ArrayIndexOutOfBoundsException; fix by snapshotting into a local int
(e.g., int fans = this.numFans; or set fans by calling SmcUtilFFM.smcGetLong
into a local) before creating fanSpeeds and using that local for the loop limit
and array size, ensuring you still update this.numFans appropriately (assign to
this.numFans after the snapshot if needed); update usages of SMC_KEY_FAN_NUM,
SMC_KEY_FAN_SPEED, SmcUtilFFM.smcGetLong and SmcUtilFFM.smcGetFloat in
MacSensorsFFM to use the local snapshot variable for consistency.
---
Nitpick comments:
In
`@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacFirmwareFFM.java`:
- Around line 145-147: The toUtf8(byte[] data) helper currently removes all NULs
instead of stopping at the first NUL like JNA's Native.toString(), causing
different behavior when bytes exist after a NUL terminator; update toUtf8 to
find the first 0 byte (NUL) in the input and construct the String only from
data[0..nulIndex) using StandardCharsets.UTF_8, then trim the result so it
matches JNA semantics while preserving existing trimming 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: afa3db95-81eb-4325-8b86-988d3aa54da7
📒 Files selected for processing (4)
oshi-core-java25/src/main/java/oshi/ffm/mac/IOKitFunctions.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacFirmwareFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.javaoshi-core-java25/src/main/java/oshi/util/platform/mac/SmcUtilFFM.java
🚧 Files skipped from review as they are similar to previous changes (1)
- oshi-core-java25/src/main/java/oshi/ffm/mac/IOKitFunctions.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: Test JDK 21, macos-latest
- GitHub Check: Test JDK 21, windows-latest
- GitHub Check: Test JDK 25, windows-latest
- GitHub Check: Test JDK 25, macos-latest
- GitHub Check: Test JDK 11, macos-latest
- GitHub Check: Analyze (java)
- GitHub Check: Codacy Static Code Analysis
🧰 Additional context used
🧠 Learnings (1)
📚 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/util/platform/mac/SmcUtilFFM.java
🔇 Additional comments (3)
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacFirmwareFFM.java (1)
55-143: Clean resource management with proper try-finally blocks.The nested try-finally structure ensures that IOKit handles (
platformExpert,iter,entry) are released even if exceptions occur during property reads. This is an improvement over the JNA version which releases entries without exception protection. The logic and property mappings match the JNAMacFirmware.queryEfi()exactly.oshi-core-java25/src/main/java/oshi/util/platform/mac/SmcUtilFFM.java (1)
84-111: FFM SMC flow looks solid and consistent with JNA behavior.
smcOpen/smcCloselifecycle handling, struct-call marshalling, and float/long decoding paths look correct for this migration.Also applies to: 134-195, 197-254
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.java (1)
29-43: Temperature/voltage query flow and connection cleanup are clean.The fallback logic and
finally-based close handling are well structured.Also applies to: 66-80
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/src/main/java/oshi/hardware/platform/mac/MacSensors.java`:
- Around line 54-57: The field numFans in MacSensors is a plain int and can
exhibit stale reads across threads; make it volatile to match the FFM
implementation and ensure thread-safe visibility: update the MacSensors class
declaration to declare the field as volatile int numFans (same semantics as
MacSensorsFFM) so the local snapshot usage (int fans = this.numFans) and
subsequent assignments (this.numFans = fans) have proper memory visibility.
🪄 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: 633a3a21-16d7-4f51-9450-03bcb26c04ab
📒 Files selected for processing (3)
CHANGELOG.mdoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacSensors.java
✅ Files skipped from review due to trivial changes (1)
- CHANGELOG.md
📜 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: Analyze (java)
- GitHub Check: Test JDK 11, macos-latest
- GitHub Check: Test JDK 21, macos-latest
🔇 Additional comments (1)
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.java (1)
52-59: Good race fix inqueryFanSpeeds().Using a single local
fanssnapshot for both array size and loop bound removes the previous AIOOBE window, andvolatile numFanskeeps cross-thread visibility sound.
Reading a volatile field multiple times allows a concurrent write to produce inconsistent values between the array allocation and loop bound, causing ArrayIndexOutOfBoundsException. Snapshot this.numFans into a local variable before use, write back to this.numFans after the SMC read, and use the local exclusively for the array size and loop bound. Applies to both oshi-core MacSensors and oshi-core-java25 MacSensorsFFM.
Summary
Migrates all IOKit and SMC-dependent hardware implementations, replacing JNA IOConnect, IORegistryEntry, and SmcUtil with FFM equivalents.
New FFM Hardware Classes
FFM Infrastructure Changes
IOKitFunctions: addedIOServiceOpen,IOServiceClose,IOConnectCallStructMethodMacSystem: added SMC struct layouts:SMC_KEY_DATA,SMC_VAL, and sub-structsMacSystemFunctions: addedhost_processor_info,getloadavg(needed for a later commit)IOKitFunctions / CoreFoundationFunctions: fixed to load their frameworks explicitly rather than relying on JNA having loaded them firstForeignFunctions: addedframeworkLookup(String)which searches /System/Library/Frameworks (Apple core) then/Library/Frameworks(third-party) usingLIBRARY_ARENAfor proper classloader-tied lifecycleMigration Pattern
Per the established pattern (
MacOperatingSystemFFMextendsMacOperatingSystem):createComputerSystem()andcreateSensors()moved out of the abstractMacHardwareAbstractionLayerbase intoMacHardwareAbstractionLayerJNAMacHardwareAbstractionLayerFFMoverrides both with FFM implementationsTesting
SystemInfoTest(JNA) andSystemInfoFFMTest(FFM) produce identical output for all migrated sections (Sensor values differ only by the expected amount between the two sequential runs.)Summary by CodeRabbit
New Features
Refactor
Chores