Skip to content

Run NativeFreeComparisonTest on NetBSD, and report an unknown current PID or TID as 0 everywhere - #3754

Merged
dbwiddis merged 4 commits into
oshi:masterfrom
dbwiddis:nativefree-comparison-netbsd
Sep 26, 2026
Merged

dbwiddis merged 4 commits into
oshi:masterfrom
dbwiddis:nativefree-comparison-netbsd

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Sep 26, 2026 •

Copy link
Copy Markdown
Member

NativeFreeComparisonTest on NetBSD

The native-free provider supports Linux and NetBSD, but its comparison test ran only on Linux. It now runs on both. On NetBSD it is meaningful only where pkgsrc java-jna supplies libjnidispatch, which the JDK 25 NetBSD CI job installs; otherwise JNA falls back to the same command-line code.

NetBSD has three providers, and the two comparison tests share JNA as their baseline: NativeComparisonTest checks FFM against JNA, and NativeFreeComparisonTest checks native-free against JNA. #3745 added NetBSD to NativeComparisonTest along with the FFM port, so FFM was already covered; native-free was the provider left uncompared. Before #3433 gave NetBSD's JNA provider a native path through java-jna, the NetBSD JNA classes were the command-line code the native-free provider uses, so the comparison would have checked a class against itself. With both tests running, all three providers are compared on Linux and NetBSD.

  • getHz / getPageSize (a cast to LinuxOperatingSystem) keep a Linux-only gate.
  • currentProcess re-reads a snapshot taken mid-posix_spawn, the same degraded-row check NativeComparisonTest uses, and allows the seconds-resolution ps start-time tolerance on NetBSD.

The first NetBSD run passed every comparison except one: the current thread ID (JNA 4156 from _lwp_self, native-free 26 from Thread.getId()).

Unknown current process and thread IDs

OperatingSystem.getThreadId() documents 0 when the ID is unknown, and most implementations of it and of getProcessId() already return 0 on failure. Five did not:

Implementation Before After
NetBsdOperatingSystem.getThreadId() (native-free / no JNA) Java Thread.getId() 0
NetBsdOperatingSystem.getProcessId() -1 on an unparseable JVM name 0
NetBsdOperatingSystemFFM getProcessId() / getThreadId() -1 on a failed native call 0
WindowsOperatingSystemFFM getProcessId() / getThreadId() -1 on a failed native call 0

getProcessId() now documents the same 0-when-unknown contract.

Following those values into their callers turned up two more bugs of the same kind:

  • The BSD, Solaris and AIX process queries treat a negative PID as "all processes", so with a -1 current PID getCurrentProcess() returned whichever process came first. It now returns its stand-in without a lookup when the PID is unknown; it cannot look up 0 instead, since PID 0 is a real kernel or idle process on most platforms.
  • SolarisOperatingSystem and AixOperatingSystem.getProcess(int) returned an arbitrary process for any negative PID. They now return null, as BsdOperatingSystem already did.

A Java thread ID was also unsafe in NetBsdOperatingSystem.getCurrentThread(), which matches ps LWP rows against it: a collision picked another thread. With 0 it falls back to the same stub thread the other BSDs use.

Tests

  • OperatingSystemTest (oshi-common): getCurrentProcess() never looks up an unknown PID.
  • The JNA and FFM OS tests assert a positive PID, a non-negative TID, and getProcess(-1) == null on every platform.

Verification

  • Both NetBSD jobs (no-JNA JDK 21, and JNA + FFM JDK 25) green on the fork.
  • macOS: oshi-common, oshi-core and oshi-core-ffm tests green; full gate including -Perror-prone,aggregate-coverage.
  • Not verified locally: Windows FFM, Solaris and AIX. The Windows and Solaris paths run in this PR's CI; AIX runs on the cfarm job.

Summary by CodeRabbit

  • Bug Fixes
    • Unknown process and thread IDs now consistently return 0 across platforms.
    • Current-process lookup safely handles unknown process IDs, and negative process IDs return no result on Solaris and AIX.
    • NetBSD process and thread ID reporting no longer returns misleading values.

The native-free provider supports Linux and NetBSD, but the comparison
test was gated to Linux, so its NetBSD code was never compared against
the native path. It now runs on both; the comparison is meaningful on
NetBSD only where pkgsrc java-jna supplies libjnidispatch, which the
JDK 25 NetBSD CI job installs.

- The two Linux-only methods (getHz, getPageSize via a cast to
  LinuxOperatingSystem) keep their own Linux gate.
- currentProcess re-reads a snapshot taken mid-posix_spawn, the same
  degraded-row check NativeComparisonTest uses, and compares start times
  within the seconds-resolution ps tolerance on NetBSD.
- The thread-ID assertion moves to the end of operatingSystemInfo so a
  mismatch cannot hide the assertions before it.
