Skip to content

FFM migration of WindowsOSProcess - #3126

Merged
dbwiddis merged 4 commits into
oshi:masterfrom
rohan-coder02:feature/ffm-windows-osprocess
Apr 11, 2026
Merged

dbwiddis merged 4 commits into
oshi:masterfrom
rohan-coder02:feature/ffm-windows-osprocess

Conversation

@rohan-coder02

@rohan-coder02 rohan-coder02 commented Apr 8, 2026 •

Copy link
Copy Markdown
Collaborator

Summary:

Migrates WindowsOSProcess from JNA to FFM (Foreign Function & Memory API) for Java 25+.

Files Created/Updated:

  • Create NtDllFFM.java with process structures (PROCESS_BASIC_INFORMATION, PEB, RTL_USER_PROCESS_PARAMETERS, UNICODE_STRING) and NtQueryInformationProcess
  • Create Shell32FFM.java with CommandLineToArgv
  • Create WindowsOSProcessFFM.java implementing OSProcess using FFM
  • Extend Kernel32FFM.java with OpenProcess, GetProcessAffinityMask, IsWow64Process, ReadProcessMemory, QueryFullProcessImageName, LocalFree
  • Extend Advapi32FFM.java with LookupAccountSid, ConvertSidToStringSid
  • Add process access rights constants to WinNTFFM.java
  • Add ERROR_ACCESS_DENIED to WinErrorFFM.java
  • Update WindowsOperatingSystemFFM to use WindowsOSProcessFFM

Testing:

Verified on Windows with a simple test program:

import oshi.SystemInfoFFM;
import oshi.software.os.OSProcess;
import oshi.software.os.OperatingSystem;
import java.util.List;
 
public class TestOSHI {
    public static void main(String[] args) {
        SystemInfoFFM si = new SystemInfoFFM();
        OperatingSystem os = si.getOperatingSystem();
        System.out.println("OS: " + os);
        System.out.println("PID: " + os.getProcessId());
        OSProcess p = os.getProcess(os.getProcessId());
        if (p != null) {
            System.out.println("Name: " + p.getName());
            System.out.println("User: " + p.getUser());
            System.out.println("Path: " + p.getPath());
            System.out.println("Threads: " + p.getThreadCount());
            System.out.println("RSS: " + (p.getResidentSetSize()/1024/1024) + " MB");
            System.out.println("Bitness: " + p.getBitness() + "-bit");
        }
        List<OSProcess> procs = os.getProcesses(
            OperatingSystem.ProcessFiltering.ALL_PROCESSES,
            OperatingSystem.ProcessSorting.RSS_DESC, 5);
        for (OSProcess proc : procs) {
            System.out.printf("PID %6d: %-20s (%d MB)%n",
                proc.getProcessID(), proc.getName(), proc.getResidentSetSize()/1024/1024);
        }
    }
}

Test Output (Windows)

--- Current Process ---
Name: java
PID: 1416
User: Administrator
Path: C:\Users\Administrator\Documents\zulu25.32.21-ca-jdk25.0.2-win_x64\bin\java.exe
Threads: 21
RSS: 40 MB
Bitness: 64-bit
 
--- Top 5 Processes ---
PID   3068: MsMpEng              (114 MB)
PID   1416: java                 (53 MB)
PID   4520: explorer             (27 MB)
PID   3032: WindowsTerminal      (10 MB)
PID   3856: dwm                  (8 MB)

All process information (name, PID, user, path, threads, memory, bitness, process listing) retrieved successfully via FFM.

Summary by CodeRabbit

  • New Features

    • Added comprehensive Windows process retrieval via FFM: executable path, working directory, command line & arguments, environment, user/group, threads, memory/IO and timing.
    • Improved process listing/querying with parallel construction and smarter filtering.
  • Bug Fixes

    • More robust remote process reads and safer handling of access-denied or truncated results.

@coderabbitai

coderabbitai Bot commented Apr 8, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds Windows FFM (Foreign Function & Memory) bindings and a new FFM-based Windows process model. New classes expose Advapi32, Kernel32, NtDll, Shell32 native calls, constants, and helpers; WindowsOSProcessFFM and WindowsOperatingSystemFFM use these bindings to collect process attributes (paths, command line, env, user/group, threads, memory, bitness).

Changes

