Skip to content

Remove JNA native library requirement for NetBSD - #3310

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:netbsd-no-native
May 31, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:netbsd-no-native

Conversation

@dbwiddis

@dbwiddis dbwiddis commented May 31, 2026 •

Copy link
Copy Markdown
Member

Summary

Remove all JNA native library dependencies from the NetBSD platform implementation, making NetBSD the first oshi-core platform that works entirely without native library support. (Necessary to stay true to the "no native libraries" promise as JNA does not distribute its binary build for NetBSD: it's available as a package, but its use is minimal so an all-command-line port makes sense.)

  • Replace JNA sysctl/getpid/getloadavg/getrlimit calls with command-line alternatives
  • NetBSD no longer requires the pkgsrc java-jna package
  • Add gcc70 (GCC Compile Farm) NetBSD physical hardware test to unix.yaml
  • Update NetBSD VM test to verify the no-native path (java-jna not installed)
  • Remove stale netbsd-port branch trigger from unix.yaml

Passing tests (no JNA installed): https://github.com/dbwiddis/oshi/actions/runs/26703084248

Test plan

  • NetBSD VM without java-jna: 0 test failures (77 passing, 91 skipped)
  • NetBSD gcc70 physical hardware with JNA: 0 test failures
  • Compiles cleanly with spotless, checkstyle, forbiddenapis
  • Verify gcc70 job works from upstream (requires AIX_OSHI_KEY secret)

Summary by CodeRabbit

  • Bug Fixes

    • Improved NetBSD system info: more reliable CPU ticks, per-CPU loads, and load averages; better process metrics and working-directory resolution with fallbacks.
  • Refactor

    • Simplified NetBSD system utilities to use command-line sysctl paths, reducing native/JNA reliance.
  • Tests

    • NetBSD-specific test adjustments to avoid incompatible native-dependent tests.
  • Chores

    • CI updates for NetBSD test jobs and added Java management support.

@coderabbitai

coderabbitai Bot commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR removes JNA/native sysctl usage on NetBSD, replacing it with command-line sysctl parsing and Java runtime APIs; it updates NetBSD consumer classes, the sysctl utility, CI workflow, module dependencies, and a test to reflect the JNA removal.

Changes

NetBSD JNA Removal and Command-Line Sysctl Migration

Layer / File(s) Summary
Module, CI, and test configuration updates
oshi-core/src/main/java/module-info.java, .github/workflows/unix.yaml, oshi-core/src/test/java/oshi/jna/util/FileUtilJNATest.java
Adds requires java.management; to module descriptor. Removes netbsd-port branch from workflow. testnetbsd job no longer installs JNA/native library; new testnetbsd-gcc70 SSH job added. FileUtilJNATest is disabled on NetBSD.
NetBsdSysctlUtil foundation refactor
oshi-core/src/main/java/oshi/util/platform/unix/netbsd/NetBsdSysctlUtil.java
Removes JNA/native sysctl overloads that accepted int[] MIBs and returned Structure/Memory; retains only sysctl(String name, ...) command-line implementations.
NetBsdCentralProcessor CPU state and load metrics
oshi-core/src/main/java/oshi/hardware/platform/unix/netbsd/NetBsdCentralProcessor.java
Moves CPU state constants into class; switches CPU brand/arch lookups to hw.model/hw.machine; parses kern.cp_time and per-CPU kern.cp_time.<cpu> from sysctl output; reads vm.loadavg via sysctl -n.
NetBsdOSProcess system integration
oshi-core/src/main/java/oshi/software/os/unix/netbsd/NetBsdOSProcess.java
Replaces JNA ARGMAX initializer with NetBsdSysctlUtil.sysctl("kern.argmax", ...); uses os.arch for bitness; removes cross-process environment retrieval; uses kern.maxfilesperproc/kern.maxfiles sysctl for fd limits.
NetBsdOperatingSystem system identification
oshi-core/src/main/java/oshi/software/os/unix/netbsd/NetBsdOperatingSystem.java
Uses string-key sysctl (kern.ostype, kern.osrelease, kern.version) for OS info; derives PID from RuntimeMXBean name and thread id from Thread.currentThread().getId(); removes NetBsdLibc imports.
FstatUtil working directory fallback
oshi-core/src/main/java/oshi/util/platform/unix/netbsd/FstatUtil.java
getCwd(pid) first tries /proc/<pid>/cwd readlink, then falls back to parsing fstat -p <pid> output for the wd field.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • oshi/oshi#3307: Introduced NetBSD JNA/native library support (NetBsdLibc and native NetBsdSysctlUtil overloads) that this PR removes.

Poem

🐰 I hopped through NetBSD fields of code,
Memory and JNA down the road,
sysctl strings now sing so clear,
Java threads and parsers cheer,
Tests and CI follow lightened load.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.78% 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 'Remove JNA native library requirement for NetBSD' directly and accurately summarizes the main objective of the changeset.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 and usage tips.

@codecov

codecov Bot commented May 31, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 66 lines in your changes missing coverage. Please review.
✅ Project coverage is 71.77%. Comparing base (8b308de) to head (330dd08).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...e/platform/unix/netbsd/NetBsdCentralProcessor.java 0.00% 45 Missing ⚠️
.../oshi/software/os/unix/netbsd/NetBsdOSProcess.java 0.00% 10 Missing ⚠️
...software/os/unix/netbsd/NetBsdOperatingSystem.java 0.00% 6 Missing ⚠️
...java/oshi/util/platform/unix/netbsd/FstatUtil.java 0.00% 5 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3310      +/-   ##
============================================
+ Coverage     71.52%   71.77%   +0.25%     
  Complexity       76       76              
============================================
  Files           433      433              
  Lines         16917    16846      -71     
  Branches       2752     2748       -4     
============================================
- Hits          12100    12092       -8     
+ Misses         3333     3269      -64     
- Partials       1484     1485       +1     
Flag Coverage Δ
linux 38.32% <0.00%> (+0.16%) ⬆️
macos 38.62% <0.00%> (+0.16%) ⬆️
windows 46.11% <0.00%> (+0.13%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 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.

@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: 5

🧹 Nitpick comments (2)
.github/workflows/unix.yaml (1)

169-190: 💤 Low value

Clarify job names to distinguish VM from physical hardware.

Both testnetbsd (line 169) and testnetbsd-gcc70 (line 190) are named "Test JDK 11, NetBSD" with only a subtle VM/no-VM distinction. This could cause confusion in CI status displays.

📝 Proposed naming improvement
-    name: Test JDK 11, NetBSD VM
+    name: Test JDK 11, NetBSD 10.1 VM
-    name: Test JDK 11, NetBSD
+    name: Test JDK 11, NetBSD gcc70 (physical)
🤖 Prompt for 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.

In @.github/workflows/unix.yaml around lines 169 - 190, The job display names
are ambiguous; update the name fields to clearly distinguish VM vs physical
hardware: change the job with id/test name testnetbsd (uses vmactions/netbsd-vm,
id: test-netbsd) to something like "Test JDK 11, NetBSD (VM)" or "Test JDK 11,
NetBSD — VM" and change the testnetbsd-gcc70 job to "Test JDK 11, NetBSD (GCC
farm)" or "Test JDK 11, NetBSD — physical (GCC farm)" so CI status displays
clearly indicate which run is the VM and which is on the GCC compile farm.
oshi-core/src/main/java/oshi/software/os/unix/netbsd/NetBsdOperatingSystem.java (1)

147-150: ⚡ Quick win

Use a real PID API instead of parsing RuntimeMXBean.getName().

The Javadoc says RuntimeMXBean.getName() may be any implementation-defined JVM name, while RuntimeMXBean.getPid() and ProcessHandle.pid() expose the actual PID directly. Parsing split("@")[0] can therefore return -1 on JVMs that do not use the HotSpot-style name format. (docs.oracle.com)

Suggested fix
     public int getProcessId() {
-        // RuntimeMXBean name format is "pid@hostname"
-        String name = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
-        return ParseUtil.parseIntOrDefault(name.split("@")[0], -1);
+        return Math.toIntExact(ProcessHandle.current().pid());
     }
🤖 Prompt for 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.

In
`@oshi-core/src/main/java/oshi/software/os/unix/netbsd/NetBsdOperatingSystem.java`
around lines 147 - 150, The getProcessId method in NetBsdOperatingSystem
currently parses RuntimeMXBean.getName(), which is implementation-defined;
replace this with a real PID API: call
java.lang.management.RuntimeMXBean.getPid() when available or use
ProcessHandle.current().pid() (preferred on Java 9+), and only fall back to the
current parseInt-on-name approach as a last resort; update getProcessId to
return the PID from RuntimeMXBean.getPid() / ProcessHandle.current().pid() and
remove reliance on name.split("@")[0].
🤖 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 @.github/workflows/unix.yaml:
- Around line 188-210: The workflow step "Test in NetBSD" in job
testnetbsd-gcc70 uses the unpinned action reference appleboy/ssh-action@master;
replace that with a specific commit SHA (pin) from the appleboy/ssh-action
release history to avoid supply-chain risk (e.g.,
appleboy/ssh-action@<commit-sha>), ensuring you update the uses value only and
keep the rest of the step (host, username, key, port, script) unchanged.

In
`@oshi-core/src/main/java/oshi/hardware/platform/unix/netbsd/NetBsdCentralProcessor.java`:
- Around line 360-366: The code in NetBsdCentralProcessor that fills the
double[] average currently leaves entries at 0.0 when sysctl fails or returns
fewer values; initialize or set all unavailable entries to the documented
sentinel -1.0. Change the logic around the average array population (variable
average, nelem, loads, ParseUtil.parseDoubleOrDefault) so that average is
initialized to -1d for all positions (or explicitly assign -1d to any index i >=
loads.length after parsing) and ensure trim/empty sysctl output is handled so no
element is left as 0.0.

In
`@oshi-core/src/main/java/oshi/software/os/unix/netbsd/NetBsdOperatingSystem.java`:
- Around line 164-166: The current implementation of
NetBsdOperatingSystem.getThreadId() returns the Java thread id which does not
match the NetBSD LWP id used by NetBsdOSThread.getThreadId(); replace the Java
id with the kernel LWP id by calling NetBsdLibc._lwp_self() (cast to int) so
getThreadId() and NetBsdOperatingSystem.getCurrentThread() match the
PsThreadColumns.LID values; also add the necessary NetBsdLibc reference/import
and handle any native call exceptions if present.

In `@oshi-core/src/main/java/oshi/util/platform/unix/netbsd/FstatUtil.java`:
- Around line 35-36: In FstatUtil (the method parsing fstat output) the guard
uses if (split.length > 3 && "wd".equals(split[3])) but then accesses split[4],
which can throw ArrayIndexOutOfBoundsException; change the length check to
ensure at least 5 elements (e.g., split.length > 4 or split.length >= 5) before
accessing split[4], keeping the existing "wd" check and return behavior in the
same block.

---

Nitpick comments:
In @.github/workflows/unix.yaml:
- Around line 169-190: The job display names are ambiguous; update the name
fields to clearly distinguish VM vs physical hardware: change the job with
id/test name testnetbsd (uses vmactions/netbsd-vm, id: test-netbsd) to something
like "Test JDK 11, NetBSD (VM)" or "Test JDK 11, NetBSD — VM" and change the
testnetbsd-gcc70 job to "Test JDK 11, NetBSD (GCC farm)" or "Test JDK 11, NetBSD
— physical (GCC farm)" so CI status displays clearly indicate which run is the
VM and which is on the GCC compile farm.

In
`@oshi-core/src/main/java/oshi/software/os/unix/netbsd/NetBsdOperatingSystem.java`:
- Around line 147-150: The getProcessId method in NetBsdOperatingSystem
currently parses RuntimeMXBean.getName(), which is implementation-defined;
replace this with a real PID API: call
java.lang.management.RuntimeMXBean.getPid() when available or use
ProcessHandle.current().pid() (preferred on Java 9+), and only fall back to the
current parseInt-on-name approach as a last resort; update getProcessId to
return the PID from RuntimeMXBean.getPid() / ProcessHandle.current().pid() and
remove reliance on name.split("@")[0].
🪄 Autofix (Beta)

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

Run ID: eb8695fd-4937-4644-b4c1-36a037e1002f

📥 Commits

Reviewing files that changed from the base of the PR and between 088e39b and 3a54c85.

📒 Files selected for processing (8)
  • .github/workflows/unix.yaml
  • oshi-core/src/main/java/module-info.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/netbsd/NetBsdCentralProcessor.java
  • oshi-core/src/main/java/oshi/software/os/unix/netbsd/NetBsdOSProcess.java
  • oshi-core/src/main/java/oshi/software/os/unix/netbsd/NetBsdOperatingSystem.java
  • oshi-core/src/main/java/oshi/util/platform/unix/netbsd/FstatUtil.java
  • oshi-core/src/main/java/oshi/util/platform/unix/netbsd/NetBsdSysctlUtil.java
  • oshi-core/src/test/java/oshi/jna/util/FileUtilJNATest.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). (13)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-04-06T04:45:47.644Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3121
File: oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java:53-53
Timestamp: 2026-04-06T04:45:47.644Z
Learning: In the oshi/oshi project, only interfaces and classes in the root packages `oshi`, `oshi.hardware`, and `oshi.software.os` are considered the public API. Code in subpackages that represent specific implementations/platforms (e.g., `oshi.software.os.linux`, `oshi.hardware.platform.linux`, and similar subpackages) is implementation detail. When reviewing, do not treat changes to classes in these platform-specific subpackages as public API breaks (for example: making `LinuxOperatingSystem` abstract, narrowing constructor visibility, or adding/removing abstract methods should not be flagged as breaking public API).

Applied to files:

  • oshi-core/src/main/java/oshi/software/os/unix/netbsd/NetBsdOperatingSystem.java
  • oshi-core/src/main/java/oshi/software/os/unix/netbsd/NetBsdOSProcess.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/netbsd/NetBsdCentralProcessor.java
🪛 zizmor (1.25.2)
.github/workflows/unix.yaml

[error] 196-196: unpinned action reference (unpinned-uses): action is not pinned to a hash (required by blanket policy)

(unpinned-uses)

🔇 Additional comments (4)
oshi-core/src/main/java/module-info.java (1)

47-47: LGTM!

.github/workflows/unix.yaml (1)

167-186: LGTM!

oshi-core/src/test/java/oshi/jna/util/FileUtilJNATest.java (1)

14-14: LGTM!

Also applies to: 21-21

oshi-core/src/main/java/oshi/util/platform/unix/netbsd/FstatUtil.java (1)

27-31: LGTM!

Comment thread .github/workflows/unix.yaml Resolved
Comment on lines 239 to 255
public long getSoftOpenFileLimit() {
if (getProcessID() == this.os.getProcessId()) {
final Resource.Rlimit rlimit = new Resource.Rlimit();
NetBsdLibc.INSTANCE.getrlimit(NetBsdLibc.RLIMIT_NOFILE, rlimit);
return rlimit.rlim_cur;
} else {
return -1L; // not supported
long limit = NetBsdSysctlUtil.sysctl("kern.maxfilesperproc", 0L);
if (limit <= 0) {
limit = NetBsdSysctlUtil.sysctl("kern.maxfiles", 0L);
}
return limit > 0 ? limit : -1L;
}
return -1L;
}

@Override
public long getHardOpenFileLimit() {
if (getProcessID() == this.os.getProcessId()) {
final Resource.Rlimit rlimit = new Resource.Rlimit();
NetBsdLibc.INSTANCE.getrlimit(NetBsdLibc.RLIMIT_NOFILE, rlimit);
return rlimit.rlim_max;
} else {
return -1L; // not supported
long limit = NetBsdSysctlUtil.sysctl("kern.maxfiles", 0L);
return limit > 0 ? limit : -1L;
}

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Query the per-process descriptor RLIMITs here instead of kernel maxima.

getSoftOpenFileLimit() / getHardOpenFileLimit() are supposed to report the current process limit, but kern.maxfiles is the system-wide file-table cap, and NetBSD already exposes per-process descriptor limits at proc.pid.rlimit.descriptors.{soft,hard}. This change can therefore overreport the current process limits whenever the process is below the kernel maximum. (man.netbsd.org)

Suggested fix
     public long getSoftOpenFileLimit() {
         if (getProcessID() == this.os.getProcessId()) {
-            long limit = NetBsdSysctlUtil.sysctl("kern.maxfilesperproc", 0L);
-            if (limit <= 0) {
-                limit = NetBsdSysctlUtil.sysctl("kern.maxfiles", 0L);
-            }
+            long limit = NetBsdSysctlUtil.sysctl("proc." + getProcessID() + ".rlimit.descriptors.soft", 0L);
             return limit > 0 ? limit : -1L;
         }
         return -1L;
     }

     `@Override`
     public long getHardOpenFileLimit() {
         if (getProcessID() == this.os.getProcessId()) {
-            long limit = NetBsdSysctlUtil.sysctl("kern.maxfiles", 0L);
+            long limit = NetBsdSysctlUtil.sysctl("proc." + getProcessID() + ".rlimit.descriptors.hard", 0L);
             return limit > 0 ? limit : -1L;
         }
         return -1L;
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public long getSoftOpenFileLimit() {
if (getProcessID() == this.os.getProcessId()) {
final Resource.Rlimit rlimit = new Resource.Rlimit();
NetBsdLibc.INSTANCE.getrlimit(NetBsdLibc.RLIMIT_NOFILE, rlimit);
return rlimit.rlim_cur;
} else {
return -1L; // not supported
long limit = NetBsdSysctlUtil.sysctl("kern.maxfilesperproc", 0L);
if (limit <= 0) {
limit = NetBsdSysctlUtil.sysctl("kern.maxfiles", 0L);
}
return limit > 0 ? limit : -1L;
}
return -1L;
}
@Override
public long getHardOpenFileLimit() {
if (getProcessID() == this.os.getProcessId()) {
final Resource.Rlimit rlimit = new Resource.Rlimit();
NetBsdLibc.INSTANCE.getrlimit(NetBsdLibc.RLIMIT_NOFILE, rlimit);
return rlimit.rlim_max;
} else {
return -1L; // not supported
long limit = NetBsdSysctlUtil.sysctl("kern.maxfiles", 0L);
return limit > 0 ? limit : -1L;
}
public long getSoftOpenFileLimit() {
if (getProcessID() == this.os.getProcessId()) {
long limit = NetBsdSysctlUtil.sysctl("proc." + getProcessID() + ".rlimit.descriptors.soft", 0L);
return limit > 0 ? limit : -1L;
}
return -1L;
}
`@Override`
public long getHardOpenFileLimit() {
if (getProcessID() == this.os.getProcessId()) {
long limit = NetBsdSysctlUtil.sysctl("proc." + getProcessID() + ".rlimit.descriptors.hard", 0L);
return limit > 0 ? limit : -1L;
}
return -1L;
}

Replace all JNA native calls with command-line alternatives so NetBSD
works without the pkgsrc java-jna package:
- sysctl MIB-based calls -> sysctl -n string-based calls
- getpid() -> ManagementFactory.getRuntimeMXBean().getName()
- _lwp_self() -> Thread.currentThread().getId()
- getloadavg() -> sysctl -n vm.loadavg parsing
- getrlimit() -> sysctl kern.maxfiles/kern.maxfilesperproc
- Native.LONG_SIZE -> os.arch system property
- kern.cp_time binary sysctl -> parse string output
- ARGMAX via JNA -> sysctl -n kern.argmax
- NetBsdSysctlUtil rewritten to pure command-line (no JNA imports)
- CPU state constants moved from NetBsdLibc to CentralProcessor
- getCwd fallback via fstat when /proc not mounted
- Disable FileUtilJNATest on NetBSD (requires JNA native library)

Also:
- Remove stale netbsd-port branch from unix.yaml trigger
- Add gcc70 (GCC Compile Farm) NetBSD job to unix.yaml
- Update NetBSD VM job to not install java-jna (tests no-native path)
- Add requires java.management to module-info
- Initialize load average array to -1d sentinel
- Fix fstat bounds check for getCwd parsing
- Disambiguate CI job names: (VM) vs (GCC farm)
@dbwiddis
dbwiddis force-pushed the netbsd-no-native branch from 3a54c85 to 330dd08 Compare May 31, 2026 04:45

@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-core/src/main/java/oshi/software/os/unix/netbsd/NetBsdOperatingSystem.java`:
- Around line 147-150: Replace the runtime MXBean parsing in getProcessId() with
the standard ProcessHandle API: call ProcessHandle.current().pid() and return it
cast to int; remove the split/ParseUtil.parseIntOrDefault logic in
NetBsdOperatingSystem.getProcessId(). Also guard with a try/catch to return -1
on any unexpected error (or if pid doesn't fit in int) to preserve existing
failure semantics.
🪄 Autofix (Beta)

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

Run ID: fb5cc401-b8b5-408a-8210-06e8f9cf4163

📥 Commits

Reviewing files that changed from the base of the PR and between 3a54c85 and 330dd08.

📒 Files selected for processing (8)
  • .github/workflows/unix.yaml
  • oshi-core/src/main/java/module-info.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/netbsd/NetBsdCentralProcessor.java
  • oshi-core/src/main/java/oshi/software/os/unix/netbsd/NetBsdOSProcess.java
  • oshi-core/src/main/java/oshi/software/os/unix/netbsd/NetBsdOperatingSystem.java
  • oshi-core/src/main/java/oshi/util/platform/unix/netbsd/FstatUtil.java
  • oshi-core/src/main/java/oshi/util/platform/unix/netbsd/NetBsdSysctlUtil.java
  • oshi-core/src/test/java/oshi/jna/util/FileUtilJNATest.java
🚧 Files skipped from review as they are similar to previous changes (5)
  • oshi-core/src/test/java/oshi/jna/util/FileUtilJNATest.java
  • oshi-core/src/main/java/module-info.java
  • oshi-core/src/main/java/oshi/util/platform/unix/netbsd/FstatUtil.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/netbsd/NetBsdCentralProcessor.java
  • oshi-core/src/main/java/oshi/software/os/unix/netbsd/NetBsdOSProcess.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). (11)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-04-06T04:45:47.644Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3121
File: oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java:53-53
Timestamp: 2026-04-06T04:45:47.644Z
Learning: In the oshi/oshi project, only interfaces and classes in the root packages `oshi`, `oshi.hardware`, and `oshi.software.os` are considered the public API. Code in subpackages that represent specific implementations/platforms (e.g., `oshi.software.os.linux`, `oshi.hardware.platform.linux`, and similar subpackages) is implementation detail. When reviewing, do not treat changes to classes in these platform-specific subpackages as public API breaks (for example: making `LinuxOperatingSystem` abstract, narrowing constructor visibility, or adding/removing abstract methods should not be flagged as breaking public API).

Applied to files:

  • oshi-core/src/main/java/oshi/software/os/unix/netbsd/NetBsdOperatingSystem.java
🪛 zizmor (1.25.2)
.github/workflows/unix.yaml

[error] 196-196: unpinned action reference (unpinned-uses): action is not pinned to a hash (required by blanket policy)

(unpinned-uses)

🔇 Additional comments (3)
.github/workflows/unix.yaml (2)

196-196: Unresolved action pinning on SSH step.

Still uses appleboy/ssh-action@master; this was already flagged and remains unresolved in the current diff.


167-187: LGTM!

oshi-core/src/main/java/oshi/software/os/unix/netbsd/NetBsdOperatingSystem.java (1)

164-165: This still returns a Java thread id, not the NetBSD LWP id.

Line 165 feeds getCurrentThread() with a Java thread id, but the OSThread instances returned from proc.getThreadDetails() are matched against NetBSD thread ids sourced from ps's LID column. Those ids are different domains, so the lookup can still miss the current thread and fall back to an invalid placeholder.

#!/bin/bash
set -euo pipefail

fd 'NetBsdOperatingSystem.java$' -x sed -n '163,174p' {}
fd 'NetBsdOSProcess.java$' -x rg -n -C2 '\bLID\b|PsThreadColumns'
fd 'NetBsdOSThread.java$' -x rg -n -C2 'threadId|PsThreadColumns\.LID'

Comment on lines 147 to +150
public int getProcessId() {
return NetBsdLibc.INSTANCE.getpid();
// RuntimeMXBean name format is "pid@hostname"
String name = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
return ParseUtil.parseIntOrDefault(name.split("@")[0], -1);

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

What does the Java SE specification guarantee about RuntimeMXBean.getName() format, and is ProcessHandle.current().pid() the standard API for retrieving the current process ID?

💡 Result:

The Java SE specification does not guarantee any specific format for the string returned by RuntimeMXBean.getName [1][2]. The specification explicitly states that the returned value can be any arbitrary string, and that a Java virtual machine (JVM) implementation may choose to embed platform-specific information within it [1][2]. Consequently, the format can vary between different JVM implementations and even between different executions of the same JVM [1]. ProcessHandle.current.pid is the standard, modern API for retrieving the current process ID (PID) in Java [3][4]. Introduced in Java 9, the ProcessHandle interface provides a native and reliable way to access process information, including the PID, without relying on non-standard system properties or platform-specific hacks [3][5][4].

Citations:


Use the standard PID API instead of parsing RuntimeMXBean.getName()

RuntimeMXBean.getName()’s string format is not specified by Java SE (it’s arbitrary/implementation-defined), so splitting on pid@hostname can yield non-PID values and make getProcessId() return -1, breaking current-process checks (e.g., NetBsdOSProcess’s current-process env var exposure). Use ProcessHandle.current().pid() instead.

🩹 Proposed fix
     `@Override`
     public int getProcessId() {
-        // RuntimeMXBean name format is "pid@hostname"
-        String name = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
-        return ParseUtil.parseIntOrDefault(name.split("@")[0], -1);
+        return Math.toIntExact(ProcessHandle.current().pid());
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public int getProcessId() {
return NetBsdLibc.INSTANCE.getpid();
// RuntimeMXBean name format is "pid@hostname"
String name = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
return ParseUtil.parseIntOrDefault(name.split("@")[0], -1);
`@Override`
public int getProcessId() {
return Math.toIntExact(ProcessHandle.current().pid());
}
🤖 Prompt for 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.

In
`@oshi-core/src/main/java/oshi/software/os/unix/netbsd/NetBsdOperatingSystem.java`
around lines 147 - 150, Replace the runtime MXBean parsing in getProcessId()
with the standard ProcessHandle API: call ProcessHandle.current().pid() and
return it cast to int; remove the split/ParseUtil.parseIntOrDefault logic in
NetBsdOperatingSystem.getProcessId(). Also guard with a try/catch to return -1
on any unexpected error (or if pid doesn't fit in int) to preserve existing
failure semantics.

@dbwiddis
dbwiddis merged commit 1373684 into oshi:master May 31, 2026
20 checks passed
@dbwiddis
dbwiddis deleted the netbsd-no-native branch May 31, 2026 05:15
dbwiddis added a commit that referenced this pull request Jul 7, 2026
…ack (#3433)

* Restore optional JNA native access for NetBSD with command-line fallback

NetBSD's JNA native support was removed in #3310 because JNA does not distribute
a native binary for NetBSD (only the optional pkgsrc java-jna package), and OSHI
does not require installing dependencies. This restores the native path while
keeping the command-line implementation as a runtime fallback.

A JNA-availability gate (NetBsdSysctlUtil.JNA_AVAILABLE, following the Solaris
HAS_KSTAT2 pattern) forces NetBsdLibc.INSTANCE at class load and catches
UnsatisfiedLinkError. When JNA is available the new *JNA subclasses use native
sysctl (cp_time ticks, load average), getpid/_lwp_self for process/thread
identity, getrlimit for open-file limits, and kern.proc_args for other
processes' environment; otherwise each method delegates to the command-line
NetBsd* base classes in oshi-common.

The oshi-core JNA SystemInfo now selects the *JNA NetBSD classes; oshi-core-ffm
continues to use the native-free command-line classes. Common
NetBsdOperatingSystem gains an overridable createProcess factory and
NetBsdHardwareAbstractionLayer is de-finalized, mirroring the FreeBSD hooks.

NetBsdLibc gains RLIMIT_NOFILE = 8 (NetBSD's value); JNA's inherited
Resource.RLIMIT_NOFILE is the Linux value 7, so the pre-#3310 code would have
queried the wrong resource.

unix.yaml now runs the NetBSD VM both without java-jna (command-line path) and
with it (native path).

* Add CHANGELOG entry for #3433

* Parse NetBSD process environment by bytes, not Java chars

The KERN_PROC_ENV sysctl payload is a NUL-delimited native byte buffer;
advancing the offset by String.length() misaligns on a multibyte charset.
Parse via ParseUtil.parseByteArrayToStrings on the raw bytes instead (the same
byte-based helper used by the command-line queryArguments).
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