Repository navigation
Fix macOS JNA-backend divergences from the FFM backend - #3473
Conversation
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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (11)
📜 Recent review details⏰ Context from checks skipped due to timeout. (9)
🧰 Additional context used🧠 Learnings (2)📚 Learning: 2026-07-06T19:25:59.225ZApplied to files:
📚 Learning: 2026-04-06T04:45:47.644ZApplied to files:
🪛 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. (redos-non-literal-regex-java) 🔇 Additional comments (14)
📝 WalkthroughWalkthroughmacOS 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. ChangesmacOS native handling
Estimated code review effort: 2 (Simple) | ~10 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
Codecov Report❌ Patch coverage is ❌ 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
* 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.
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
SmcUtilSP78 — 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— returnfalsefromupdateDiskStatswhen no matching IOMedia device is found (was reporting false success).MacFileSystemJNA— keep the mount-derived volume name whenDAVolumeNameis absent (was clobbering it to null).Null/bounds guards (each would
NPE/misbehave on an edge native result; FFM already guarded them)MacNetworkIfJNAnull localized display name → fall back to the BSD interface name.MacNetworkParamsJNAnullai_canonname→ empty domain name.MacDisplayJNAzero-length EDID → skip (was producing a bogus extraDisplay).MacPowerSourceJNAnull power-source list → empty list.Plus a non-behavioral tidy:
MacGpuStatsJNApre-computes the normalized card name in its constructor, mirroring the FFM twin.🤖 Generated with Claude Code
Summary by CodeRabbit