Skip to content

Consolidate remaining FFM catch arms onto ExceptionUtil / ForeignFunctions helpers - #3355

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:exception-util-sweep
Jun 8, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:exception-util-sweep

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Jun 8, 2026 •

Copy link
Copy Markdown
Member

Summary

Follow-up to #3352 that finishes the FFM catch-arm consolidation. Six remaining try { ... } catch (Throwable) { return default; } sites now route through the existing ExceptionUtil / ForeignFunctions helpers so the swallow-and-default behaviour lives in one tested place per pattern.

  • ExceptionUtil candidates (no Arena owned at the catch site): IOReportClientFFM.sampleGpuTicks, MacInternetProtocolStatsFFM.queryFdList, MacInternetProtocolStatsFFM.queryIPConnection → ExceptionUtil.getOrDefault.
  • Arena-helper candidates missed in Use ForeignFunctions arena helpers in IOKitUtilFFM and Advapi32UtilFFM #3352 (the audit heuristic latched onto nested inner try keywords instead of the outer try (Arena)): HkeyUserDataFFM.lookupAccountBySid, MacInternetProtocolStatsFFM.getConnections, MacOSProcessFFM.updateAttributes → ForeignFunctions.callInArenaOrDefault / callInArenaBooleanOrDefault. updateAttributes hoists its this.state = INVALID side-effect outside the helper so the catch arm itself stays pure.

ExceptionUtil grows Level-taking overloads in parity with ForeignFunctions.callInArenaOrDefault's signature. Existing (supplier, default, log, msg) methods become one-line delegates that pass Level.DEBUG, preserving behaviour for the 20+ existing callers. New call sites log at TRACE: SLF4J's level guard resolves to a single JIT-inlined isTraceEnabled() check when TRACE isn't configured, so the success-path cost is effectively zero; enabling TRACE on the offending class surfaces the swallowed throwable when debugging. No public API removal, no signature changes — JAPICMP stays quiet (and ExceptionUtil is not annotated @PublicApi either way).

Per-file:

File Change
oshi-common/.../ExceptionUtil.java +9 Level-taking overloads; 9 existing methods become delegates
oshi-common/.../ExceptionUtilTest.java +10 tests covering the new overloads
oshi-core-ffm/.../IOReportClientFFM.java sampleGpuTicks → getOrDefault
oshi-core-ffm/.../HkeyUserDataFFM.java lookupAccountBySid → callInArenaOrDefault
oshi-core-ffm/.../MacInternetProtocolStatsFFM.java three catches converted (one Arena-helper, two ExceptionUtil; both partial-result returns pass their in-scope list as default)
oshi-core-ffm/.../MacOSProcessFFM.java updateAttributes → callInArenaBooleanOrDefault; state = INVALID hoisted outside helper

Sites intentionally left alone: IOReportClientFFM.sampleGpuUtilization (L167) and samplePowerWatts (L221). Their outer finally { cfRelease(sample); } cleanup with mid-body sample ownership transfer doesn't fit the helper's try/catch/default shape without a structural refactor that costs more clarity than it recovers.

Coverage parity (pom.xml)

JaCoCo's <excludes> adds **/ffm/** alongside the existing **/jna/**. Both namespaces are mostly FFM/JNA mapping declarations and helper utilities whose coverage tells us little. The implementation classes (*FFM and *JNA in hardware.platform.* and software.os.*) stay in scope.

Test plan

  • ./mvnw -pl oshi-common,oshi-core-ffm -am spotless:apply checkstyle:check install javadoc:javadoc -DskipTests — all gates pass locally
  • ./mvnw -pl oshi-common,oshi-core-ffm -am test — full suite green on macOS arm64; 10 new ExceptionUtil tests added
  • CI green across all platforms

