Skip to content

Complete Mac HAL migration: JNA-free inheritance chain - #3111

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:ffm-mac-hw
Apr 3, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:ffm-mac-hw

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Apr 3, 2026 •

Copy link
Copy Markdown
Member

Summary

Completes the FFM Mac-unique hardware abstraction layer migration. Initializing SystemInfoFFM and calling all getters recursively will not classload any com.sun.jna or oshi.jna classes from the Mac hardware path (with two exception, see Future Work).

New classes

MacCentralProcessorFFM: Full FFM port of MacCentralProcessor. Replaces SystemB host statistics calls with MacSystemFunctions + Arena-allocated structs, IOKitUtil/IORegistryEntry/IOIterator with FFM equivalents, SysctlUtil with SysctlUtilFFM, and all closeable JNA structs with Arena.allocate().

MacGraphicsCardFFM: Mirrors MacGraphicsCard; createStatsSession() returns MacGpuStatsFFM; VRAM resolution uses SysctlUtilFFM.

MacGpuStatsFFM: FFM port of MacGpuStats. All CF/IOKit/SMC calls use FFM equivalents. Wired to IOReportClientFFM for GPU ticks, power, and utilization (with IOAccelerator fallback on the first call before a delta is available).

IOReportFunctions: Bindings for the private libIOReport.dylib, which lives in the macOS dyld shared cache and is resolved by dlopen via System.mapLibraryName("IOReport") — the same mechanism JNA's Native.load("IOReport") uses. Catches IllegalArgumentException for systems where it is absent; all 9 function handles are guarded behind isAvailable().

IOReportClientFFM: Full FFM port of IOReportClient with an identical public API (create(), sampleGpuTicks(), sampleGpuUtilization(), samplePowerWatts(), close()).

Modified classes

MacHardwareAbstractionLayer: Stripped redundant abstract re-declarations of interface methods; now contains only the three concrete Mac-specific implementations (getLogicalVolumeGroups, getSoundCards, getPrinters) that don't use native methods. MacHardwareAbstractionLayerJNA and MacHardwareAbstractionLayerFFM implement the remaining methods directly.

AbstractCentralProcessor: Replaces JNA Platform.isLinux() with SystemInfo.getCurrentPlatform() == PlatformEnum.LINUX, removing the last JNA import from this shared base class.

AbstractPowerSource: Replaces JNA Platform.getOSType() in the default throw with SystemInfo.getCurrentPlatform(), removing the last JNA import from this shared base class.

Future Work

SystemInfo.getCurrentPlatform() itself still uses JNA's Platform class for OS detection. This is a cross-platform concern that will be addressed closer to the point of completely removing JNA dependencies from the java25 module.

UnixPrinter.getPrinters() still uses JNA to optionally load libcups (with an lpstat fallback). This is also cross-platform as it will be used by Linux and will be deferred to the Linux migration series of PRs.

Summary by CodeRabbit

  • New Features

    • Expanded macOS GPU telemetry: utilization %, power (W), active/idle ticks, VRAM usage, and temperature
    • Improved graphics card detection with richer model, vendor, version and VRAM extraction
    • Enhanced macOS CPU detection and frequency reporting with better Apple Silicon support
  • Refactor

    • Migrated macOS hardware implementations to a unified FFM-backed approach
    • Standardized platform detection and HAL wiring for macOS components

@coderabbitai

coderabbitai Bot commented Apr 3, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds macOS FFM native IOReport bindings and a per-instance IOReport subscription client, FFM-backed GPU/CPU hardware implementations and HAL wiring, small platform refactors (sysctl/Platform checks), and supporting native bindings/utilities across macOS-specific packages.

Changes

Cohort / File(s) Summary
IOReport FFM bindings
oshi-core-java25/src/main/java/oshi/ffm/mac/IOReportFunctions.java
New FFM MethodHandle wrappers for private IOReport APIs with runtime availability detection and public wrapper methods for IOReport symbols.
IOReport subscription client
oshi-core-java25/src/main/java/oshi/driver/mac/IOReportClientFFM.java
New final class: factory create(), synchronized sampling methods (sampleGpuTicks, sampleGpuUtilization, samplePowerWatts), CF resource management, and idempotent close().
GPU telemetry & discovery
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java, oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGraphicsCardFFM.java, oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java
New MacGpuStatsFFM using IOReport/IOAccelerator fallbacks; MacGraphicsCardFFM parses system_profiler and creates FFM stats sessions; small parsing reset fix in existing MacGraphicsCard.
CPU FFM implementation & layouts
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacCentralProcessorFFM.java, oshi-core-java25/src/main/java/oshi/ffm/mac/MacSystem.java
New MacCentralProcessorFFM implementing CPU identification/topology/ticks/frequency via FFM; added HOST_CPU_LOAD_INFO_DATA layout and CPU_TICKS path element.
HAL wiring & JNA parity
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerFFM.java, oshi-core/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerJNA.java, oshi-core/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayer.java
FFM HAL now constructs FFM processor and GPU implementations; JNA HAL adds processor/graphics overrides; base Mac HAL had several overrides removed to centralize implementations.
Misc native helpers
oshi-core-java25/src/main/java/oshi/ffm/mac/MacSystemFunctions.java, oshi-core/src/main/java/oshi/jna/platform/mac/SystemB.java
Added FFM and JNA bindings for vm_deallocate to allow explicit native memory release.
Platform refactors & small API tweaks
oshi-core/src/main/java/oshi/hardware/common/AbstractCentralProcessor.java, oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java, CHANGELOG.md
Replaced com.sun.jna.Platform usage with SystemInfo/PlatformEnum checks, adjusted error messages, and consolidated changelog entries.
Other macOS adjustments
oshi-core-java25/src/main/java/oshi/software/os/mac/MacOperatingSystemFFM.java, oshi-core/src/main/java/oshi/hardware/platform/mac/MacCentralProcessor.java
Refactored thread counting to single-buffer iteration; added vm_deallocate cleanup in CPU load parsing with guarded deallocation and logging.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant MacGpuStatsFFM
    participant IOReportClientFFM
    participant IOReportFunctions
    participant IOReport

    Client->>MacGpuStatsFFM: getGpuTicks()/getGpuUtilization()/getPowerDraw()
    activate MacGpuStatsFFM
    MacGpuStatsFFM->>IOReportClientFFM: sampleGpuTicks()/sampleGpuUtilization()/samplePowerWatts()
    activate IOReportClientFFM
    IOReportClientFFM->>IOReportFunctions: IOReportCreateSamples / IOReportCreateSamplesDelta / IOReportSimpleGetIntegerValue
    activate IOReportFunctions
    IOReportFunctions->>IOReport: call native IOReport symbols
    IOReport-->>IOReportFunctions: CF dictionaries/arrays (channels, samples)
    deactivate IOReportFunctions
    IOReportClientFFM->>IOReportClientFFM: parse residency/energy, compute deltas
    IOReportClientFFM-->>MacGpuStatsFFM: ticks/utilization/power
    deactivate IOReportClientFFM
    MacGpuStatsFFM-->>Client: metric values
    deactivate MacGpuStatsFFM
