Skip to content

Return -1 from parseHertz instead of throwing on a non-decimal separator - #3581

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:parsehertz-nfe
Aug 4, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:parsehertz-nfe

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes CodeQL Code Quality finding #632 (java/uncaught-number-format-exception, ParseUtil.java:216) — which turns out to be real, having been dismissed as a false positive in two earlier triage passes on the strength of this comment:

// Regexp enforces #(.#) format so no test for NFE required
double value = Double.valueOf(matcher.group(1)) * multipliers.getOrDefault(matcher.group(3), -1L);

The comment is wrong. The pattern is (\d+(.\d+)?) ?([kKMGT]?Hz).* and the dot is not escaped, so it matches any character rather than a decimal point:

"2.00MHz"                 group(1)="2.00"  -> 2.0
"2,00MHz"                 group(1)="2,00"  -> NumberFormatException
"Intel Core i7 @ 2,40GHz" group(1)="2,40"  -> NumberFormatException

parseHertz is documented to return -1 when it cannot parse, so this throws where it promises a sentinel. It is reached from ProcessorIdentifier's vendor frequency, MacGlobalMemory's speed, and the Linux/NetBSD/OpenBSD/AIX CPU-frequency parsers — all reading strings OSHI does not control. A comma decimal separator is the realistic trigger.

The fix, and the fix that was not made

Parse through ParseUtil.parseDoubleOrDefault, the existing soft-fail helper, and require the unit multiplier to be positive instead of inferring failure from a negative product.

The unescaped dot is deliberately left alone, with a comment explaining why. Escaping it is the obvious-looking cleanup and it is a regression. I wrote that version first and measured it:

input unescaped . (kept) escaped \.
"1.80GHz" 1800000000 1800000000
"2,40GHz" -1 -1
"2 40GHz" -1 40000000000 ✗
"2X00MHz" -1 0 ✗

Matching any separator pulls the malformed number into the value group whole, where the parse fails and -1 comes back. Escaping lets find() re-anchor on a fragment and return a plausible but wrong frequency — a 40 GHz processor. The accidental behavior is the correct one, so it is now pinned by tests and documented.

Tests

testParseHertzNonDecimalSeparator covers comma, space, and letter separators plus the decimal cases that must keep working. It is a guard in both directions:

  • restoring Double.valueOf → NumberFormatException: For input string: "2,40"
  • escaping the dot → Expected: is <-1L> but: was <40000000000L>

Also in this PR

Narrows the #3579 CHANGELOG entry. It claimed the macOS FFM firmware/baseboard/computer-system/CPU strings were mangled; probing every affected field on an Apple Silicon host at bf7f1783ad^ and at master gives byte-identical output, because those fields are single-string and unpadded there, and the one genuine multi-string property on that host ("compatible" = <"J416cAP","Mac14,6","AppleARM">) is read through the path #3579 deliberately left alone. The entry now says it aligns the backends and states the conditions under which the old decode would corrupt.

Per maintainer, Double.valueOf is not being added to forbidden-apis.txt — this was its only use in main code, and the site would have been exempted anyway.

Verification

Full ./mvnw clean spotless:apply sortpom:sort checkstyle:check install forbiddenapis:check javadoc:javadoc green on JDK 26: 1311/119/96 tests, 0 failures, 0 checkstyle violations.

Summary by CodeRabbit

  • Bug Fixes

    • Improved hertz parsing for malformed or unsupported decimal separators.
    • Invalid values now safely return -1 instead of causing parsing errors.
    • Valid decimal-point and integer hertz values continue to parse correctly.
  • Documentation

    • Updated the 7.4.4 changelog with macOS FFM decoding alignment and the hertz parsing fix.

HERTZ_PATTERN's decimals group is "(.\d+)?" with an unescaped dot, so it
matches any separator, not a decimal point. A frequency written with a
comma -- which a localized string can carry -- put "2,40" in the value
group, and Double.valueOf then threw NumberFormatException out of a method
documented to return -1 when it cannot parse. parseHertz is reached from
ProcessorIdentifier's vendor frequency, MacGlobalMemory's speed, and the
Linux, NetBSD, OpenBSD and AIX CPU frequency parsers, all of which read
strings OSHI does not control.

Parse through ParseUtil.parseDoubleOrDefault, the existing soft-fail
helper, and require the unit multiplier to be positive rather than
inferring failure from a negative product.

