Skip to content

Use ForeignFunctions arena helpers in IOKitUtilFFM and Advapi32UtilFFM - #3352

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:ffm-arena-helper-sweep
Jun 8, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:ffm-arena-helper-sweep

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Jun 8, 2026 •

Copy link
Copy Markdown
Member

Summary

Replaces seven hand-rolled try (Arena = Arena.ofConfined()) … catch (Throwable) { return default; } blocks across IOKitUtilFFM (5) and Advapi32UtilFFM (2) with the existing callInArenaOrDefault / callInArenaIntOrDefault / callInArenaBooleanOrDefault helpers in ForeignFunctions. Centralises the swallow-and-return pattern so the catch-default convention lives in one place, matching how Mac*FFM, LinuxUsbDeviceFFM, and the *CentralProcessorFFM family already do it.

  • Logged at TRACE with static-literal messages. When TRACE is not configured the call collapses to a single isTraceEnabled() check that the JIT inlines and the branch predictor pegs — the runtime cost on the success path is effectively zero. The benefit is a debug signal that previously did not exist: enabling TRACE on the offending utility class surfaces the swallowed throwable when chasing an unexpected null/0/false return.
  • IOKitUtilFFM picks up a private static final Logger LOG field; Advapi32UtilFFM already had one.

Sites intentionally left alone after closer reading: IOReportClientFFM (outer catches cover CFString/CFType allocations beyond the Arena, or try (CFTypeRef) resources with finally { cfRelease } cleanup that must run after the catch), MacInternetProtocolStatsFFM and HkeyUserDataFFM (Arena passed in as a parameter), and MacOSProcessFFM L600 (inner catch inside a larger Arena scope).

Test plan

  • ./mvnw -pl oshi-core-ffm -am spotless:apply checkstyle:check install javadoc:javadoc -DskipTests — all gates pass locally
  • ./mvnw -pl oshi-core-ffm -am test — full FFM test suite green on macOS arm64
  • CI green across all platforms (mac, windows, linux, freebsd, openbsd, solaris, aix)

Summary by CodeRabbit

  • Refactor
    • Updated macOS IOKit utility to use centralized error-handling wrappers with trace-level logging.
    • Updated Windows registry utility to use shared wrapper functions for consistent error handling and logging across helper methods.

Replace seven hand-rolled `try (Arena = Arena.ofConfined()) … catch
(Throwable) { return default; }` blocks with the existing
`callInArenaOrDefault` / `callInArenaIntOrDefault` /
`callInArenaBooleanOrDefault` helpers in `ForeignFunctions`. Centralising
the swallow keeps the catch-and-return pattern DRY and matches the
convention already used in `Mac*FFM`, `LinuxUsbDeviceFFM`, and the
`*CentralProcessorFFM` family.

The helpers log via the SLF4J fluent API. Logged at TRACE: when TRACE is
not enabled the call resolves to a single `isTraceEnabled()` check, which
the JIT inlines and the branch predictor pegs almost immediately, so the
runtime cost on the success path is effectively zero. When someone needs
to chase an unexpected null/0/false return, enabling TRACE on the
offending class surfaces the swallowed throwable — a signal we did not
have before. Messages are static literals so no string is constructed on
the success path.

Inner try/finally `RegCloseKey` blocks in `Advapi32UtilFFM` stay inside
the lambda; outer-catch sites in `IOReportClientFFM`,
`MacInternetProtocolStatsFFM`, `MacOSProcessFFM`, and `HkeyUserDataFFM`
were intentionally left alone — their catches cover scopes broader than
the Arena open, or the Arena is passed in as a parameter, so the helper
does not fit cleanly.
@coderabbitai

coderabbitai Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Two FFM platform-specific utility classes (IOKitUtilFFM for macOS, Advapi32UtilFFM for Windows) are refactored to consolidate confined arena lifecycle management and error handling by delegating to shared callInArena*OrDefault wrapper functions that log failures at TRACE level and return configured defaults.

Changes

FFM Confined Arena Wrapper Migration

Layer / File(s) Summary
macOS IOKit wrapper consolidation
oshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/IOKitUtilFFM.java
IOKitUtilFFM introduces SLF4J Logger and imports arena wrapper functions, adds a static LOG field, and refactors getMasterPort(), getMatchingService(String), getMatchingServices(String), getMatchingServices(MemorySegment), and getBSDNameMatchingDict(String) to execute within callInArenaIntOrDefault / callInArenaOrDefault closures instead of local try (Arena) blocks, with TRACE logging and typed default returns (0 or null) on failure.
Windows registry wrapper consolidation
oshi-core-ffm/src/main/java/oshi/ffm/util/platform/windows/Advapi32UtilFFM.java
Advapi32UtilFFM imports TRACE level and arena wrapper functions, then refactors registryGetValue(...) and registryValueExists(...) to delegate confined arena execution and error handling to callInArenaOrDefault and callInArenaBooleanOrDefault respectively, replacing inline try-with-resources / catch blocks with wrapper-managed execution and TRACE logging.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • oshi/oshi#3284: Introduces the shared ForeignFunctions.callInArena*OrDefault helper wrappers that are applied in this PR.
  • oshi/oshi#3285: Applies the same arena wrapper consolidation pattern to Linux FFM classes alongside the main PR's macOS and Windows refactorings.
  • oshi/oshi#3289: Migrates other Windows FFM code to use the shared callInArena*OrDefault arena-call helpers, following the same pattern as Advapi32UtilFFM in this PR.

Poem

🐰 With arenas now wrapped in helpers so fine,
macOS and Windows both dance in a line,
No try-catch debris, just logger TRACE light,
Defaults gently held when the FFM calls take flight. 🌟

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title directly and accurately describes the main change: replacing hand-rolled Arena try-with-resources blocks with ForeignFunctions helper methods in two utility classes.
Docstring Coverage ✅ Passed Docstring coverage is 87.50% which is sufficient. The required threshold is 80.00%.
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ 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 68.24%. Comparing base (36a1206) to head (87e46b9).
⚠️ Report is 1 commits behind head on master.

❗ There is a different number of reports uploaded between BASE (36a1206) and HEAD (87e46b9). Click for more details.

HEAD has 1 upload less than BASE
Flag BASE (36a1206) HEAD (87e46b9)
solaris 1 0
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3352      +/-   ##
============================================
- Coverage     74.95%   68.24%   -6.71%     
  Complexity       76       76              
============================================
  Files           602      602              
  Lines         25845    25832      -13     
  Branches       3990     3984       -6     
============================================
- Hits          19371    17629    -1742     
- Misses         4217     6187    +1970     
+ Partials       2257     2016     -241     
Flag Coverage Δ
freebsd 23.19% <0.00%> (+<0.01%) ⬆️
linux 26.87% <0.00%> (+0.01%) ⬆️
macos 30.24% <75.00%> (+0.01%) ⬆️
openbsd 22.52% <0.00%> (+<0.01%) ⬆️
solaris ?
windows 36.23% <25.00%> (+0.02%) ⬆️

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.

@dbwiddis
dbwiddis merged commit 75bd34a into oshi:master Jun 8, 2026
37 of 39 checks passed
@dbwiddis
dbwiddis deleted the ffm-arena-helper-sweep branch June 8, 2026 01:01
dbwiddis added a commit that referenced this pull request Jun 8, 2026
…tions helpers (#3355)

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