Loading
sequenceDiagram
    participant Client
    participant MacGraphicsCardFFM
    participant SystemProfiler
    participant IORegistry
    participant MacGpuStatsFFM

    Client->>MacGraphicsCardFFM: getGraphicsCards()
    activate MacGraphicsCardFFM
    MacGraphicsCardFFM->>SystemProfiler: exec SPDisplaysDataType
    SystemProfiler-->>MacGraphicsCardFFM: textual GPU info
    MacGraphicsCardFFM->>MacGraphicsCardFFM: parse model/vendor/VRAM/version
    alt VRAM missing on Apple
        MacGraphicsCardFFM->>IORegistry: sysctl hw.memsize
        IORegistry-->>MacGraphicsCardFFM: memsize
    end
    MacGraphicsCardFFM->>MacGpuStatsFFM: createStatsSession(isAppleSilicon, name)
    MacGpuStatsFFM-->>MacGraphicsCardFFM: session
    MacGraphicsCardFFM-->>Client: List<GraphicsCard>
    deactivate MacGraphicsCardFFM
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • mprins

Poem

🐰 I hopped through CF strings and FFM lanes,
Subscribed to IOReport and counted GPU trains,
Ticks and watts in tidy arrays I bring,
A rabbit with MethodHandles—what a thing! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.19% 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 title 'Complete Mac HAL migration: JNA-free inheritance chain' accurately and specifically describes the main objective of this changeset—completing the macOS HAL migration to FFM while removing JNA dependencies from the inheritance chain.

✏️ 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

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 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 68.45%. Comparing base (4d99d58) to head (7092dce).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3111      +/-   ##
==========================================
+ Coverage   67.35%   68.45%   +1.10%     
==========================================
  Files          37       37              
  Lines        1994     1994              
  Branches      323      323              
==========================================
+ Hits         1343     1365      +22     
+ Misses        541      517      -24     
- 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: 1

🧹 Nitpick comments (4)
oshi-core-java25/src/main/java/oshi/ffm/mac/IOReportFunctions.java (1)

53-58: Javadoc/implementation mismatch: NPE instead of UnsupportedOperationException.

The class Javadoc (lines 22-23) states that methods throw UnsupportedOperationException if the library is absent, but the implementation returns null from require() when unavailable. This causes a NullPointerException on invokeExact(), not UnsupportedOperationException.

Either update the Javadoc to clarify that callers must check isAvailable() first, or add a defensive check:

Option 1: Update Javadoc (recommended, minimal change)
  * <p>
- * IOReport is a private Apple framework. It may not be present on all systems. {`@link` `#isAvailable`()} must be checked
- * before calling any method; all methods throw {`@link` UnsupportedOperationException} if the library is absent.
+ * IOReport is a private Apple framework. It may not be present on all systems. Callers <b>must</b> check
+ * {`@link` `#isAvailable`()} before invoking any method; behavior is undefined (typically {`@code` NullPointerException})
+ * if methods are called when the library is unavailable.
Option 2: Add defensive check in require()
     private static MethodHandle require(String symbol, FunctionDescriptor fd) {
         if (!AVAILABLE) {
-            return null;
+            throw new UnsupportedOperationException("IOReport library is not available");
         }
         return LINKER.downcallHandle(IO_REPORT_LIBRARY.findOrThrow(symbol), fd);
     }

Then each wrapper method would throw at static init time if unavailable—though this changes error timing.

🤖 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/ffm/mac/IOReportFunctions.java` around
lines 53 - 58, The require(...) method currently returns null when AVAILABLE is
false which leads to NullPointerException on subsequent invokeExact() calls
rather than the Javadoc-stated UnsupportedOperationException; either update the
class Javadoc to state callers must check isAvailable() before calling wrapper
methods (reference isAvailable(), require(String, FunctionDescriptor),
AVAILABLE) or change require(...) to throw new
UnsupportedOperationException("IOReport library not available") when !AVAILABLE
so LINKER.downcallHandle(...) is never called and wrapper initialization fails
with the documented exception (references: require, LINKER.downcallHandle,
IO_REPORT_LIBRARY.findOrThrow).
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java (1)

292-303: Consider pre-compiling the pattern for name matching.

Pattern.compile() is called on each invocation of matchesName(), which is called per IOAccelerator service. While the impact is minimal (typically few GPU services), pre-compiling would be cleaner:

Suggested refactor
 private boolean matchesName(String model) {
     if (model == null || model.isEmpty()) {
         return false;
     }
     String normModel = TRADEMARK_PATTERN.matcher(model.toLowerCase(Locale.ROOT)).replaceAll("").trim();
     String normName = TRADEMARK_PATTERN.matcher(cardName.toLowerCase(Locale.ROOT)).replaceAll("").trim();
     if (normModel.equals(normName)) {
         return true;
     }
-    Matcher m = Pattern.compile("\\b" + Pattern.quote(normName) + "\\b").matcher(normModel);
-    return m.find();
+    // Word-boundary match as fallback
+    return normModel.contains(normName);
 }

Or cache the compiled pattern if the word-boundary semantics are important.

🤖 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/MacGpuStatsFFM.java`
around lines 292 - 303, matchesName currently compiles Pattern.compile("\\b" +
Pattern.quote(normName) + "\\b") on every call; instead precompile and reuse a
Pattern for the card name to avoid repeated compilation: when the GPU cardName
is initialized/normalized (the same place that computes normName), create and
store a field like nameWordPattern = Pattern.compile("\\b" +
Pattern.quote(normName) + "\\b") and then have matchesName use that precompiled
nameWordPattern (alongside the existing TRADEMARK_PATTERN processing of the
input model) rather than calling Pattern.compile each invocation.
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacCentralProcessorFFM.java (2)

193-200: Minor: Prefer Stream.of() over Arrays.asList().stream().

For creating a stream from inline elements, Stream.of(...) is more direct.

