Skip to content

Migrate macOS IOKit/SMC hardware to FFM - #3109

Merged
dbwiddis merged 3 commits into
oshi:masterfrom
dbwiddis:ffm-mac-hw
Apr 2, 2026
Merged

dbwiddis merged 3 commits into
oshi:masterfrom
dbwiddis:ffm-mac-hw

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Apr 2, 2026 •

Copy link
Copy Markdown
Member

Summary

Migrates all IOKit and SMC-dependent hardware implementations, replacing JNA IOConnect, IORegistryEntry, and SmcUtil with FFM equivalents.

New FFM Hardware Classes

New Class Replaces
MacComputerSystemFFM MacComputerSystem
MacBaseboardFFM MacBaseboard
MacFirmwareFFM MacFirmware
MacSensorsFFM MacSensors
SmcUtilFFM SmcUtil

FFM Infrastructure Changes

IOKitFunctions: added IOServiceOpen, IOServiceClose, IOConnectCallStructMethod
MacSystem: added SMC struct layouts: SMC_KEY_DATA, SMC_VAL, and sub-structs
MacSystemFunctions: added host_processor_info, getloadavg (needed for a later commit)
IOKitFunctions / CoreFoundationFunctions: fixed to load their frameworks explicitly rather than relying on JNA having loaded them first
ForeignFunctions: added frameworkLookup(String) which searches /System/Library/Frameworks (Apple core) then /Library/Frameworks (third-party) using LIBRARY_ARENA for proper classloader-tied lifecycle

Migration Pattern

Per the established pattern (MacOperatingSystemFFM extends MacOperatingSystem):

  • createComputerSystem() and createSensors() moved out of the abstract MacHardwareAbstractionLayer base into MacHardwareAbstractionLayerJNA
  • MacHardwareAbstractionLayerFFM overrides both with FFM implementations

Testing