Cohort / File(s) Summary
Advapi32 additions
oshi-core-java25/src/main/java/oshi/ffm/windows/Advapi32FFM.java
Added token constants (TokenUser, TokenPrimaryGroup) and new downcall-backed wrappers: LookupAccountSid(...) and ConvertSidToStringSid(...).
Kernel32 extensions
oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
Added downcalls and wrappers for OpenProcess, GetProcessAffinityMask, IsWow64Process, ReadProcessMemory, QueryFullProcessImageName (with dynamic buffer retry) and LocalFree.
New NtDll bindings & layouts
oshi-core-java25/src/main/java/oshi/ffm/windows/NtDllFFM.java
New class with NtQueryInformationProcess downcall, numerous StructLayout definitions and exported offsets, plus readUnicodeString(...) helper to read UNICODE_STRING from remote process memory.
Shell32 helper
oshi-core-java25/src/main/java/oshi/ffm/windows/Shell32FFM.java
New class binding CommandLineToArgvW and CommandLineToArgv(String) helper that converts a command line wide string to Java argument list and frees native argv.
Win error / NT constants
oshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.java, oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java
Added ERROR_ACCESS_DENIED and process access rights constants (PROCESS_QUERY_INFORMATION, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_VM_READ).
FFM-based process implementation
oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
New thread-safe OSProcess implementation using FFM bindings to populate name/path/state/times/IO/affinity/bitness/threads, resolve user/group, command-line, arguments, CWD and environment via PEB/remote reads or fallbacks; memoized suppliers used.
Operating system process listing
oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java
Added/overrode process APIs (getProcesses, getProcess, queryAllProcesses), processMapToList(...) pipeline with memoization, WTS integration, parallel construction of WindowsOSProcessFFM, and minor logging tweaks.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant WinOS as WindowsOperatingSystemFFM
    participant Memoizer
    participant ProcessFFM as WindowsOSProcessFFM
    participant FFM as FFM Bindings
    participant Native as Windows Native APIs

    Caller->>WinOS: getProcesses()/getProcess(pid)
    WinOS->>Memoizer: obtain cached process/thread metrics
    Memoizer-->>WinOS: ProcessPerformanceData
    WinOS->>ProcessFFM: construct WindowsOSProcessFFM(pid,...)
    ProcessFFM->>FFM: OpenProcess(pid)
    FFM->>Native: Kernel32!OpenProcess
    Native-->>FFM: process handle
    ProcessFFM->>FFM: IsWow64Process(handle) / QueryFullProcessImageName(handle)
    FFM->>Native: Kernel32!IsWow64Process / QueryFullProcessImageName
    Native-->>FFM: bitness / image path
    ProcessFFM->>FFM: NtQueryInformationProcess(handle)
    FFM->>Native: NtDll!NtQueryInformationProcess
    Native-->>FFM: PROCESS_BASIC_INFORMATION / PEB pointer
    ProcessFFM->>FFM: ReadProcessMemory(handle, peb/params)
    FFM->>Native: Kernel32!ReadProcessMemory
    Native-->>FFM: remote memory bytes (command line, env, CWD)
    ProcessFFM->>FFM: CommandLineToArgv(commandLine) / LookupAccountSid / ConvertSidToStringSid
    FFM->>Native: Shell32!CommandLineToArgvW / Advapi32!LookupAccountSidW / Advapi32!ConvertSidToStringSidW
    Native-->>FFM: argv pointer / account info / SID string
    ProcessFFM->>Caller: populated OSProcess instance
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰 Soft paws on keys I tap and twirl,

I hunt for SIDs and flags that whirl,
I bind the calls from kernel deep,
I read the PEB while others sleep,
Hooray — processes revealed in a curl! 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'FFM migration of WindowsOSProcess' clearly and concisely summarizes the main objective of the pull request—migrating the WindowsOSProcess implementation from JNA to FFM.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
✨ Simplify code
  • Create PR with simplified code

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 Apr 8, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 62.21%. Comparing base (5b317dd) to head (9809d23).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3126      +/-   ##
============================================
+ Coverage     62.08%   62.21%   +0.12%     
  Complexity       12       12              
============================================
  Files            39       39              
  Lines          2329     2329              
  Branches        407      407              
============================================
+ Hits           1446     1449       +3     
+ Misses          775      770       -5     
- Partials        108      110       +2     

☔ 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: 7

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java`:
- Around line 448-457: The QueryFullProcessImageName helper currently allocates
a fixed 260-char buffer and returns empty on failure; change it to retry with a
growing buffer when the buffer is too small: in
QueryFullProcessImageName(MemorySegment hProcess, int dwFlags, Arena arena)
start with maxPath=260, loop (e.g., doubling maxPath up to a sane limit)
reallocating buffer = arena.allocate(JAVA_CHAR, maxPath) and sizeSegment =
arena.allocate(JAVA_INT) (or reset sizeSegment) before each call to
QueryFullProcessImageName; after a successful call return
Optional.of(readWideString(buffer)) using the returned size from sizeSegment,
and if QueryFullProcessImageName fails check for the buffer-insufficient
condition (via the reported size or GetLastError/expected indication) to
continue retrying, otherwise break and return Optional.empty. Ensure you
reference and update JAVA_CHAR, JAVA_INT, readWideString, MemorySegment, and
Arena usages accordingly.

In `@oshi-core-java25/src/main/java/oshi/ffm/windows/Shell32FFM.java`:
- Around line 61-70: The code in Shell32FFM currently uses a fixed reinterpret
size argPtr.reinterpret(1024) which truncates long arguments; replace that with
logic that determines the wide-string length dynamically by walking from argPtr
until a UTF-16 null (two zero bytes) is found (using ADDRESS.byteSize() / 2
steps) and then reinterpret the segment to the computed byte length
(lengthInChars * 2) before calling readWideString, or alternatively change
readWideString to accept a MemorySegment pointer and read characters until the
null terminator directly; update the loop that references
argvPtr/argvArray/argPtr to compute the correct size instead of using 1024.

In
`@oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java`:
- Around line 225-234: The code currently intersects WTS results with process
data (using ProcessWtsData.queryProcessWtsMap and mapKeys.retainAll), causing
all processes to be dropped if WTS enumeration fails; instead iterate the
processMap keys (or original pids set) and build WindowsOSProcessFFM for each
pid while optionally looking up WTS info from ProcessWtsData.queryProcessWtsMap
(which may be empty), i.e. replace the retainAll logic with streaming over
processMap.keySet().parallelStream() (or pids) and call new
WindowsOSProcessFFM(pid, this, finalProcessMap, processWtsMap, finalThreadMap)
so WTS enrichment is optional rather than gating the result set. Ensure
WindowsOSProcessFFM (constructor) can handle a missing/empty entry in
processWtsMap.

In
`@oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java`:
- Around line 417-423: The code flips this.state to INVALID when
Kernel32FFM.QueryFullProcessImageName fails, which incorrectly removes
otherwise-valid processes; change the logic in the IS_WINDOWS7_OR_GREATER branch
so that on a missing path (pathOpt.isPresent() == false) you do not modify
this.state (leave it as-is) and do not overwrite this.path (keep previous value
or leave empty) — i.e., only assign this.path when QueryFullProcessImageName
returns a value and never set this.state = INVALID in that failure path; update
the block around Kernel32FFM.QueryFullProcessImageName, this.path, and
this.state accordingly.
- Around line 583-606: LookupAccountSid is populating the domain into
domainBuffer but the code only uses the short account name; modify the block
using LookupAccountSid to also read the domain via readWideString(domainBuffer)
and construct a domain-qualified account (e.g., domain + "\\" + accountName)
when domain is non-empty and not Constants.UNKNOWN, replacing the current
accountName assignment; return that domain-qualified name in the Pair along with
sidString (keep using domainBuffer, domainLen, accountName, readWideString,
LookupAccountSid, and the existing Pair construction).
- Around line 348-363: The current updateAttributes() calls
updateAttributes(pcb.get(...), wts.get(...)) which can NPE when
buildProcessMapFromRegistry(...) omits this pid or Wts map is null; wrap the
method body in a try { ... } catch (Throwable t) { return false; } (no logging)
so updateAttributes() preserves its boolean-failure contract; ensure you still
call ProcessPerformanceData.buildProcessMapFromRegistry(null), fallback to
buildProcessMapFromPerfCounters(pids), call queryMatchingThreads(pids) when
USE_PROCSTATE_SUSPENDED, and ProcessWtsData.queryProcessWtsMap(pids) inside the
try, then return updateAttributes(pcb.get(this.getProcessID()),
wts.get(this.getProcessID())) as before.
- Around line 597-603: The code in WindowsOSProcessFFM uses
Advapi32FFM.ConvertSidToStringSid to get a native string into sidStringPtr and
reads it via readWideString but never frees the buffer, leaking native memory;
after reading the string (the block using sidStringPtr/sidPtr and readWideString
in WindowsOSProcessFFM) call Kernel32FFM.LocalFree on the returned pointer (the
MemorySegment strPtr) to release the buffer allocated by ConvertSidToStringSid,
ensuring LocalFree is invoked only when strPtr.address() != 0 and after
readWideString completes.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e219b141-79a4-49fe-a2e9-75b1372e1c12

📥 Commits

Reviewing files that changed from the base of the PR and between c760ab0 and 3ca7b71.

📒 Files selected for processing (8)
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Advapi32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/NtDllFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Shell32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.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). (7)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 21, macos-latest
🧰 Additional context used
🧠 Learnings (4)
📚 Learning: 2026-04-03T02:07:47.621Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3110
File: oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java:119-121
Timestamp: 2026-04-03T02:07:47.621Z
Learning: In OSHI’s Java FFM/API implementation classes (e.g., *FFM.java) that implement/override `updateAttributes()`, preserve the intentional failure-handling pattern: catch `Throwable` and return `false` without logging. `updateAttributes()` is a public API whose contract is to signal failure via the boolean return value, and callers rely on that return value (so emitting logs from this path is not desired and should not be introduced during review unless the method contract changes).

Applied to files:

  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Shell32FFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Advapi32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/NtDllFFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
📚 Learning: 2026-03-29T20:01:06.452Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java11/src/main/java/module-info.java:10-17
Timestamp: 2026-03-29T20:01:06.452Z
Learning: In the oshi project, `oshi-core-java25/src/main/java/module-info.java` intentionally does NOT export `oshi.util.platform.unix.freebsd`, `oshi.util.platform.unix.openbsd`, or `oshi.util.platform.unix.solaris`, because the FFM (Foreign Function & Memory) implementation only supports Windows, macOS, and Linux. This differs from `oshi-core-java11/src/main/java/module-info.java` which exports all Unix platform packages. The asymmetry is by design.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
📚 Learning: 2026-03-29T20:03:00.830Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java:87-89
Timestamp: 2026-03-29T20:03:00.830Z
Learning: In the OSHI FFM codebase (oshi-core-java25), all PDH/Kernel32/COM wrapper methods in classes like PdhFFM, Kernel32FFM, etc. declare `throws Throwable` solely as a compiler artifact of `MethodHandle.invokeExact`. They are native calls and do not throw Java checked exceptions in practice. The enclosing `getOpenFileDescriptors()` method in PdhUtilFFM already has an outer `catch (Throwable t)` that covers the entire method body including any `finally` blocks, so no exception-masking concern exists for cleanup calls like `PdhCloseQuery` in `finally`.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/ffm/windows/Shell32FFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/NtDllFFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
📚 Learning: 2026-04-08T00:58:07.212Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3125
File: oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java:131-133
Timestamp: 2026-04-08T00:58:07.212Z
Learning: In `oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java` and `oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java`, the `getPowerSources()` method intentionally returns a singleton list wrapping a single `getPowerSource("System Battery")` call, and the enumeration loop short-circuits after the first eligible battery pack. This matches the longstanding JNA behavior and is not a bug. A broader refactor to support zero-or-more batteries across both implementations is planned for a later date. Do not flag this as an issue.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java

@rohan-coder02
rohan-coder02 force-pushed the feature/ffm-windows-osprocess branch from 3ca7b71 to 00005ba Compare April 8, 2026 11:06

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

🧹 Nitpick comments (1)
oshi-core-java25/src/main/java/oshi/ffm/windows/Advapi32FFM.java (1)

166-175: Update Javadoc to document memory ownership for ConvertSidToStringSid.

The StringSid output parameter receives an allocation that must be freed by the caller via Kernel32FFM.LocalFree(...). This should be explicitly documented in the parameter and return value description to prevent memory leaks in future uses:

Suggested documentation update
     /**
      * Converts a SID to a string format.
      *
      * `@param` Sid        The SID to convert
-     * `@param` StringSid  Pointer to receive the string SID
+     * `@param` StringSid  Pointer to receive the allocated string SID pointer (LPWSTR*)
+     *                   Caller must free the returned buffer with Kernel32FFM.LocalFree(...)
      * `@return` true if successful
      */
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core-java25/src/main/java/oshi/ffm/windows/Advapi32FFM.java` around
lines 166 - 175, Update the Javadoc for ConvertSidToStringSid to document memory
ownership: state that the output parameter StringSid receives a newly allocated
pointer that the caller is responsible for freeing (when the call succeeds)
using Kernel32FFM.LocalFree(...); document that Sid is an input-only parameter
and that on success the caller must call Kernel32FFM.LocalFree on the returned
StringSid to avoid leaks, and clarify the boolean return indicates success of
the conversion.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@oshi-core-java25/src/main/java/oshi/ffm/windows/Advapi32FFM.java`:
- Around line 166-175: Update the Javadoc for ConvertSidToStringSid to document
memory ownership: state that the output parameter StringSid receives a newly
allocated pointer that the caller is responsible for freeing (when the call
succeeds) using Kernel32FFM.LocalFree(...); document that Sid is an input-only
parameter and that on success the caller must call Kernel32FFM.LocalFree on the
returned StringSid to avoid leaks, and clarify the boolean return indicates
success of the conversion.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c44f5874-8087-4746-a4d4-3da19d4d78e4

📥 Commits

Reviewing files that changed from the base of the PR and between 3ca7b71 and 00005ba.

📒 Files selected for processing (8)
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Advapi32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/NtDllFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Shell32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java
✅ Files skipped from review due to trivial changes (3)
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
🚧 Files skipped from review as they are similar to previous changes (4)
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Shell32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/NtDllFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.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). (7)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Test JDK 11, windows-latest
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-04-03T02:07:47.621Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3110
File: oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java:119-121
Timestamp: 2026-04-03T02:07:47.621Z
Learning: In OSHI’s Java FFM/API implementation classes (e.g., *FFM.java) that implement/override `updateAttributes()`, preserve the intentional failure-handling pattern: catch `Throwable` and return `false` without logging. `updateAttributes()` is a public API whose contract is to signal failure via the boolean return value, and callers rely on that return value (so emitting logs from this path is not desired and should not be introduced during review unless the method contract changes).

Applied to files:

  • oshi-core-java25/src/main/java/oshi/ffm/windows/Advapi32FFM.java
🔇 Additional comments (2)
oshi-core-java25/src/main/java/oshi/ffm/windows/Advapi32FFM.java (2)

137-140: Token info constants look correct.

No concerns on Line 138 and Line 139; the added constants align with expected token information class usage.


141-161: LookupAccountSidW binding and wrapper are consistent.

The downcall signature and boolean return handling on Line 141–160 match the surrounding FFM wrapper pattern.

@rohan-coder02
rohan-coder02 force-pushed the feature/ffm-windows-osprocess branch from 00005ba to 79b7c57 Compare April 8, 2026 11:25

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

🧹 Nitpick comments (1)
oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java (1)

479-485: Make LocalFree harder to misuse at call sites.

LocalFree encodes success/failure in its return value, but callers can easily ignore it (as seen in Shell32FFM), which can silently hide failed frees. Consider adding a checked helper (boolean LocalFreeChecked(...)) and using it where cleanup correctness matters.

Suggested API addition
 public static MemorySegment LocalFree(MemorySegment hMem) {
     try {
         return (MemorySegment) LocalFree.invokeExact(hMem);
     } catch (Throwable t) {
         LOG.debug("Kernel32FFM.LocalFree failed: {}", t.getMessage());
         return hMem;
     }
 }
+
+public static boolean LocalFreeChecked(MemorySegment hMem) {
+    MemorySegment result = LocalFree(hMem);
+    return result == null || result.address() == 0;
+}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java` around
lines 479 - 485, Add a safer, checked wrapper around Kernel32FFM.LocalFree to
make failures harder to ignore: implement a new method boolean
LocalFreeChecked(MemorySegment hMem) in Kernel32FFM that calls the existing
LocalFree(MemorySegment) and returns true if the return value indicates success
(null/zero per Native API) and false otherwise, and log a warning/error with the
throwable/message on failure; then replace critical cleanup call sites (e.g., in
Shell32FFM where LocalFree results are currently ignored) to call
LocalFreeChecked and handle or propagate a false result appropriately.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java`:
- Around line 479-485: Add a safer, checked wrapper around Kernel32FFM.LocalFree
to make failures harder to ignore: implement a new method boolean
LocalFreeChecked(MemorySegment hMem) in Kernel32FFM that calls the existing
LocalFree(MemorySegment) and returns true if the return value indicates success
(null/zero per Native API) and false otherwise, and log a warning/error with the
throwable/message on failure; then replace critical cleanup call sites (e.g., in
Shell32FFM where LocalFree results are currently ignored) to call
LocalFreeChecked and handle or propagate a false result appropriately.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6609fdef-a1f0-4b61-ac4f-ef793626deed

📥 Commits

Reviewing files that changed from the base of the PR and between 00005ba and 79b7c57.

📒 Files selected for processing (8)
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Advapi32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/NtDllFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Shell32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java
✅ Files skipped from review due to trivial changes (2)
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java
🚧 Files skipped from review as they are similar to previous changes (4)
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Shell32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/NtDllFFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Advapi32FFM.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). (7)
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: 2026-03-29T20:03:00.830Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java:87-89
Timestamp: 2026-03-29T20:03:00.830Z
Learning: In the OSHI FFM codebase (oshi-core-java25), all PDH/Kernel32/COM wrapper methods in classes like PdhFFM, Kernel32FFM, etc. declare `throws Throwable` solely as a compiler artifact of `MethodHandle.invokeExact`. They are native calls and do not throw Java checked exceptions in practice. The enclosing `getOpenFileDescriptors()` method in PdhUtilFFM already has an outer `catch (Throwable t)` that covers the entire method body including any `finally` blocks, so no exception-masking concern exists for cleanup calls like `PdhCloseQuery` in `finally`.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
📚 Learning: 2026-03-29T20:01:06.452Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java11/src/main/java/module-info.java:10-17
Timestamp: 2026-03-29T20:01:06.452Z
Learning: In the oshi project, `oshi-core-java25/src/main/java/module-info.java` intentionally does NOT export `oshi.util.platform.unix.freebsd`, `oshi.util.platform.unix.openbsd`, or `oshi.util.platform.unix.solaris`, because the FFM (Foreign Function & Memory) implementation only supports Windows, macOS, and Linux. This differs from `oshi-core-java11/src/main/java/module-info.java` which exports all Unix platform packages. The asymmetry is by design.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
📚 Learning: 2026-04-03T02:07:47.621Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3110
File: oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java:119-121
Timestamp: 2026-04-03T02:07:47.621Z
Learning: In OSHI’s Java FFM/API implementation classes (e.g., *FFM.java) that implement/override `updateAttributes()`, preserve the intentional failure-handling pattern: catch `Throwable` and return `false` without logging. `updateAttributes()` is a public API whose contract is to signal failure via the boolean return value, and callers rely on that return value (so emitting logs from this path is not desired and should not be introduced during review unless the method contract changes).

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
🔇 Additional comments (7)
oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java (5)

176-188: LGTM!

The configuration flag and memoized suppliers follow established OSHI patterns. Instance-level memoization is appropriate for the process/thread maps, and the VALID_PROCESS predicate provides clean filtering logic.


190-204: LGTM!

The public API methods are clean delegations to processMapToList. The getProcess null check is appropriate for the single-process lookup case.


246-260: LGTM!

Static helper methods correctly delegate to the underlying ProcessPerformanceData and ThreadPerformanceData builders with null to indicate "all" mode, as expected by the memoized suppliers.


225-225: No null-safety issue — queryProcessWtsMap always returns a non-null Map.

The method at ProcessWtsData.queryProcessWtsMap() creates and returns either a HashMap from queryProcessWtsMapFromWTS() or queryProcessWtsMapFromPerfMon(). Both code paths instantiate a new HashMap and return it; neither path returns null. The test suite confirms the method returns a non-null Map, and similar code throughout the codebase (e.g., WindowsOperatingSystem.java:317) calls keySet() without null checks, treating the result as guaranteed non-null.

			> Likely an incorrect or invalid review comment.

206-213: No issue here; processMap is guaranteed non-null after fallback.

The buildProcessMapFromPerfCounters() method always returns a non-empty or empty HashMap, never null (visible at line 106: Map<Integer, PerfCounterBlock> processMap = new HashMap<>();). While buildProcessMapFromRegistry() can return null, the fallback logic ensures that when registry fails, processMap is assigned a HashMap instance. Therefore, the processMap.keySet() calls on lines 232/236 are safe from NullPointerException.

			> Likely an incorrect or invalid review comment.
oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java (2)

340-437: FFM wrapper additions look consistent and safe.

OpenProcess, GetProcessAffinityMask, IsWow64Process, ReadProcessMemory, and the boolean QueryFullProcessImageName wrapper follow the established OSHI FFM pattern (native call + guarded fallback), and the failure paths are coherent with Optional/boolean return contracts.

Based on learnings: in OSHI FFM wrappers, catch (Throwable) around MethodHandle.invokeExact is intentional and not a checked-exception design issue.


448-468: Retry-based buffer growth for process image path is a good fix.

The looped allocation strategy (260 → up to 32K) removes the previous fixed-buffer limitation and is a solid improvement for long-path cases.

@dbwiddis dbwiddis left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good! A few tweaks.

Remember to run spotless:apply and checkstyle:check before committing.

{rohan-coder02} and others added 2 commits April 11, 2026 09:01
- Create NtDllFFM, Shell32FFM, WindowsOSProcessFFM
- Extend Kernel32FFM and Advapi32FFM with process functions
- Add process constants to WinNTFFM and WinErrorFFM
- Fix buffer sizing, memory leaks, null handling, PID filtering
@dbwiddis
dbwiddis force-pushed the feature/ffm-windows-osprocess branch from 79b7c57 to 3cc35dc Compare April 11, 2026 17:05
@dbwiddis
dbwiddis force-pushed the feature/ffm-windows-osprocess branch from 3cc35dc to 4b473d4 Compare April 11, 2026 17:25

@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 the current code and only fix it if needed.

Inline comments:
In
`@oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java`:
- Around line 491-494: OpenProcessToken is requesting TOKEN_DUPLICATE (0x0002)
unnecessarily when only TOKEN_QUERY (0x0008) is needed for GetTokenInformation;
change the call sites that pass "0x0008 | 0x0002" to request just TOKEN_QUERY so
OpenProcessToken succeeds for query-only tokens (update both occurrences around
where hToken is obtained and where getTokenAccountInfo(TokenUser, arena) is
called), ensuring getUser() and getGroup() use only TOKEN_QUERY.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 098fa611-4d58-4129-8d01-4d53843327d5

📥 Commits

Reviewing files that changed from the base of the PR and between 3cc35dc and 4b473d4.

📒 Files selected for processing (1)
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.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). (9)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (7)
📚 Learning: 2026-04-03T02:07:47.621Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3110
File: oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java:119-121
Timestamp: 2026-04-03T02:07:47.621Z
Learning: In OSHI’s Java FFM/API implementation classes (e.g., *FFM.java) that implement/override `updateAttributes()`, preserve the intentional failure-handling pattern: catch `Throwable` and return `false` without logging. `updateAttributes()` is a public API whose contract is to signal failure via the boolean return value, and callers rely on that return value (so emitting logs from this path is not desired and should not be introduced during review unless the method contract changes).

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
📚 Learning: 2026-04-10T22:44:32.055Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3136
File: oshi-core-java25/src/main/java/oshi/software/os/linux/LinuxOperatingSystemFFM.java:46-53
Timestamp: 2026-04-10T22:44:32.055Z
Learning: In OSHI's `AuxvFFM.queryAuxv()` (oshi-core-java25/src/main/java/oshi/driver/linux/proc/AuxvFFM.java), the do-while loop is safe even when `/proc/self/auxv` cannot be read: `FileUtil.readAllBytesAsBuffer` returns an empty ByteBuffer on failure, and `FileUtil.readLongFromBuffer`/`readIntFromBuffer` return 0L when reading past the buffer limit. This 0L equals AT_NULL, causing the loop to exit immediately with an empty map, which triggers the `getconf`/hardcoded-default fallback in callers like `LinuxOperatingSystemFFM`. Do not flag this do-while loop or the static initializer that calls `AuxvFFM.queryAuxv()` as unsafe.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
📚 Learning: 2026-03-29T20:03:00.830Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java:87-89
Timestamp: 2026-03-29T20:03:00.830Z
Learning: In the OSHI FFM codebase (oshi-core-java25), all PDH/Kernel32/COM wrapper methods in classes like PdhFFM, Kernel32FFM, etc. declare `throws Throwable` solely as a compiler artifact of `MethodHandle.invokeExact`. They are native calls and do not throw Java checked exceptions in practice. The enclosing `getOpenFileDescriptors()` method in PdhUtilFFM already has an outer `catch (Throwable t)` that covers the entire method body including any `finally` blocks, so no exception-masking concern exists for cleanup calls like `PdhCloseQuery` in `finally`.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
📚 Learning: 2026-04-05T05:39:21.126Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3117
File: oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java:62-65
Timestamp: 2026-04-05T05:39:21.126Z
Learning: In OSHI's Linux FFM/JNA udev code, a null guard on `udev_enumerate_new()` is unnecessary if `udev_new()` has already been guarded: per libudev semantics, `udev_enumerate_new()` only returns NULL when udev itself is broken (e.g. OOM), so a successful `udev_new()` implies `udev_enumerate_new()` will succeed as well. Do not flag missing null checks on `udev_enumerate_new()` as an issue.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
📚 Learning: 2026-04-08T00:58:10.736Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3125
File: oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java:131-133
Timestamp: 2026-04-08T00:58:10.736Z
Learning: In `oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java` and `oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java`, the `getPowerSources()` method intentionally returns a singleton list wrapping a single `getPowerSource("System Battery")` call, and the enumeration loop short-circuits after the first eligible battery pack. This matches the longstanding JNA behavior and is not a bug. A broader refactor to support zero-or-more batteries across both implementations is planned for a later date. Do not flag this as an issue.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
📚 Learning: 2026-04-05T05:40:45.797Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3117
File: oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java:62-65
Timestamp: 2026-04-05T05:40:45.797Z
Learning: In OSHI's Linux FFM and JNA udev code, a null guard on `udev_enumerate_new()` is intentionally absent and should not be flagged. This is consistent across all four FFM classes (LinuxPowerSourceFFM, LinuxHWDiskStoreFFM, LinuxLogicalVolumeGroupFFM, LinuxUsbDeviceFFM) and the JNA implementation (which also does not guard `enumerateNew()` for null). Per libudev semantics, `udev_enumerate_new()` only returns NULL when udev itself is broken (e.g. OOM), so a successful `udev_new()` (which is guarded) implies `udev_enumerate_new()` will succeed. Adding a null guard would be both redundant and inconsistent with the established pattern.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
📚 Learning: 2026-04-06T22:30:07.083Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3122
File: oshi-core/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceJNA.java:215-234
Timestamp: 2026-04-06T22:30:07.083Z
Learning: In `oshi-core/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceJNA.java`, the `found` flag in `getControllerIdByLocation` is intentionally set to `true` as soon as either `vendor-id` or `device-id` is found in a matching service's parent. This is a deliberate design choice: a partial match (one of the two IDs) is preferred over continuing to iterate, because iterating further risks pairing IDs from two different and potentially mismatched services. Do not flag this as a bug or suggest splitting into separate `foundVendor`/`foundProduct` flags.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
🔇 Additional comments (1)
oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java (1)

623-625: Remove this review comment; the guard is correct.

The equality WindowsOperatingSystem.isX86() == isWow(h, arena) is intentionally comparing OS processor architecture with the target process's bitness. On 32-bit Windows, all processes are 32-bit; on 64-bit Windows, 64-bit native processes have isWow() false while 32-bit WOW64 processes have isWow() true. This correctly allows memory access only when the JVM and target process share the same bitness and prevents a 64-bit JVM from reading a 32-bit WOW64 process. The identical pattern exists in the older JNA implementation and is the correct design.

@dbwiddis

Copy link
Copy Markdown
Member

@CodeRabbit full review

@coderabbitai

coderabbitai Bot commented Apr 11, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

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

🧹 Nitpick comments (1)
oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java (1)

132-155: Consider extracting version detection to a shared utility.

The isWindowsVistaOrGreater() and isWindows7OrGreater() methods parse os.version manually. This pattern likely exists in the JNA implementation as well.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java`
around lines 132 - 155, The two methods isWindowsVistaOrGreater and
isWindows7OrGreater duplicate os.version parsing; extract this logic into a
shared utility (e.g., WindowsVersionUtil or OsVersionHelper) that parses
System.getProperty("os.version") once into major/minor ints (using
ParseUtil.parseIntOrDefault) and exposes a reusable comparator method like
isWindowsVersionOrGreater(int major, int minor) or getters getMajor/getMinor;
update isWindowsVistaOrGreater and isWindows7OrGreater to delegate to that
utility (or, if JNA already provides an equivalent helper, call that instead) to
remove duplication and centralize version logic.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In
`@oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java`:
- Around line 132-155: The two methods isWindowsVistaOrGreater and
isWindows7OrGreater duplicate os.version parsing; extract this logic into a
shared utility (e.g., WindowsVersionUtil or OsVersionHelper) that parses
System.getProperty("os.version") once into major/minor ints (using
ParseUtil.parseIntOrDefault) and exposes a reusable comparator method like
isWindowsVersionOrGreater(int major, int minor) or getters getMajor/getMinor;
update isWindowsVistaOrGreater and isWindows7OrGreater to delegate to that
utility (or, if JNA already provides an equivalent helper, call that instead) to
remove duplication and centralize version logic.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c6e332fd-17d7-433e-bf8b-abed7ee16b25

📥 Commits

Reviewing files that changed from the base of the PR and between 5b317dd and 4b473d4.

📒 Files selected for processing (8)
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Advapi32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/NtDllFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Shell32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.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). (1)
  • GitHub Check: Codacy Static Code Analysis
🧰 Additional context used
🧠 Learnings (8)
📚 Learning: 2026-04-03T02:07:47.621Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3110
File: oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java:119-121
Timestamp: 2026-04-03T02:07:47.621Z
Learning: In OSHI’s Java FFM/API implementation classes (e.g., *FFM.java) that implement/override `updateAttributes()`, preserve the intentional failure-handling pattern: catch `Throwable` and return `false` without logging. `updateAttributes()` is a public API whose contract is to signal failure via the boolean return value, and callers rely on that return value (so emitting logs from this path is not desired and should not be introduced during review unless the method contract changes).

Applied to files:

  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Shell32FFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/NtDllFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Advapi32FFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
📚 Learning: 2026-03-29T20:03:00.830Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java:87-89
Timestamp: 2026-03-29T20:03:00.830Z
Learning: In the OSHI FFM codebase (oshi-core-java25), all PDH/Kernel32/COM wrapper methods in classes like PdhFFM, Kernel32FFM, etc. declare `throws Throwable` solely as a compiler artifact of `MethodHandle.invokeExact`. They are native calls and do not throw Java checked exceptions in practice. The enclosing `getOpenFileDescriptors()` method in PdhUtilFFM already has an outer `catch (Throwable t)` that covers the entire method body including any `finally` blocks, so no exception-masking concern exists for cleanup calls like `PdhCloseQuery` in `finally`.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Shell32FFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/NtDllFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Advapi32FFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
📚 Learning: 2026-04-10T22:44:32.055Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3136
File: oshi-core-java25/src/main/java/oshi/software/os/linux/LinuxOperatingSystemFFM.java:46-53
Timestamp: 2026-04-10T22:44:32.055Z
Learning: In OSHI's `AuxvFFM.queryAuxv()` (oshi-core-java25/src/main/java/oshi/driver/linux/proc/AuxvFFM.java), the do-while loop is safe even when `/proc/self/auxv` cannot be read: `FileUtil.readAllBytesAsBuffer` returns an empty ByteBuffer on failure, and `FileUtil.readLongFromBuffer`/`readIntFromBuffer` return 0L when reading past the buffer limit. This 0L equals AT_NULL, causing the loop to exit immediately with an empty map, which triggers the `getconf`/hardcoded-default fallback in callers like `LinuxOperatingSystemFFM`. Do not flag this do-while loop or the static initializer that calls `AuxvFFM.queryAuxv()` as unsafe.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/ffm/windows/Shell32FFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
📚 Learning: 2026-04-08T00:58:10.736Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3125
File: oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java:131-133
Timestamp: 2026-04-08T00:58:10.736Z
Learning: In `oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java` and `oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java`, the `getPowerSources()` method intentionally returns a singleton list wrapping a single `getPowerSource("System Battery")` call, and the enumeration loop short-circuits after the first eligible battery pack. This matches the longstanding JNA behavior and is not a bug. A broader refactor to support zero-or-more batteries across both implementations is planned for a later date. Do not flag this as an issue.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
📚 Learning: 2026-03-29T20:01:06.452Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java11/src/main/java/module-info.java:10-17
Timestamp: 2026-03-29T20:01:06.452Z
Learning: In the oshi project, `oshi-core-java25/src/main/java/module-info.java` intentionally does NOT export `oshi.util.platform.unix.freebsd`, `oshi.util.platform.unix.openbsd`, or `oshi.util.platform.unix.solaris`, because the FFM (Foreign Function & Memory) implementation only supports Windows, macOS, and Linux. This differs from `oshi-core-java11/src/main/java/module-info.java` which exports all Unix platform packages. The asymmetry is by design.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/NtDllFFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
📚 Learning: 2026-04-05T05:39:21.126Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3117
File: oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java:62-65
Timestamp: 2026-04-05T05:39:21.126Z
Learning: In OSHI's Linux FFM/JNA udev code, a null guard on `udev_enumerate_new()` is unnecessary if `udev_new()` has already been guarded: per libudev semantics, `udev_enumerate_new()` only returns NULL when udev itself is broken (e.g. OOM), so a successful `udev_new()` implies `udev_enumerate_new()` will succeed as well. Do not flag missing null checks on `udev_enumerate_new()` as an issue.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
📚 Learning: 2026-04-05T05:40:45.797Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3117
File: oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java:62-65
Timestamp: 2026-04-05T05:40:45.797Z
Learning: In OSHI's Linux FFM and JNA udev code, a null guard on `udev_enumerate_new()` is intentionally absent and should not be flagged. This is consistent across all four FFM classes (LinuxPowerSourceFFM, LinuxHWDiskStoreFFM, LinuxLogicalVolumeGroupFFM, LinuxUsbDeviceFFM) and the JNA implementation (which also does not guard `enumerateNew()` for null). Per libudev semantics, `udev_enumerate_new()` only returns NULL when udev itself is broken (e.g. OOM), so a successful `udev_new()` (which is guarded) implies `udev_enumerate_new()` will succeed. Adding a null guard would be both redundant and inconsistent with the established pattern.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
📚 Learning: 2026-04-06T22:30:07.083Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3122
File: oshi-core/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceJNA.java:215-234
Timestamp: 2026-04-06T22:30:07.083Z
Learning: In `oshi-core/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceJNA.java`, the `found` flag in `getControllerIdByLocation` is intentionally set to `true` as soon as either `vendor-id` or `device-id` is found in a matching service's parent. This is a deliberate design choice: a partial match (one of the two IDs) is preferred over continuing to iterate, because iterating further risks pairing IDs from two different and potentially mismatched services. Do not flag this as a bug or suggest splitting into separate `foundVendor`/`foundProduct` flags.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
🔇 Additional comments (19)
oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java (6)