Summary by CodeRabbit

  • New Features

    • Enhanced logging infrastructure with configurable severity levels for improved error diagnostics and troubleshooting.
    • Improved exception handling across system operations with consistent fallback mechanisms.
  • Tests

    • Improved test reliability for file system operations on platforms with fluctuating storage metrics.

@coderabbitai

coderabbitai Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 314ec34e-4373-4e9a-938a-3a3a1bee930e

📥 Commits

Reviewing files that changed from the base of the PR and between 9118bc3 and a94832d.

📒 Files selected for processing (7)
  • oshi-common/src/main/java/oshi/util/ExceptionUtil.java
  • oshi-common/src/test/java/oshi/util/ExceptionUtilTest.java
  • oshi-core-ffm/src/main/java/oshi/driver/mac/IOReportClientFFM.java
  • oshi-core-ffm/src/main/java/oshi/driver/windows/registry/HkeyUserDataFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/mac/MacInternetProtocolStatsFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java
  • oshi-core/src/test/java/oshi/software/os/shared/FileSystemTest.java
🚧 Files skipped from review as they are similar to previous changes (6)
  • oshi-common/src/test/java/oshi/util/ExceptionUtilTest.java
  • oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java
  • oshi-core-ffm/src/main/java/oshi/driver/windows/registry/HkeyUserDataFFM.java
  • oshi-core-ffm/src/main/java/oshi/driver/mac/IOReportClientFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/mac/MacInternetProtocolStatsFFM.java
  • oshi-common/src/main/java/oshi/util/ExceptionUtil.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). (15)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 26, windows-latest
  • GitHub Check: Test JDK 26, macos-latest
  • GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Test JDK 25, FreeBSD (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
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`.
📚 Learning: 2026-04-03T18:44:48.200Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3112
File: oshi-core/src/main/java/oshi/PlatformEnum.java:63-66
Timestamp: 2026-04-03T18:44:48.200Z
Learning: In oshi/oshi PlatformEnum.java, the DRAGONFLYBSD enum constant is intentionally added for platform detection only (no implementation classes exist yet). It allows UnsupportedOperationException messages to say "DragonFly BSD" rather than "Unknown". Full DragonFly BSD support is tracked in issue `#2583`. Do not flag the missing switch-case implementations as a bug.

Applied to files:

  • oshi-core/src/test/java/oshi/software/os/shared/FileSystemTest.java
📚 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/test/java/oshi/software/os/shared/FileSystemTest.java
🔇 Additional comments (3)
oshi-core/src/test/java/oshi/software/os/shared/FileSystemTest.java (3)

12-14: LGTM!


28-32: LGTM!


83-83: LGTM!


📝 Walkthrough

Walkthrough

This PR extends ExceptionUtil with SLF4J Level-parameterized logging overloads and refactors five FFM-based driver files to use centralized exception-handling helpers instead of inline try-catch-return patterns. Additionally, a file system test is updated to account for total space fluctuations on FreeBSD alongside Solaris.

Changes

Structured exception logging with configurable levels

Layer / File(s) Summary
ExceptionUtil Level-parameterized logging overloads
oshi-common/src/main/java/oshi/util/ExceptionUtil.java
SLF4J Level import added. Nine new public overloads introduced for getOrDefault, getIntOrDefault, getLongOrDefault, getBooleanOrDefault, getDoubleOrDefault, getOptional, getOptionalInt, getOptionalLong, and runOrLog, each accepting a Level parameter. Existing debug-only overloads refactored to delegate to the new Level variants using Level.DEBUG. Exception logging updated to log.atLevel(level).setCause(t).log(msg, t.getMessage()).
ExceptionUtil test coverage for Level variants
oshi-common/src/test/java/oshi/util/ExceptionUtilTest.java
Level import added. Test suite added covering all new Level-accepting overloads, with Level.TRACE failure-path assertions across get*OrDefault and getOptional* variants and runOrLog, plus Level.WARN success-path check for getOrDefault.
GPU tick sampling with structured failure logging
oshi-core-ffm/src/main/java/oshi/driver/mac/IOReportClientFFM.java
SLF4J Logger, LoggerFactory, TRACE, and ExceptionUtil.getOrDefault imports added. Class-level LOG field initialized. sampleGpuTicks() refactored to wrap GPU tick collection in getOrDefault with GpuTicks(0,0) default and TRACE-level logging, replacing inline try-catch.
Windows registry lookups with structured failure logging
oshi-core-ffm/src/main/java/oshi/driver/windows/registry/HkeyUserDataFFM.java
Static imports for Level.TRACE and callInArenaOrDefault added. lookupAccountBySid() refactored to delegate arena lifecycle and exception handling to callInArenaOrDefault, replacing try-with-resources pattern and enabling TRACE-level failure logging.
IP connection enumeration with structured failure logging
oshi-core-ffm/src/main/java/oshi/software/os/mac/MacInternetProtocolStatsFFM.java
SLF4J Logger field and static imports for TRACE and getOrDefault added. getConnections() wrapped in callInArenaOrDefault for arena-based enumeration with failure logging. queryFdList() and queryIPConnection() wrapped in getOrDefault, returning partial results and logging failures instead of explicit try-catch blocks.
Process attribute collection with structured failure logging
oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java
Static imports for TRACE and callInArenaBooleanOrDefault added. updateAttributes() refactored to wrap native attribute collection in callInArenaBooleanOrDefault, replacing inline try-catch with arena-aware lambda that returns false on failure and logs at TRACE level.

File system test coverage for platform-specific behavior

Layer / File(s) Summary
Platform set and total space fluctuation assertion
oshi-core/src/test/java/oshi/software/os/shared/FileSystemTest.java
Set and EnumSet imports added. FLUCTUATING_TOTAL_SPACE constant defined with PlatformEnum.SOLARIS and PlatformEnum.FREEBSD. Total space unchanged assertion updated to skip check for all platforms in the set instead of only Solaris.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • oshi/oshi#3272: Prior PR that introduced the initial ExceptionUtil and Level-based logging API that this PR extends with additional overloads and broader driver integration.
  • oshi/oshi#3284: Introduced callInArenaOrDefault and related FFM arena helpers that are now used throughout this PR's driver refactors for structured exception handling.
  • oshi/oshi#3293: Modified IOReportClientFFM.sampleGpuTicks() CoreFoundation/FFM lifetime management; this PR refactors the same method's exception handling and logging on top of those changes.

🐰 Logs cascade down with style so true,
Nine new overloads let the level shine through,
FFM drivers dancing, exceptions now caught,
Structured and TRACE'd, with clarity wrought! 🎯

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 55.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main objective: consolidating FFM catch arms (exception handling) into centralized ExceptionUtil and ForeignFunctions helpers, which matches the primary changes in the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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 Jun 8, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 75.02%. Comparing base (75bd34a) to head (a94832d).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3355      +/-   ##
============================================
+ Coverage     74.96%   75.02%   +0.06%     
  Complexity       76       76              
============================================
  Files           602      602              
  Lines         25832    25832              
  Branches       3984     3983       -1     
============================================
+ Hits          19364    19381      +17     
+ Misses         4217     4199      -18     
- Partials       2251     2252       +1     
Flag Coverage Δ
freebsd 23.23% <67.85%> (+0.03%) ⬆️
linux 26.92% <67.85%> (+0.05%) ⬆️
macos 30.29% <96.42%> (+0.04%) ⬆️
openbsd 22.56% <67.85%> (+0.04%) ⬆️
solaris 24.85% <67.85%> (+0.06%) ⬆️
windows 36.24% <71.42%> (+0.03%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 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 (2)
pom.xml (1)

827-827: ⚡ Quick win

Document the rationale for excluding all FFM code from coverage.

The blanket **/ffm/** exclusion lacks an explanatory comment (unlike other exclusion categories at lines 832–836, 840, 857, etc.) and makes many existing specific FFM exclusions redundant (e.g., **/LinuxGpuStatsFFM* at line 846, **/WindowsGraphicsCardFFM* at line 862).

If FFM code is excluded because it requires Java 25+ and is difficult to exercise in CI (similar to the rationale for JNA), consider adding a comment to document this. If the exclusion is meant to be temporary or only applies to certain FFM modules, prefer keeping the specific exclusions rather than a catch-all pattern.

📝 Suggested comment addition
                        <exclude>**/demo/**</exclude>
+                        <!-- FFM (Foreign Function & Memory) integration layer: requires Java 25+ and native access setup -->
                        <exclude>**/ffm/**</exclude>
                        <exclude>**/jna/**</exclude>
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pom.xml` at line 827, Add a short explanatory comment above the blanket
coverage exclusion "**/ffm/**" in the pom.xml indicating why all FFM code is
excluded (e.g., requires Java 25+, difficult to exercise in CI, or temporary
exclusion), and clarify scope (global vs specific modules) and intended
duration; if the exclusion is meant to apply only to certain FFM classes instead
of all FFM code, remove the catch‑all and retain the existing specific
exclusions such as "**/LinuxGpuStatsFFM*" and "**/WindowsGraphicsCardFFM*" to
avoid overbroad coverage gaps.
oshi-common/src/test/java/oshi/util/ExceptionUtilTest.java (1)

307-385: 🏗️ Heavy lift

These tests don't verify the new level-aware behavior.

This block only checks the return defaults and “does not throw” paths. If ExceptionUtil ignored the supplied level and always logged at DEBUG, or stopped attaching the thrown cause, every added test here would still pass. Please capture one emitted event or mock the logger/builder for at least one overload so the new contract is actually pinned down.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@oshi-common/src/test/java/oshi/util/ExceptionUtilTest.java` around lines 307
- 385, Add a test that actually verifies the level-aware logging behavior by
capturing/emulating the logger and asserting the emitted event contains the
configured Level and the thrown cause: instrument the existing tests (e.g.,
testGetOrDefaultWithTraceLevel or testRunOrLogWithTraceLevel) to replace LOG
with a mock or a test appender (or Mockito spy) and assert that
ExceptionUtil.getOrDefault (or ExceptionUtil.runOrLog) logs at Level.TRACE and
includes the RuntimeException as the logged throwable; update only one overload
test to perform this capture so the contract is pinned down.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@oshi-common/src/main/java/oshi/util/ExceptionUtil.java`:
- Around line 154-160: The log calls in ExceptionUtil (e.g., getOrDefault and
the other overloaded methods in this class) incorrectly pass the Throwable twice
by calling log(msg, t) after setCause(t), so the `{}` placeholder is not
populated; change each occurrence to pass the exception message (t.getMessage())
as the parameter to log (or call log(msg) if no `{}` is present) and keep
setCause(t) so the stacktrace is attached only once—update every instance around
the methods named getOrDefault and the other exception-handling overloads to
remove the throwable from the varargs and use t.getMessage() for `{}`
substitution.

---

Nitpick comments:
In `@oshi-common/src/test/java/oshi/util/ExceptionUtilTest.java`:
- Around line 307-385: Add a test that actually verifies the level-aware logging
behavior by capturing/emulating the logger and asserting the emitted event
contains the configured Level and the thrown cause: instrument the existing
tests (e.g., testGetOrDefaultWithTraceLevel or testRunOrLogWithTraceLevel) to
replace LOG with a mock or a test appender (or Mockito spy) and assert that
ExceptionUtil.getOrDefault (or ExceptionUtil.runOrLog) logs at Level.TRACE and
includes the RuntimeException as the logged throwable; update only one overload
test to perform this capture so the contract is pinned down.

In `@pom.xml`:
- Line 827: Add a short explanatory comment above the blanket coverage exclusion
"**/ffm/**" in the pom.xml indicating why all FFM code is excluded (e.g.,
requires Java 25+, difficult to exercise in CI, or temporary exclusion), and
clarify scope (global vs specific modules) and intended duration; if the
exclusion is meant to apply only to certain FFM classes instead of all FFM code,
remove the catch‑all and retain the existing specific exclusions such as
"**/LinuxGpuStatsFFM*" and "**/WindowsGraphicsCardFFM*" to avoid overbroad
coverage gaps.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 0b2ea1d7-7d16-4020-a5cf-8f3bb6b2c47e

📥 Commits

Reviewing files that changed from the base of the PR and between 0861a79 and 9118bc3.

📒 Files selected for processing (7)
  • oshi-common/src/main/java/oshi/util/ExceptionUtil.java
  • oshi-common/src/test/java/oshi/util/ExceptionUtilTest.java
  • oshi-core-ffm/src/main/java/oshi/driver/mac/IOReportClientFFM.java
  • oshi-core-ffm/src/main/java/oshi/driver/windows/registry/HkeyUserDataFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/mac/MacInternetProtocolStatsFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java
  • pom.xml
📜 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). (17)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 26, ubuntu-latest
  • GitHub Check: Test JDK 26, windows-latest
  • GitHub Check: Test JDK 26, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: Test JDK 25, FreeBSD (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (7)
📓 Common learnings
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`.
📚 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:

  • pom.xml
  • oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java
📚 Learning: 2026-04-03T02:07:49.467Z
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:49.467Z
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-ffm/src/main/java/oshi/driver/mac/IOReportClientFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/mac/MacInternetProtocolStatsFFM.java
📚 Learning: 2026-04-15T04:56:18.352Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3163
File: oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java:97-103
Timestamp: 2026-04-15T04:56:18.352Z
Learning: In CoreFoundationTest.java (oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java), asserting exact CFGetRetainCount deltas (+1 after retain, -1 after release) is intentional and considered reliable for freshly created CF objects (e.g., CFStringRef via CFStringRef.createCFString) where the test holds sole ownership. Do not flag these assertions as flaky — the Apple "avoid CFGetRetainCount" advisory applies to shared/framework-managed objects, not exclusively owned objects in unit tests.

Applied to files:

  • oshi-core-ffm/src/main/java/oshi/driver/mac/IOReportClientFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/mac/MacInternetProtocolStatsFFM.java
📚 Learning: 2026-04-17T23:43:35.860Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3168
File: oshi-core-java25/src/main/java/oshi/ffm/windows/PdhFFM.java:0-0
Timestamp: 2026-04-17T23:43:35.860Z
Learning: In `oshi-core-java25/src/main/java/oshi/ffm/windows/PdhFFM.java`, the `PDH_RAW_COUNTER_LAYOUT` Java FFM struct layout must place `FirstValue` at byte offset 16 (not 12). The native MSVC compiler inserts 4 bytes of implicit alignment padding before the `LONGLONG FirstValue` field (after CStatus=4 bytes + FILETIME TimeStamp=8 bytes = 12 bytes), because LONGLONG requires 8-byte alignment. The total struct size is 40 bytes (with trailing padding). Do not use JAVA_LONG_UNALIGNED without explicit padding here, as that incorrectly places FirstValue at offset 12 and causes reads of garbage counter values.

Applied to files:

  • oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/mac/MacInternetProtocolStatsFFM.java
  • oshi-core-ffm/src/main/java/oshi/driver/windows/registry/HkeyUserDataFFM.java
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/util/ExceptionUtil.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-ffm/src/main/java/oshi/driver/windows/registry/HkeyUserDataFFM.java
🔇 Additional comments (10)
oshi-core-ffm/src/main/java/oshi/driver/mac/IOReportClientFFM.java (2)

7-8: LGTM!

Also applies to: 18-20, 40-40


115-130: LGTM!

oshi-core-ffm/src/main/java/oshi/driver/windows/registry/HkeyUserDataFFM.java (2)

11-12: LGTM!


106-136: LGTM!

oshi-core-ffm/src/main/java/oshi/software/os/mac/MacInternetProtocolStatsFFM.java (4)

11-12: LGTM!

Also applies to: 57-57, 68-70, 84-84


152-176: LGTM!


181-198: LGTM!


202-262: LGTM!

oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java (2)

13-14: LGTM!


473-605: LGTM!

…tions helpers

Continuation of the centralisation work from #3352. Six more
`try { ... } catch (Throwable) { return default; }` sites now route their
swallow-and-return through the existing `ExceptionUtil` /
`ForeignFunctions` helpers so the catch-and-default behaviour lives in
one tested place per pattern:

* `IOReportClientFFM.sampleGpuTicks`,
  `MacInternetProtocolStatsFFM.queryFdList`, and
  `MacInternetProtocolStatsFFM.queryIPConnection` move to
  `ExceptionUtil.getOrDefault` (no Arena owned at the catch site).
* `HkeyUserDataFFM.lookupAccountBySid`,
  `MacInternetProtocolStatsFFM.getConnections`, and
  `MacOSProcessFFM.updateAttributes` move to
  `ForeignFunctions.callInArenaOrDefault` /
  `callInArenaBooleanOrDefault` — these are catches paired with
  `try (Arena = Arena.ofConfined())` that the heuristic missed in #3352.
  `updateAttributes` hoists its `this.state = INVALID` side-effect
  outside the helper so the catch arm itself stays pure.

`ExceptionUtil` grows `Level`-taking overloads in parity with
`ForeignFunctions.callInArenaOrDefault`'s signature. Existing
`(supplier, default, log, msg)` methods become one-line delegates
passing `Level.DEBUG`, preserving behaviour for the 20+ existing
callers. New call sites log at `TRACE`: SLF4J's level guard collapses
to a single JIT-inlined `isTraceEnabled()` check when TRACE is not
configured, so the success-path cost is effectively zero, while
turning TRACE on for the offending class surfaces the swallowed
throwable when debugging. The fluent log call passes `t.getMessage()`
as the substitution argument (matching `ForeignFunctions`'s pattern),
so `{}` placeholders in caller messages render as the throwable's
message string rather than its full `toString()`. No public API
removal, no signature changes — JAPICMP stays quiet.

`IOReportClientFFM.sampleGpuUtilization` (L167) and `samplePowerWatts`
(L221) were considered but left as-is: their outer
`finally { cfRelease(sample); }` cleanup with mid-body sample
ownership transfer doesn't fit the helper's try/catch/default shape
without a structural refactor that costs more clarity than it
recovers.

Folds in two unrelated fixes that surfaced from CI on the prior push:

* `FileSystemTest` now skips the "total space should not change after
  update" assertion on FreeBSD in addition to Solaris — ZFS pools
  report a dynamically computed total that can fluctuate by a few MB
  between back-to-back queries due to pool/dataset metadata refresh.
  Uses an `EnumSet` named `FLUCTUATING_TOTAL_SPACE` so future
  platforms with the same behaviour can be added without growing the
  conditional. DragonFly's HAMMER2 doesn't share this property, so
  it's left out.

A planned `**/ffm/**` jacoco exclusion (mirroring the existing
`**/jna/**`) was prepared and then dropped from this PR — it
accidentally drops 25 real driver classes in `oshi.ffm.driver.*`
(AIX perfstat, Solaris PsInfo + kstat, Windows InstalledApps) from
coverage. The underlying structure needs cleanup first: those
drivers belong in `oshi.driver.*` alongside the Mac/Linux/Windows
FFM drivers, and the Windows FFM mapping files (`*FFM.java`) should
follow the same `*Functions.java` convention used elsewhere. Handle
in a follow-up PR.
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