Skip to content

Fix Windows JNA-backend divergences from the FFM backend - #3478

Merged
dbwiddis merged 8 commits into
oshi:masterfrom
dbwiddis:windows-jna-consistency-fixes
Jul 18, 2026
Merged

dbwiddis merged 8 commits into
oshi:masterfrom
dbwiddis:windows-jna-consistency-fixes

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Jul 18, 2026 •

Copy link
Copy Markdown
Member

The default JNA backend had several Windows bugs where it behaved differently from (and less correctly than) the opt-in FFM backend. Found by an audit of every Windows JNA/FFM twin pair; each fix aligns JNA to the existing FFM behavior. One commit per fix.

Windows runtime behavior is exercised only on CI (JDK 21/25/26 + the JNA/FFM comparison); these could not be validated locally on non-Windows hardware.

Wrong-result / crash fixes

  • WindowsPowerSourceJNA — the BATTERY_SYSTEM_BATTERY && !BATTERY_IS_SHORT_TERM guard wrapped only the capacity/status block; device name, manufacture date, temperature, and batteryFound = true still ran for any battery. A non-system or short-term battery (e.g. a UPS) enumerated before the real system battery was returned with placeholder capacity and stopped the search. Skip such batteries with continue, matching the FFM backend.
  • PerfCounterWildcardQuery — on a PDH collect failure the method returned a populated instance list paired with an empty value map, so the caller skipped the WMI fallback and downstream consumers keyed on the value map (e.g. ProcessPerformanceData) threw an NPE. Return an empty pair per the method's contract.
  • WindowsFileSystemJNA — the results of GetVolumeInformation, GetVolumePathNamesForVolumeName, and GetDiskFreeSpaceEx were ignored, so a volume that could not be stat'd (e.g. an optical/removable drive with no media) was added as a phantom file store with a blank name and zero size. Skip the volume on any failed query.
  • WindowsSoundCardJNA — a driver key missing DriverVersion/ProviderName/DriverDesc threw ERROR_FILE_NOT_FOUND (only ERROR_ACCESS_DENIED was swallowed), aborting the whole enumeration. Read each sub-value through a helper that returns an empty string when absent.

Hardening (edge-path)

  • HkeyPerformanceDataUtilJNA — validate the result after the ERROR_MORE_DATA buffer-grow retry and return null on a hard error rather than an unvalidated buffer.
  • SessionWtsData — a session whose client address can't be queried (some service/console sessions) is recorded with a "::" host instead of being dropped.
  • LogicalProcessorInformation — iterate all group affinities of a NUMA node (groupMasks when groupCount > 1) so a node spanning more than 64 logical processors doesn't drop the processors beyond its first group on large multi-processor-group servers. Falls back to the single groupMask when groupMasks is unpopulated, so single-group systems are unaffected.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved Windows battery detection by skipping UPS and short-term battery devices.
    • Prevented invalid performance-data buffers by verifying success before returning results.
    • Improved Windows volume detection by skipping volumes when native queries fail, avoiding phantom file stores.
    • Fixed sound card enumeration to tolerate missing or non-string registry fields.
    • Improved session reporting by recording sessions with a placeholder host when client address lookup fails.
    • Corrected logical processor/NUMA reporting across multiple processor groups and ensured continued CPUID mapping.

dbwiddis added 6 commits July 17, 2026 20:27
The BATTERY_SYSTEM_BATTERY && !BATTERY_IS_SHORT_TERM guard wrapped only the
capacity/status block; the device-name, manufacture-date, temperature, and
estimated-time reads plus batteryFound = true still ran for any enumerated
battery. On a machine where a non-system or short-term battery (e.g. a UPS)
enumerated before the real system battery, that battery was returned with
placeholder capacity (RELATIVE units, max capacity 1) and the search stopped
before finding the real one.

Skip such batteries with continue, matching WindowsPowerSourceFFM.
When instance enumeration and counter-adds succeeded but PdhCollectQueryData
failed (updateQuery() not > 0), the method returned the populated instance list
paired with an empty value map. The caller sees a non-empty instance list,
returns without falling back to WMI, and downstream consumers that index the
value map by the returned instances (e.g. ProcessPerformanceData keyed on
IDPROCESS) throw a NullPointerException.