Without JNA or FFM, NetBsdOperatingSystem.getThreadId() returned Java's
Thread.getId(), a different numbering from the kernel LWP ID the native
paths return. OperatingSystem.getThreadId() promises the OS thread ID or 0
when unknown, and getCurrentThread() matches ps rows against this value,
so a Java ID that happened to equal another LWP's ID picked the wrong
thread. Return 0 instead; getCurrentThread() then falls back to the same
stub thread the other BSDs use when the ID does not match.

Found by running NativeFreeComparisonTest on NetBSD (expected 4156 from
_lwp_self, got 26 from Thread.getId).
OperatingSystem.getThreadId() documents 0 when the ID is unknown, and
most implementations of getThreadId() and getProcessId() return 0 when
their native call fails. Five did not:

- NetBsdOperatingSystem.getProcessId() (native-free) returned -1 when the
  JVM name could not be parsed.
- NetBsdOperatingSystemFFM returned -1 from both getpid and _lwp_self.
- WindowsOperatingSystemFFM returned -1 from both GetCurrentProcessId and
  GetCurrentThreadId.

getProcessId() now documents the same 0-when-unknown contract, and these
return 0.

A -1 was worse than a wrong number: the BSD, Solaris and AIX process
queries treat a negative PID as "all processes", so getCurrentProcess()
would have returned whichever process came first. getCurrentProcess() now
returns its stand-in without a lookup when the PID is unknown, since PID
0 is a real kernel or idle process on most platforms. SolarisOperatingSystem
and AixOperatingSystem.getProcess(int) also reject a negative PID, as
BsdOperatingSystem already did; a caller passing one got an arbitrary
process back.
@coderabbitai

coderabbitai Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 08de33a9-b206-4573-bfed-596892464b20

📥 Commits

Reviewing files that changed from the base of the PR and between a0216f1 and c2f1a6f.

📒 Files selected for processing (11)
  • CHANGELOG.md
  • oshi-benchmark/src/test/java/oshi/comparison/NativeFreeComparisonTest.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/aix/AixOperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/netbsd/NetBsdOperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/solaris/SolarisOperatingSystem.java
  • oshi-common/src/main/java/oshi/software/os/OperatingSystem.java
  • oshi-common/src/test/java/oshi/software/os/OperatingSystemTest.java
  • oshi-core-ffm/src/main/java/oshi/software/os/unix/netbsd/NetBsdOperatingSystemFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java
  • oshi-core-ffm/src/test/java/oshi/ffm/OperatingSystemFFMTest.java
  • oshi-core/src/test/java/oshi/software/os/shared/OperatingSystemTest.java

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

📜 Recent review details
⏰ Context from checks skipped due to timeout. (6)
  • GitHub Check: Test JDK 25, OpenBSD
  • GitHub Check: Test JDK 25, OpenIndiana
  • GitHub Check: Test JDK 25, FreeBSD
  • GitHub Check: Test JDK 25, NetBSD
  • GitHub Check: Lint (ForbiddenAPIs, Javadoc, SLF4J)
  • GitHub Check: Analyze (java)
🧰 Additional context used
📓 Path-based instructions (4)
`oshi-core-ffm` may not reference `com.sun.jna.**`.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/unix/netbsd/NetBsdOperatingSystemFFM.java
  • oshi-core-ffm/src/test/java/oshi/ffm/OperatingSystemFFMTest.java
`oshi-common` may not reference `com.sun.jna.**`, `java.lang.foreign.**`, or any `System.load`/`loadLibrary`.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • oshi-common/src/test/java/oshi/software/os/OperatingSystemTest.java
  • oshi-common/src/main/java/oshi/software/os/OperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/aix/AixOperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/solaris/SolarisOperatingSystem.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/netbsd/NetBsdOperatingSystem.java
Test files are named `*Test.java`.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • oshi-common/src/test/java/oshi/software/os/OperatingSystemTest.java
  • oshi-core/src/test/java/oshi/software/os/shared/OperatingSystemTest.java
  • oshi-core-ffm/src/test/java/oshi/ffm/OperatingSystemFFMTest.java
  • oshi-benchmark/src/test/java/oshi/comparison/NativeFreeComparisonTest.java
Add a `CHANGELOG.md` entry under *Next Release* **only for user-visible changes**.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • CHANGELOG.md
🧠 Learnings (1)
📚 Learning: 2026-08-15T15:43:29.296Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3628
File: oshi-core-ffm/src/main/java/oshi/driver/windows/registry/HkeyUserDataFFM.java:108-108
Timestamp: 2026-08-15T15:43:29.296Z
Learning: In the OSHI Java codebase, use the sentinel-over-null convention at public API boundaries. Private helpers may return an explicitly JSpecify-annotated nullable value when the caller handles the missing result clearly and locally; callers must check for null before accessing the result. For example, methods such as lookupAccountBySid(String) may return String Nullable [] when queryUserSessions() performs the required null check.