SystemInfoTest (JNA) and SystemInfoFFMTest (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

    • Expanded macOS hardware monitoring: SMC-backed CPU temperature, fan speeds, and voltage.
    • Richer macOS system info: improved manufacturer, model, firmware, baseboard, serial and UUID detection.
    • Added native-backed processor/load queries and additional IOKit integrations.
  • Refactor

    • Modernized macOS native integration with framework-scoped symbol resolution for more reliable native lookups.
  • Chores

    • Changelog updated with related bug fixes/improvements.

…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
@coderabbitai

coderabbitai Bot commented Apr 2, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c955a739-a328-4545-8d0b-50fb5af36303

📥 Commits

Reviewing files that changed from the base of the PR and between 1aaba78 and 9e769a2.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacSensors.java
✅ Files skipped from review due to trivial changes (3)
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacSensors.java
  • CHANGELOG.md
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.java
📜 Recent review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Test JDK 11, macos-latest

📝 Walkthrough

Walkthrough

Adds 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

Cohort / File(s) Summary
FFM Framework Infrastructure
oshi-core-java25/src/main/java/oshi/ffm/ForeignFunctions.java, oshi-core-java25/src/main/java/oshi/ffm/mac/CoreFoundationFunctions.java, oshi-core-java25/src/main/java/oshi/ffm/mac/IOKitFunctions.java
Added frameworkLookup(String) and FRAMEWORK_SEARCH_PATHS; created framework-scoped SymbolLookup constants and rewired CoreFoundation/IOKit symbol resolution to use them; added IOKit downcalls (IOServiceOpen, IOServiceClose, IOConnectCallStructMethod).
SMC Structs & System APIs
oshi-core-java25/src/main/java/oshi/ffm/mac/MacSystem.java, oshi-core-java25/src/main/java/oshi/ffm/mac/MacSystemFunctions.java
Added SMC-related StructLayout and PathElement constants; added FFM bindings for host_processor_info and getloadavg.
SMC Utility
oshi-core-java25/src/main/java/oshi/util/platform/mac/SmcUtilFFM.java
New thread-safe SMC utility implementing open/close, cached key-info, SMC read via IOConnectCallStructMethod, and value decoding (float/long) with fallbacks and caching.
FFM Hardware Implementations
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacComputerSystemFFM.java, oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacBaseboardFFM.java, oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacFirmwareFFM.java
New FFM-based ComputerSystem, Baseboard, and Firmware classes querying IORegistry properties, decoding UTF‑8 bytes, trimming NULs, applying fallbacks, and memoizing results.
FFM Sensors
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.java
New FFM-backed Sensors using SmcUtilFFM: CPU temp with Apple Silicon "as" key fallback, fan speeds with lazy cached count, and CPU voltage handling.
HAL Routing Changes
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerFFM.java, oshi-core/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayer.java, oshi-core/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerJNA.java
FFM HAL now constructs FFM ComputerSystem and Sensors; original Mac HAL removed JNA-specific overrides; JNA HAL regained explicit overrides for ComputerSystem and Sensors.
Minor / Changelog / JNA Sensor tweak
CHANGELOG.md, oshi-core/src/main/java/oshi/hardware/platform/mac/MacSensors.java
Added changelog entry and made numFans volatile with stable-local read in MacSensors.queryFanSpeeds().

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Suggested reviewers

  • mprins

Poem

🐰 I hopped through frameworks, swift and spry,
I peeked at AppleSMC with a gleam in my eye.
I fetched the temps, the fans, the volts so neat,
Marshaled bytes to numbers— tidy and sweet.
Hooray for FFM—hop, hop, repeat!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.69% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately and concisely describes the main change: migrating macOS IOKit/SMC hardware implementations from JNA to FFM.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
✨ Simplify code
  • Create PR with simplified 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented Apr 2, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 68.50%. Comparing base (bbc6284) to head (9e769a2).
⚠️ Report is 1 commits behind head on master.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 over String.format.

Using String.format incurs 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.format is 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 wrapping platformExpert in 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

📥 Commits

Reviewing files that changed from the base of the PR and between bbc6284 and 08a97c1.

📒 Files selected for processing (13)
  • oshi-core-java25/src/main/java/oshi/ffm/ForeignFunctions.java
  • oshi-core-java25/src/main/java/oshi/ffm/mac/CoreFoundationFunctions.java
  • oshi-core-java25/src/main/java/oshi/ffm/mac/IOKitFunctions.java
  • oshi-core-java25/src/main/java/oshi/ffm/mac/MacSystem.java
  • oshi-core-java25/src/main/java/oshi/ffm/mac/MacSystemFunctions.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacBaseboardFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacComputerSystemFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacFirmwareFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.java
  • oshi-core-java25/src/main/java/oshi/util/platform/mac/SmcUtilFFM.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayer.java
  • oshi-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.java
  • oshi-core-java25/src/main/java/oshi/ffm/mac/CoreFoundationFunctions.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacBaseboardFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacComputerSystemFFM.java
  • oshi-core-java25/src/main/java/oshi/util/platform/mac/SmcUtilFFM.java
  • oshi-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.java
  • oshi-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() and createSensors() 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. Using LIBRARY_ARENA (backed by Arena.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_LIBRARY lookup scoped to CoreFoundation.framework is cleaner and more explicit than relying on the process-wide SYMBOL_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 for host_processor_info and getloadavg.

Both signatures match their native counterparts. Using CAPTURE_CALL_STATE for host_processor_info is appropriate since Mach kernel calls may set errno. The getloadavg binding correctly uses ADDRESS for the double[] parameter and JAVA_INT for 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 match MacBaseboard.java exactly. The string normalization (UTF-8 decode, trim, NUL removal) properly handles native byte arrays, and platformExpert.release() ensures the IOKit resource is freed.

oshi-core-java25/src/main/java/oshi/ffm/mac/IOKitFunctions.java (1)

286-298: IOConnectCallStructMethod binding looks correct.

The size_t parameters are correctly mapped to JAVA_LONG for 64-bit macOS. The outputStructCnt is a pointer to size_t (in-out parameter), so ADDRESS is appropriate.

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

19-27: LGTM!

The FFM factory methods correctly return MacComputerSystemFFM and MacSensorsFFM, 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 queries IOPlatformExpertDevice for 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 in AbstractSensors (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: toUtf8 helper 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 in smcOpen is correct.

The smcService.release() is properly placed in a finally block, 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 format
  • FPE2: fixed-point with 2-bit exponent via ParseUtil.byteArrayToFloat
  • FLT: IEEE 754 little-endian float

231-250: Thread-safe key info caching with ConcurrentHashMap.

The caching pattern is correct: check cache first, then populate on miss. Since ConcurrentHashMap.get() and put() are atomic, and duplicate puts would store identical values, no additional synchronization is needed.


252-259: ⚠️ Potential issue | 🟡 Minor

Unused arena parameter in smcCall method signature at line 231.

The smcCall method creates its own confined Arena but ignores the arena parameter passed from the caller. Looking at the call site in smcGetKeyInfo (line 242), an arena is 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_VAL layout (52 bytes) explicitly specifies padding that JNA applies implicitly via native struct alignment. The JNA SMCVal has field order byte[5] key, int dataSize, byte[5] dataType, byte[32] bytes. On macOS, JNA automatically pads 3 bytes after key[5] to align dataSize to a 4-byte boundary, and 3 bytes after dataType[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 after key[5] and dataType[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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 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

📥 Commits

Reviewing files that changed from the base of the PR and between 08a97c1 and 4d1c06e.

📒 Files selected for processing (4)
  • oshi-core-java25/src/main/java/oshi/ffm/mac/IOKitFunctions.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacFirmwareFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.java
  • oshi-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 JNA MacFirmware.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/smcClose lifecycle 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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4d1c06e and 1aaba78.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.java
  • oshi-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 in queryFanSpeeds().

Using a single local fans snapshot for both array size and loop bound removes the previous AIOOBE window, and volatile numFans keeps 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant