Skip to content

Guarantee getCurrentProcess() never returns null - #3583

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:current-process-nonnull
Aug 5, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:current-process-nonnull

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

Summary

OperatingSystem#getCurrentProcess() is documented as returning "the current process", with no mention of null. It delegated to getProcess(int), which is documented to return null when the process is not found:

/**
 * Gets the current process.
 *
 * @return the current process          ← no null in the contract
 */
default OSProcess getCurrentProcess() {
    return getProcess(getProcessId());  ← "null otherwise"
}

The contract was already the stronger one. The implementation quietly broke it.

Why this is not theoretical

Every non-Linux getCurrentThread() dereferences the result unguarded — AIX, FreeBSD, OpenBSD, NetBSD, DragonFly and macOS all do:

OSProcess proc = getCurrentProcess();
final int tid = getThreadId();
return proc.getThreadDetails().stream().filter(t -> t.getThreadId() == tid).findFirst()
        .orElse(new XxxOSThread(proc.getProcessID(), tid));

AIX CI produced precisely that NullPointerException when a truncated perfstat_process list omitted the calling JVM. The truncation cause is fixed separately in #3582; this is the other half, since a denied /proc entry or a query race would do the same.

Adding six null guards would treat the symptom. The current process exists by definition, so a null is a failed read, not a missing process — and the fix belongs in the one method that promises otherwise.

Change

The default method substitutes a package-private CurrentProcessStub when the platform query comes up empty. The stand-in carries the two facts still known to be true — the process ID, and that it is running — and reports the unknown/zero/empty defaults elsewhere that callers already handle from a live process.

Its empty thread list is the load-bearing detail: it lets each platform's getCurrentThread() fall through to its existing orElse(new XxxOSThread(pid, tid)) branch rather than throwing, so the degraded result is a real thread object with the correct pid and tid.

The stand-in lives in oshi.software.os so the default itself enforces the guarantee. An earlier revision of this PR put the substitution in an AbstractOperatingSystem override instead, which left a direct implementor of the interface — reachable through the SystemInfoProvider SPI — still getting null from a method whose javadoc promised otherwise. Placing it in oshi.software.os means that package imports oshi.software.common for the first time, a package cycle; that is acceptable here, as oshi.util and oshi.hardware already import each other.

Tests

OperatingSystemTest.testDefaultGetCurrentProcess covers this through MINIMAL, which implements the interface directly rather than extending AbstractOperatingSystem, and whose getProcess(int) returns null for every pid as a failed native read would.

That test previously asserted the null, and failed on this change with:

Expected: is null
     but: was <OSProcess@6adca2a0[processID=1, name=]>

which is the regression coverage for the default itself. It now asserts the contract and the stand-in's empty-not-null accessors.

Compatibility and verification

japicmp reports Semantic versioning suggestion: 0.0.1 — the stand-in is package-private, so no public API is added, and callers that null-check getCurrentProcess() keep compiling; their check simply stops being reachable.

Full ./mvnw clean spotless:apply sortpom:sort checkstyle:check install forbiddenapis:check javadoc:javadoc green on JDK 26: 1311/119/96 tests, 0 failures. Live-checked on macOS that the normal path is unaffected — the real process is still returned, arguments and environment unchanged.

Note: the CHANGELOG entry will conflict with #3582's if that merges first; trivial to resolve.

Summary by CodeRabbit

  • Bug Fixes

    • Improved reliability when retrieving the current process, including on systems where process details cannot be read.
    • Prevented failures when obtaining the current thread by guaranteeing a non-null current-process result.
    • Preserved the process ID and running status while safely providing fallback values for unavailable details.
  • Documentation

    • Clarified the current-process behavior and fallback guarantees in the API documentation.
    • Added release notes for version 7.4.4.

@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: cd5749d2-19da-4ccc-bd33-99dead754195

📥 Commits

Reviewing files that changed from the base of the PR and between b2cdb43 and c4bdb55.

📒 Files selected for processing (4)
  • CHANGELOG.md
  • oshi-common/src/main/java/oshi/software/os/CurrentProcessStub.java
  • oshi-common/src/main/java/oshi/software/os/OperatingSystem.java
  • oshi-common/src/test/java/oshi/software/os/OperatingSystemTest.java
