Repository navigation
Fix Windows JNA-backend divergences from the FFM backend - #3478
Conversation
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.
|
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 (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📜 Recent review details⏰ Context from checks skipped due to timeout. (14)
📝 WalkthroughWalkthroughWindows 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. ChangesWindows collection paths
Estimated code review effort: 3 (Moderate) | ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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 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
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:
|
There was a problem hiding this comment.
🧹 Nitpick comments (2)
oshi-core/src/main/java/oshi/driver/windows/LogicalProcessorInformation.java (2)
131-134: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winDefensively 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. Ifnode.groupMasksis padded beyondnode.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 asGROUP_AFFINITYrecords.Defensively bounding the loop by
groupCountprevents 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 valueRename
pkgCpuidMaptocoreCpuidMapfor clarity.This map is keyed by
coreId(populated on line 146) and is passed togetPhysProcs, which explicitly names its parametercoreCpuidMap. Renaming the local variable avoids confusion withpkgId.💡 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
📒 Files selected for processing (8)
CHANGELOG.mdoshi-core/src/main/java/oshi/driver/windows/LogicalProcessorInformation.javaoshi-core/src/main/java/oshi/driver/windows/registry/HkeyPerformanceDataUtilJNA.javaoshi-core/src/main/java/oshi/driver/windows/registry/SessionWtsData.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsSoundCardJNA.javaoshi-core/src/main/java/oshi/software/os/windows/WindowsFileSystemJNA.javaoshi-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.javaoshi-core/src/main/java/oshi/driver/windows/LogicalProcessorInformation.javaoshi-core/src/main/java/oshi/software/os/windows/WindowsFileSystemJNA.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsSoundCardJNA.javaoshi-core/src/main/java/oshi/driver/windows/registry/HkeyPerformanceDataUtilJNA.javaoshi-core/src/main/java/oshi/util/platform/windows/PerfCounterWildcardQuery.javaoshi-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.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsSoundCardJNA.javaoshi-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!
…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.
835425a to
f4ea9f1
Compare
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— theBATTERY_SYSTEM_BATTERY && !BATTERY_IS_SHORT_TERMguard wrapped only the capacity/status block; device name, manufacture date, temperature, andbatteryFound = truestill 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 withcontinue, 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 ofGetVolumeInformation,GetVolumePathNamesForVolumeName, andGetDiskFreeSpaceExwere 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 missingDriverVersion/ProviderName/DriverDescthrewERROR_FILE_NOT_FOUND(onlyERROR_ACCESS_DENIEDwas 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 theERROR_MORE_DATAbuffer-grow retry and returnnullon 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 (groupMaskswhengroupCount > 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 singlegroupMaskwhengroupMasksis unpopulated, so single-group systems are unaffected.🤖 Generated with Claude Code
Summary by CodeRabbit