Skip to content

Fix macOS JNA-backend divergences from the FFM backend - #3473

Merged
dbwiddis merged 11 commits into
oshi:masterfrom
dbwiddis:mac-jna-ffm-fixes
Jul 18, 2026
Merged

dbwiddis merged 11 commits into
oshi:masterfrom
dbwiddis:mac-jna-ffm-fixes

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Jul 18, 2026 •

Copy link
Copy Markdown
Member

The default JNA backend had several macOS bugs where it behaved differently from (and less correctly than) the opt-in FFM backend. Found by an audit of every JNA/FFM twin pair; each fix aligns JNA to the existing FFM behavior. Validated live via NativeComparisonTest -Pnative-comparison (JNA==FFM) on Apple Silicon.

Behavior fixes

  • SmcUtil SP78 — read the fractional byte unsigned (& 0xFF); Intel Mac sensor temperatures were under-reported (and could go negative) whenever the fractional part was ≥ 0.5 °C.
  • MacOSProcessJNA — decode the process working directory as UTF-8 instead of US-ASCII.
  • Who — decode utmpx login-session user/line/host fields as UTF-8.
  • MacHWDiskStoreJNA — return false from updateDiskStats when no matching IOMedia device is found (was reporting false success).
  • MacFileSystemJNA — keep the mount-derived volume name when DAVolumeName is absent (was clobbering it to null).

Null/bounds guards (each would NPE/misbehave on an edge native result; FFM already guarded them)

  • MacNetworkIfJNA null localized display name → fall back to the BSD interface name.
  • MacNetworkParamsJNA null ai_canonname → empty domain name.
  • MacDisplayJNA zero-length EDID → skip (was producing a bogus extra Display).
  • MacPowerSourceJNA null power-source list → empty list.

Plus a non-behavioral tidy: MacGpuStatsJNA pre-computes the normalized card name in its constructor, mirroring the FFM twin.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved macOS sensor temperature readings.
    • Corrected UTF-8 handling for process paths and login session details.
    • Added safeguards for missing or invalid hardware, network, power, filesystem, and display data.
    • Improved GPU identification and disk status reporting.
    • Prevented failures when macOS provides incomplete native system information.

dbwiddis added 11 commits July 17, 2026 19:10
Align MacGpuStatsJNA with MacGpuStatsFFM by computing the normalized card
name and its word-boundary pattern once in the constructor rather than on
every matchesName() call. Behavior is identical; the JNA backend now reads
the same as the FFM one and avoids recompiling the regex per query.
The SP78 SMC datatype is a fixed-point value whose low byte is an unsigned
1/256 fraction, but MacGpuStatsJNA read it via a signed byte, under-reporting
temperatures by up to ~1C whenever that byte was >= 0x80. Mask it to 0xFF to
match SmcUtilFFM (and the SP78 definition). Affects Intel CPU/GPU temperature
readings (TC0P and other SP78 keys).
updateDiskStats returned true whenever the service iterator was non-null,
even when the drive was null or not an IOMedia object -- claiming success
without updating any statistics. Track whether an IOMedia device was actually
found and return that, matching MacHWDiskStoreFFM.
MacFileSystemJNA assigned the DiskArbitration volume name unconditionally, so
an unnamed volume overwrote the real mount-derived name with the null
fallback ("unknown"). Only overwrite when the key is present, matching
MacFileSystemFFM.
MacOSProcessJNA decoded the current-working-directory path as US-ASCII while
the process name (and MacOSProcessFFM) use UTF-8, corrupting non-ASCII cwd
paths. Use UTF-8.
Who decoded the utmpx user/line/host fields as US-ASCII while WhoFFM uses
UTF-8, so non-ASCII usernames or remote hostnames produced different OSSession
values (and could flip session validity). Use UTF-8.
SCNetworkInterfaceGetLocalizedDisplayName can return null; MacNetworkIfJNA
dereferenced it directly and would NPE. Fall back to the BSD interface name
when it is null, matching MacNetworkIfFFM.
getaddrinfo can succeed without populating ai_canonname; MacNetworkParamsJNA
called .trim() on it directly and would NPE. Return an empty string when it is
null, matching MacNetworkParamsFFM.
A display whose EDID property is present but empty produced an extra empty
Display in the JNA backend. Only add the display when the EDID has bytes,
matching MacDisplayFFM.
MacPowerSourceJNA called getCount() on the IOPSCopyPowerSourcesList result
without a null check and would NPE when no list was returned. Guard it and
return an empty list, matching MacPowerSourceFFM.
@coderabbitai

coderabbitai Bot commented Jul 18, 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: 9e2f67fb-c330-4ebc-8559-74edde92c785

📥 Commits

Reviewing files that changed from the base of the PR and between d923553 and 5775b47.

📒 Files selected for processing (11)
  • CHANGELOG.md
  • oshi-core/src/main/java/oshi/driver/mac/Who.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacDisplayJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStatsJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacNetworkIfJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSourceJNA.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacFileSystemJNA.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacNetworkParamsJNA.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java
  • oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java
