Skip to content

Bound the varargs test helpers on the last index they read - #3560

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:codeql-varargs-bounds
Aug 2, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:codeql-varargs-bounds

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Aug 2, 2026 •

Copy link
Copy Markdown
Member

CodeQL Code Quality reported seven java/index-out-of-bounds findings (severity error) across the two test files added in #3543 and #3546:

  • MacGpuStatsTest.java:117
  • WindowsLogicalVolumeGroupTest.java:85, :97 (×2), :108, :109, :120

Each is the same shape. A private varargs helper walks its arguments in fixed-size groups, striding by two or three, but bounds the loop on the first index of the group rather than the last. Reading namesAndIds[i + 1] under a loop guarded only by i < namesAndIds.length runs off the end whenever the caller passes a partial group.

Unlike the useless-null-check and dereferenced-value-may-be-null findings on these files, this one is not a false positive. Every call site today passes a complete multiple, so nothing can throw as written, but the helpers make no such guarantee and the finding will resurface each time the files move.

Bounding each loop on the last index it reads is what CodeQL's range analysis needs to see, and it turns a would-be ArrayIndexOutOfBoundsException into one fewer row for a caller that miscounts — which a test's own assertions will catch immediately.

The two production stride loops were checked and left alone:

  • ParseUtil.hexStringToByteArray already rejects odd-length input with an explicit (len & 0x1) != 0 guard.
  • HkeyPerformanceDataUtil.buildCounterIndexMap starts at i = 1 and reads backwards to i - 1, so both indices are always in range.

Neither was flagged, and both are correct as written.

Test-only, so no CHANGELOG entry.

Full gate green on oshi-common: spotless, checkstyle, install, forbiddenapis, javadoc, and 1264 tests successful / 0 failed.

Summary by CodeRabbit

  • Tests
    • Improved test fixture handling for incomplete input data.
    • Prevented errors when trailing or unmatched test parameters are provided.
    • Added safer handling for incomplete storage and graphics test scenarios.

CodeQL Code Quality reported seven java/index-out-of-bounds findings
(severity error) across the two test files added in #3543 and #3546.

Each finding is the same shape: a private varargs helper walks its
arguments in fixed-size groups, striding by two or three, but bounds the
loop on the first index of the group rather than the last. Reading
namesAndIds[i + 1] under a loop guarded only by i < namesAndIds.length
runs off the end whenever the caller passes a partial group.

Unlike the useless-null-check and dereferenced-value-may-be-null
findings on these files, this one is not a false positive. Every call
site today passes a complete multiple, so nothing can throw as written,
but the helpers make no such guarantee and the finding will resurface
each time the files move.

Bounding each loop on the last index it reads is what CodeQL's range
analysis needs to see, and it turns a would-be
ArrayIndexOutOfBoundsException into one fewer row for a caller that
miscounts -- which a test's own assertions will catch immediately.

The two production stride loops were checked and left alone:
ParseUtil.hexStringToByteArray already rejects odd-length input with an
explicit (len & 0x1) != 0 guard, and
HkeyPerformanceDataUtil.buildCounterIndexMap starts at i = 1 and reads
backwards to i - 1, so both indices are always in range. Neither was
flagged.

Test-only, so no CHANGELOG entry.
@coderabbitai

coderabbitai Bot commented Aug 2, 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 Plus

Run ID: b2315994-e9a4-47a2-80be-d849e2ca970d

📥 Commits

Reviewing files that changed from the base of the PR and between a1c9bb0 and 1c5e9ad.

📒 Files selected for processing (2)
  • oshi-common/src/test/java/oshi/hardware/common/platform/mac/MacGpuStatsTest.java
  • oshi-common/src/test/java/oshi/hardware/common/platform/windows/WindowsLogicalVolumeGroupTest.java
📜 Recent review details
⏰ Context from checks skipped due to timeout. (8)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 21, ubuntu-latest
  • GitHub Check: Test JDK 26, ubuntu-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🔇 Additional comments (2)
oshi-common/src/test/java/oshi/hardware/common/platform/mac/MacGpuStatsTest.java (1)

114-118: LGTM!

oshi-common/src/test/java/oshi/hardware/common/platform/windows/WindowsLogicalVolumeGroupTest.java (1)

80-84: LGTM!

Also applies to: 95-95, 107-107, 119-119


📝 Walkthrough

Walkthrough

Test fixture helpers now ignore incomplete trailing varargs input. Mac GPU statistics require complete key/value pairs. Windows volume fixtures require complete pair or triple records.

Changes

Varargs fixture safety

Layer / File(s) Summary
Mac GPU fixture parsing
oshi-common/src/test/java/oshi/hardware/common/platform/mac/MacGpuStatsTest.java
The stats helper processes complete key/value pairs only.
Windows volume fixture parsing
oshi-common/src/test/java/oshi/hardware/common/platform/windows/WindowsLogicalVolumeGroupTest.java
Pool and pool-to-disk helpers require pairs. Virtual-disk and physical-disk helpers require complete triples. Incomplete trailing arguments are ignored.

Estimated code review effort: 1 (Trivial) | ~5 minutes

