Repository navigation
Fix SonarCloud bugs, blockers, and string duplication - #3192
Conversation
Bugs (integer overflow in FFM code): - Use long arithmetic for MemorySegment offsets in LogicalProcessorInformationFFM (13 issues) - Use long literals in SessionWtsDataFFM constant expressions - Use long offset in WindowsCentralProcessorFFM frequency parsing - Use long in WindowsNetworkIfFFM alias slice size - Use long in Advapi32UtilFFM buffer allocation Blockers (missing test assertions): - Add assertDoesNotThrow to IOReportClientTest.testCloseIsIdempotent - Add futures size assertion to GpuStatsTest.testConcurrentAccessDoesNotThrow String duplication (S1192): - Extract Temperature/Voltage constants in WindowsSensorsFFM - Extract GPU_CORE constant in WindowsGpuStatsFFM - Extract WMI_HANDLER_NULL constant in Win32ProcessorFFM and Win32ProcessorJNA Signed-off-by: Daniel Widdis <[email protected]> Signed-off-by: Dan Widdis <[email protected]>
📝 WalkthroughWalkthroughThis PR converts integer-based offset and buffer size calculations to long-based arithmetic throughout Windows FFM driver classes to prevent potential integer overflow, extracts hardcoded strings into named constants for maintainability and consistency, and enhances test assertions for better validation coverage. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches✨ Simplify code
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 |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
oshi-core-ffm/src/main/java/oshi/util/platform/windows/Advapi32UtilFFM.java (1)
290-299:⚠️ Potential issue | 🟡 MinorCarry the long-sized buffer length through to
lpcbData.Line 295 now avoids int overflow for allocation, but Line 297 still computes
size + 4as anintbefore passing the buffer size back intoRegQueryValueEx. Keep one checkedlongsize and cast only after validating it fits the Java-sideintstorage.Proposed fix
for (int attempt = 0; attempt < 3 && rc != ERROR_SUCCESS; attempt++) { // Allocate extra for double-null terminator - data = arena.allocate(size + 4L); + long dataSize = Integer.toUnsignedLong(size) + 4L; + if (dataSize > Integer.MAX_VALUE) { + throw new IllegalStateException("Registry value too large: " + dataSize + " bytes"); + } + data = arena.allocate(dataSize); data.fill((byte) 0); - lpcbData.set(JAVA_INT, 0, size + 4); + lpcbData.set(JAVA_INT, 0, (int) dataSize);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@oshi-core-ffm/src/main/java/oshi/util/platform/windows/Advapi32UtilFFM.java` around lines 290 - 299, The code currently allocates with a long-sized buffer (size + 4L) via arena.allocate but then writes size + 4 back into lpcbData as an int before calling RegQueryValueEx; preserve the checked long buffer length (e.g., use a long variable like bufferLen = size + 4L), validate that bufferLen <= Integer.MAX_VALUE, then set lpcbData.set(JAVA_INT, 0, (int)bufferLen) only after validation and pass that int to RegQueryValueEx; adjust the loop around RegQueryValueEx, the size variable, lpcbData writes, and the arena.allocate call (references: lpcbData, size, bufferLen, arena.allocate, RegQueryValueEx) so we never truncate a long buffer length into an int before validation.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Outside diff comments:
In `@oshi-core-ffm/src/main/java/oshi/util/platform/windows/Advapi32UtilFFM.java`:
- Around line 290-299: The code currently allocates with a long-sized buffer
(size + 4L) via arena.allocate but then writes size + 4 back into lpcbData as an
int before calling RegQueryValueEx; preserve the checked long buffer length
(e.g., use a long variable like bufferLen = size + 4L), validate that bufferLen
<= Integer.MAX_VALUE, then set lpcbData.set(JAVA_INT, 0, (int)bufferLen) only
after validation and pass that int to RegQueryValueEx; adjust the loop around
RegQueryValueEx, the size variable, lpcbData writes, and the arena.allocate call
(references: lpcbData, size, bufferLen, arena.allocate, RegQueryValueEx) so we
never truncate a long buffer length into an int before validation.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: ee4cc743-6db8-4a49-af6b-242a483d0e58
📒 Files selected for processing (11)
oshi-core-ffm/src/main/java/oshi/driver/windows/LogicalProcessorInformationFFM.javaoshi-core-ffm/src/main/java/oshi/driver/windows/registry/SessionWtsDataFFM.javaoshi-core-ffm/src/main/java/oshi/driver/windows/wmi/Win32ProcessorFFM.javaoshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsCentralProcessorFFM.javaoshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsGpuStatsFFM.javaoshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsNetworkIfFFM.javaoshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsSensorsFFM.javaoshi-core-ffm/src/main/java/oshi/util/platform/windows/Advapi32UtilFFM.javaoshi-core/src/main/java/oshi/driver/windows/wmi/Win32ProcessorJNA.javaoshi-core/src/test/java/oshi/driver/mac/IOReportClientTest.javaoshi-core/src/test/java/oshi/hardware/platform/shared/GpuStatsTest.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Test JDK 21, windows-latest
- GitHub Check: Test JDK 11, macos-latest
- GitHub Check: Analyze (java)
- GitHub Check: Test JDK 11, windows-latest
- GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
- GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
- GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
- GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
- GitHub Check: Test JDK 21, macos-latest
🧰 Additional context used
🧠 Learnings (10)
📓 Common learnings
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3168
File: oshi-core-java25/src/main/java/oshi/ffm/windows/PdhFFM.java:0-0
Timestamp: 2026-04-17T23:43:33.461Z
Learning: In `oshi-core-java25/src/main/java/oshi/ffm/windows/PdhFFM.java`, the `PDH_RAW_COUNTER_LAYOUT` Java FFM struct layout must place `FirstValue` at byte offset 16 (not 12). The native MSVC compiler inserts 4 bytes of implicit alignment padding before the `LONGLONG FirstValue` field (after CStatus=4 bytes + FILETIME TimeStamp=8 bytes = 12 bytes), because LONGLONG requires 8-byte alignment. The total struct size is 40 bytes (with trailing padding). Do not use JAVA_LONG_UNALIGNED without explicit padding here, as that incorrectly places FirstValue at offset 12 and causes reads of garbage counter values.
📚 Learning: 2026-04-18T03:18:03.725Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3170
File: oshi-benchmark/src/test/java/oshi/comparison/PerfmonComparisonTest.java:177-183
Timestamp: 2026-04-18T03:18:03.725Z
Learning: In `oshi-benchmark/src/test/java/oshi/comparison/PerfmonComparisonTest.java`, GPU engine PDH instance counts (from `GpuInformationJNA.queryGpuEngineCounters()` / `GpuInformationFFM.queryGpuEngineCounters()`) are highly volatile — counts can differ dramatically (e.g., 53 vs 40) even between queries taken milliseconds apart. Do not assert instance count equality or exact instance list matching between JNA and FFM results. The only reliable assertion is that both are empty or both are non-empty (`assertThat(ffm.getA().isEmpty()).isEqualTo(jna.getA().isEmpty())`).
Applied to files:
oshi-core/src/test/java/oshi/hardware/platform/shared/GpuStatsTest.javaoshi-core/src/test/java/oshi/driver/mac/IOReportClientTest.javaoshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsGpuStatsFFM.java
📚 Learning: 2026-04-11T05:51:52.684Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3139
File: oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxGpuStatsFFM.java:36-58
Timestamp: 2026-04-11T05:51:52.684Z
Learning: In OSHI's `LinuxGpuStats` (oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxGpuStats.java), the abstract `nvml*` methods (nvmlGetVramUsed, nvmlGetCoreClockMhz, nvmlGetMemoryClockMhz, nvmlGetTemperature, nvmlGetPowerDraw, nvmlGetFanSpeedPercent) are contractually expected to return `-1` (long or double) on failure. The base class applies `if (val >= 0)` guards before using any NVML result and falls through to sysfs/hwmon paths when negative. Subclasses (LinuxGpuStatsJNA, LinuxGpuStatsFFM) correctly pass through the -1 sentinel unchanged — do not flag this as a missing clamp or contract violation.
Applied to files:
oshi-core/src/test/java/oshi/hardware/platform/shared/GpuStatsTest.javaoshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsGpuStatsFFM.java
📚 Learning: 2026-04-17T23:43:33.461Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3168
File: oshi-core-java25/src/main/java/oshi/ffm/windows/PdhFFM.java:0-0
Timestamp: 2026-04-17T23:43:33.461Z
Learning: In `oshi-core-java25/src/main/java/oshi/ffm/windows/PdhFFM.java`, the `PDH_RAW_COUNTER_LAYOUT` Java FFM struct layout must place `FirstValue` at byte offset 16 (not 12). The native MSVC compiler inserts 4 bytes of implicit alignment padding before the `LONGLONG FirstValue` field (after CStatus=4 bytes + FILETIME TimeStamp=8 bytes = 12 bytes), because LONGLONG requires 8-byte alignment. The total struct size is 40 bytes (with trailing padding). Do not use JAVA_LONG_UNALIGNED without explicit padding here, as that incorrectly places FirstValue at offset 12 and causes reads of garbage counter values.
Applied to files:
oshi-core-ffm/src/main/java/oshi/util/platform/windows/Advapi32UtilFFM.javaoshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsNetworkIfFFM.javaoshi-core-ffm/src/main/java/oshi/driver/windows/registry/SessionWtsDataFFM.javaoshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsCentralProcessorFFM.javaoshi-core-ffm/src/main/java/oshi/driver/windows/LogicalProcessorInformationFFM.java
📚 Learning: 2026-04-10T22:44:36.786Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3136
File: oshi-core-java25/src/main/java/oshi/software/os/linux/LinuxOperatingSystemFFM.java:46-53
Timestamp: 2026-04-10T22:44:36.786Z
Learning: In OSHI's `AuxvFFM.queryAuxv()` (oshi-core-java25/src/main/java/oshi/driver/linux/proc/AuxvFFM.java), the do-while loop is safe even when `/proc/self/auxv` cannot be read: `FileUtil.readAllBytesAsBuffer` returns an empty ByteBuffer on failure, and `FileUtil.readLongFromBuffer`/`readIntFromBuffer` return 0L when reading past the buffer limit. This 0L equals AT_NULL, causing the loop to exit immediately with an empty map, which triggers the `getconf`/hardcoded-default fallback in callers like `LinuxOperatingSystemFFM`. Do not flag this do-while loop or the static initializer that calls `AuxvFFM.queryAuxv()` as unsafe.
Applied to files:
oshi-core-ffm/src/main/java/oshi/util/platform/windows/Advapi32UtilFFM.javaoshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsCentralProcessorFFM.javaoshi-core-ffm/src/main/java/oshi/driver/windows/LogicalProcessorInformationFFM.java
📚 Learning: 2026-04-19T01:28:43.529Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3174
File: oshi-benchmark/src/test/java/oshi/comparison/WmiComparisonTest.java:237-257
Timestamp: 2026-04-19T01:28:43.529Z
Learning: In `oshi-benchmark/src/test/java/oshi/comparison/WmiComparisonTest.java`, the WMI comparison tests (e.g., `testProcessor`) intentionally validate only index 0 and a few representative fields per WMI data type (String, uint16, uint32, uint64). Exhaustive row-by-row comparison is deliberately avoided for numerically heavy multi-row tables. The design rationale is: matching row counts + a few selected fields covering each data type is sufficient to verify JNA vs FFM driver parity. Do not suggest looping over all rows for these tests.
Applied to files:
oshi-core-ffm/src/main/java/oshi/driver/windows/registry/SessionWtsDataFFM.javaoshi-core-ffm/src/main/java/oshi/driver/windows/wmi/Win32ProcessorFFM.javaoshi-core/src/main/java/oshi/driver/windows/wmi/Win32ProcessorJNA.java
📚 Learning: 2026-04-18T22:53:49.248Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3173
File: oshi-core-java25/src/main/java/oshi/util/platform/windows/WmiQueryHandlerFFM.java:107-193
Timestamp: 2026-04-18T22:53:49.248Z
Learning: In OSHI's `WmiQueryHandlerFFM` (oshi-core-java25) and the JNA `WmiQueryHandler` (oshi-core), the `failedWmiClassNames` cache intentionally keys failures by WMI class name only (not namespace). This is a pre-existing, accepted pattern shared between both implementations. Do not flag this as a bug in future reviews — the project maintainer (dbwiddis) confirmed it does not impact callers and the added complexity of a composite namespace+class key is not warranted.
Applied to files:
oshi-core-ffm/src/main/java/oshi/driver/windows/registry/SessionWtsDataFFM.javaoshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsCentralProcessorFFM.javaoshi-core-ffm/src/main/java/oshi/driver/windows/wmi/Win32ProcessorFFM.javaoshi-core/src/main/java/oshi/driver/windows/wmi/Win32ProcessorJNA.java
📚 Learning: 2026-04-12T19:34:59.050Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:34:59.050Z
Learning: The counterintuitive naming of `PhysicalProcessor.getEfficiency()` / `EfficiencyClass` in OSHI (where a higher value means MORE performance and LESS efficiency, so P-cores get higher values than E-cores) is intentionally inherited from Microsoft's `PROCESSOR_RELATIONSHIP.EfficiencyClass` Win32 API: "A core with a higher value for the efficiency class has intrinsically greater performance and less efficiency." OSHI follows this same convention for cross-platform consistency. Do not flag P-cores being assigned higher efficiency values as a bug.
Applied to files:
oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsCentralProcessorFFM.javaoshi-core/src/main/java/oshi/driver/windows/wmi/Win32ProcessorJNA.javaoshi-core-ffm/src/main/java/oshi/driver/windows/LogicalProcessorInformationFFM.java
📚 Learning: 2026-04-08T00:58:10.736Z
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:10.736Z
Learning: In `oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java` and `oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java`, the `getPowerSources()` method intentionally returns a singleton list wrapping a single `getPowerSource("System Battery")` call, and the enumeration loop short-circuits after the first eligible battery pack. This matches the longstanding JNA behavior and is not a bug. A broader refactor to support zero-or-more batteries across both implementations is planned for a later date. Do not flag this as an issue.
Applied to files:
oshi-core/src/main/java/oshi/driver/windows/wmi/Win32ProcessorJNA.java
📚 Learning: 2026-04-12T19:22:14.417Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:14.417Z
Learning: In OSHI's `PhysicalProcessor.getEfficiency()` API (CentralProcessor interface), a higher efficiency class value means GREATER performance and LESS efficiency (counterintuitive naming). P-cores (performance cores) get a higher value (e.g., 1), and E-cores (efficiency cores) get a lower value (e.g., 0). This is documented in the CentralProcessor javadoc. Do not flag code that assigns higher efficiency values to ARM_P_CORES or Intel P-cores as a bug.
Applied to files:
oshi-core-ffm/src/main/java/oshi/driver/windows/LogicalProcessorInformationFFM.java
🔇 Additional comments (14)
oshi-core/src/test/java/oshi/driver/mac/IOReportClientTest.java (1)
12-12: LGTM — the no-throw expectation is now explicit.Nice targeted fix for the SonarCloud blocker: the second
close()call is asserted without changing the test’s lifecycle behavior.Also applies to: 118-118
oshi-core/src/test/java/oshi/hardware/platform/shared/GpuStatsTest.java (1)
193-193: Looks good — this closes the assertion gap cleanly.The new check is deterministic here because the test creates exactly one task per
threadsiteration and then verifies the returnedFuturecount after all tasks complete.oshi-core/src/main/java/oshi/driver/windows/wmi/Win32ProcessorJNA.java (1)
25-25: Looks good — the duplicated WMI null message is centralized cleanly.The
requireNonNullbehavior is unchanged, and the JNA-specific message remains clear.Also applies to: 30-42
oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsNetworkIfFFM.java (1)
167-169: Looks good — the alias slice now uses long byte-length arithmetic.The
WCHAR[257]capacity is unchanged, and the FFM API receives a long-sized length directly.oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsSensorsFFM.java (1)
40-41: Looks good — sensor string reuse is clearer without changing behavior.The extracted
TEMPERATUREandVOLTAGEconstants are applied consistently across the OHM and LHM paths.Also applies to: 65-85, 196-219
oshi-core-ffm/src/main/java/oshi/driver/windows/registry/SessionWtsDataFFM.java (1)
56-63: Looks good — the WTSINFO offsets now stay in long arithmetic.The computed layout offsets remain the same, while avoiding intermediate int multiplication.
oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsGpuStatsFFM.java (1)
35-35: Looks good —GPU_COREremoves duplication without touching GPU fallback semantics.The LHM comparisons and fallback sensor lookups still use the same
"GPU Core"value.Also applies to: 113-120, 177-193, 220-238
oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsCentralProcessorFFM.java (1)
124-128: Looks good — the FFM buffer size and per-processor offsets now use long arithmetic.The registry buffer capacity and
ProcessorPowerInformationfield offsets remain unchanged.Also applies to: 267-286
oshi-core-ffm/src/main/java/oshi/driver/windows/wmi/Win32ProcessorFFM.java (1)
24-24: Looks good — the FFM WMI null message is centralized consistently.The query construction and
queryWMIcalls are unchanged.Also applies to: 29-41
oshi-core-ffm/src/main/java/oshi/driver/windows/LogicalProcessorInformationFFM.java (5)
86-108: LGTM — offset arithmetic is widened before FFM access.Using
long offsetandoffset + 4Lkeeps the byte-offset calculation in the same width expected byMemorySegment, which addresses the overflow risk cleanly.
157-165: LGTM — processor-core offsets remain correct withlongarithmetic.The
groupread atdataOffset + 32is equivalent to theGroupMaskbase plus the 8-byte mask field, and the widened offsets avoid pre-access overflow.
167-180: LGTM — NUMA affinity traversal now uses widened stride math.The
16Lstride keeps multi-group affinity offsets inlongarithmetic before reading from the segment.
182-192: LGTM — cache parsing is consistently widened.The fixed cache-field offsets now derive from a
long dataOffset, matching the FFM accessor contract without changing the parsed layout.
194-211: LGTM — package group-mask offsets are safely widened.The
gmOffsetcalculation now avoidsintoverflow for repeatedGROUP_AFFINITYentries, and the fallback path still useslong-based offsets.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #3192 +/- ##
==========================================
+ Coverage 57.98% 58.10% +0.11%
==========================================
Files 421 421
Lines 20272 20263 -9
Branches 3563 3563
==========================================
+ Hits 11755 11774 +19
+ Misses 6750 6729 -21
+ Partials 1767 1760 -7
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Description
Addresses SonarCloud findings that are blocking the quality gate.
Bugs — integer overflow in FFM offset arithmetic (21 of 22 bugs)
All FFM code that computes
MemorySegmentoffsets was usingintarithmetic before passing to methods that takelong. While these buffers are small enough that overflow is unlikely in practice, the fix is trivial and eliminates the SonarCloud quality gate failure.baseOffset/dataOffset/affinityOffset/gmOffsetfrominttolongacross all four parse methods and the main loop (13 issues)Lsuffix to constant expressionslong, addedLto allocation sizeLto alias slice sizeLto buffer allocationThe remaining bug (thread-safety of
WindowsCentralProcessor.utilityBaseMultiplier) is a false positive — the field is only accessed from asynchronizedmethod.Blockers — missing test assertions (2 of 3)
assertDoesNotThrowassertThat(futures.size(), is(threads))to concurrent testThe remaining blocker (
WindowsForeignFunctions.checkSuccessalways returns same value) is a false positive — the method returns the inputrcwhich varies.String duplication — extracted constants (5 of 46)
Focused on the critical-severity duplications:
WindowsSensorsFFM:TEMPERATUREandVOLTAGEconstantsWindowsGpuStatsFFM:GPU_COREconstantWin32ProcessorFFM/Win32ProcessorJNA:WMI_HANDLER_NULLconstantTesting
Compiles cleanly across all modules. Spotless clean.
Summary by CodeRabbit
Release Notes
Bug Fixes
Tests
Refactor