🚧 Files skipped from review as they are similar to previous changes (4)
  • oshi-common/src/main/java/oshi/software/os/OperatingSystem.java
  • CHANGELOG.md
  • oshi-common/src/test/java/oshi/software/os/OperatingSystemTest.java
  • oshi-common/src/main/java/oshi/software/os/CurrentProcessStub.java
📜 Recent review details
⏰ Context from checks skipped due to timeout. (7)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 26, ubuntu-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Analyze (java)

📝 Walkthrough

Walkthrough

getCurrentProcess() now guarantees a non-null result. Failed lookups return a running CurrentProcessStub with the current PID and safe default values. Tests verify the fallback contract, and the changelog records the fix.

Changes

Current process fallback

Layer / File(s) Summary
Fallback process implementation
oshi-common/src/main/java/oshi/software/os/CurrentProcessStub.java
Adds a package-private fallback process with the current PID, RUNNING state, empty collections, default attribute values, and a non-refreshing updateAttributes() method.
Current-process lookup contract
oshi-common/src/main/java/oshi/software/os/OperatingSystem.java, oshi-common/src/test/java/oshi/software/os/OperatingSystemTest.java, CHANGELOG.md
Updates getCurrentProcess() to return the fallback when lookup fails. Documents the non-null contract, verifies the fallback in tests, and records the fix.

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

Possibly related PRs

  • oshi/oshi#3582: Addresses missing current-process data through AIX perfstat_process retries.

Poem

A rabbit checks the process line,
No null is found; the state is fine.
The PID hops safely into view,
With empty threads and defaults too.
“Run on,” says Bun, “the fallback’s true!”

🚥 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 primary change: guaranteeing that getCurrentProcess() never returns null.
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.

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

Actionable comments posted: 1

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

Inline comments:
In `@oshi-common/src/main/java/oshi/software/os/OperatingSystem.java`:
- Around line 257-263: Update the default current-process method in
OperatingSystem to enforce its documented non-null contract when
getProcess(getProcessId()) returns null, using the specified fallback process
with the current PID, RUNNING state, and unknown defaults. Add a regression test
using a direct OperatingSystem implementation that does not extend
AbstractOperatingSystem and verifies the method never returns null.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e4b0acfb-15b8-44c4-8f0a-a3df88689217

📥 Commits

Reviewing files that changed from the base of the PR and between b56a6a9 and 2750d17.

📒 Files selected for processing (5)
  • CHANGELOG.md
  • oshi-common/src/main/java/oshi/software/common/AbstractOperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/CurrentProcessStub.java
  • oshi-common/src/main/java/oshi/software/os/OperatingSystem.java
  • oshi-common/src/test/java/oshi/software/common/CurrentProcessStubTest.java
📜 Review details
⏰ Context from checks skipped due to timeout. (7)
  • 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: Analyze (java)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🧰 Additional context used
📓 Path-based instructions (8)
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/software/os/OperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/AbstractOperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/CurrentProcessStub.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/software/os/OperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/AbstractOperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/CurrentProcessStub.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/software/os/OperatingSystem.java
  • oshi-common/src/test/java/oshi/software/common/CurrentProcessStubTest.java
  • oshi-common/src/main/java/oshi/software/common/AbstractOperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/CurrentProcessStub.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/software/os/OperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/AbstractOperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/CurrentProcessStub.java
**/*.{java,xml,properties,md}

📄 CodeRabbit inference engine (AGENTS.md)

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

Files:

  • oshi-common/src/main/java/oshi/software/os/OperatingSystem.java
  • oshi-common/src/test/java/oshi/software/common/CurrentProcessStubTest.java
  • oshi-common/src/main/java/oshi/software/common/AbstractOperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/CurrentProcessStub.java
  • CHANGELOG.md
**/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/software/common/CurrentProcessStubTest.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/software/common/CurrentProcessStubTest.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
🧠 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/software/os/OperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/AbstractOperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/CurrentProcessStub.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/software/os/OperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/AbstractOperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/CurrentProcessStub.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/software/os/OperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/AbstractOperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/CurrentProcessStub.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/software/os/OperatingSystem.java
  • oshi-common/src/test/java/oshi/software/common/CurrentProcessStubTest.java
  • oshi-common/src/main/java/oshi/software/common/AbstractOperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/CurrentProcessStub.java
🔇 Additional comments (4)
oshi-common/src/main/java/oshi/software/common/CurrentProcessStub.java (1)

1-116: LGTM!