483-551: Pre-existing issue: TOKEN_DUPLICATE is unnecessary.

Lines 491 and 526 request TOKEN_QUERY | TOKEN_DUPLICATE (0x0008 | 0x0002), but only TOKEN_QUERY is needed for GetTokenInformation. This was noted in a past review and acknowledged as a pre-existing bug to be fixed in a follow-up PR.


74-130: LGTM!

The class structure correctly:

  • Extends AbstractOSProcess with memoized suppliers for lazy evaluation
  • Initializes bitness from the OS and later checks for WOW64
  • Stores the thread counter block reference for thread details

338-357: LGTM!

The updateAttributes() method correctly follows the OSHI pattern: catches Throwable and returns false without logging, preserving the boolean-failure contract.


359-428: LGTM!

The private updateAttributes(pcb, wts) correctly:

  • Returns false with INVALID state when pcb is null
  • Doesn't set INVALID on path lookup failure (process remains valid)
  • Properly closes the process handle in a finally block

553-614: LGTM!

The getTokenAccountInfo method correctly:

  • Builds domain-qualified account names (domain\name)
  • Frees the SID string buffer via LocalFree(strPtr) after reading

616-701: LGTM!

The queryCwdCommandlineEnvironment method correctly:

  • Checks bitness compatibility before reading PEB
  • Validates each memory read result before proceeding
  • Properly closes the process handle in a finally block
  • Returns safe defaults on any failure path
oshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.java (1)

9-9: LGTM!

The ERROR_ACCESS_DENIED constant correctly matches the Windows API value (5) and follows the existing pattern in this interface.

oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java (4)

329-352: LGTM!

The OpenProcess wrapper correctly handles null/zero address returns and follows the established pattern of returning Optional.empty() on failure with debug logging.


354-415: LGTM!

The GetProcessAffinityMask, IsWow64Process, and ReadProcessMemory wrappers correctly use the isSuccess() pattern and follow the established FFM wrapper conventions.


447-468: LGTM!

The retry logic for QueryFullProcessImageName correctly handles long paths by doubling the buffer size up to 32K. The check returnedSize < maxPath appropriately distinguishes buffer-too-small failures from other errors.


470-485: LGTM!

The LocalFree wrapper correctly returns the input segment on failure, which is a safe fallback since callers can check the return value (NULL on success per Windows API).

oshi-core-java25/src/main/java/oshi/ffm/windows/Shell32FFM.java (1)

41-91: LGTM!

The CommandLineToArgv implementation correctly:

  • Handles null/empty input gracefully
  • Dynamically calculates string lengths by scanning for null terminators
  • Frees the native memory via LocalFree in a finally block
  • Returns an unmodifiable empty list on any failure
oshi-core-java25/src/main/java/oshi/ffm/windows/NtDllFFM.java (2)

