Repository navigation
Refactor PowerSource hierarchy and add Windows FFM implementation - #3125
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughRefactors power-source discovery into a protected per-platform hook, adds Windows FFM SetupAPI/Kernel32/PowrProf bindings, implements FFM- and JNA-based Windows PowerSource providers and HAL, updates SystemInfo to instantiate the Windows FFM HAL, and adjusts platform PowerSource classes to use the new hook. Changes
Sequence Diagram(s)sequenceDiagram
participant Sys as SystemInfo
participant HAL as WindowsHardwareAbstractionLayerFFM
participant PS as WindowsPowerSourceFFM
participant Setup as SetupApiFFM
participant K32 as Kernel32FFM
participant Win as Windows API
Sys->>HAL: getPowerSources()
HAL->>PS: getPowerSources()
PS->>Setup: SetupDiGetClassDevs(GUID_DEVCLASS_BATTERY)
Setup->>Win: SetupDiGetClassDevsW
Win-->>Setup: hDevInfo
Setup-->>PS: Optional<MemorySegment>
loop enumerate interfaces
PS->>Setup: SetupDiEnumDeviceInterfaces(...)
Setup->>Win: SetupDiEnumDeviceInterfaces
Win-->>Setup: interface data
Setup-->>PS: enum result
alt interface found
PS->>Setup: SetupDiGetDeviceInterfaceDetail (probe then read)
Setup->>Win: SetupDiGetDeviceInterfaceDetailW
Win-->>Setup: device path
Setup-->>PS: Optional<String>
PS->>K32: CreateFile(devicePath)
K32->>Win: CreateFileW
Win-->>K32: hDevice
K32-->>PS: Optional<MemorySegment>
loop per IOCTL
PS->>K32: DeviceIoControl(IOCTL_*)
K32->>Win: DeviceIoControl
Win-->>K32: data / success
K32-->>PS: boolean / data
end
PS->>PS: derive/filter battery attributes
end
end
PS->>Setup: SetupDiDestroyDeviceInfoList
Setup->>Win: SetupDiDestroyDeviceInfoList
PS-->>HAL: List<PowerSource>
HAL-->>Sys: List<PowerSource>
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
✨ Simplify 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. Comment |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #3125 +/- ##
==========================================
+ Coverage 66.96% 67.55% +0.58%
==========================================
Files 37 37
Lines 2025 2034 +9
Branches 336 340 +4
==========================================
+ Hits 1356 1374 +18
+ Misses 549 542 -7
+ Partials 120 118 -2 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java (2)
97-112: Consider using caller-provided Arena for consistency.
SetupDiGetDeviceInterfaceDetailSizeusesArena.ofAuto()internally for allocatingrequiredSize, while other methods in this class expect an Arena parameter. While this works, it creates an inconsistency and the auto-managed arena lives until GC.♻️ Suggested improvement
Consider accepting an
Arenaparameter for consistency with other methods:- public static int SetupDiGetDeviceInterfaceDetailSize(MemorySegment hDevInfo, MemorySegment deviceInterfaceData) { + public static int SetupDiGetDeviceInterfaceDetailSize(MemorySegment hDevInfo, MemorySegment deviceInterfaceData, Arena arena) { try { - Arena arena = Arena.ofAuto(); MemorySegment requiredSize = arena.allocate(JAVA_INT);🤖 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/SetupApiFFM.java` around lines 97 - 112, The method SetupDiGetDeviceInterfaceDetailSize currently creates its own Arena via Arena.ofAuto(), causing inconsistency and non-deterministic lifetime; change its signature to accept an Arena parameter (e.g., SetupDiGetDeviceInterfaceDetailSize(Arena arena, MemorySegment hDevInfo, MemorySegment deviceInterfaceData)), allocate requiredSize from that provided arena instead of Arena.ofAuto(), and remove the internal Arena.ofAuto() usage; update all callers to pass their existing Arena instances so allocation lifetimes remain consistent with other methods in SetupApiFFM (reference the method name SetupDiGetDeviceInterfaceDetail and Kernel32FFM.GetLastError usage to locate the related logic).
124-143: Same Arena.ofAuto() pattern - consider consistency.
SetupDiGetDeviceInterfaceDetailalso usesArena.ofAuto()internally. Since this method allocates larger buffers (the device path string), using a caller-provided arena would give callers more control over memory lifetime.🤖 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/SetupApiFFM.java` around lines 124 - 143, The method SetupDiGetDeviceInterfaceDetail currently creates its own Arena via Arena.ofAuto(), which prevents callers from controlling memory lifetime; change the method signature to accept an Arena (e.g., Arena arena) from the caller, remove the internal Arena.ofAuto() creation, and allocate detail and reqSize from that provided arena (detail, reqSize) so the caller manages scope and cleanup; keep the rest of the logic (invoking SetupDiGetDeviceInterfaceDetail, checking isSuccess(result), and using readWideString(detail.asSlice(4))) unchanged and ensure no automatic close is performed inside this method.oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java (1)
92-92: Architecture detection may be fragile on some JVMs.The check
System.getProperty("os.arch", "").contains("64")works for common cases (amd64,x86_64) but could be more explicit. However, this matches the pattern used elsewhere in the codebase.Consider using a more explicit check if portability becomes an issue:
private static final boolean IS_64BIT = "amd64".equals(System.getProperty("os.arch")) || "x86_64".equals(System.getProperty("os.arch"));🤖 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/hardware/platform/windows/WindowsPowerSourceFFM.java` at line 92, The architecture detection using the IS_64BIT constant in WindowsPowerSourceFFM is fragile; update the assignment to check for explicit architecture strings instead of contains("64") — e.g., compare System.getProperty("os.arch") against known 64-bit identifiers like "amd64" and "x86_64" (and any other project-standard values) so IS_64BIT becomes a deterministic boolean; locate the private static final boolean IS_64BIT declaration in WindowsPowerSourceFFM and replace the contains-based check with explicit equality checks against the accepted 64-bit strings.
🤖 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 73-80: The wrapper DeviceIoControl currently passes
MemorySegment.NULL for both lpOverlapped and lpBytesReturned which causes
synchronous calls to fail; allocate a temporary 32-bit DWORD MemorySegment
(e.g., with MemorySegment.allocateNative / appropriate ValueLayout) to act as
lpBytesReturned, pass that segment instead of MemorySegment.NULL to
DeviceIoControl.invokeExact, keep lpOverlapped as MemorySegment.NULL for
synchronous calls, and read/ignore the DWORD after the call; reference
DeviceIoControl, DeviceIoControl.invokeExact, lpBytesReturned, and
MemorySegment.NULL when making the change.
In `@oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java`:
- Around line 35-39: The SP_DEVICE_INTERFACE_DATA StructLayout currently uses
sequenceLayout(16, JAVA_INT.withName("byte")) which allocates 64 bytes for the
GUID; change that sequenceLayout to use JAVA_BYTE (e.g., sequenceLayout(16,
JAVA_BYTE).withName("InterfaceClassGuid")) so the GUID is 16 bytes, and add a
static import for java.lang.foreign.ValueLayout.JAVA_BYTE; update the
SP_DEVICE_INTERFACE_DATA declaration accordingly to restore correct field
offsets for the structure.
---
Nitpick comments:
In `@oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java`:
- Around line 97-112: The method SetupDiGetDeviceInterfaceDetailSize currently
creates its own Arena via Arena.ofAuto(), causing inconsistency and
non-deterministic lifetime; change its signature to accept an Arena parameter
(e.g., SetupDiGetDeviceInterfaceDetailSize(Arena arena, MemorySegment hDevInfo,
MemorySegment deviceInterfaceData)), allocate requiredSize from that provided
arena instead of Arena.ofAuto(), and remove the internal Arena.ofAuto() usage;
update all callers to pass their existing Arena instances so allocation
lifetimes remain consistent with other methods in SetupApiFFM (reference the
method name SetupDiGetDeviceInterfaceDetail and Kernel32FFM.GetLastError usage
to locate the related logic).
- Around line 124-143: The method SetupDiGetDeviceInterfaceDetail currently
creates its own Arena via Arena.ofAuto(), which prevents callers from
controlling memory lifetime; change the method signature to accept an Arena
(e.g., Arena arena) from the caller, remove the internal Arena.ofAuto()
creation, and allocate detail and reqSize from that provided arena (detail,
reqSize) so the caller manages scope and cleanup; keep the rest of the logic
(invoking SetupDiGetDeviceInterfaceDetail, checking isSuccess(result), and using
readWideString(detail.asSlice(4))) unchanged and ensure no automatic close is
performed inside this method.
In
`@oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java`:
- Line 92: The architecture detection using the IS_64BIT constant in
WindowsPowerSourceFFM is fragile; update the assignment to check for explicit
architecture strings instead of contains("64") — e.g., compare
System.getProperty("os.arch") against known 64-bit identifiers like "amd64" and
"x86_64" (and any other project-standard values) so IS_64BIT becomes a
deterministic boolean; locate the private static final boolean IS_64BIT
declaration in WindowsPowerSourceFFM and replace the contains-based check with
explicit equality checks against the accepted 64-bit strings.
🪄 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: 7b46e387-8c1e-4142-8b0c-02d94cfd4460
📒 Files selected for processing (21)
oshi-core-java25/src/main/java/oshi/ffm/SystemInfo.javaoshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/com/GuidFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayerFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayer.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.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). (6)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Test JDK 21, macos-latest
- GitHub Check: Test JDK 25, macos-latest
- GitHub Check: Analyze (java)
- GitHub Check: Test JDK 11, macos-latest
- GitHub Check: Test JDK 25, windows-latest
🧰 Additional context used
🧠 Learnings (11)
📚 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/hardware/platform/unix/aix/AixPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayer.javaoshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdPowerSource.javaoshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.javaoshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.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/src/main/java/oshi/hardware/platform/unix/aix/AixPowerSource.javaoshi-core-java25/src/main/java/oshi/ffm/SystemInfo.javaoshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdPowerSource.javaoshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayerFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.java
📚 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, the public API is strictly limited to interfaces and classes in the `oshi`, `oshi.hardware`, and `oshi.software.os` packages. All platform-specific code under subpackages like `oshi.software.os.linux`, `oshi.hardware.platform.linux`, etc., is considered implementation detail — not public API. Do not flag changes to platform-specific classes (e.g., making `LinuxOperatingSystem` abstract, narrowing constructor visibility, adding abstract methods) as public API breaks.
Applied to files:
oshi-core-java25/src/main/java/oshi/ffm/SystemInfo.javaoshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayerFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 Learning: 2026-04-03T18:44:46.910Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3112
File: oshi-core/src/main/java/oshi/PlatformEnum.java:63-66
Timestamp: 2026-04-03T18:44:46.910Z
Learning: In oshi/oshi PlatformEnum.java, the DRAGONFLYBSD enum constant is intentionally added for platform detection only (no implementation classes exist yet). It allows UnsupportedOperationException messages to say "DragonFly BSD" rather than "Unknown". Full DragonFly BSD support is tracked in issue `#2583`. Do not flag the missing switch-case implementations as a bug.
Applied to files:
oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdPowerSource.javaoshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.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/hardware/platform/mac/MacPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/com/GuidFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayerFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
📚 Learning: 2026-04-03T18:43:50.370Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3112
File: oshi-core/src/main/java/oshi/PlatformEnum.java:99-100
Timestamp: 2026-04-03T18:43:50.370Z
Learning: In oshi/oshi PlatformEnum.java, the DragonFly BSD detection uses `osName.equalsIgnoreCase("dragonflybsd")` intentionally, mirroring the exact same check in JNA's `Platform.java` source. Java's `os.name` property on DragonFly BSD is "dragonflybsd" (no space), so `startsWith("DragonFly")` is NOT the correct pattern here. Do not suggest changing it to `startsWith`.
Applied to files:
oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.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.javaoshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 Learning: 2026-04-05T05:40:43.357Z
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:43.357Z
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/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 Learning: 2026-04-05T05:39:18.791Z
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:18.791Z
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/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.java
📚 Learning: 2026-04-05T05:40:43.357Z
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:43.357Z
Learning: In OSHI’s Linux FFM implementations (e.g., LinuxPowerSourceFFM, LinuxHWDiskStoreFFM, LinuxLogicalVolumeGroupFFM, LinuxUsbDeviceFFM) and the corresponding JNA udev code, do not require/flag a missing null check around `udev_enumerate_new()`/`enumerateNew()`. Per libudev semantics, `udev_enumerate_new()` returns NULL only if udev itself is broken (e.g., OOM). Since `udev_new()` is already guarded and is the successful prerequisite for enumeration, treating `udev_enumerate_new()` as non-null is consistent with the established pattern; adding a redundant null guard would be inconsistent.
Applied to files:
oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java
📚 Learning: 2026-04-05T05:39:18.791Z
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:18.791Z
Learning: When reviewing OSHI Linux FFM/JNA code that uses libudev, do not flag a missing null check on `udev_enumerate_new()` if `udev_new()` has already been guarded. Per libudev semantics, `udev_enumerate_new()` returns NULL only when the udev context itself is broken (e.g., OOM), so a successful `udev_new()` implies `udev_enumerate_new()` should succeed as well. Therefore, lack of a redundant null guard on `udev_enumerate_new()` is acceptable in this pattern.
Applied to files:
oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java
🔇 Additional comments (26)
oshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.java (1)
11-12: LGTM!The added Windows error constants are correctly valued per the Windows SDK:
ERROR_NO_MORE_ITEMS = 259is the standard enumeration termination code, andERROR_SUCCESS = 0is the standard success indicator.oshi-core-java25/src/main/java/oshi/ffm/windows/com/GuidFFM.java (1)
119-127: LGTM!The
GUID_DEVCLASS_BATTERYfactory method correctly encodes{72631E54-78A4-11D0-BCF7-00AA00B7B32A}and follows the established pattern of other well-known GUID methods in this class.oshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixPowerSource.java (1)
31-34: LGTM!The
queryPowerSources()override correctly delegates to the staticgetPowerSources()factory, aligning with theAbstractPowerSourcerefactoring pattern while preserving AIX's documented behavior of returning an empty list.oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdPowerSource.java (1)
38-41: LGTM!The
queryPowerSources()override fixes the previously missing OpenBSD dispatch (as noted in PR objectives) and correctly delegates to the staticgetPowerSources()factory method.oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.java (1)
40-43: LGTM!The
queryPowerSources()override correctly delegates to the staticgetPowerSources()factory, aligning FreeBSD power source discovery with the updatedAbstractPowerSourceflow.oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.java (1)
55-58: LGTM!The
queryPowerSources()override correctly delegates to the staticgetPowerSources()factory, aligning Solaris power source discovery with the updatedAbstractPowerSourceflow.oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.java (1)
50-53: LGTM!The
queryPowerSources()override correctly delegates to the staticgetPowerSources()factory, aligning the macOS FFM power source implementation with the updatedAbstractPowerSourceflow.oshi-core-java25/src/main/java/oshi/ffm/SystemInfo.java (1)
15-15: LGTM!The Windows FFM entry point now correctly routes to
WindowsHardwareAbstractionLayerFFM, which aligns with the existing pattern for macOS and Linux and enables the new FFM-based power source implementation.Also applies to: 62-62
oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.java (1)
66-78: Good wrapper hook for the Linux leaf implementations.The copy constructor preserves the full inherited snapshot, and
queryPowerSources()keeps the base Linux implementation on the existing sysfs discovery path without duplicatingbuildPowerSource()plumbing.oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java (1)
177-187: Nice inversion of control.Moving refresh discovery behind
queryPowerSources()keepsupdateAttributes()backend-agnostic and lets each leaf own its platform-specific lookup path.oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSource.java (1)
16-49: Good split between shared protocol and backend-specific enumeration.Centralizing the Windows battery IOCTL/capability constants here removes duplication from the JNA and FFM leaves, and the protected constructor prevents direct instantiation of the incomplete shared layer.
oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.java (2)
31-38: LGTM! Clean delegation pattern.The package-private copy constructor properly delegates to the parent's protected copy constructor, and
queryPowerSources()correctly delegates to the staticgetPowerSources()factory. This aligns with the newAbstractPowerSourcepolymorphic dispatch design.
77-77: Correct wrapping of buildPowerSource result.Wrapping the
LinuxPowerSourcereturned bybuildPowerSource()inLinuxPowerSourceJNAensures the JNA-specificqueryPowerSources()override is available for instance-level updates.oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java (3)
33-40: LGTM! Consistent with JNA variant.The FFM implementation follows the same copy-constructor and delegation pattern as
LinuxPowerSourceJNA, maintaining consistency across the codebase.
88-88: Correct wrapping pattern.Properly wraps the
buildPowerSource()result to ensure FFM-specificqueryPowerSources()is used for updates.
100-103: Good fallback strategy with logging.The catch-all with a warning log and graceful fallback to sysfs enumeration is appropriate for FFM code where native calls can fail unexpectedly.
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java (5)
45-60: LGTM! Standard constructor and delegation pattern.The constructor properly delegates to the parent class, and
queryPowerSources()correctly delegates togetPowerSources().
133-267: Good fix for hBattery handle leak.The
finallyblock at line 265-266 ensureshBatteryis properly closed viaCloseHandle, addressing the handle leak mentioned in the PR objectives.
196-206: Good optimization: reusable buffer for string queries.Using a single 1024-byte
Memorybuffer for device name, manufacturer, and serial number queries is more efficient than growing buffers iteratively, as noted in the PR objectives.
250-256: Division by zero is protected by the conditional check.The fallback calculation at lines 250-256 only executes when
psPowerUsageRate != 0, soMath.abs(psPowerUsageRate)is safe.
286-298: Clean helper method for battery string queries.The
batteryQueryStringhelper encapsulates the common pattern for querying device name, manufacturer, and serial number, returning an empty string on failure.oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java (2)
47-59: LGTM! Clean Optional-based error handling.The wrapper correctly returns
Optional.empty()on invalid handles and catches Throwable for FFM safety.
71-85: LGTM! Good tri-state return design.Returning
1for success,0for no more items, and-1for other errors provides clear semantics for the caller's enumeration loop.oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java (3)
51-73: LGTM! Correct battery structure layouts.The struct layouts for
BATTERY_QUERY_INFORMATION,BATTERY_INFORMATION,BATTERY_WAIT_STATUS,BATTERY_STATUS, andBATTERY_MANUFACTURE_DATEmatch the Windows SDK definitions.
155-323: LGTM! Well-structured FFM implementation with proper resource management.The implementation correctly:
- Uses
Arena.ofConfined()for explicit lifetime management- Closes
hBatteryin afinallyblock (line 316)- Closes
hdevin afinallyblock (line 320)- Filters non-system and UPS batteries (lines 221-224)
- Handles query failures gracefully with
continue
331-340: LGTM! Clean helper method.The
batteryQueryStringhelper efficiently reuses the providedbqiandnameBufsegments, returning an empty string on failure.
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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/SetupApiFFM.java`:
- Around line 36-39: SP_DEVICE_INTERFACE_DATA has incorrect padding and field
layout: remove the 4-byte padding after cbSize, place InterfaceClassGuid
immediately after cbSize (16-byte sequence), keep Flags as a JAVA_INT after the
GUID, and replace the split ReservedLo/ReservedHi with a single pointer-sized
Reserved field so the struct matches Windows' SP_DEVICE_INTERFACE_DATA (cbSize,
GUID, Flags, ULONG_PTR). Update the StructLayout definition for
SP_DEVICE_INTERFACE_DATA accordingly so that writing cbSize (used by
WindowsPowerSourceFFM when calling SetupDiEnumDeviceInterfaces) yields the
correct native size and offsets.
In
`@oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java`:
- Around line 131-133: The getPowerSources method currently returns a singleton
placeholder by wrapping getPowerSource("System Battery"), which fabricates a
battery on systems with none and prevents multi-battery discovery; change the
implementation to enumerate and collect actual PowerSource instances (call the
helper that inspects packs for each discovered pack rather than returning a
synthetic singleton), avoid early return/short-circuiting when the first
eligible pack is found (ensure the loop that probes packs aggregates all
matches), and return an empty list when no real batteries are discovered; update
any related helper usage (getPowerSource and the pack-enumeration logic) to
support building and returning a List<PowerSource> of zero or more real
batteries.
- Around line 289-294: The battery manufacture date parsing uses
LocalDate.of(year, month, day) with only minimal checks and can throw
DateTimeException for malformed firmware values; update the logic around where
year/month/day are read from bmd (using JAVA_SHORT/OFF_BMD_YEAR,
JAVA_BYTE/OFF_BMD_MONTH, JAVA_BYTE/OFF_BMD_DAY) to either validate upper bounds
(e.g., month <= 12 && day <= 31) before calling LocalDate.of or wrap the
LocalDate.of(...) invocation in a try-catch(DateTimeException) and only set
psManufactureDate on success, leaving it null on invalid input to avoid aborting
battery enumeration.
🪄 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: 9a81b4e0-8dce-433f-a748-3c69ed66ab85
📒 Files selected for processing (4)
CHANGELOG.mdoshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
✅ Files skipped from review due to trivial changes (1)
- CHANGELOG.md
📜 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). (8)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Test JDK 11, macos-latest
- GitHub Check: Test JDK 25, macos-latest
- GitHub Check: Test JDK 25, windows-latest
- GitHub Check: Test JDK 21, macos-latest
- GitHub Check: Test JDK 11, windows-latest
- GitHub Check: Test JDK 21, windows-latest
- GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (8)
📚 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/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 Learning: 2026-04-05T05:40:43.357Z
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:43.357Z
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/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 Learning: 2026-04-05T05:39:18.791Z
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:18.791Z
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/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 Learning: 2026-04-06T22:30:05.807Z
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:05.807Z
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/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 Learning: 2026-04-06T21:48:09.616Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3122
File: oshi-core/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceJNA.java:85-111
Timestamp: 2026-04-06T21:48:09.616Z
Learning: In `oshi-core/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceJNA.java` (and `MacUsbDeviceFFM.java`), the `id = 0L` sentinel is intentional when `device.getParentEntry(IOSERVICE)` returns null. It acts as a catch-all controller group for devices whose controller cannot be identified (an edge case that "should never happen" given the IORegistry format). Do not flag this as a bug or suggest skipping such devices; the design intentionally avoids both silently dropping orphaned devices and placing them at the top level without a controller context.
Applied to files:
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/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 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, the public API is strictly limited to interfaces and classes in the `oshi`, `oshi.hardware`, and `oshi.software.os` packages. All platform-specific code under subpackages like `oshi.software.os.linux`, `oshi.hardware.platform.linux`, etc., is considered implementation detail — not public API. Do not flag changes to platform-specific classes (e.g., making `LinuxOperatingSystem` abstract, narrowing constructor visibility, adding abstract methods) as public API breaks.
Applied to files:
oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.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/SetupApiFFM.java
…ibutes, FFM Windows implementation - Add protected abstract queryPowerSources() to AbstractPowerSource; wire updateAttributes() to call it instead of a static platform switch. This removes hardwired JNA dispatch and fixes the missing OpenBSD case. - Make WindowsPowerSource abstract; extract shared IOCTL codes, capability flags, and BatteryQueryInformationLevel ordinals as protected constants. Add WindowsPowerSourceJNA (renamed from WindowsPowerSource) and WindowsPowerSourceFFM as final leaf classes, each implementing queryPowerSources() and getPowerSources(). - Add LinuxPowerSourceJNA and LinuxPowerSourceFFM as final leaf classes wrapping the existing udev enumeration. Add a protected copy-constructor to LinuxPowerSource so leaf classes can wrap buildPowerSource() results without re-stating all 21 parameters. - Add queryPowerSources() to all remaining concrete platform classes: MacPowerSource, MacPowerSourceFFM, FreeBsdPowerSource, OpenBsdPowerSource, SolarisPowerSource, AixPowerSource. - Fix hBattery handle leak in WindowsPowerSourceJNA: move CloseHandle into a finally block on the try-with-resources. - Replace iterative 256-byte buffer growth loop in batteryQueryString with a single 1024-byte allocation reused across all three string queries (device name, manufacturer, serial number).
9b4337d to
8b4a30a
Compare
There was a problem hiding this comment.
♻️ Duplicate comments (1)
oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java (1)
36-38:⚠️ Potential issue | 🔴 Critical
SP_DEVICE_INTERFACE_DATAlayout has incorrect padding beforeReserved.The explicit
paddingLayout(4)andwithByteAlignment(4)are incorrect. On 64-bit Windows,Reserved(aULONG_PTR) is 8 bytes at offset 24 (no padding needed since 24 is 8-byte aligned). On 32-bit,Reservedis 4 bytes at offset 24. The current layout placesReservedat offset 28 with forced 4-byte alignment, resulting in a 36-byte struct instead of the correct 32 bytes (64-bit) or 28 bytes (32-bit).This will cause
SetupDiEnumDeviceInterfacesto reject the buffer whencbSizeis written asSP_DEVICE_INTERFACE_DATA.byteSize().Proposed fix
public static final StructLayout SP_DEVICE_INTERFACE_DATA = structLayout(JAVA_INT.withName("cbSize"), MemoryLayout.sequenceLayout(16, JAVA_BYTE).withName("InterfaceClassGuid"), JAVA_INT.withName("Flags"), - MemoryLayout.paddingLayout(4), ADDRESS.withByteAlignment(4).withName("Reserved")); + ADDRESS.withName("Reserved"));🤖 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/SetupApiFFM.java` around lines 36 - 38, SP_DEVICE_INTERFACE_DATA currently forces a 4-byte padding and 4-byte alignment causing Reserved to land at offset 28; remove the explicit MemoryLayout.paddingLayout(4) and the ADDRESS.withByteAlignment(4) so the layout is: JAVA_INT cbSize, 16-byte GUID sequence, JAVA_INT Flags, then ADDRESS Reserved (let the platform default alignment place Reserved at offset 24 on both 32/64-bit). Update the SP_DEVICE_INTERFACE_DATA declaration accordingly so Reserved is simply ADDRESS.withName("Reserved") without manual padding/alignment.
🧹 Nitpick comments (1)
oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java (1)
46-58: Unusedarenaparameter inSetupDiGetClassDevs.The
arenaparameter is declared but never used in this method. The returned handle is a raw Windows handle that doesn't require arena allocation.Proposed fix
- public static Optional<MemorySegment> SetupDiGetClassDevs(MemorySegment classGuid, int flags, Arena arena) { + public static Optional<MemorySegment> SetupDiGetClassDevs(MemorySegment classGuid, int flags) {Update callers accordingly.
🤖 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/SetupApiFFM.java` around lines 46 - 58, Remove the unused Arena parameter from the method signature of SetupDiGetClassDevs and any related internal references; update callers to stop passing an Arena and call the new signature (use the existing invocation of SetupDiGetClassDevs.invokeExact and Kernel32FFM.isInvalidHandle unchanged). Ensure imports and method references are adjusted so no compilation errors remain where SetupDiGetClassDevs(MemorySegment, int, Arena) was used.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java`:
- Around line 36-38: SP_DEVICE_INTERFACE_DATA currently forces a 4-byte padding
and 4-byte alignment causing Reserved to land at offset 28; remove the explicit
MemoryLayout.paddingLayout(4) and the ADDRESS.withByteAlignment(4) so the layout
is: JAVA_INT cbSize, 16-byte GUID sequence, JAVA_INT Flags, then ADDRESS
Reserved (let the platform default alignment place Reserved at offset 24 on both
32/64-bit). Update the SP_DEVICE_INTERFACE_DATA declaration accordingly so
Reserved is simply ADDRESS.withName("Reserved") without manual
padding/alignment.
---
Nitpick comments:
In `@oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java`:
- Around line 46-58: Remove the unused Arena parameter from the method signature
of SetupDiGetClassDevs and any related internal references; update callers to
stop passing an Arena and call the new signature (use the existing invocation of
SetupDiGetClassDevs.invokeExact and Kernel32FFM.isInvalidHandle unchanged).
Ensure imports and method references are adjusted so no compilation errors
remain where SetupDiGetClassDevs(MemorySegment, int, Arena) was used.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: aaff6c42-457c-40a1-8902-3f9c10b3c8a6
📒 Files selected for processing (22)
CHANGELOG.mdoshi-core-java25/src/main/java/oshi/ffm/SystemInfo.javaoshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/com/GuidFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayerFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayer.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java
✅ Files skipped from review due to trivial changes (7)
- oshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixPowerSource.java
- oshi-core-java25/src/main/java/oshi/ffm/SystemInfo.java
- oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.java
- oshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.java
- CHANGELOG.md
- oshi-core-java25/src/main/java/oshi/ffm/windows/com/GuidFFM.java
- oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
🚧 Files skipped from review as they are similar to previous changes (9)
- oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.java
- oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.java
- oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayer.java
- oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.java
- oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayerFFM.java
- oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdPowerSource.java
- oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java
- oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java
- oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSource.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). (6)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Test JDK 25, macos-latest
- GitHub Check: Test JDK 11, macos-latest
- GitHub Check: Test JDK 25, windows-latest
- GitHub Check: Test JDK 11, windows-latest
- GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (12)
📓 Common learnings
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.
📚 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/src/main/java/oshi/hardware/platform/mac/MacPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.javaoshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 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/hardware/platform/mac/MacPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.javaoshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java
📚 Learning: 2026-04-05T05:40:43.357Z
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:43.357Z
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/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
📚 Learning: 2026-04-05T05:39:18.791Z
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:18.791Z
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/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.java
📚 Learning: 2026-04-03T18:44:46.910Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3112
File: oshi-core/src/main/java/oshi/PlatformEnum.java:63-66
Timestamp: 2026-04-03T18:44:46.910Z
Learning: In oshi/oshi PlatformEnum.java, the DRAGONFLYBSD enum constant is intentionally added for platform detection only (no implementation classes exist yet). It allows UnsupportedOperationException messages to say "DragonFly BSD" rather than "Unknown". Full DragonFly BSD support is tracked in issue `#2583`. Do not flag the missing switch-case implementations as a bug.
Applied to files:
oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.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/SetupApiFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
📚 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, the public API is strictly limited to interfaces and classes in the `oshi`, `oshi.hardware`, and `oshi.software.os` packages. All platform-specific code under subpackages like `oshi.software.os.linux`, `oshi.hardware.platform.linux`, etc., is considered implementation detail — not public API. Do not flag changes to platform-specific classes (e.g., making `LinuxOperatingSystem` abstract, narrowing constructor visibility, adding abstract methods) as public API breaks.
Applied to files:
oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.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/SetupApiFFM.java
📚 Learning: 2026-04-06T22:30:05.807Z
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:05.807Z
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/ffm/windows/SetupApiFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.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/ffm/windows/SetupApiFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.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: Do not flag `getPowerSources()` as incorrect when it returns a singleton list that wraps `getPowerSource("System Battery")` and/or short-circuits the enumeration after the first eligible battery pack in the Windows power source JNA/FFM implementations. This is intentional for longstanding JNA behavior; a refactor to support zero-or-more batteries is planned later, so the current single-battery behavior should be treated as by-design rather than a bug.
Applied to files:
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
🔇 Additional comments (11)
oshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSource.java (1)
50-53: Clean implementation of the polymorphic dispatch hook.The
queryPowerSources()override correctly delegates to the staticgetPowerSources()factory, enabling polymorphic attribute updates without platform-specific imports in the abstract base.oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.java (2)
31-38: Well-structured copy constructor and query hook pattern.The package-private copy constructor delegating to
super(src)cleanly wraps baseLinuxPowerSourceinstances without duplicating the large parameter list. ThequeryPowerSources()override follows the established delegation pattern.
45-91: Correct udev enumeration with proper resource management and fallback.The implementation correctly:
- Falls back to
LinuxPowerSource.getPowerSources()when udev is unavailable- Uses try-finally blocks for proper cleanup of udev resources
- Wraps each discovered power source in the JNA-specific subclass
oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java (2)
177-183: Clean abstraction for platform-specific power source discovery.The protected abstract
queryPowerSources()method provides a clean hook for platform implementations to supply power source data, decoupling the base class from platform-specific imports and enabling polymorphic dispatch inupdateAttributes().
185-216:updateAttributes()correctly delegates to the new polymorphic hook.The implementation properly iterates through the platform-specific results and updates all fields when a matching power source is found. The boolean return correctly indicates whether the battery was found.
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java (2)
57-69: Correct implementation of the query hook with intentional singleton pattern.The
queryPowerSources()override delegates to the static factory, andgetPowerSources()returns a singleton list as designed (per the planned future refactor for multi-battery support).
102-278: Robust battery enumeration with proper resource cleanup.The implementation correctly:
- Validates the device info handle before enumeration
- Uses try-with-resources for closeable JNA structures
- Closes the battery handle in a
finallyblock (line 266), fixing the prior handle leak- Destroys the device info list after enumeration (line 277)
- Breaks early on
ERROR_NO_MORE_ITEMS(line 272-273)The DeviceIoControl-based data collection follows the Windows battery enumeration pattern correctly.
oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java (4)
121-133: Correct implementation of the query hook with intentional singleton pattern.The
queryPowerSources()override andgetPowerSources()singleton list follow the established design (multi-battery refactor planned for later).
165-337: Well-structured FFM battery enumeration with proper resource management.The implementation correctly:
- Uses a confined
Arenafor all memory allocations- Properly closes handles via
finallyblocks (hBattery at line 330, hdev at line 334)- Validates intermediate results before proceeding
- Guards against divide-by-zero in time calculations (line 319 checks
psPowerUsageRate != 0)The DeviceIoControl calls and struct layouts align with the Windows battery API.
288-297: Manufacture date validation correctly handles malformed firmware data.The bounds checking (
year > 1900 && month >= 1 && month <= 12 && day >= 1 && day <= 31) combined with the try-catch forDateTimeExceptionproperly guards against invalid date combinations (e.g., February 30) from corrupt battery firmware.
92-103: Robust 64-bit detection with appropriate fallback.The
sun.cpu.bitsproperty provides authoritative bitness when available. Theos.archfallback covers all common 64-bit architectures. This is more reliable than previous approaches.
8b4a30a to
d6dce4c
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java (1)
303-312: Inconsistent return value on query failure.The helper returns
""whenDeviceIoControlfails, but the caller initializespsDeviceName,psManufacturer, andpsSerialNumbertoConstants.UNKNOWN. This creates inconsistency—a failed query returns empty string, but unqueried values would be "Unknown".♻️ Suggested fix for consistency
if (!Kernel32FFM.DeviceIoControl(hBattery, IOCTL_BATTERY_QUERY_INFORMATION, bqi, (int) bqi.byteSize(), nameBuf, (int) nameBuf.byteSize())) { - return ""; + return Constants.UNKNOWN; }🤖 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/hardware/platform/windows/WindowsPowerSourceFFM.java` around lines 303 - 312, batteryQueryString returns an empty string on DeviceIoControl failure which conflicts with callers that initialize psDeviceName/psManufacturer/psSerialNumber to Constants.UNKNOWN; change batteryQueryString to return Constants.UNKNOWN on failure so callers and helper are consistent (update the failure branch in batteryQueryString that currently checks Kernel32FFM.DeviceIoControl to return Constants.UNKNOWN and keep successful path returning WindowsForeignFunctions.readWideString(nameBuf)).
🤖 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/hardware/platform/windows/WindowsPowerSourceFFM.java`:
- Around line 224-231: psRemainingCapacityPercent calculation can divide by zero
if psMaxCapacity (set from bi.get(JAVA_INT, OFF_BI_FULL)) is 0; update
WindowsPowerSourceFFM to guard before computing psRemainingCapacityPercent by
checking psMaxCapacity > 0 (or fallback to 1) and compute
psRemainingCapacityPercent = Math.min(1d, (double) psCurrentCapacity / safeMax)
where safeMax is psMaxCapacity unless it's <= 0 then use 1 (or skip division and
set percent to 0); reference psMaxCapacity, psCurrentCapacity, and
psRemainingCapacityPercent to locate the change.
---
Nitpick comments:
In
`@oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java`:
- Around line 303-312: batteryQueryString returns an empty string on
DeviceIoControl failure which conflicts with callers that initialize
psDeviceName/psManufacturer/psSerialNumber to Constants.UNKNOWN; change
batteryQueryString to return Constants.UNKNOWN on failure so callers and helper
are consistent (update the failure branch in batteryQueryString that currently
checks Kernel32FFM.DeviceIoControl to return Constants.UNKNOWN and keep
successful path returning WindowsForeignFunctions.readWideString(nameBuf)).
🪄 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: 6aa82b3a-84c9-4c21-9ce7-2caedfe4064b
📒 Files selected for processing (6)
CHANGELOG.mdoshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/PowrProfFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSource.java
✅ Files skipped from review due to trivial changes (1)
- CHANGELOG.md
🚧 Files skipped from review as they are similar to previous changes (1)
- oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.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). (5)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Test JDK 25, macos-latest
- GitHub Check: Test JDK 25, windows-latest
- GitHub Check: Test JDK 11, macos-latest
- GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (11)
📓 Common learnings
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.
📚 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: Do not flag `getPowerSources()` as incorrect when it returns a singleton list that wraps `getPowerSource("System Battery")` and/or short-circuits the enumeration after the first eligible battery pack in the Windows power source JNA/FFM implementations. This is intentional for longstanding JNA behavior; a refactor to support zero-or-more batteries is planned later, so the current single-battery behavior should be treated as by-design rather than a bug.
Applied to files:
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSource.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
📚 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/hardware/platform/windows/WindowsPowerSource.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/ffm/windows/PowrProfFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.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/ffm/windows/PowrProfFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 Learning: 2026-04-05T05:40:43.357Z
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:43.357Z
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/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 Learning: 2026-04-06T22:30:05.807Z
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:05.807Z
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/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.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/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 Learning: 2026-04-05T05:39:18.791Z
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:18.791Z
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/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 Learning: 2026-04-06T21:48:09.616Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3122
File: oshi-core/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceJNA.java:85-111
Timestamp: 2026-04-06T21:48:09.616Z
Learning: In `oshi-core/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceJNA.java` (and `MacUsbDeviceFFM.java`), the `id = 0L` sentinel is intentional when `device.getParentEntry(IOSERVICE)` returns null. It acts as a catch-all controller group for devices whose controller cannot be identified (an edge case that "should never happen" given the IORegistry format). Do not flag this as a bug or suggest skipping such devices; the design intentionally avoids both silently dropping orphaned devices and placing them at the top level without a controller context.
Applied to files:
oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
📚 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, the public API is strictly limited to interfaces and classes in the `oshi`, `oshi.hardware`, and `oshi.software.os` packages. All platform-specific code under subpackages like `oshi.software.os.linux`, `oshi.hardware.platform.linux`, etc., is considered implementation detail — not public API. Do not flag changes to platform-specific classes (e.g., making `LinuxOperatingSystem` abstract, narrowing constructor visibility, adding abstract methods) as public API breaks.
Applied to files:
oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
🔇 Additional comments (10)
oshi-core-java25/src/main/java/oshi/ffm/windows/PowrProfFFM.java (1)
19-64: Well-structured FFM struct definitions for Windows battery API.The struct layouts accurately match the Windows
batclass.hdefinitions:
BATTERY_QUERY_INFORMATION(12 bytes)BATTERY_INFORMATION(36 bytes) with correct padding forReserved[3]BATTERY_WAIT_STATUS(20 bytes)BATTERY_STATUS(16 bytes)BATTERY_MANUFACTURE_DATE(4 bytes)The
offset()helper cleanly extracts byte offsets usingStructLayout.byteOffsetwithPathElement.groupElement.oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSource.java (2)
18-33: Robust 64-bit detection with comprehensive architecture coverage.The bitness detection correctly prioritizes the JVM-provided
sun.cpu.bitsproperty and falls back toos.archparsing. The fallback covers all relevant 64-bit Windows architectures (x86_64, amd64, aarch64, ia64).
35-67: Clean refactoring to enable polymorphic power source implementations.The protected constants (IOCTL codes, capability flags, query levels) and constructor enable
WindowsPowerSourceJNAandWindowsPowerSourceFFMsubclasses to share this common Windows-specific logic while implementing their ownqueryPowerSources()methods.oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java (4)
36-38: SP_DEVICE_INTERFACE_DATA layout correctly matches Windows SDK.The struct layout places
InterfaceClassGuidat offset 4 (immediately aftercbSize), withFlagsat offset 20 and pointer-sizedReservedat offset 24, yielding 32 bytes on 64-bit—matching the native definition.
46-84: Clean SetupAPI wrapper design with appropriate error handling.
SetupDiGetClassDevsreturnsOptional.empty()on invalid handle, avoiding null-pointer issuesSetupDiEnumDeviceInterfacesuses a tri-state return (0/1/-1) that cleanly maps to "no more items", "success", and "error", enabling proper loop control in callers
143-153: LGTM!Simple cleanup wrapper with consistent error handling pattern.
125-141:cbSizevalues are correct.The code correctly sets
cbSizeto 8 on 64-bit and 6 on 32-bit forSP_DEVICE_INTERFACE_DETAIL_DATA, matching the official Windows SDK requirements. No changes needed.oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java (3)
68-92: Clean implementation of the power source hierarchy.The constructor correctly delegates to the protected
WindowsPowerSourcebase constructor, andqueryPowerSources()properly delegates to the static factory method, enabling the polymorphic dispatch pattern introduced inAbstractPowerSource.updateAttributes().
124-163: Proper resource management with try-finally blocks.The code correctly uses nested try-finally blocks to ensure
SetupDiDestroyDeviceInfoList(hdev)andKernel32FFM.CloseHandle(hBattery)are called even when enumeration fails partway through. This addresses the handle leak mentioned in the PR objectives.
242-285: Date validation and fallback time estimation are well-implemented.The manufacture date parsing correctly validates bounds and catches
DateTimeExceptionfor invalid day-of-month combinations (e.g., April 31). The estimated time calculation appropriately usesMath.abs(psPowerUsageRate)since rate can be negative (discharging) or positive (charging), and provides a sensible fallback when the OS query fails.
d6dce4c to
bf2baf6
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java (1)
203-205:⚠️ Potential issue | 🟡 MinorUse a validated max capacity for derived values.
Some firmware reports
FullChargedCapacity <= 0. With the raw value here, Line 231 can becomeNaN/1.0, and the fallback branch at Lines 279-281 can go negative. Compute the percentage/time from a safe local instead of the unchecked battery value.🛡️ Minimal fix
psDesignCapacity = bi.get(JAVA_INT, OFF_BI_DESIGNED); psMaxCapacity = bi.get(JAVA_INT, OFF_BI_FULL); + int safeMaxCapacity = psMaxCapacity > 0 ? psMaxCapacity : 1; psCycleCount = bi.get(JAVA_INT, OFF_BI_CYCLE); @@ - psRemainingCapacityPercent = Math.min(1d, (double) psCurrentCapacity / psMaxCapacity); + psRemainingCapacityPercent = Math.min(1d, + Math.max(0d, (double) psCurrentCapacity / safeMaxCapacity)); @@ if (psTimeRemainingInstant <= 0 && psPowerUsageRate != 0) { psTimeRemainingInstant = psDischarging ? psCurrentCapacity * 3600d / Math.abs(psPowerUsageRate) - : (psMaxCapacity - psCurrentCapacity) * 3600d / Math.abs(psPowerUsageRate); + : Math.max(0d, safeMaxCapacity - psCurrentCapacity) * 3600d + / Math.abs(psPowerUsageRate); }Also applies to: 224-231, 278-281
🤖 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/hardware/platform/windows/WindowsPowerSourceFFM.java` around lines 203 - 205, The code reads raw capacities (psDesignCapacity, psMaxCapacity) in WindowsPowerSourceFFM and uses them directly to compute percentages/times, which can yield NaN/1.0 or negative fallbacks when FullChargedCapacity <= 0; fix by validating and normalizing the max capacity into a local safe variable (e.g., maxCapacitySafe) right after reading psDesignCapacity/psMaxCapacity: if psMaxCapacity > 0 use it, else if psDesignCapacity > 0 use psDesignCapacity, else set maxCapacitySafe = 1 to avoid division by zero; then use maxCapacitySafe for all derived percent/time calculations and ensure any fallback charge/time computations clamp to >= 0.0.
🤖 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/hardware/platform/windows/WindowsPowerSourceFFM.java`:
- Around line 303-311: In batteryQueryString, don't return an empty string on
IOCTL failure; when Kernel32FFM.DeviceIoControl fails (or when the read result
is empty), return Constants.UNKNOWN so transient query errors don't overwrite
existing fallbacks—update batteryQueryString (where bqi is prepared via bqi.set
and DeviceIoControl is called) to return Constants.UNKNOWN on failure and/or
empty read instead of "".
---
Duplicate comments:
In
`@oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java`:
- Around line 203-205: The code reads raw capacities (psDesignCapacity,
psMaxCapacity) in WindowsPowerSourceFFM and uses them directly to compute
percentages/times, which can yield NaN/1.0 or negative fallbacks when
FullChargedCapacity <= 0; fix by validating and normalizing the max capacity
into a local safe variable (e.g., maxCapacitySafe) right after reading
psDesignCapacity/psMaxCapacity: if psMaxCapacity > 0 use it, else if
psDesignCapacity > 0 use psDesignCapacity, else set maxCapacitySafe = 1 to avoid
division by zero; then use maxCapacitySafe for all derived percent/time
calculations and ensure any fallback charge/time computations clamp to >= 0.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: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 9836afb7-b9e7-4f4c-b932-0cd0ab3c102c
📒 Files selected for processing (6)
CHANGELOG.mdoshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/PowrProfFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core/src/main/java/oshi/util/Util.java
✅ Files skipped from review due to trivial changes (2)
- oshi-core/src/main/java/oshi/util/Util.java
- CHANGELOG.md
📜 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). (5)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Test JDK 25, windows-latest
- GitHub Check: Test JDK 11, macos-latest
- GitHub Check: Test JDK 25, macos-latest
- GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (10)
📓 Common learnings
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.
📚 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/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 Learning: 2026-04-05T05:40:43.357Z
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:43.357Z
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/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 Learning: 2026-04-05T05:39:18.791Z
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:18.791Z
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/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.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/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/PowrProfFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 Learning: 2026-04-06T22:30:05.807Z
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:05.807Z
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/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 Learning: 2026-04-06T21:48:09.616Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3122
File: oshi-core/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceJNA.java:85-111
Timestamp: 2026-04-06T21:48:09.616Z
Learning: In `oshi-core/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceJNA.java` (and `MacUsbDeviceFFM.java`), the `id = 0L` sentinel is intentional when `device.getParentEntry(IOSERVICE)` returns null. It acts as a catch-all controller group for devices whose controller cannot be identified (an edge case that "should never happen" given the IORegistry format). Do not flag this as a bug or suggest skipping such devices; the design intentionally avoids both silently dropping orphaned devices and placing them at the top level without a controller context.
Applied to files:
oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.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/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/PowrProfFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.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: Do not flag `getPowerSources()` as incorrect when it returns a singleton list that wraps `getPowerSource("System Battery")` and/or short-circuits the enumeration after the first eligible battery pack in the Windows power source JNA/FFM implementations. This is intentional for longstanding JNA behavior; a refactor to support zero-or-more batteries is planned later, so the current single-battery behavior should be treated as by-design rather than a bug.
Applied to files:
oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
📚 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, the public API is strictly limited to interfaces and classes in the `oshi`, `oshi.hardware`, and `oshi.software.os` packages. All platform-specific code under subpackages like `oshi.software.os.linux`, `oshi.hardware.platform.linux`, etc., is considered implementation detail — not public API. Do not flag changes to platform-specific classes (e.g., making `LinuxOperatingSystem` abstract, narrowing constructor visibility, adding abstract methods) as public API breaks.
Applied to files:
oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
bf2baf6 to
4d96ca3
Compare
|
@CodeRabbit full review |
✅ Actions performedFull review triggered. |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java (1)
286-298: ReturnConstants.UNKNOWNon query failure for consistency with FFM.The FFM counterpart (lines 312, 315) returns
Constants.UNKNOWNwhenDeviceIoControlfails or returns an empty string. Returning""here can overwrite theConstants.UNKNOWNdefaults set for device name, manufacturer, and serial number.♻️ Suggested fix (matching FFM implementation)
private static String batteryQueryString(HANDLE hBattery, int tag, int infoLevel, Memory nameBuf) { try (BATTERY_QUERY_INFORMATION bqi = new BATTERY_QUERY_INFORMATION(); CloseableIntByReference dwOut = new CloseableIntByReference()) { bqi.BatteryTag = tag; bqi.InformationLevel = infoLevel; bqi.write(); if (!Kernel32.INSTANCE.DeviceIoControl(hBattery, IOCTL_BATTERY_QUERY_INFORMATION, bqi.getPointer(), bqi.size(), nameBuf, (int) nameBuf.size(), dwOut, null)) { - return ""; + return Constants.UNKNOWN; } - return CHAR_WIDTH > 1 ? nameBuf.getWideString(0) : nameBuf.getString(0); + String result = CHAR_WIDTH > 1 ? nameBuf.getWideString(0) : nameBuf.getString(0); + return result.isEmpty() ? Constants.UNKNOWN : result; } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java` around lines 286 - 298, In batteryQueryString, when Kernel32.INSTANCE.DeviceIoControl fails or yields an empty result you should return Constants.UNKNOWN (to match FFM) instead of an empty string; update the failure branch (the if that currently returns "") to return Constants.UNKNOWN, and after reading the buffer (CHAR_WIDTH check) ensure you treat an empty returned String as Constants.UNKNOWN before returning; reference batteryQueryString, DeviceIoControl, IOCTL_BATTERY_QUERY_INFORMATION and Constants.UNKNOWN when making this change.
🤖 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/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java`:
- Around line 217-220: The current WindowsPowerSourceJNA code calls
LocalDate.of(bmd.Year, bmd.Month, bmd.Day) after only checking year>1900 and
month/day>0; update this to mirror the FFM implementation by validating upper
bounds (e.g., month between 1-12, day within 1-31) and wrap the LocalDate.of
invocation in a try/catch to catch DateTimeException, falling back to null or
skipping assignment for malformed dates; reference the bmd struct and
LocalDate.of call in WindowsPowerSourceJNA and ensure the catch prevents the
DateTimeException from propagating.
- Around line 191-193: The computation of psRemainingCapacityPercent in
WindowsPowerSourceJNA.java does an unguarded division by psMaxCapacity
(FullChargedCapacity) which can be zero; update the block that sets
psRemainingCapacityPercent to first check that psMaxCapacity > 0 and only
compute psRemainingCapacityPercent = Math.min(1d, (double) psCurrentCapacity /
psMaxCapacity) when it is > 0, otherwise set psRemainingCapacityPercent to a
safe default (match the FFM implementation, e.g., 1d or the same fallback used
there) to avoid division-by-zero.
---
Nitpick comments:
In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java`:
- Around line 286-298: In batteryQueryString, when
Kernel32.INSTANCE.DeviceIoControl fails or yields an empty result you should
return Constants.UNKNOWN (to match FFM) instead of an empty string; update the
failure branch (the if that currently returns "") to return Constants.UNKNOWN,
and after reading the buffer (CHAR_WIDTH check) ensure you treat an empty
returned String as Constants.UNKNOWN before returning; reference
batteryQueryString, DeviceIoControl, IOCTL_BATTERY_QUERY_INFORMATION and
Constants.UNKNOWN when making this change.
🪄 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: 8f6337ca-8075-46da-a3dd-e4c263de9d3b
📒 Files selected for processing (24)
CHANGELOG.mdoshi-core-java25/src/main/java/oshi/ffm/SystemInfo.javaoshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/PowrProfFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/com/GuidFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayerFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayer.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.javaoshi-core/src/main/java/oshi/util/Util.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 (17)
📓 Common learnings
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.
📚 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/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdPowerSource.javaoshi-core-java25/src/main/java/oshi/ffm/SystemInfo.javaoshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSource.javaoshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.javaoshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayerFFM.javaoshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.javaCHANGELOG.mdoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.javaoshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/PowrProfFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayer.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/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdPowerSource.javaoshi-core-java25/src/main/java/oshi/ffm/SystemInfo.javaoshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.javaoshi-core/src/main/java/oshi/util/Util.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayerFFM.javaoshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.javaoshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 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/hardware/platform/unix/openbsd/OpenBsdPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSource.javaoshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayer.java
📚 Learning: 2026-04-03T18:44:46.910Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3112
File: oshi-core/src/main/java/oshi/PlatformEnum.java:63-66
Timestamp: 2026-04-03T18:44:46.910Z
Learning: In oshi/oshi PlatformEnum.java, the DRAGONFLYBSD enum constant is intentionally added for platform detection only (no implementation classes exist yet). It allows UnsupportedOperationException messages to say "DragonFly BSD" rather than "Unknown". Full DragonFly BSD support is tracked in issue `#2583`. Do not flag the missing switch-case implementations as a bug.
Applied to files:
oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.javaoshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.java
📚 Learning: 2026-04-03T18:43:50.370Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3112
File: oshi-core/src/main/java/oshi/PlatformEnum.java:99-100
Timestamp: 2026-04-03T18:43:50.370Z
Learning: In oshi/oshi PlatformEnum.java, the DragonFly BSD detection uses `osName.equalsIgnoreCase("dragonflybsd")` intentionally, mirroring the exact same check in JNA's `Platform.java` source. Java's `os.name` property on DragonFly BSD is "dragonflybsd" (no space), so `startsWith("DragonFly")` is NOT the correct pattern here. Do not suggest changing it to `startsWith`.
Applied to files:
oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.java
📚 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, the public API is strictly limited to interfaces and classes in the `oshi`, `oshi.hardware`, and `oshi.software.os` packages. All platform-specific code under subpackages like `oshi.software.os.linux`, `oshi.hardware.platform.linux`, etc., is considered implementation detail — not public API. Do not flag changes to platform-specific classes (e.g., making `LinuxOperatingSystem` abstract, narrowing constructor visibility, adding abstract methods) as public API breaks.
Applied to files:
oshi-core-java25/src/main/java/oshi/ffm/SystemInfo.javaoshi-core/src/main/java/oshi/util/Util.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.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-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java` (and similar FFM/API implementations in OSHI), the `updateAttributes()` method intentionally uses `catch (Throwable e) { return false; }` without logging. This is by design: `updateAttributes()` is a public API method whose contract is to return `false` on failure; callers consume the boolean and would never see log output, so adding a log statement is not desired.
Applied to files:
oshi-core-java25/src/main/java/oshi/ffm/SystemInfo.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/hardware/platform/mac/MacPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayerFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/com/GuidFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/PowrProfFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java
📚 Learning: 2026-04-05T05:40:43.357Z
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:43.357Z
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/ffm/windows/com/GuidFFM.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.javaoshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.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.javaoshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 Learning: 2026-04-05T05:39:18.791Z
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:18.791Z
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/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.javaoshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 Learning: 2026-04-06T22:30:05.807Z
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:05.807Z
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/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
📚 Learning: 2026-04-06T21:48:09.616Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3122
File: oshi-core/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceJNA.java:85-111
Timestamp: 2026-04-06T21:48:09.616Z
Learning: In `oshi-core/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceJNA.java` (and `MacUsbDeviceFFM.java`), the `id = 0L` sentinel is intentional when `device.getParentEntry(IOSERVICE)` returns null. It acts as a catch-all controller group for devices whose controller cannot be identified (an edge case that "should never happen" given the IORegistry format). Do not flag this as a bug or suggest skipping such devices; the design intentionally avoids both silently dropping orphaned devices and placing them at the top level without a controller context.
Applied to files:
oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.javaoshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.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: Do not flag `getPowerSources()` as incorrect when it returns a singleton list that wraps `getPowerSource("System Battery")` and/or short-circuits the enumeration after the first eligible battery pack in the Windows power source JNA/FFM implementations. This is intentional for longstanding JNA behavior; a refactor to support zero-or-more batteries is planned later, so the current single-battery behavior should be treated as by-design rather than a bug.
Applied to files:
oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSource.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java
📚 Learning: 2026-04-05T05:40:43.357Z
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:43.357Z
Learning: In OSHI’s Linux FFM implementations (e.g., LinuxPowerSourceFFM, LinuxHWDiskStoreFFM, LinuxLogicalVolumeGroupFFM, LinuxUsbDeviceFFM) and the corresponding JNA udev code, do not require/flag a missing null check around `udev_enumerate_new()`/`enumerateNew()`. Per libudev semantics, `udev_enumerate_new()` returns NULL only if udev itself is broken (e.g., OOM). Since `udev_new()` is already guarded and is the successful prerequisite for enumeration, treating `udev_enumerate_new()` as non-null is consistent with the established pattern; adding a redundant null guard would be inconsistent.
Applied to files:
oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java
📚 Learning: 2026-04-05T05:39:18.791Z
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:18.791Z
Learning: When reviewing OSHI Linux FFM/JNA code that uses libudev, do not flag a missing null check on `udev_enumerate_new()` if `udev_new()` has already been guarded. Per libudev semantics, `udev_enumerate_new()` returns NULL only when the udev context itself is broken (e.g., OOM), so a successful `udev_new()` implies `udev_enumerate_new()` should succeed as well. Therefore, lack of a redundant null guard on `udev_enumerate_new()` is acceptable in this pattern.
Applied to files:
oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java
🔇 Additional comments (35)
CHANGELOG.md (1)
10-10: Changelog entry accurately reflects the PR scope.Line 10 is clear, correctly linked, and aligned with the implemented PowerSource/Windows FFM refactor.
oshi-core/src/main/java/oshi/util/Util.java (1)
25-45:is64Bit()initialization path looks clean and efficient.The one-time static computation with a simple accessor is appropriate for frequent call sites and avoids repeated property lookups.
oshi-core-java25/src/main/java/oshi/ffm/windows/com/GuidFFM.java (1)
119-127: Good addition of a dedicated battery class GUID helper.This keeps GUID construction centralized and improves readability at call sites using SetupAPI battery interface enumeration.
oshi-core-java25/src/main/java/oshi/ffm/windows/PowrProfFFM.java (1)
21-64: Struct layouts and computed offsets are well structured.Using named
StructLayoutdefinitions plus centralized offset derivation is a solid approach for maintaining FFM interop correctness.oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdPowerSource.java (1)
38-41:queryPowerSources()delegation is correctly wired.This cleanly integrates OpenBSD with the new per-platform query hook while preserving existing discovery behavior.
oshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSource.java (1)
50-53: Mac query hook override looks correct.Delegating to
getPowerSources()keeps behavior unchanged while conforming to the newAbstractPowerSourcedispatch flow.oshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixPowerSource.java (1)
31-34: AIX hook integration is straightforward and correct.The override preserves the existing empty-result behavior while adopting the new query contract.
oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.java (1)
40-43: FreeBSD delegation togetPowerSources()is correct.This is a clean adoption of the new platform query hook with no functional drift.
oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.java (1)
50-53: FFM macOS query hook override is correctly implemented.The delegation preserves existing behavior and aligns with the new
AbstractPowerSourcequery architecture.oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.java (1)
55-58: LGTM!The
queryPowerSources()override correctly delegates to the existing staticgetPowerSources()method, aligning with the newAbstractPowerSourcehook mechanism. This is consistent with the pattern used in other platform implementations.oshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.java (1)
7-13: LGTM!The Win32 error constants are correctly defined with their standard values:
ERROR_NO_MORE_ITEMS = 259is properly used for SetupDi enumeration termination (as shown inSetupApiFFM.SetupDiEnumDeviceInterfaces)ERROR_SUCCESS = 0is the standard success codeoshi-core-java25/src/main/java/oshi/ffm/SystemInfo.java (1)
15-15: LGTM!The Windows branch now correctly instantiates
WindowsHardwareAbstractionLayerFFM, which overridesgetPowerSources()to use the FFM-based implementation. This aligns with the PR's objective to add Windows FFM support while falling back to JNA for other hardware methods (as documented in line 26's Javadoc).Also applies to: 62-62
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayer.java (2)
29-29: LGTM!Removing
finalfrom the class declaration enablesWindowsHardwareAbstractionLayerFFMto extend this class, which is the correct design for the FFM subclass pattern used in this PR.
51-54: LGTM!The
getPowerSources()delegation toWindowsPowerSourceJNA.getPowerSources()correctly reflects the renamed class hierarchy whereWindowsPowerSourceis now abstract andWindowsPowerSourceJNAprovides the JNA-based implementation.oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayerFFM.java (1)
1-23: LGTM!This is a clean FFM-based Windows HAL implementation that:
- Extends
WindowsHardwareAbstractionLayerand only overridesgetPowerSources()to use the FFM implementation- Follows the established pattern used by other FFM HAL classes (Mac, Linux)
- Has clear Javadoc explaining that FFM implementations are added incrementally
oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java (2)
177-183: LGTM!The new
protected abstract queryPowerSources()method cleanly decouples platform-specific dispatch from the abstract base class. The Javadoc clearly documents that subclasses should delegate to their staticgetPowerSources()factory methods.
185-216: LGTM!The
updateAttributes()method correctly uses the newqueryPowerSources()hook. The iteration and field-copying logic is unchanged, maintaining backward compatibility.oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java (1)
30-37: LGTM - Win32 constants are correctly defined.The CreateFile-related constants match their Win32 definitions:
GENERIC_READ = 0x80000000andGENERIC_WRITE = 0x40000000are correct access flagsFILE_SHARE_READ/WRITE,OPEN_EXISTING, andFILE_ATTRIBUTE_NORMALare standard valuesINVALID_HANDLE_VALUE = -1Lis correct for 64-bit handle validationNote:
GENERIC_READ(0x80000000) has the high bit set, which makes it negative when interpreted as a signed Javaint. This is expected behavior—the FFM layer will pass the raw bit pattern correctly to the native API.oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.java (2)
66-73: LGTM!The protected copy constructor correctly extracts all 20
AbstractPowerSourcefields via getters and forwards them to the main constructor. This pattern enablesLinuxPowerSourceJNAandLinuxPowerSourceFFMto wrapLinuxPowerSourceinstances created bybuildPowerSource().
75-78: LGTM!The
queryPowerSources()override correctly delegates to the staticgetPowerSources()method, consistent with the pattern used in other platform implementations.oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSource.java (1)
16-50: LGTM!The refactoring from a concrete
finalclass to anabstractbase class is well-structured. The protected constructor and shared Windows-specific constants (IOCTL codes, capability flags, query levels) provide a clean foundation for the JNA and FFM implementations to extend.oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java (2)
33-40: LGTM!The package-private copy constructor and
queryPowerSources()override properly integrate with the refactoredAbstractPowerSourcedispatch pattern. The delegation togetPowerSources()and wrapping ofbuildPowerSource()results inLinuxPowerSourceFFMinstances is consistent with the JNA counterpart.
88-88: LGTM!Wrapping
buildPowerSource(name, props)in aLinuxPowerSourceFFMinstance ensures the returned objects have the correct runtime type for the FFM-basedqueryPowerSources()override.oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java (3)
37-39: LGTM!Making
isInvalidHandlepublic allowsSetupApiFFMto reuse it for handle validation. The comparison againstWinNTFFM.INVALID_HANDLE_VALUEcentralizes the sentinel check.
52-68: LGTM!The
CreateFilewrapper correctly:
- Passes
MemorySegment.NULLfor optionallpSecurityAttributesandhTemplateFile- Validates the returned handle with
isInvalidHandle()- Returns
Optional.empty()on failure with debug logging
70-83: LGTM!The
DeviceIoControlwrapper now correctly allocates alpBytesReturnedbuffer viaArena.ofConfined()as required for synchronous calls. The confined arena ensures the buffer is valid for the duration of the call and properly deallocated afterward.oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.java (2)
31-38: LGTM!The package-private copy constructor and
queryPowerSources()override mirror the FFM counterpart, providing consistent integration with the refactoredAbstractPowerSourcedispatch pattern.
45-91: LGTM!The udev enumeration logic properly:
- Falls back to
LinuxPowerSource.getPowerSources()when udev is unavailable or fails- Guards
udev_new()for null before proceeding- Cleans up resources via finally blocks
- Wraps discovered power sources in
LinuxPowerSourceJNAinstancesoshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java (3)
37-39: LGTM!The
SP_DEVICE_INTERFACE_DATAlayout correctly defines:
cbSize(DWORD) at offset 0InterfaceClassGuid(16-byte GUID) immediately afterFlags(DWORD) at offset 20Reserved(ULONG_PTR via ADDRESS) for pointer-sized alignmentThis matches the Win32 struct definition and produces the correct
byteSize()of 32 bytes on 64-bit.
71-85: LGTM!The tri-state return convention (1 = success, 0 = no more items, -1 = error) provides clear semantics for the caller to distinguish between "end of enumeration" and "actual failure", avoiding silent termination on transient errors.
125-141: LGTM!The
cbSizeinitialization (8for 64-bit,6for 32-bit) correctly matches theSP_DEVICE_INTERFACE_DETAIL_DATAstructure requirements. Reading the device path viareadWideString(detail.asSlice(4))correctly skips thecbSizefield.oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java (3)
68-92: LGTM!The public constructor and
queryPowerSources()→getPowerSources()delegation properly integrate with the refactoredAbstractPowerSourceframework. The singleton list behavior matches the JNA implementation by design.
124-298: LGTM!The battery enumeration flow is well-structured:
- SetupAPI device enumeration with proper handle cleanup in
finallyblocks- Battery tag validation before querying detailed information
- Division-by-zero guard via
maxCapacitySafe(line 206-207)- Date validation with range checks and
DateTimeExceptioncatch (lines 252-258)- Handle leak fix:
hBatteryis closed infinally(line 292)
306-316: LGTM!The
batteryQueryStringhelper correctly returnsConstants.UNKNOWNon IOCTL failure or empty result, preventing blank strings from overwriting fallback values.oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java (1)
45-69: LGTM!The public constructor and
queryPowerSources()→getPowerSources()delegation properly integrate with the refactoredAbstractPowerSourceframework.
SP_DEVICE_INTERFACE_DATA GUID size, Arena lifetime, IS_64BIT detection
- Kernel32FFM.DeviceIoControl: allocate a real DWORD for lpBytesReturned
instead of passing NULL; synchronous calls fail with
ERROR_INVALID_PARAMETER
when lpOverlapped is NULL and lpBytesReturned is also NULL.
- SetupApiFFM.SP_DEVICE_INTERFACE_DATA: fix GUID field from
sequenceLayout(16, JAVA_INT) (64 bytes) to sequenceLayout(16,
JAVA_BYTE)
(16 bytes), restoring correct struct field offsets.
- SetupApiFFM.SetupDiGetDeviceInterfaceDetailSize and
SetupDiGetDeviceInterfaceDetail: accept caller-provided Arena instead
of
creating Arena.ofAuto() internally, making allocation lifetimes
consistent
with the rest of SetupApiFFM.
- WindowsPowerSourceFFM.IS_64BIT: replace fragile contains("64") with
explicit arch checks matching JNA's Platform.is64Bit() logic,
including
sun.cpu.bits system property as primary source.
- CHANGELOG: add entry for #3125.
4d96ca3 to
f207122
Compare
Refactors the
PowerSourceclass hierarchy to eliminate a hardwired JNA platform switch inAbstractPowerSource.updateAttributes(), fixes a missing OpenBSD dispatch, closes a Windows battery handle leak, and adds a full FFM implementation of Windows battery querying.Changes
AbstractPowerSourceupdateAttributes()with aprotected abstract List<PowerSource> queryPowerSources()method.getPowerSources()factory, making dispatch fully polymorphic.Windows
WindowsPowerSource→WindowsPowerSourceJNA(final).WindowsPowerSourcebase holding shared IOCTL codes, capability flags, andBatteryQueryInformationLevelordinals asprotected static finalconstants.WindowsPowerSourceFFM(final, inoshi-core-java25): a complete FFM-based Windows battery implementation usingDeviceIoControlviaSetupApiFFMandKernel32FFM.hBatteryhandle leak inWindowsPowerSourceJNA:CloseHandleis now called in afinallyblock.batteryQueryStringwith a single 1024-byte buffer allocated once and reused across all three string queries (device name, manufacturer, serial number).Linux
LinuxPowerSourceJNAandLinuxPowerSourceFFMas final leaf classes wrapping the existing udev enumeration path.protectedcopy-constructor toLinuxPowerSourceso leaf classes can wrapbuildPowerSource()results without repeating all 21 parameters.LinuxPowerSource.queryPowerSources()remains as the sysfs fallback, used when udev is unavailable.Other platforms
queryPowerSources()overrides toMacPowerSource,MacPowerSourceFFM,FreeBsdPowerSource,OpenBsdPowerSource,SolarisPowerSource, andAixPowerSource.OpenBsdPowerSourceparameter update (it was absent from the old static switch).Summary by CodeRabbit
New Features
Refactor