📜 Recent review details
⏰ Context from checks skipped due to timeout. (9)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 26, windows-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)
  • GitHub Check: Test JDK 25, FreeBSD (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2026-07-06T19:25:59.225Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3432
File: oshi-common/src/main/java/oshi/util/ExceptionUtil.java:26-56
Timestamp: 2026-07-06T19:25:59.225Z
Learning: In this repo’s SLF4J 1.x-compatible logging code, do not flag cases where a logger call uses SLF4J 1.6+ implicit-cause handling—e.g., `log.error("...{}", value, t)` (or similar with a single `{}` placeholder) where `t` is passed as the final/trailing argument. SLF4J will attach `t` as the log event’s cause with the full stack trace; this is equivalent to SLF4J 2.x’s fluent `atLevel(...).setCause(t).log(...)` and is intentionally used to preserve SLF4J 1.x runtime compatibility.

Applied to files:

  • oshi-core/src/main/java/oshi/driver/mac/Who.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacDisplayJNA.java
  • oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacFileSystemJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacNetworkIfJNA.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSourceJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreJNA.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacNetworkParamsJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStatsJNA.java
📚 Learning: 2026-04-06T04:45:47.644Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3121
File: oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java:53-53
Timestamp: 2026-04-06T04:45:47.644Z
Learning: In the oshi/oshi project, only interfaces and classes in the root packages `oshi`, `oshi.hardware`, and `oshi.software.os` are considered the public API. Code in subpackages that represent specific implementations/platforms (e.g., `oshi.software.os.linux`, `oshi.hardware.platform.linux`, and similar subpackages) is implementation detail. When reviewing, do not treat changes to classes in these platform-specific subpackages as public API breaks (for example: making `LinuxOperatingSystem` abstract, narrowing constructor visibility, or adding/removing abstract methods should not be flagged as breaking public API).

Applied to files:

  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacDisplayJNA.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacFileSystemJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacNetworkIfJNA.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSourceJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreJNA.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacNetworkParamsJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStatsJNA.java
🪛 ast-grep (0.44.1)
oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStatsJNA.java

[warning] 68-68: Regular expression is compiled from a non-literal, possibly user-controlled value. A crafted regex (or input matched against one) can trigger catastrophic backtracking and hang the thread (ReDoS). Use a hardcoded literal pattern, wrap untrusted text with Pattern.quote(...), or validate/length-limit the input and enforce a matching timeout before passing it to Pattern.compile / String.matches / String.replaceAll / String.replaceFirst.
Context: Pattern.compile("\b" + Pattern.quote(normCardName) + "\b")
Note: [CWE-1333] Inefficient Regular Expression Complexity.

(redos-non-literal-regex-java)

🔇 Additional comments (14)
oshi-core/src/main/java/oshi/driver/mac/Who.java (1)

46-48: LGTM!

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

262-262: LGTM!

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

57-57: LGTM!

oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java (1)

132-134: LGTM!

CHANGELOG.md (1)

10-10: LGTM!

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

117-119: LGTM!

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

47-49: LGTM!

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

9-9: LGTM!


62-67: LGTM!

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

129-133: LGTM!

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

94-231: LGTM!

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

7-8: LGTM!


58-69: LGTM!


285-288: LGTM!


📝 Walkthrough

Walkthrough

macOS JNA integrations now decode selected native strings as UTF-8, guard null or invalid native results, correct SP78 sensor fractions, improve GPU name matching, and report disk updates accurately. The changelog records these fixes.

Changes

macOS native handling

Layer / File(s) Summary
Native string and scalar decoding
CHANGELOG.md, oshi-core/src/main/java/oshi/driver/mac/Who.java, oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java, oshi-core/src/main/java/oshi/software/os/mac/MacNetworkParamsJNA.java, oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java
macOS session and process paths use UTF-8, canonical-name handling tolerates null values, SP78 fractional bytes are treated as unsigned, and the changelog records the fixes.
Optional native values and resource guards
oshi-core/src/main/java/oshi/hardware/platform/mac/MacDisplayJNA.java, oshi-core/src/main/java/oshi/hardware/platform/mac/MacNetworkIfJNA.java, oshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSourceJNA.java, oshi-core/src/main/java/oshi/software/os/mac/MacFileSystemJNA.java
Display, network, power-source, and filesystem integrations guard missing native values and return empty power-source results when necessary.
Hardware state and GPU matching
oshi-core/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreJNA.java, oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStatsJNA.java
Disk statistics report success only after an actual update, while GPU names use cached normalization and a compiled pattern.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

  • oshi/oshi#3398: Both modify the macOS display JNA code path.
  • oshi/oshi#3470: Both touch macOS session retrieval through Who.queryUtxent().

Poem

A bunny hops through UTF-8 air,
With safer pointers everywhere.
Sensors read fractions bright,
GPUs match names just right.
Empty lists guard the night—
Mac JNA now feels light!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.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 accurately summarizes the main change: aligning macOS JNA behavior with the FFM backend.
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.
✨ 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.

@codecov

codecov Bot commented Jul 18, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 64.28571% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.16%. Comparing base (d923553) to head (5775b47).

Files with missing lines Patch % Lines
...java/oshi/hardware/platform/mac/MacDisplayJNA.java 0.00% 2 Missing ⚠️
...va/oshi/hardware/platform/mac/MacNetworkIfJNA.java 50.00% 0 Missing and 1 partial ⚠️
...in/java/oshi/software/os/mac/MacFileSystemJNA.java 50.00% 0 Missing and 1 partial ⚠️
...java/oshi/software/os/mac/MacNetworkParamsJNA.java 0.00% 0 Missing and 1 partial ⚠️

❌ Your patch check has failed because the patch coverage (64.28%) is below the target coverage (70.00%). You can increase the patch coverage or adjust the target coverage.

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3473      +/-   ##
============================================
- Coverage     75.23%   75.16%   -0.07%     
  Complexity       76       76              
============================================
  Files           589      589              
  Lines         21511    21516       +5     
  Branches       3593     3597       +4     
============================================
- Hits          16184    16173      -11     
- Misses         3369     3380      +11     
- Partials       1958     1963       +5     
Flag Coverage Δ
freebsd 27.70% <0.00%> (-0.02%) ⬇️
linux 32.28% <0.00%> (+<0.01%) ⬆️
macos 32.80% <64.28%> (-0.05%) ⬇️
openbsd 27.02% <0.00%> (+<0.01%) ⬆️
solaris 29.53% <0.00%> (-0.02%) ⬇️
windows 40.93% <0.00%> (-0.04%) ⬇️

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 106e809 into oshi:master Jul 18, 2026
19 checks passed
@dbwiddis
dbwiddis deleted the mac-jna-ffm-fixes branch July 18, 2026 02:49
dbwiddis added a commit that referenced this pull request Jul 18, 2026
* Return empty from ParseUtil.getStringBetween on a single unmatched delimiter

A line containing the delimiter exactly once (e.g. a truncated "key = 'value")
made substring(firstOcc + 1, lastIndexOf) cross its indexes and throw an
uncaught StringIndexOutOfBoundsException through the *nix HAL string parsers.
Return "" when the delimiter is absent or appears only once.

* Throw IllegalArgumentException for mismatched tick arrays in getSystemCpuLoadBetweenTicks

The two-argument overload iterated ticks.length and indexed oldTicks, throwing
ArrayIndexOutOfBoundsException on mismatched lengths where the interface
documents IllegalArgumentException. Validate the lengths up front, matching the
sibling overloads.

* Fix off-by-one bounds guard in Solaris Prtvtoc bytes/sector parsing

The guard checked split.length > 0 but read split[1]; a degenerate header line
would satisfy the guard and throw ArrayIndexOutOfBoundsException. Require length
> 1 to match the accessed index.

* Decode FreeBSD and Solaris utmpx session strings as UTF-8

The JNA Who drivers decoded ut_user/ut_line/ut_host as US-ASCII while the FFM
backend uses UTF-8, so any byte >= 0x80 produced different session strings.
Decode as UTF-8, matching FFM and the macOS alignment from #3473.

* Query native utmpx for Solaris sessions in the FFM backend

SolarisOperatingSystemFFM had no getSessions override, so it fell back to the
who command while the JNA backend reads the native utmpx database, yielding
different session host/time fields. Add getutxent/setutxent/endutxent bindings
and a Solaris utmpx StructLayout to SolarisLibcFunctions, a Solaris WhoFFM
mirroring the JNA driver, and a getSessions override honoring USE_WHO_COMMAND.
The utmpx layout mirrors the JNA SolarisUtmpx struct (validated by the JNA==FFM
comparison test on the illumos CI runner).

* Add CHANGELOG entry for #3484

* Require full-length tick arrays in getSystemCpuLoadBetweenTicks

The two-argument overload only checked the two arrays against each other, so two
equal-but-short arrays passed validation and then threw ArrayIndexOutOfBounds at
ticks[IOWAIT.getIndex()]. Require both arrays to equal TickType.values().length,
matching the single-argument overload.

* Add a shared readFixedWidthString helper for bounded native field decoding

Reading a fixed-width native char field with asSlice(offset,size).getString(0)
requires a NUL within the field; a value that exactly fills the field carries
none, so getString scans past it (IndexOutOfBoundsException). Add
ForeignFunctions.readFixedWidthString, which decodes as UTF-8 up to the first
NUL or the field width (matching JNA's Native.toString), and use it for every
fixed-width field read: the Solaris/FreeBSD/macOS utmpx user, line, and host
fields, and the macOS process pbi_comm name.
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