36-105: LGTM!

The Windows structure layouts are correctly defined for 64-bit systems with appropriate padding and field ordering. The exported offset constants enable safe field access.


107-163: LGTM!

The NtQueryInformationProcess wrapper correctly returns -1 on failure (distinct from STATUS_SUCCESS = 0). The readUnicodeString helper properly validates the length and buffer pointer before attempting to read from remote process memory.

oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java (1)

30-33: LGTM!

The process access right constants match their official Windows API values.

oshi-core-java25/src/main/java/oshi/ffm/windows/Advapi32FFM.java (1)

136-179: LGTM!

The token information class constants are correct, and both LookupAccountSid and ConvertSidToStringSid wrappers follow established patterns. The Javadoc for ConvertSidToStringSid correctly documents that callers must free the returned buffer via LocalFree.

oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java (3)

49-49: LGTM!

The @ThreadSafe annotation correctly documents the thread-safety guarantees of this class.


63-104: LGTM!

The enableDebugPrivilege() method now correctly uses SLF4J structured placeholders ({}) instead of string concatenation for logging.


207-245: LGTM!

The processMapToList pipeline correctly:

  • Uses memoized suppliers for performance data
  • Intersects WTS keys with processMap keys for queryAllProcesses() (ensuring full data availability)
  • Filters by processMap availability only for specific PIDs (WTS enrichment is optional)
  • Parallel-streams the process construction and filters via VALID_PROCESS

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.

2 participants