oshi-common/src/main/java/oshi/software/common/AbstractOperatingSystem.java (1)

105-114: LGTM!

oshi-common/src/test/java/oshi/software/common/CurrentProcessStubTest.java (1)

27-163: LGTM!

CHANGELOG.md (1)

17-17: LGTM!

@codecov

codecov Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 43.47826% with 13 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.72%. Comparing base (b2cdb43) to head (c4bdb55).

Files with missing lines Patch % Lines
...main/java/oshi/software/os/CurrentProcessStub.java 35.00% 13 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3583      +/-   ##
============================================
- Coverage     79.82%   79.72%   -0.11%     
+ Complexity     4100     4099       -1     
============================================
  Files           709      710       +1     
  Lines         24220    24242      +22     
  Branches       4051     4052       +1     
============================================
- Hits          19334    19327       -7     
- Misses         2736     2762      +26     
- Partials       2150     2153       +3     
Flag Coverage Δ
linux 37.65% <39.13%> (-0.01%) ⬇️
macos 38.42% <43.47%> (-0.05%) ⬇️
windows 45.37% <43.47%> (-0.02%) ⬇️

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 force-pushed the current-process-nonnull branch from 988e1e7 to 626872e Compare August 4, 2026 23:57
@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

OperatingSystem#getCurrentProcess() is documented to return "the current
process", with no mention of null, but it delegated to getProcess(int),
which is documented to return null when the process is not found. The
contract was already the stronger one; the implementation quietly broke it.

That is not theoretical. Every non-Linux getCurrentThread() dereferences it
without a guard -- AIX, FreeBSD, OpenBSD, NetBSD, DragonFly and macOS all
do

    OSProcess proc = getCurrentProcess();
    return proc.getThreadDetails().stream()...

and AIX CI produced exactly that NullPointerException when a truncated
perfstat list omitted the calling JVM. Adding six null guards would treat
the symptom; the current process exists by definition, so a null is a
failed read -- a truncated native list, a denied /proc entry, a race with
the query -- and the fix belongs in the one method that promises otherwise.

Substitute CurrentProcessStub in the default method when the platform query
comes up empty. The stand-in carries the two facts still known to be true,
the process ID and a RUNNING state, and reports the unknown/zero/empty
defaults elsewhere that callers already handle from a live process. Its
empty thread list is what lets each platform's getCurrentThread() fall
through to its existing orElse(new XxxOSThread(pid, tid)) branch instead of
throwing.

The stand-in lives in oshi.software.os, package-private, so the default
itself can enforce the guarantee rather than leaving it to an override in
AbstractOperatingSystem -- which would have left a direct implementor of
the interface, reachable through the SystemInfoProvider SPI, still getting
null from a method whose javadoc says otherwise. Placing it there means
oshi.software.os imports oshi.software.common for the first time; that is a
package cycle, and an acceptable one, since oshi.util and oshi.hardware
already import each other.

OperatingSystemTest.testDefaultGetCurrentProcess covers this through
MINIMAL, which implements the interface directly rather than extending
AbstractOperatingSystem. It previously asserted the null and failed on this
change with "Expected: is null but: was OSProcess[processID=1]"; it now
asserts the contract and the stand-in's empty-not-null accessors.

japicmp: 0.0.1. The stand-in is package-private, so no public API is added,
and callers that null-check getCurrentProcess() keep compiling -- their
check simply stops being reachable.
@dbwiddis
dbwiddis force-pushed the current-process-nonnull branch from 626872e to c4bdb55 Compare August 5, 2026 00:03
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@dbwiddis
dbwiddis merged commit f5290f3 into oshi:master Aug 5, 2026
16 checks passed
@dbwiddis
dbwiddis deleted the current-process-nonnull branch August 5, 2026 00:14
dbwiddis added a commit that referenced this pull request Aug 12, 2026
AIX's perfstat_process count-then-fill is a documented, load-dependent
race (#3582) where a bounded retry reduces but cannot fully eliminate a
miss on the current process under heavy process churn on a shared host;
that miss degrades to CurrentProcessStub's zero defaults (#3583) rather
than crashing. OshiMetricsTest's process.thread.count/memory.virtual/
uptime assertions didn't account for that degraded-but-valid case,
unlike NativeComparisonTest which already tolerates the same class of
AIX transient read miss.

Extends the existing BSD zero-tolerance carve-out (structural, not a
race) to also cover AIX for these three assertions.
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