The unescaped dot is left as is, and a comment now says why: matching any
separator pulls the malformed number into the value group whole, where the
parse fails and the documented -1 is returned. Escaping it looks like a
cleanup but is a regression -- the match re-anchors on a fragment, so
"2 40GHz" is reported as a 40 GHz processor and "2X00MHz" as 0 rather than
as unparseable. The inline comment claiming the pattern made a
NumberFormatException impossible was simply wrong, and is gone.

testParseHertzNonDecimalSeparator covers the comma, space and letter
separators along with the decimal cases that must keep working. It fails
both ways: restoring Double.valueOf throws, and escaping the dot returns
40000000000.

Also narrows the #3579 changelog entry. It claimed the macOS FFM strings
were mangled; probing every affected field on an Apple Silicon host before
and after that change gives byte-identical output, because those fields are
single-string and unpadded there. The entry now says it aligns the backends
and describes the conditions under which the old decode would corrupt.
@coderabbitai

coderabbitai Bot commented Aug 4, 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: 692f9991-3b0c-429d-9ad8-8fa09f5d4b76

📥 Commits

Reviewing files that changed from the base of the PR and between d28c09b and 5c48078.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • oshi-common/src/main/java/oshi/util/ParseUtil.java
  • oshi-common/src/test/java/oshi/util/ParseUtilTest.java
📜 Recent review details
⏰ Context from checks skipped due to timeout. (8)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 26, ubuntu-latest
  • GitHub Check: Test JDK 21, ubuntu-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{java,xml,properties,md}

📄 CodeRabbit inference engine (AGENTS.md)

Do not commit generated output, target/, or IDE files.

Files:

  • CHANGELOG.md
  • oshi-common/src/main/java/oshi/util/ParseUtil.java
  • oshi-common/src/test/java/oshi/util/ParseUtilTest.java
CHANGELOG.md

📄 CodeRabbit inference engine (AGENTS.md)

Add a Next Release changelog entry only for user-visible changes; omit pure refactors, deduplication, test-only changes, and CI configuration changes.

Files:

  • CHANGELOG.md
oshi-common/src/main/java/**/*.java

📄 CodeRabbit inference engine (AGENTS.md)

oshi-common/src/main/java/**/*.java: Keep oshi-common pure Java: do not reference JNA, FFM (java.lang.foreign), or System.load/loadLibrary; place parsing, conversion, validation, caching, and shared implementation logic here when it is not native-API-specific.
Before adding a general parsing helper, check oshi.util.ParseUtil; use its existing parsing methods or add shared primitives there rather than duplicating parsers in platform drivers.
Read runtime configuration from oshi-common/src/main/resources/oshi.properties through GlobalConfig or Java system properties; do not introduce a separate configuration mechanism.

Files:

  • oshi-common/src/main/java/oshi/util/ParseUtil.java
{oshi-common,oshi-core}/src/main/java/**/*.java

📄 CodeRabbit inference engine (AGENTS.md)

Use Java 8 language and API compatibility: do not use var, records, switch expressions, text blocks, List.of, Stream.toList(), or other post-Java-8 features.

Files:

  • oshi-common/src/main/java/oshi/util/ParseUtil.java
**/*.java

📄 CodeRabbit inference engine (AGENTS.md)

**/*.java: Do not use banned numeric parsing APIs such as Integer.parseInt, Long.parseLong, Double.parseDouble, or Integer.decode; use the corresponding tolerant ParseUtil methods.
Do not import org.slf4j.event.**; use oshi.util.LogLevel instead.

Files:

  • oshi-common/src/main/java/oshi/util/ParseUtil.java
  • oshi-common/src/test/java/oshi/util/ParseUtilTest.java
**/src/main/java/**/*.java

📄 CodeRabbit inference engine (AGENTS.md)

**/src/main/java/**/*.java: Keep external imports synchronized with config/import-control.xml, the module's module-info.java, and, when necessary, its Maven configuration.
Provide Javadoc for every public and protected type and method; use imported simple class names rather than fully qualified names in code and Javadoc links.
Use the repository's concurrency annotation (@ThreadSafe, @Immutable, @NotThreadSafe, or @GuardedBy) on new classes, matching the modeled class where appropriate.
Memoize constant or expensive, slowly changing system values with oshi.util.Memoizer.memoize, generally using a Supplier<T> and defaultExpiration() when refresh is required.
Do not duplicate non-native logic between platform implementations; hoist parsing, conversion, filtering, caching, validation, and sentinel handling into oshi-common where possible.

Files:

  • oshi-common/src/main/java/oshi/util/ParseUtil.java
**/src/test/java/**/*Test.java

📄 CodeRabbit inference engine (AGENTS.md)