Possibly related PRs

  • oshi/oshi#3543: Updates the related MacGpuStatsTest helper and hardens varargs fixture parsing.

Poem

A bunny checks each pair in line,
And triples must be complete and fine.
Stray tails no longer cause a fright,
The test fixtures hop through right.
>^.^<

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.86% 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 clearly and concisely describes the varargs loop-bound changes in the test helpers.
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 Aug 2, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.34%. Comparing base (a1c9bb0) to head (1c5e9ad).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##             master    #3560   +/-   ##
=========================================
  Coverage     79.34%   79.34%           
  Complexity     3790     3790           
=========================================
  Files           706      706           
  Lines         24264    24264           
  Branches       4057     4057           
=========================================
  Hits          19253    19253           
- Misses         2821     2824    +3     
+ Partials       2190     2187    -3     
Flag Coverage Δ
linux 36.79% <ø> (+0.04%) ⬆️
macos 37.67% <ø> (-0.06%) ⬇️
windows 44.60% <ø> (-0.03%) ⬇️

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 a50c1cc into oshi:master Aug 2, 2026
17 checks passed
@dbwiddis
dbwiddis deleted the codeql-varargs-bounds branch August 2, 2026 15:47
dbwiddis added a commit that referenced this pull request Aug 23, 2026
… the stub-test log noise (#3706)

* Report an absent SMC once, and stop stub tests logging on every platform

Two unrelated sources of log noise, both surfaced by reading a Windows CI
log and finding macOS and Linux warnings in it.

The production bug is in SmcUtil. Every temperature, fan speed and voltage
query opens its own SMC connection, so when the AppleSMC service is absent
the failure was reported at ERROR several times per sampling interval, for
the life of the process. That is the normal state on a virtual machine,
which does not virtualize the SMC.

SmcOpenFailure latches each reason a connection could not be opened: one
instance per backend holding that backend's logger, so the message is still
attributed to SmcUtil or SmcUtilFFM rather than to the helper. The first
occurrence is logged at a level that reflects what it means -- WARN for an
absent service, which is a degradation OSHI recovers from by reporting no
sensors, and ERROR for a service that is present but will not open -- and
every later occurrence at DEBUG. The absent-service message now also names
the likely cause. Both twins call it, and it covers the FFM-only null
connect handle case, which repeated the same way.

Note that this is not an Apple Silicon condition: IOKitUtil.getMatchingService
("AppleSMC") does succeed on real Apple Silicon, matching the
AppleSMCKeysEndpoint subclass, so nothing here is gated on the architecture.

The remaining thirteen lines were oshi-common stub tests, not platform
probes. MacCentralProcessor, MacGpuStats and LinuxCentralProcessor are
tested with the native boundary overridden, so nothing reaches the host and
the warnings appear identically on all eight CI jobs. Each is the correct
production output for the degraded path the test asks for, so an @EnabledOnOs
gate would delete the test from seven jobs and still print on the eighth.
The three loggers are lowered to ERROR in oshi-common's test configuration
instead, which is the mechanism that file already uses for oshi.util. The
keys are deliberately oshi-common only: oshi-core and oshi-core-ffm run the
same classes against the real platform, where the warning means something.

A full clean reactor build now emits one library log line, the deliberate
LogUtilTest smoke test against the real SLF4J binding.

* Fix two CodeQL Code Quality findings in MacCentralProcessorTest

java/index-out-of-bounds on the accClusters varargs helper is real, and the
same shape as the seven fixed in #3560: the loop strides by two but was
bounded on the first index of the pair while the body reads i + 1, so an
odd-length argument list runs off both the argument array and the array
being built. Bounded on the last index the body reads.

java/useless-null-check on the stub's sysctlInts and sysctlLongs guards has
now been re-minted four times, and has been dismissed each time because the
guards are load-bearing: AbstractCentralProcessor's constructor calls the
overridable sysctlInt() before any subclass field initializer runs, so the
maps really are null during construction. Fixing the cause instead of
dismissing again. The tell was already in the file -- sysctlStrings has no
field initializer and has never been flagged, while the two carrying
= new HashMap<>() always are, because CodeQL reasons that the initializer is
non-null without modelling the initialization order.

Dropping those two initializers and assigning both maps in the constructor
body, where sysctlStrings was already assigned, is behavior-identical: field
initializers run immediately after super() and before the constructor body.
It makes all five guards uniform and states the ordering hazard in a comment
rather than leaving it implicit. The guards themselves are unchanged.

No CHANGELOG entry: test-only.

* Guard the JNA SMC connection handle, matching the FFM twin

Review catch on the previous commit. IOServiceOpen returning KERN_SUCCESS
with a null connection was handled on the FFM side but not on the JNA side,
which wrapped whatever the pointer held in an IOConnect and returned it. A
caller null-checks the return to decide whether the SMC is usable, so it
would have proceeded with an unusable connection, every read failing
silently to a sentinel and no diagnostic logged.

Reports through the same latched nullConnection() the FFM backend uses, and
returns null so the existing failure handling applies. The service release
in the finally block is unchanged.
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