Applied to files:

  • oshi-benchmark/src/test/java/oshi/comparison/NativeFreeComparisonTest.java

📝 Walkthrough

Walkthrough

Unknown process and thread IDs now use zero in the changed implementations. Current-process lookup avoids querying nonpositive PIDs, and AIX and Solaris return null for negative process lookups. Native-free comparisons now include NetBSD with platform-specific checks.

Changes

Process identity and lookup

Layer / File(s) Summary
Unknown ID defaults and current-process fallback
oshi-common/src/main/java/oshi/software/os/OperatingSystem.java, oshi-common/src/main/java/oshi/software/common/os/unix/netbsd/NetBsdOperatingSystem.java, oshi-core-ffm/src/main/java/oshi/software/os/unix/netbsd/NetBsdOperatingSystemFFM.java, oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java, oshi-common/src/test/java/oshi/software/os/OperatingSystemTest.java, CHANGELOG.md
The API documents zero for an unknown PID and uses a stand-in when the PID is not positive. NetBSD and Windows implementations return zero for unavailable IDs. The test checks that lookup is skipped when the PID is zero.
Negative PID lookup handling
oshi-common/src/main/java/oshi/software/common/os/unix/aix/AixOperatingSystem.java, oshi-common/src/main/java/oshi/software/common/os/unix/solaris/SolarisOperatingSystem.java, oshi-core/src/test/java/oshi/software/os/shared/OperatingSystemTest.java, oshi-core-ffm/src/test/java/oshi/ffm/OperatingSystemFFMTest.java
AIX and Solaris return null for negative PIDs. Tests check current ID values and verify that looking up PID -1 returns null.
Linux and NetBSD native-free comparisons
oshi-benchmark/src/test/java/oshi/comparison/NativeFreeComparisonTest.java
The comparison test runs on Linux and NetBSD. Linux-only checks remain restricted to Linux. NetBSD-specific checks account for thread ID differences, retry degraded process snapshots, and allow a start-time difference of up to 2,000 ms.

Priority: ⬇️ Low

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Merge Risk: ⚪ Minimal · up to c2f1a

No merge-blocking issue was identified; the NetBSD comparison fails with an assertion if a process snapshot remains unavailable.

Security Architecture Review

Security architecture risk: 🔵 Low · up to c2f1a

The changed lookup path avoids treating an unknown process ID as a real process. No introduced security exposure is established, but the behavior of the NetBSD current-thread fallback remains uncertain.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The demonstrated lookup effect is on local operating-system process and thread identity returned to library callers. The reviewed paths do not establish a new remote entrypoint or privilege-bearing sink.

Trust Boundaries and Controls

  • observed — NetBSD native-free obtains a PID from the JVM name and uses 0 on parse failure. The shared current-process guard then avoids a process lookup for that unknown identity.

Resilience and Maintainability Implications

  • inferred — NetBSD thread enumeration can parse an unrecognized LID as 0, and its validity filter excludes invalid state rather than zero IDs. Whether such a row can be returned and mistaken for the current thread remains unverified.

Hardening Proposals

  • proposed — Test unknown NetBSD PID and TID through getCurrentThread, including a malformed zero-LID row, and consider preventing unknown IDs from matching process or thread rows.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 24.32% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 37 functions across 10 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main changes: adding NetBSD coverage to NativeFreeComparisonTest and standardizing unknown process and thread IDs as 0.
Full details: Docstring Coverage

Explanation

Docstring coverage is 24.32% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 37 functions across 10 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR

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

A rabbit checks the process IDs at dawn
Unknowns turn to zero, neat and clear
Negative lookups return no process
NetBSD joins the test run, ears up
The rabbit hops along, content with the checks

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Sep 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 77.77778% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.32%. Comparing base (3fe9222) to head (c2f1a6f).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...oftware/common/os/unix/aix/AixOperatingSystem.java 0.00% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3754      +/-   ##
============================================
+ Coverage     80.30%   80.32%   +0.01%     
- Complexity       83      218     +135     
============================================
  Files           717      717              
  Lines         25662    25666       +4     
  Branches       4335     4336       +1     
============================================
+ Hits          20608    20616       +8     
  Misses         2833     2833              
+ Partials       2221     2217       -4     
Flag Coverage Δ
freebsd 35.92% <11.11%> (+<0.01%) ⬆️
linux 39.78% <11.11%> (+0.02%) ⬆️
macos 40.59% <11.11%> (-0.05%) ⬇️
netbsd 34.63% <33.33%> (+0.02%) ⬆️
openbsd 35.15% <11.11%> (+0.01%) ⬆️
solaris 36.51% <33.33%> (+<0.01%) ⬆️
windows 46.90% <33.33%> (+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 1b673de into oshi:master Sep 26, 2026
19 checks passed
@dbwiddis
dbwiddis deleted the nativefree-comparison-netbsd branch September 26, 2026 23:19
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