Return an empty list and empty map on collect failure, per the method's
contract, so the WMI fallback runs. Matches PerfDataUtilFFM.
The return values of GetVolumeInformation, GetVolumePathNamesForVolumeName, and
GetDiskFreeSpaceEx were ignored, so a volume that could not be stat'd (e.g. an
optical or removable drive with no media, enumerated because of
SEM_FAILCRITICALERRORS) was still added as a phantom OSFileStore with a blank
name and zero size. Check each result and skip the volume on failure, matching
WindowsFileSystemFFM.
A driver key present but missing DriverVersion, ProviderName, or DriverDesc made
registryGetStringValue throw ERROR_FILE_NOT_FOUND, which the catch only swallows
for ERROR_ACCESS_DENIED, so a single incomplete audio-device key aborted the
entire enumeration and the caller got zero sound cards plus an exception. Read
each sub-value through a helper that returns an empty string when absent,
matching WindowsSoundCardFFM.
…aUtilJNA

The ERROR_MORE_DATA grow loop exits on any status other than ERROR_MORE_DATA,
including a hard error on the re-query, after which the method returned the
unvalidated buffer. Add a post-loop ERROR_SUCCESS check that closes the buffer
and returns null on failure, matching HkeyPerformanceDataUtilFFM.
When WTSQuerySessionInformation(WTS_CLIENTADDRESS) failed or returned a null
buffer, the session was dropped entirely, so some service/console sessions were
missing from getSessions(). Record the session with a "::" host instead of
skipping it, matching SessionWtsDataFFM.
@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: 74e5ff24-4fd3-4512-94e1-ee33f0aa47b8

📥 Commits

Reviewing files that changed from the base of the PR and between 835425a and f4ea9f1.

📒 Files selected for processing (2)
  • CHANGELOG.md
  • oshi-core/src/main/java/oshi/driver/windows/LogicalProcessorInformation.java
🚧 Files skipped from review as they are similar to previous changes (2)
  • oshi-core/src/main/java/oshi/driver/windows/LogicalProcessorInformation.java
  • CHANGELOG.md
📜 Recent review details
⏰ Context from checks skipped due to timeout. (14)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 26, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 26, ubuntu-latest
  • GitHub Check: Test JDK 26, windows-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, 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: Test JDK 25, FreeBSD (+ JNA==FFM)
  • GitHub Check: Analyze (java)

📝 Walkthrough

Walkthrough

Windows JNA collection paths now handle multi-group NUMA nodes, filter unsupported batteries, tolerate missing sound-card registry values, preserve sessions with unknown hosts, skip failed volume queries, and validate registry/PDH results. The changelog records these fixes.

Changes

Windows collection paths

Layer / File(s) Summary
NUMA processor-group mapping
oshi-core/src/main/java/oshi/driver/windows/LogicalProcessorInformation.java
NUMA processing iterates all processor-group affinity masks and creates logical processors for each set bit.
Hardware enumeration guards
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java, oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsSoundCardJNA.java
Power-source discovery skips UPS and short-term batteries; sound-card registry reads use empty-string fallbacks for missing or non-string values.
Session and volume failure handling
oshi-core/src/main/java/oshi/driver/windows/registry/SessionWtsData.java, oshi-core/src/main/java/oshi/software/os/windows/WindowsFileSystemJNA.java, CHANGELOG.md
Sessions with failed client-address queries receive "::", failed volume queries are skipped, and the changelog records the fixes.
Performance query validation
oshi-core/src/main/java/oshi/driver/windows/registry/HkeyPerformanceDataUtilJNA.java, oshi-core/src/main/java/oshi/util/platform/windows/PerfCounterWildcardQuery.java
Failed registry and PDH collection results are rejected so callers receive null or empty results for fallback handling.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related PRs

  • oshi/oshi#3125: Also changes Windows battery enumeration to filter UPS and short-term batteries.

Poem

I hop through groups where processors run,
Skip faulty batteries in the sun.
Empty registry strings cause no fright,
Failed volumes vanish from sight.
Sessions keep their hosts unknown—
Robust Windows paths now grow strong!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: aligning Windows JNA backend behavior with the FFM backend.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 38.88889% with 22 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.09%. Comparing base (5aa6519) to head (f4ea9f1).
⚠️ Report is 3 commits behind head on master.