♻️ Suggested simplification
 private List<String> getFeatureFlagsFromSysctl() {
-    List<String> x86Features = Arrays.asList("features", "extfeatures", "leaf7_features").stream().map(f -> {
+    List<String> x86Features = Stream.of("features", "extfeatures", "leaf7_features").map(f -> {
         String key = "machdep.cpu." + f;
         String features = SysctlUtilFFM.sysctl(key, "", false);
         return Util.isBlank(features) ? null : (key + ": " + features);
     }).filter(Objects::nonNull).collect(Collectors.toList());
     return x86Features.isEmpty() ? ExecutingCommand.runNative("sysctl -a hw.optional") : x86Features;
 }
🤖 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/MacCentralProcessorFFM.java`
around lines 193 - 200, The stream creation in getFeatureFlagsFromSysctl() uses
Arrays.asList(...).stream() unnecessarily; replace Arrays.asList("features",
"extfeatures", "leaf7_features").stream() with Stream.of("features",
"extfeatures", "leaf7_features") so the same mapping/filtering logic (the lambda
that builds key = "machdep.cpu."+f and calls SysctlUtilFFM.sysctl, the
Util.isBlank check, and collection into x86Features) remains unchanged, and then
keep the existing fallback to ExecutingCommand.runNative("sysctl -a
hw.optional") when x86Features is empty.

234-240: Consider using Collectors.toMap instead of forEach with side effects.

The current implementation uses forEach to populate a map, which is a side-effecting operation. Using Collectors.toMap would be more idiomatic.

♻️ More idiomatic stream usage
     if (isArmCpu) {
-        Map<Integer, Long> physFreqMap = new HashMap<>();
-        getPhysicalProcessors().stream().forEach(p -> physFreqMap.put(p.getPhysicalProcessorNumber(),
-                p.getEfficiency() > 0 ? performanceCoreFrequency : efficiencyCoreFrequency));
+        Map<Integer, Long> physFreqMap = getPhysicalProcessors().stream()
+                .collect(Collectors.toMap(
+                        PhysicalProcessor::getPhysicalProcessorNumber,
+                        p -> p.getEfficiency() > 0 ? performanceCoreFrequency : efficiencyCoreFrequency));
         return getLogicalProcessors().stream().map(LogicalProcessor::getPhysicalProcessorNumber)
                 .map(p -> physFreqMap.getOrDefault(p, performanceCoreFrequency)).mapToLong(f -> f).toArray();
     }
🤖 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/MacCentralProcessorFFM.java`
around lines 234 - 240, The code in queryCurrentFreq() builds physFreqMap via
getPhysicalProcessors().stream().forEach(...) causing side effects; replace that
with a pure collector using Collectors.toMap to build the Map in one expression
(e.g., collect(Collectors.toMap(p -> p.getPhysicalProcessorNumber(), p ->
p.getEfficiency() > 0 ? performanceCoreFrequency : efficiencyCoreFrequency))).
Ensure you keep the same fallback behavior when later mapping logical processors
(getLogicalProcessors().stream()...physFreqMap.getOrDefault(...,
performanceCoreFrequency)) and import Collectors if needed.
🤖 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/MacCentralProcessorFFM.java`:
- Around line 293-303: The loop in MacCentralProcessorFFM that iterates
procCount and writes into ticks[cpu] can overflow if host_processor_info returns
more CPUs than ticks (logical processors); modify the code in the method that
fills ticks to cap the iteration count to Math.min(procCount, ticks.length) (or
getLogicalProcessorCount()) before the for-loop, so you only access valid
indexes of ticks, and log or otherwise handle the case where procCount >
ticks.length to surface the mismatch instead of silently throwing/catching an
exception.

---

Nitpick comments:
In `@oshi-core-java25/src/main/java/oshi/ffm/mac/IOReportFunctions.java`:
- Around line 53-58: The require(...) method currently returns null when
AVAILABLE is false which leads to NullPointerException on subsequent
invokeExact() calls rather than the Javadoc-stated
UnsupportedOperationException; either update the class Javadoc to state callers
must check isAvailable() before calling wrapper methods (reference
isAvailable(), require(String, FunctionDescriptor), AVAILABLE) or change
require(...) to throw new UnsupportedOperationException("IOReport library not
available") when !AVAILABLE so LINKER.downcallHandle(...) is never called and
wrapper initialization fails with the documented exception (references: require,
LINKER.downcallHandle, IO_REPORT_LIBRARY.findOrThrow).

In
`@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacCentralProcessorFFM.java`:
- Around line 193-200: The stream creation in getFeatureFlagsFromSysctl() uses
Arrays.asList(...).stream() unnecessarily; replace Arrays.asList("features",
"extfeatures", "leaf7_features").stream() with Stream.of("features",
"extfeatures", "leaf7_features") so the same mapping/filtering logic (the lambda
that builds key = "machdep.cpu."+f and calls SysctlUtilFFM.sysctl, the
Util.isBlank check, and collection into x86Features) remains unchanged, and then
keep the existing fallback to ExecutingCommand.runNative("sysctl -a
hw.optional") when x86Features is empty.
- Around line 234-240: The code in queryCurrentFreq() builds physFreqMap via
getPhysicalProcessors().stream().forEach(...) causing side effects; replace that
with a pure collector using Collectors.toMap to build the Map in one expression
(e.g., collect(Collectors.toMap(p -> p.getPhysicalProcessorNumber(), p ->
p.getEfficiency() > 0 ? performanceCoreFrequency : efficiencyCoreFrequency))).
Ensure you keep the same fallback behavior when later mapping logical processors
(getLogicalProcessors().stream()...physFreqMap.getOrDefault(...,
performanceCoreFrequency)) and import Collectors if needed.

In
`@oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java`:
- Around line 292-303: matchesName currently compiles Pattern.compile("\\b" +
Pattern.quote(normName) + "\\b") on every call; instead precompile and reuse a
Pattern for the card name to avoid repeated compilation: when the GPU cardName
is initialized/normalized (the same place that computes normName), create and
store a field like nameWordPattern = Pattern.compile("\\b" +
Pattern.quote(normName) + "\\b") and then have matchesName use that precompiled
nameWordPattern (alongside the existing TRADEMARK_PATTERN processing of the
input model) rather than calling Pattern.compile each invocation.
🪄 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: 854995fd-285d-43d3-8c04-18effd1037a5

📥 Commits

Reviewing files that changed from the base of the PR and between 4d99d58 and 52d0a10.

📒 Files selected for processing (11)
  • oshi-core-java25/src/main/java/oshi/driver/mac/IOReportClientFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/mac/IOReportFunctions.java
  • oshi-core-java25/src/main/java/oshi/ffm/mac/MacSystem.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacCentralProcessorFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGraphicsCardFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerFFM.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractCentralProcessor.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.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). (8)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (4)
📚 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/hardware/common/AbstractPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractCentralProcessor.java
  • oshi-core-java25/src/main/java/oshi/ffm/mac/IOReportFunctions.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacCentralProcessorFFM.java
📚 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/MacHardwareAbstractionLayerFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGraphicsCardFFM.java
  • oshi-core-java25/src/main/java/oshi/driver/mac/IOReportClientFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacCentralProcessorFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.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/IOReportFunctions.java
📚 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-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java` (and similar FFM/API implementations in OSHI), the `updateAttributes()` method intentionally uses `catch (Throwable e) { return false; }` without logging. This is by design: `updateAttributes()` is a public API method whose contract is to return `false` on failure; callers consume the boolean and would never see log output, so adding a log statement is not desired.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/ffm/mac/IOReportFunctions.java
🔇 Additional comments (25)
oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java (1)

232-233: LGTM!

The change correctly replaces JNA's Platform.getOSType() with OSHI's own SystemInfo.getCurrentPlatform() for the error message, aligning with the PR objective to remove JNA dependencies from the Mac hardware path.

oshi-core/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerJNA.java (2)

32-35: LGTM!

The createProcessor() override correctly returns a JNA-based MacCentralProcessor instance, maintaining the existing behavior while enabling the parallel FFM implementation in MacHardwareAbstractionLayerFFM.


72-75: LGTM!

The getGraphicsCards() override correctly delegates to the JNA-based MacGraphicsCard.getGraphicsCards(), consistent with the inheritance refactoring pattern.

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

409-413: LGTM!

The HOST_CPU_LOAD_INFO_DATA struct layout correctly models the macOS host_cpu_load_info structure with a cpu_ticks array of CPU_STATE_MAX (4) integers. The definition is consistent with macOS headers and the naming follows the established pattern in this file.

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

62-68: LGTM on the FFM bindings structure.

The MethodHandle creation pattern with require() and the wrapper method signatures are consistent and correct. The throws Throwable declaration is necessary due to MethodHandle.invokeExact() semantics. Based on learnings, these are native calls that don't throw Java checked exceptions in practice.

oshi-core-java25/src/main/java/oshi/driver/mac/IOReportClientFFM.java (3)

58-103: LGTM on IOReportClientFFM.create() implementation.

The factory method correctly:

  • Guards with isAvailable() check
  • Creates CF strings and releases them in finally
  • Handles subscription creation failures
  • Releases intermediate gpuChannels/energyChannels on all paths

The catch (Throwable) returning null is consistent with the established OSHI pattern for FFM/API methods.


141-182: LGTM on delta-based utilization sampling.

The implementation correctly:

  • Stores the first sample as baseline (returning -1d on first call)
  • Computes delta between consecutive samples
  • Releases the old prevSampleUtil before reassigning
  • Handles the off state subtraction for utilization calculation

241-256: LGTM on idempotent close().

The synchronized close() correctly releases all held CF references (prevSampleUtil, prevSamplePower, subscribedChannels, subscription) and is idempotent via the closed flag check.

oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java (2)

62-66: LGTM on constructor and IOReport client initialization.

The constructor correctly initializes the IOReportClientFFM which may be null if IOReport is unavailable. All sampling methods properly handle this null case with fallbacks or sentinel values.


241-290: LGTM on IORegistry traversal for performance statistics.

The queryPerfStats() method correctly:

  • Uses try-finally for CF object cleanup (iter, perfStatsKey, modelKey, props, service)
  • Calls CFRetain on the stats segment before returning it (ensuring the reference survives props.release())
  • Returns early when a matching service is found, properly releasing the iterator
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGraphicsCardFFM.java (2)

37-75: LGTM on graphics card discovery via system_profiler.

The parsing logic correctly handles:

  • Multiple GPU cards in the output
  • Accumulating version/revision info into a list
  • Flushing the previous card when a new "chipset model" line is encountered
  • Processing the final card after the loop

77-85: LGTM on VRAM resolution with Apple Silicon fallback.

For Apple Silicon GPUs where discrete VRAM isn't reported, falling back to hw.memsize (total system memory) is a reasonable approximation since the GPU shares unified memory. This aligns with how Apple Silicon handles GPU memory allocation.

oshi-core/src/main/java/oshi/hardware/common/AbstractCentralProcessor.java (1)

304-306: Behavior change: Auxv.queryAuxv() now skipped on Android in processor ID calculation.

The change from Platform.isLinux() (which returns true for both Linux and Android) to SystemInfo.getCurrentPlatform() == PlatformEnum.LINUX means hwcap will no longer be queried on Android devices for processor ID calculation, defaulting to 0L.

This is a deliberate change—grayscale handling exists elsewhere (readAllBytes returns empty array if /proc/self/auxv is unreadable). However, note that LinuxOperatingSystem.java (lines 131, 138) calls Auxv.queryAuxv() unconditionally in its static initializer, which still executes on Android. Clarify whether Android should skip Auxv entirely or if this change is platform-specific to AbstractCentralProcessor only.

oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacCentralProcessorFFM.java (10)

1-47: LGTM - Well-organized imports and licensing.

The file structure follows OSHI conventions with appropriate FFM imports, logging, and utility classes. The static imports for FFM functions are clean.


67-73: Thread-safety note: frequency fields are effectively immutable after construction.

The performanceCoreFrequency and efficiencyCoreFrequency fields are non-volatile but only written during construction (via calculateNominalFrequencies() called from queryProcessorId()). Since the class is @ThreadSafe, this works correctly due to safe publication guarantees of final fields and constructor completion before external access.


75-136: LGTM - CPU identification logic is well-structured.

The method properly handles both Apple Silicon and Intel architectures with appropriate sysctl queries and fallback defaults.


138-165: LGTM - Processor count initialization follows expected patterns.

The logical-to-physical processor mapping and efficiency core detection for ARM chips are well-implemented.


202-231: LGTM - FFM-based CPU tick collection is well-implemented.

The Arena usage with try-with-resources ensures proper resource cleanup, error handling follows OSHI patterns, and unsigned integer conversion is correctly applied.


253-273: LGTM - Load average implementation is correct.

The bounds checking, memory allocation, and fallback to -1 on failure follow expected conventions.


326-340: LGTM - Platform expert query with proper resource cleanup.

The IORegistryEntry is properly released in the finally block, and there's a sensible default fallback.


342-379: LGTM - IOKit iteration with proper resource management.

The iteration pattern correctly releases each IORegistryEntry after processing, with a finally block to handle the iterator cleanup.


387-413: LGTM - ARM frequency calculation with correct resource cleanup.

The nested try-finally pattern properly handles all exit paths: normal iteration, early return when "pmgr" is found, and exception cases.


415-422: LGTM - Frequency extraction from byte array.

The slicing logic correctly extracts 4 bytes from the specified offset position.

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

23-26: LGTM - Processor creation wired to FFM implementation.

The override correctly delegates to the new MacCentralProcessorFFM class.


68-71: LGTM - Graphics card delegation wired to FFM implementation.

The override correctly delegates to MacGraphicsCardFFM.getGraphicsCards().

@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-java25/src/main/java/oshi/hardware/platform/mac/MacGraphicsCardFFM.java`:
- Around line 37-75: In getGraphicsCards(), state variables deviceId, vendor,
vram and versionInfoList are not fully reset between cards causing data leakage;
when you detect a new "chipset model" (in the loop handling split[0] == "chipset
model") and after adding the previous MacGraphicsCardFFM to cardList, reset
deviceId = Constants.UNKNOWN, vendor = Constants.UNKNOWN, vram = 0 and clear
versionInfoList (and ensure you also reset these before adding the final card
after the loop) so each new MacGraphicsCardFFM is constructed only from fields
found for that card.
🪄 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: 2de8098c-2c06-46d4-8382-4becab6da560

📥 Commits

Reviewing files that changed from the base of the PR and between 52d0a10 and 6b4267a.

📒 Files selected for processing (12)
  • CHANGELOG.md
  • oshi-core-java25/src/main/java/oshi/driver/mac/IOReportClientFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/mac/IOReportFunctions.java
  • oshi-core-java25/src/main/java/oshi/ffm/mac/MacSystem.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacCentralProcessorFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGraphicsCardFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerFFM.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractCentralProcessor.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.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
✅ Files skipped from review due to trivial changes (2)
  • oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java
  • CHANGELOG.md
🚧 Files skipped from review as they are similar to previous changes (4)
  • oshi-core/src/main/java/oshi/hardware/common/AbstractCentralProcessor.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerJNA.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/mac/IOReportFunctions.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 25, windows-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, 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/MacGraphicsCardFFM.java
  • oshi-core-java25/src/main/java/oshi/driver/mac/IOReportClientFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacCentralProcessorFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java
🔇 Additional comments (28)
oshi-core-java25/src/main/java/oshi/ffm/mac/MacSystem.java (1)

409-413: LGTM!

The HOST_CPU_LOAD_INFO_DATA struct layout correctly models the macOS host_cpu_load_info_data_t structure, with cpu_ticks as a sequence of CPU_STATE_MAX (4) integers. The CPU_TICKS path element properly enables field access for the FFM CPU implementation.

oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacCentralProcessorFFM.java (7)

202-231: Correct tick index mapping between native and API layouts.

The implementation properly uses MacSystem.CPU_STATE_* constants to index into the native cpu_ticks array and TickType.*.getIndex() to write to the output array. This correctly decouples the macOS native layout (USER=0, SYSTEM=1, IDLE=2, NICE=3) from the API contract (USER=0, NICE=1, SYSTEM=2, IDLE=3).

Memory management with Arena.ofConfined() in try-with-resources ensures proper cleanup.


293-308: Bounds checking properly implemented.

The defensive bound check using Math.min(procCount, ticks.length) prevents potential ArrayIndexOutOfBoundsException if host_processor_info returns more processors than expected. The warning log at lines 294-295 helps diagnose any mismatch.


253-273: LGTM!

Proper handling of getloadavg return value: if fewer samples are retrieved than requested, the entire array is correctly filled with -1d to signal failure. The validation of nelem bounds and error handling are appropriate.


392-427: Resource management in IORegistry iteration is correct.

The nested try-finally blocks properly handle all exit paths:

  • Early return when "pmgr" is found: inner finally releases the current device
  • Normal loop completion: devices are released iteratively within the loop
  • Outer finally always releases the iterator

151-161: Efficiency core detection relies on compatible-string mapping.

The mapping between pkgCoreKeys (used as lookup key) and compatibleStrMap (keyed by CPU index from "cpuN") works correctly for single-package Macs where pkgId=0 and coreId equals the CPU index. The comment at lines 155-158 acknowledges this as "brittle" and suggests using hw.perflevelN.physicalcpu sysctls as a more robust alternative.

For current Mac hardware (single-package M-series), this approach is correct.


315-329: LGTM!

The queryContextSwitches() and queryInterrupts() methods correctly return 0L with appropriate documentation explaining that this information is not available on macOS since 10.3.9.


331-345: LGTM!

The platformExpert() method correctly retrieves the manufacturer from the IORegistry with proper resource cleanup in the finally block, defaulting to "Apple Inc." when unavailable.

oshi-core-java25/src/main/java/oshi/driver/mac/IOReportClientFFM.java (9)

1-51: LGTM! Clean class structure with proper encapsulation.

The class design follows good practices:

  • final class with private constructor enforces factory pattern
  • Fields for subscription management are properly encapsulated
  • Constants are well-named and document the IOReport channel/group names

58-103: LGTM! Robust factory method with proper resource cleanup.

The create() method correctly:

  • Guards against unavailable IOReport
  • Uses try-finally to ensure CFStringRef and channel segments are released
  • Returns null on any failure path (consistent with OSHI's failure-handling pattern)
  • Properly manages the Arena lifecycle for the subscription output parameter

110-134: LGTM! Correct tick calculation and resource management.

The method correctly:

  • Computes active ticks as total - idle matching the GpuTicks(activeTicks, idleTicks) constructor signature
  • Releases the sample in the finally block
  • Returns sentinel (0L, 0L) on all error paths per the interface contract

141-182: LGTM! Proper delta-based utilization calculation with careful resource handling.

The implementation correctly:

  • Primes on first call by storing the baseline sample and returning -1d
  • Computes delta between previous and current samples
  • Transfers ownership of the current sample to prevSampleUtil before nullifying the local reference
  • Uses defensive null checks in the finally block to prevent double-release

189-236: LGTM! Correct power calculation and resource management.

The power calculation is correct:

  • Energy in microjoules (µJ = 10⁻⁶ J), time in nanoseconds (ns = 10⁻⁹ s)
  • energyUj * 1000.0 / dtNanos = µJ × 10³ / ns = 10⁻⁶ × 10³ / 10⁻⁹ = Watts ✓

Resource handling follows the same careful pattern as sampleGpuUtilization().


241-256: LGTM! Idempotent close with complete resource cleanup.

The close() method properly:

  • Guards against multiple invocations with the closed flag
  • Nullifies fields after release to prevent use-after-free
  • Releases all retained CoreFoundation references

258-288: LGTM! Clean extraction logic with proper resource management.

The helper correctly iterates the IOReport channels array, filters by group and channel name, and extracts the energy value. The CFStringRef for the key is properly released in the finally block.


290-332: LGTM! Robust state extraction with proper aggregation.

The method correctly:

  • Filters channels by group and optional subgroup
  • Iterates all performance states within matching channels
  • Uses merge(stateName, ticks, Long::sum) to properly aggregate ticks across multiple channels/GPUs with the same state name

334-342: LGTM! Defensive cleanup helper.

The cfRelease() wrapper provides safe cleanup with:

  • Null and MemorySegment.NULL guards
  • Exception swallowing in cleanup path (consistent with OSHI's FFM pattern for cleanup code)
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java (9)

1-69: LGTM! Well-structured class with proper initialization.

Good design choices:

  • @ThreadSafe annotation with synchronized methods
  • Pattern.quote() prevents regex injection from card names
  • Graceful handling of IOReportClientFFM.create() returning null
  • Trademark stripping enables fuzzy matching between IORegistry and system_profiler names

71-82: LGTM! Correct lifecycle management.

The close() method safely closes the IOReport client (null-checked), and isClosed() provides the required status check. The pattern follows the GpuStats interface contract.


84-91: LGTM! Correct delegation with fallback.

Properly delegates to IOReportClientFFM when available and returns the sentinel GpuTicks(0L, 0L) otherwise.


93-129: LGTM! Proper fallback chain with correct scaling.

The utilization fallback correctly:

  • Tries IOReportClient first (returns immediately on success)
  • Falls back to IOAccelerator PerformanceStatistics dictionary
  • Applies proper scaling (0xFFFFFFFFL) for the fixed-point GPU Core Utilization value
  • Returns Device Utilization % as-is since it's already a percentage

131-163: LGTM! Platform-aware VRAM lookup with proper fallback.

Correctly handles the different IOAccelerator key names between Apple Silicon and Intel Macs, with a fallback to the alternative key if the primary is unavailable.


171-208: LGTM! Robust temperature lookup with SMC priority on Apple Silicon.

The implementation correctly:

  • Opens/closes SMC connection in try-finally
  • Returns SMC temperature only if positive (valid reading)
  • Falls back to IOAccelerator dictionary for Intel or when SMC fails

210-235: LGTM! Correct sentinel returns for unsupported metrics.

Methods for unavailable metrics correctly return -1L or -1d per the GpuStats interface contract. getPowerDraw() properly delegates to IOReportClient when available.


244-293: LGTM! Careful resource management with correct ownership transfer.

The queryPerfStats() method demonstrates proper CoreFoundation memory management:

  • CFRetain() on the stats segment before returning is crucial—the stats dictionary is owned by the parent props dictionary which gets released
  • All resources (iterator, keys, service, props) are properly released in nested try-finally blocks
  • Early return with retained reference maintains ownership correctly

295-304: LGTM! Flexible name matching with trademark normalization.

The matching logic correctly handles variations between system_profiler and IOAccelerator naming, using both exact match and word-boundary search as fallback.

oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGraphicsCardFFM.java (2)

1-35: LGTM! Clean extension with proper factory method override.

The class correctly:

  • Detects Apple Silicon via os.arch property
  • Overrides createStatsSession() to provide the FFM-based implementation
  • Passes the architecture flag to MacGpuStatsFFM for platform-specific behavior

77-85: LGTM! Sensible VRAM fallback for Apple Silicon.

The resolveVram() helper correctly returns hw.memsize (total system memory) for Apple Silicon GPUs that use unified memory, while preserving the parsed value for discrete GPUs.

@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-java25/src/main/java/oshi/hardware/platform/mac/MacCentralProcessorFFM.java`:
- Around line 291-313: Add an FFM binding for vm_deallocate to
MacSystemFunctions.java (e.g., long vm_deallocate(int target_task, long address,
long size) or matching FFM types) and then free the buffer returned by
host_processor_info in MacCentralProcessorFFM: after populating ticks (or in a
finally block) call vm_deallocate(mach_task_self(), procInfoPtr.address(),
(long) procInfoCount * MacSystem.INT_SIZE) using the existing mach_task_self()
method; handle/ignore any exception from vm_deallocate so it cannot mask the
main logic.
🪄 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: feb9f1af-bb4c-423a-a6ce-9fe3f055a8ff

📥 Commits

Reviewing files that changed from the base of the PR and between 6b4267a and 1600204.

📒 Files selected for processing (13)
  • CHANGELOG.md
  • oshi-core-java25/src/main/java/oshi/driver/mac/IOReportClientFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/mac/IOReportFunctions.java
  • oshi-core-java25/src/main/java/oshi/ffm/mac/MacSystem.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacCentralProcessorFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGraphicsCardFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerFFM.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractCentralProcessor.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.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
✅ Files skipped from review due to trivial changes (2)
  • CHANGELOG.md
  • oshi-core-java25/src/main/java/oshi/ffm/mac/MacSystem.java
🚧 Files skipped from review as they are similar to previous changes (4)
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerJNA.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/mac/IOReportFunctions.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 11, 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/src/main/java/oshi/hardware/common/AbstractCentralProcessor.java
📚 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/MacGraphicsCardFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacCentralProcessorFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java
  • oshi-core-java25/src/main/java/oshi/driver/mac/IOReportClientFFM.java
🔇 Additional comments (19)
oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java (1)

69-72: LGTM! State variables are now properly reset between cards.

This correctly prevents data leakage when parsing multiple graphics cards from system_profiler output. If a subsequent card's output omits a field, it will now get Constants.UNKNOWN / 0 rather than inheriting stale values from the previous card.

oshi-core-java25/src/main/java/oshi/driver/mac/IOReportClientFFM.java (7)

58-103: LGTM! Well-structured factory with proper resource management.

The create() method correctly:

  • Guards on IOReportFunctions.isAvailable() before attempting FFM calls
  • Releases intermediate CoreFoundation references (gpuGroup, energyGroup, gpuChannels, energyChannels) in the finally block
  • Returns null on any failure path, allowing callers to gracefully fall back

110-134: LGTM! Correct implementation of GPU ticks sampling.

The method properly:

  • Returns the sentinel (0, 0) when closed or on failure (per GpuStats contract)
  • Uses MemorySegment.NULL equality checks consistent with FFM conventions
  • Releases the sample in the finally block to prevent CF object leaks

141-182: LGTM! Delta-based utilization with correct priming behavior.

The method correctly implements the delta-based utilization pattern documented in GpuStats.getGpuUtilization():

  • First call stores baseline and returns -1 (priming)
  • Subsequent calls compute delta, release old sample, and return utilization percentage
  • The sample = MemorySegment.NULL assignment after transferring ownership prevents double-release

189-236: LGTM! Power calculation with correct unit conversion.

The formula energyUj * 1000.0 / dtNanos correctly converts:

  • Energy from microjoules (µJ = 10⁻⁶ J)
  • Time from nanoseconds (ns = 10⁻⁹ s)
  • To power in watts: (µJ × 10⁻⁶) / (ns × 10⁻⁹) = µJ × 10³ / ns

The dtNanos <= 0 guard handles clock edge cases appropriately.


241-256: LGTM! Idempotent close with complete resource cleanup.

All retained CoreFoundation references are properly released: cached samples, subscribed channels, and the subscription itself.


258-332: LGTM! Helper methods correctly handle CoreFoundation dictionary traversal.

The methods properly:

  • Create and release CFStringRef keys in finally blocks
  • Check for MemorySegment.NULL before dereferencing
  • Use merge(Long::sum) to aggregate residency ticks across multiple channels (correct for multi-GPU scenarios)

334-342: LGTM! Defensive cfRelease helper.

The null and MemorySegment.NULL guards combined with swallowed exceptions ensure cleanup code doesn't throw, consistent with OSHI's FFM failure-handling patterns.

oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java (7)

63-69: LGTM! Constructor with safe initialization.

The IOReportClientFFM.create() can return null if IOReport is unavailable, and all telemetry methods properly handle this by checking ioReportClient != null before use. The pattern compilation with Pattern.quote() correctly escapes special characters in card names.


71-91: LGTM! Thread-safe lifecycle management and ticks sampling.

The close() method properly forwards to IOReportClientFFM.close(), and getGpuTicks() correctly returns the (0, 0) sentinel when the IOReport client is unavailable.


93-129: LGTM! Utilization with IOReport-first fallback to IOAccelerator.

The method correctly:

  • Prefers IOReportClientFFM.sampleGpuUtilization() when available and primed (≥ 0)
  • Falls back to IOAccelerator PerformanceStatistics with two key attempts
  • Properly scales "GPU Core Utilization" (0–0xFFFFFFFF range) to percentage

131-163: LGTM! Architecture-aware VRAM key selection.

The primary/fallback key swapping based on isAppleSilicon ensures compatibility across both Apple Silicon and Intel Macs where IOAccelerator may report VRAM under different keys.


171-217: LGTM! Temperature with SMC-first fallback and power delegation.

Temperature correctly prioritizes SMC (more accurate on Apple Silicon) before falling back to IOAccelerator. Power draw properly delegates to IOReportClientFFM when available. Both return the -1 sentinel when metrics are unavailable.


244-293: LGTM! IOAccelerator service enumeration with proper retain/release.

The CFRetain(statsSeg) before returning is essential since the parent props dictionary is released in the finally block, which would otherwise invalidate the nested PerformanceStatistics reference. The iteration correctly releases each service and the iterator.


295-304: LGTM! Flexible card name matching.

The method correctly handles both exact matches and partial matches (e.g., matching "Apple M1" within "Apple M1 Pro GPU"), with trademark symbol normalization for consistency.

oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGraphicsCardFFM.java (2)

37-78: LGTM! Past review issue addressed.

The state reset (lines 55-58) correctly clears deviceId, vendor, and vram when starting a new card, preventing data leakage between parsed cards. This matches the fix now applied to MacGraphicsCard.java as well.


80-88: LGTM! FFM-based VRAM resolution.

Uses SysctlUtilFFM.sysctl() instead of the JNA-based SysctlUtil, correctly completing the FFM migration for this code path.

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

293-299: Good defensive bound handling for CPU tick parsing.

Line 293-299’s mismatch warning plus Math.min(procCount, ticks.length) cap is the right guard against out-of-bounds writes.

oshi-core/src/main/java/oshi/hardware/common/AbstractCentralProcessor.java (1)

304-305: No action required for platform-gating change. JNA's Platform.isLinux() returns false for Android (which has its own distinct OSType), so switching to PlatformEnum.LINUX does not introduce behavior drift compared to the prior implementation.

			> Likely an incorrect or invalid review comment.

JNA-free base classes

MacHWDiskStoreFFM:
- Add isNull() guard for DADiskRef.createFromIOMedia result, mirroring
the
  existing guard for createFromBSDName

MacCentralProcessorFFM (new):
- Replace SystemB.host_statistics with MacSystemFunctions +
Arena-allocated
  HOST_CPU_LOAD_INFO_DATA struct (added to MacSystem)
- Replace SystemB.host_processor_info with MacSystemFunctions + ADDRESS
  out-param and reinterpret for flat int array
- Replace SystemB.getloadavg with MacSystemFunctions + double[] segment
- Replace IOKitUtil/IORegistryEntry/IOIterator with FFM equivalents
- Replace SysctlUtil with SysctlUtilFFM
- Replace Closeable JNA structs with Arena.allocate()

MacGpuStatsFFM (new):
- Replace IOKitUtil/CF types/Pointer with FFM equivalents
- Replace SmcUtil with SmcUtilFFM
- Wire IOReportClientFFM into getGpuTicks(), getPowerDraw(), and
  getGpuUtilization() (with IOAccelerator fallback on first call)

MacGraphicsCardFFM (new):
- Identical logic to MacGraphicsCard; createStatsSession() returns
  MacGpuStatsFFM; resolveVram uses SysctlUtilFFM

IOReportFunctions (new):
- Optional load via System.mapLibraryName("IOReport"), which resolves
from
  the dyld shared cache on macOS via dlopen, mirroring JNA's
Native.load();
  catches IllegalArgumentException for systems where it is absent

IOReportClientFFM (new):
- Full FFM port of IOReportClient with identical public API
  (create/sampleGpuTicks/sampleGpuUtilization/samplePowerWatts/close)

MacHardwareAbstractionLayer:
- createProcessor() and getGraphicsCards() made abstract

MacHardwareAbstractionLayerJNA:
- Implement createProcessor() -> MacCentralProcessor
- Implement getGraphicsCards() -> MacGraphicsCard.getGraphicsCards()

MacHardwareAbstractionLayerFFM:
- Implement createProcessor() -> MacCentralProcessorFFM
- Implement getGraphicsCards() -> MacGraphicsCardFFM.getGraphicsCards()

AbstractCentralProcessor:
- Replace JNA Platform.isLinux() with SystemInfo.getCurrentPlatform() ==
PlatformEnum.LINUX

AbstractPowerSource:
- Replace JNA Platform.getOSType() with SystemInfo.getCurrentPlatform()

With these changes, initializing SystemInfoFFM and calling all getters
recursively will not classload any com.sun.jna or oshi.jna classes from
the Mac hardware path. The remaining SystemInfo platform detection
dependency on JNA is a known future task.

@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-java25/src/main/java/oshi/software/os/mac/MacOperatingSystemFFM.java`:
- Line 162: In MacOperatingSystemFFM update the LOG.warn call that currently
passes e.getMessage() directly so it uses SLF4J parameterization and preserves
the stack trace; replace the non-parameterized call on the LOG.warn for "Failed
to query thread count" with a parameterized message that includes a {}
placeholder for the exception message and pass the exception object e as the
final argument so the logger records both the formatted message and the
exception context.
🪄 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: 7923d066-3662-4af4-9643-318eaf298915

📥 Commits

Reviewing files that changed from the base of the PR and between 1600204 and 7092dce.

📒 Files selected for processing (17)
  • CHANGELOG.md
  • oshi-core-java25/src/main/java/oshi/driver/mac/IOReportClientFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/mac/IOReportFunctions.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/MacCentralProcessorFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGraphicsCardFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerFFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/mac/MacOperatingSystemFFM.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractCentralProcessor.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacCentralProcessor.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayer.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerJNA.java
  • oshi-core/src/main/java/oshi/jna/platform/mac/SystemB.java
💤 Files with no reviewable changes (1)
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayer.java
✅ Files skipped from review due to trivial changes (2)
  • CHANGELOG.md
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacCentralProcessorFFM.java
🚧 Files skipped from review as they are similar to previous changes (2)
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacHardwareAbstractionLayerJNA.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractCentralProcessor.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, windows-latest
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 11, macos-latest
🧰 Additional context used
🧠 Learnings (4)
📚 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/hardware/common/AbstractPowerSource.java
  • oshi-core/src/main/java/oshi/jna/platform/mac/SystemB.java
  • oshi-core-java25/src/main/java/oshi/ffm/mac/MacSystem.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacCentralProcessor.java
  • oshi-core-java25/src/main/java/oshi/ffm/mac/IOReportFunctions.java
📚 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/MacHardwareAbstractionLayerFFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/mac/MacOperatingSystemFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGraphicsCardFFM.java
  • oshi-core-java25/src/main/java/oshi/driver/mac/IOReportClientFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.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/IOReportFunctions.java
📚 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-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java` (and similar FFM/API implementations in OSHI), the `updateAttributes()` method intentionally uses `catch (Throwable e) { return false; }` without logging. This is by design: `updateAttributes()` is a public API method whose contract is to return `false` on failure; callers consume the boolean and would never see log output, so adding a log statement is not desired.

Applied to files:

  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacCentralProcessor.java
  • oshi-core-java25/src/main/java/oshi/ffm/mac/IOReportFunctions.java
🔇 Additional comments (24)
oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java (1)

232-233: LGTM!

The change correctly replaces the JNA Platform.getOSType() with SystemInfo.getCurrentPlatform(), which is consistent with the switch dispatch on line 218. This also improves the error message readability by using the PlatformEnum name instead of an integer constant.

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

271-278: vm_deallocate FFM binding looks correct and consistent with existing wrappers.

The symbol lookup, descriptor shape, and wrapper method follow the established pattern in this class and integrate cleanly with the Mac FFM call layer.

oshi-core/src/main/java/oshi/jna/platform/mac/SystemB.java (1)

174-176: LGTM! The vm_deallocate signature correctly matches macOS kernel types.

The parameter types are appropriate:

  • int targetTask for vm_map_t (which is mach_port_t, a 32-bit unsigned int on macOS)
  • long address for vm_address_t (pointer-sized)
  • long size for vm_size_t (pointer-sized)

This is consistent with existing methods in com.sun.jna.platform.mac.SystemB that use int for mach ports.

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

266-287: Good memory leak fix with proper cleanup.

The try/finally block correctly ensures the native buffer allocated by host_processor_info is deallocated, fixing a memory leak that would occur on each call to queryProcessorCpuLoadTicks(). The defensive catch (Exception e) in the finally block prevents deallocation failures from masking the actual tick data.

The fully qualified oshi.jna.platform.mac.SystemB.INSTANCE is necessary since the imported SystemB refers to com.sun.jna.platform.mac.SystemB, while vm_deallocate is declared in the oshi-extended interface.

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

409-413: LGTM! Layout correctly represents the macOS host_cpu_load_info structure.

The layout with sequenceLayout(CPU_STATE_MAX, JAVA_INT) accurately matches the native structure's natural_t cpu_ticks[4] array (where natural_t is 32-bit unsigned int on macOS). The CPU_TICKS path element enables type-safe access via VarHandle with sequenceElement() as shown in the consuming code.

oshi-core-java25/src/main/java/oshi/software/os/mac/MacOperatingSystemFFM.java (1)

152-160: Good simplification and allocation reduction in getThreadCount().

Lines 152-160 are a solid cleanup: single PID materialization + one reused PROC_TASK_INFO buffer avoids stream/parallel overhead and keeps behavior aligned with the Mac JNA sibling.

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

69-72: LGTM! State reset prevents data leakage between GPU entries.

Properly resetting deviceId, vendor, and vram to their default values when parsing a new "Chipset Model" entry ensures each GPU is constructed only from its own data, not stale values from a previous card.

oshi-core-java25/src/main/java/oshi/ffm/mac/IOReportFunctions.java (3)

18-25: Documentation appropriately warns about NPE risk.

The Javadoc clearly documents that calling methods when isAvailable() returns false results in NPE since handles aren't initialized. This is acceptable defensive documentation.


31-43: Library loading pattern is correct for optional private framework.

Using tryLoad() with IllegalArgumentException handling and a static AVAILABLE flag is the appropriate pattern for loading a private Apple framework that may not be present on all systems.


61-173: The function descriptors in this file match the reverse-engineered signatures from known IOReport usage patterns (Rust bindings, open-source projects). The code already includes proper safeguards via isAvailable() checks that prevent calling methods when the private IOReport library is unavailable, mitigating the risk of signature mismatches on systems where the library is not present or differs.

Since IOReport is a private framework with no official documentation, signature changes between macOS versions remain a general architectural risk that cannot be eliminated at the code level—it requires testing on actual macOS systems at runtime, which is beyond review scope. The current implementation is sound.

oshi-core-java25/src/main/java/oshi/driver/mac/IOReportClientFFM.java (4)

58-103: Factory method correctly manages CF resources.

The create() method properly:

  • Releases temporary CFStringRef objects in the finally block
  • Releases channel dictionaries after merging
  • Returns ownership of subscription and subscribedChannels to the new instance
  • Handles all failure paths by returning null

141-182: Utilization sampling correctly manages sample ownership.

The method properly handles the first-call case by storing the sample (and nulling the local to prevent double-release), then computing deltas on subsequent calls. The delta is correctly released in its own finally block.


241-256: Idempotent close correctly releases all retained resources.

The close() method properly releases cached samples (if any) and the subscription handles in the correct order.


290-332: State extraction correctly aggregates residency ticks across channels.

The extractChannelStates() method properly filters by group/subgroup and aggregates residency values using Long::sum, handling multiple channels contributing to the same state name.

oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java (5)

63-82: Constructor and lifecycle methods are well-structured.

The constructor correctly initializes the IOReportClientFFM (handling the null case gracefully throughout) and precomputes the card name pattern for IORegistry matching. The close() method properly delegates to the client's close.


93-129: Utilization fallback chain is appropriate.

The method correctly prioritizes IOReport data, then falls back to IOAccelerator's "GPU Core Utilization" (converting from fixed-point), then "Device Utilization %" (already a percentage). Resource cleanup via try-finally is correct.


131-163: VRAM query handles both Apple Silicon and Intel GPUs.

The method appropriately uses platform-specific keys ("In use system memory" for unified memory on AS, "vramUsedBytes" for discrete VRAM on Intel) with cross-fallback for edge cases.


171-208: Temperature reading with SMC fallback is well-implemented.

The method correctly:

  • Tries SMC first on Apple Silicon (with proper connection lifecycle)
  • Validates positive temperature values before returning
  • Falls back to IOAccelerator's "Temperature(C)" key

244-293: CFRetain is critical for returning valid dictionary reference.

The CFRetain(statsSeg) at line 267 is essential: since statsSeg is obtained from props, it would become invalid when props.release() is called. The retain ensures the returned CFMutableDictionaryRef remains valid for the caller. Good resource management.

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

23-26: Correctly implements the abstract createProcessor() method.

The override fulfills the contract from AbstractHardwareAbstractionLayer and returns the FFM-specific processor implementation.


68-71: getGraphicsCards() correctly delegates to FFM implementation.

The override properly delegates to MacGraphicsCardFFM.getGraphicsCards(), completing the FFM wiring for graphics card discovery.

oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacGraphicsCardFFM.java (3)

28-35: Constructor and stats session creation are correct.

The createStatsSession() properly instantiates MacGpuStatsFFM with the Apple Silicon flag and card name, enabling platform-specific GPU telemetry.


37-77: Parsing logic correctly resets state between GPU entries.

The state variables (deviceId, vendor, vram) are properly reset when encountering a new "Chipset Model", preventing data leakage between cards. This mirrors the fix applied to the JNA version.


80-88: VRAM fallback to system memory is appropriate for Apple Silicon.

For Apple Silicon's unified memory architecture, using hw.memsize (total system RAM) as VRAM is a reasonable approximation when system_profiler doesn't report a specific VRAM value. This behavior is consistent with the JNA implementation.

} catch (Throwable e) {
// if this is a common warning for short-lived processes may need a lower log level
LOG.warn("Failed to get threads for process {}:", pid, e.getMessage());
LOG.warn("Failed to query thread count", e.getMessage());

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.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify SLF4J warn/error calls that pass e.getMessage() without placeholders.
# Expected: This command should surface suspicious logging calls for manual confirmation.

rg -nP --type=java 'LOG\.(warn|error)\(\s*"[^"]*"\s*,\s*e\.getMessage\(\)\s*\)'

Repository: oshi/oshi

Length of output: 1820


🏁 Script executed:

#!/bin/bash
# Read context around line 162 in MacOperatingSystemFFM.java
cat -n oshi-core-java25/src/main/java/oshi/software/os/mac/MacOperatingSystemFFM.java | sed -n '150,175p'

Repository: oshi/oshi

Length of output: 1307


🏁 Script executed:

#!/bin/bash
# Find all LOG.warn/error calls in MacOperatingSystemFFM.java
rg -n 'LOG\.(warn|error)' oshi-core-java25/src/main/java/oshi/software/os/mac/MacOperatingSystemFFM.java

Repository: oshi/oshi

Length of output: 353


Fix SLF4J parameterization at line 162 to preserve exception context.

Line 162 lacks a {} placeholder for the exception message and omits the exception object entirely. Other logging calls in this file (lines 131, 141) demonstrate the proper pattern.

Suggested fix
-            LOG.warn("Failed to query thread count", e.getMessage());
+            LOG.warn("Failed to query thread count: {}", e.getMessage(), e);
📝 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.

Suggested change
LOG.warn("Failed to query thread count", e.getMessage());
LOG.warn("Failed to query thread count: {}", e.getMessage(), 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/software/os/mac/MacOperatingSystemFFM.java`
at line 162, In MacOperatingSystemFFM update the LOG.warn call that currently
passes e.getMessage() directly so it uses SLF4J parameterization and preserves
the stack trace; replace the non-parameterized call on the LOG.warn for "Failed
to query thread count" with a parameterized message that includes a {}
placeholder for the exception message and pass the exception object e as the
final argument so the logger records both the formatted message and the
exception context.

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