Write tests against parsing and transformation methods using fixture data; keep acquisition methods thin. Do not add Mockito, and use JUnit 5 with Hamcrest.

Files:

  • oshi-common/src/test/java/oshi/util/ParseUtilTest.java
**/*Test.java

📄 CodeRabbit inference engine (AGENTS.md)

Test hardware-dependent behavior using invariants, plausible ranges, correct types, and ordering rather than fixed machine-specific values; treat zero and empty results as valid where applicable.

Files:

  • oshi-common/src/test/java/oshi/util/ParseUtilTest.java
🧠 Learnings (4)
📚 Learning: 2026-04-12T19:22:09.716Z
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:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/util/ParseUtil.java
📚 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-common/src/main/java/oshi/util/ParseUtil.java
📚 Learning: 2026-07-30T00:35:22.638Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3547
File: oshi-common/src/main/java/oshi/hardware/common/platform/unix/BsdFirmware.java:82-82
Timestamp: 2026-07-30T00:35:22.638Z
Learning: In OSHI, treat changes as “API-breaking” only when they affect classes (or relevant API surface) annotated with `PublicAPI`. Public classes/members that are not annotated with `PublicAPI` should be reviewed as internal implementation details, even if they are public (e.g., classes like `oshi.hardware.common.platform.unix.BsdFirmware`). Also, respect intentional visibility decisions used for tests—e.g., methods like `BsdFirmware.parseDmesg(List<String>)` may be intentionally package-private to support tests within the same package; avoid widening visibility or altering signatures unless the related `PublicAPI` contract requires it.

Applied to files:

  • oshi-common/src/main/java/oshi/util/ParseUtil.java
📚 Learning: 2026-08-03T00:46:14.953Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3566
File: oshi-common/src/main/java/oshi/software/common/os/unix/openbsd/OpenBsdNetworkParams.java:18-22
Timestamp: 2026-08-03T00:46:14.953Z
Learning: In the OSHI Java codebase, do not require duplicate Javadoc on public methods annotated with Override when the inherited Javadoc from the parent declaration adequately documents the method. The general public-member Javadoc requirement should not flag these overrides solely because they lack redundant documentation.

Applied to files:

  • oshi-common/src/main/java/oshi/util/ParseUtil.java
  • oshi-common/src/test/java/oshi/util/ParseUtilTest.java
🔇 Additional comments (3)
oshi-common/src/main/java/oshi/util/ParseUtil.java (1)

63-66: LGTM!

Also applies to: 219-222

CHANGELOG.md (1)

15-16: LGTM!

oshi-common/src/test/java/oshi/util/ParseUtilTest.java (1)

124-140: LGTM!


📝 Walkthrough

Walkthrough

parseHertz now returns -1L for malformed decimal separators instead of throwing. The change adds validation, documents the pattern requirement, adds regression tests, and updates the changelog.

Changes

parseHertz parsing

Layer / File(s) Summary
Parser validation and release notes
oshi-common/src/main/java/oshi/util/ParseUtil.java, CHANGELOG.md
parseHertz uses fallback numeric parsing and validates the value and multiplier before conversion. The changelog records the fix.
Malformed separator regression tests
oshi-common/src/test/java/oshi/util/ParseUtilTest.java
Tests cover comma, space, and letter separators, plus valid decimal-point and integer inputs.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

  • oshi/oshi#3437: Both changes add safer numeric parsing in ParseUtil and related tests.

Poem

A rabbit found a number gone astray,
With commas and letters blocking the way.
parseHertz now stays calm and neat,
Returning -1L when inputs cheat.
Decimal points still hop along—
Safe parsing makes the code more 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 and concisely describes the main change to make parseHertz return -1 instead of throwing.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 75.00000% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 79.96%. Comparing base (743b2bf) to head (5c48078).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
oshi-common/src/main/java/oshi/util/ParseUtil.java 75.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3581      +/-   ##
============================================
- Coverage     80.00%   79.96%   -0.05%     
  Complexity     3869     3869              
============================================
  Files           709      709              
  Lines         24206    24207       +1     
  Branches       4047     4047              
============================================
- Hits          19366    19356      -10     
- Misses         2689     2698       +9     
- Partials       2151     2153       +2     
Flag Coverage Δ
linux 37.67% <75.00%> (+0.03%) ⬆️
macos 38.43% <75.00%> (-0.07%) ⬇️
windows 45.40% <75.00%> (+<0.01%) ⬆️

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 b56a6a9 into oshi:master Aug 4, 2026
17 checks passed
@dbwiddis
dbwiddis deleted the parsehertz-nfe branch August 4, 2026 22:48
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