Files with missing lines Patch % Lines
...hardware/platform/windows/WindowsSoundCardJNA.java 0.00% 7 Missing ⚠️
...oshi/software/os/windows/WindowsFileSystemJNA.java 0.00% 3 Missing and 3 partials ⚠️
...hi/driver/windows/LogicalProcessorInformation.java 77.77% 0 Missing and 4 partials ⚠️
...r/windows/registry/HkeyPerformanceDataUtilJNA.java 0.00% 3 Missing and 1 partial ⚠️
...til/platform/windows/PerfCounterWildcardQuery.java 0.00% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3478      +/-   ##
============================================
- Coverage     75.22%   75.09%   -0.13%     
  Complexity       76       76              
============================================
  Files           589      589              
  Lines         21516    21530      +14     
  Branches       3597     3606       +9     
============================================
- Hits          16185    16169      -16     
- Misses         3372     3390      +18     
- Partials       1959     1971      +12     
Flag Coverage Δ
freebsd 27.70% <0.00%> (-0.01%) ⬇️
linux 32.25% <0.00%> (-0.02%) ⬇️
macos 32.78% <0.00%> (-0.08%) ⬇️
openbsd 26.99% <0.00%> (-0.04%) ⬇️
solaris 29.52% <0.00%> (-0.01%) ⬇️
windows 40.91% <38.88%> (-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.

@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.

🧹 Nitpick comments (2)
oshi-core/src/main/java/oshi/driver/windows/LogicalProcessorInformation.java (2)

131-134: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Defensively limit the array iteration to groupCount.

In JNA, variable-length C arrays (like ANYSIZE_ARRAY) are sometimes mapped to Java arrays with a fixed maximum padding length. If node.groupMasks is padded beyond node.groupCount, a for-each loop will iterate over extra elements. Depending on how JNA maps the native memory buffer, reading past the actual struct size could process uninitialized memory or interpret adjacent native structures as GROUP_AFFINITY records.

Defensively bounding the loop by groupCount prevents any potential out-of-bounds mapping issues.

🛡️ Proposed defensive bound
             GROUP_AFFINITY[] nodeGroups = node.groupCount > 1 && node.groupMasks != null && node.groupMasks.length > 0
                     ? node.groupMasks
                     : new GROUP_AFFINITY[] { node.groupMask };
-            for (GROUP_AFFINITY groupAffinity : nodeGroups) {
+            int limit = nodeGroups == node.groupMasks ? Math.min(node.groupCount, nodeGroups.length) : 1;
+            for (int i = 0; i < limit; i++) {
+                GROUP_AFFINITY groupAffinity = nodeGroups[i];
🤖 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-core/src/main/java/oshi/driver/windows/LogicalProcessorInformation.java`
around lines 131 - 134, Update the iteration over nodeGroups in
LogicalProcessorInformation to process no more than node.groupCount entries,
even when node.groupMasks contains padded elements; preserve the existing
single-group fallback and avoid reading beyond the valid native GROUP_AFFINITY
records.

124-124: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rename pkgCpuidMap to coreCpuidMap for clarity.

This map is keyed by coreId (populated on line 146) and is passed to getPhysProcs, which explicitly names its parameter coreCpuidMap. Renaming the local variable avoids confusion with pkgId.

💡 Proposed rename
-        Map<Integer, String> pkgCpuidMap = new HashMap<>();
+        Map<Integer, String> coreCpuidMap = new HashMap<>();
         for (NUMA_NODE_RELATIONSHIP node : numaNodes) {
             // ... inside the loop ...
-                        pkgCpuidMap.put(coreId, processorIdMap.getOrDefault(pkgId, ""));
+                        coreCpuidMap.put(coreId, processorIdMap.getOrDefault(pkgId, ""));
             // ...
         }
-        List<PhysicalProcessor> physProcs = getPhysProcs(cores, coreEfficiencyMap, corePkgMap, pkgCpuidMap);
+        List<PhysicalProcessor> physProcs = getPhysProcs(cores, coreEfficiencyMap, corePkgMap, coreCpuidMap);
🤖 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-core/src/main/java/oshi/driver/windows/LogicalProcessorInformation.java`
at line 124, Rename the local map variable pkgCpuidMap to coreCpuidMap in
LogicalProcessorInformation, updating its declaration and every use, including
the argument passed to getPhysProcs. Keep the map’s behavior unchanged.
🤖 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.

Nitpick comments:
In
`@oshi-core/src/main/java/oshi/driver/windows/LogicalProcessorInformation.java`:
- Around line 131-134: Update the iteration over nodeGroups in
LogicalProcessorInformation to process no more than node.groupCount entries,
even when node.groupMasks contains padded elements; preserve the existing
single-group fallback and avoid reading beyond the valid native GROUP_AFFINITY
records.
- Line 124: Rename the local map variable pkgCpuidMap to coreCpuidMap in
LogicalProcessorInformation, updating its declaration and every use, including
the argument passed to getPhysProcs. Keep the map’s behavior unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 00e702e4-c33e-499c-8331-93dfe4ff9e06

📥 Commits

Reviewing files that changed from the base of the PR and between f65b791 and 835425a.

📒 Files selected for processing (8)
  • CHANGELOG.md
  • oshi-core/src/main/java/oshi/driver/windows/LogicalProcessorInformation.java
  • oshi-core/src/main/java/oshi/driver/windows/registry/HkeyPerformanceDataUtilJNA.java
  • oshi-core/src/main/java/oshi/driver/windows/registry/SessionWtsData.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsSoundCardJNA.java
  • oshi-core/src/main/java/oshi/software/os/windows/WindowsFileSystemJNA.java
  • oshi-core/src/main/java/oshi/util/platform/windows/PerfCounterWildcardQuery.java
📜 Review details
⏰ Context from checks skipped due to timeout. (12)
  • GitHub Check: Test JDK 21, ubuntu-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 26, windows-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 26, macos-latest
  • 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 (3)
📚 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/windows/registry/SessionWtsData.java
  • oshi-core/src/main/java/oshi/driver/windows/LogicalProcessorInformation.java
  • oshi-core/src/main/java/oshi/software/os/windows/WindowsFileSystemJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsSoundCardJNA.java
  • oshi-core/src/main/java/oshi/driver/windows/registry/HkeyPerformanceDataUtilJNA.java
  • oshi-core/src/main/java/oshi/util/platform/windows/PerfCounterWildcardQuery.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.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/software/os/windows/WindowsFileSystemJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsSoundCardJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java
📚 Learning: 2026-04-08T00:58:07.212Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3125
File: oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java:131-133
Timestamp: 2026-04-08T00:58:07.212Z
Learning: Do not flag `getPowerSources()` as incorrect when it returns a singleton list that wraps `getPowerSource("System Battery")` and/or short-circuits the enumeration after the first eligible battery pack in the Windows power source JNA/FFM implementations. This is intentional for longstanding JNA behavior; a refactor to support zero-or-more batteries is planned later, so the current single-battery behavior should be treated as by-design rather than a bug.

Applied to files:

  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java
🔇 Additional comments (7)
oshi-core/src/main/java/oshi/driver/windows/registry/SessionWtsData.java (1)

105-115: LGTM!

oshi-core/src/main/java/oshi/software/os/windows/WindowsFileSystemJNA.java (1)

164-172: LGTM!

Also applies to: 185-187

CHANGELOG.md (1)

11-11: LGTM!

oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java (1)

156-208: LGTM!

oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsSoundCardJNA.java (1)

54-60: LGTM!

Also applies to: 72-78

oshi-core/src/main/java/oshi/driver/windows/registry/HkeyPerformanceDataUtilJNA.java (1)

176-182: LGTM!

oshi-core/src/main/java/oshi/util/platform/windows/PerfCounterWildcardQuery.java (1)

192-196: LGTM!

dbwiddis added 2 commits July 17, 2026 21:00
…ation

The NUMA-node loop read only the single groupMask union member, so a NUMA node
spanning more than 64 logical processors (which reports one GROUP_AFFINITY per
group in groupMasks with groupCount > 1) dropped every processor beyond the
first group on large multi-processor-group servers. Iterate all group affinities
like the existing package handling and LogicalProcessorInformationFFM, falling
back to the single groupMask when groupMasks is unpopulated so single-group
systems are unaffected.
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