Skip to content

Refactor PowerSource hierarchy and add Windows FFM implementation - #3125

Merged
dbwiddis merged 2 commits into
oshi:masterfrom
dbwiddis:win-ffm-powersupply
Apr 8, 2026
Merged

dbwiddis merged 2 commits into
oshi:masterfrom
dbwiddis:win-ffm-powersupply

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Apr 7, 2026 •

Copy link
Copy Markdown
Member

Refactors the PowerSource class hierarchy to eliminate a hardwired JNA platform switch in AbstractPowerSource.updateAttributes(), fixes a missing OpenBSD dispatch, closes a Windows battery handle leak, and adds a full FFM implementation of Windows battery querying.

Changes

AbstractPowerSource

  • Replaces the static platform switch in updateAttributes() with a protected abstract List<PowerSource> queryPowerSources() method.
  • Each concrete leaf class implements it by delegating to its own static getPowerSources() factory, making dispatch fully polymorphic.
  • Removes all platform-specific imports from the abstract base.

Windows

  • Renames WindowsPowerSource → WindowsPowerSourceJNA (final).
  • Introduces a new abstract WindowsPowerSource base holding shared IOCTL codes, capability flags, and BatteryQueryInformationLevel ordinals as protected static final constants.
  • Adds WindowsPowerSourceFFM (final, in oshi-core-java25): a complete FFM-based Windows battery implementation using DeviceIoControl via SetupApiFFM and Kernel32FFM.
  • Fixes a hBattery handle leak in WindowsPowerSourceJNA: CloseHandle is now called in a finally block.
  • Replaces the iterative 256-byte buffer growth loop in batteryQueryString with a single 1024-byte buffer allocated once and reused across all three string queries (device name, manufacturer, serial number).

Linux

  • Adds LinuxPowerSourceJNA and LinuxPowerSourceFFM as final leaf classes wrapping the existing udev enumeration path.
  • Adds a protected copy-constructor to LinuxPowerSource so leaf classes can wrap buildPowerSource() results without repeating all 21 parameters.
  • LinuxPowerSource.queryPowerSources() remains as the sysfs fallback, used when udev is unavailable.

Other platforms

  • Adds queryPowerSources() overrides to MacPowerSource, MacPowerSourceFFM, FreeBsdPowerSource, OpenBsdPowerSource, SolarisPowerSource, and AixPowerSource.
  • Fixes the previously missing OpenBsdPowerSource parameter update (it was absent from the old static switch).

Summary by CodeRabbit

  • New Features

    • Two Windows-backed power-source providers (FFM and JNA) added, providing richer battery details and improved device enumeration.
    • Windows SetupAPI and native bindings exposed to support battery discovery.
  • Refactor

    • PowerSource discovery reorganized with an instance-level query hook adopted across platforms.
    • Windows hardware layer made extensible and now delegates to the new providers for power-source data.

@coderabbitai

coderabbitai Bot commented Apr 7, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Refactors 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

Cohort / File(s) Summary
System selection & Win constants
oshi-core-java25/src/main/java/oshi/ffm/SystemInfo.java, oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java, oshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.java, oshi-core-java25/src/main/java/oshi/ffm/windows/com/GuidFFM.java
SystemInfo now instantiates WindowsHardwareAbstractionLayerFFM. Added CreateFile-related constants and INVALID_HANDLE_VALUE to WinNTFFM, added ERROR_NO_MORE_ITEMS to WinErrorFFM, and added GUID_DEVCLASS_BATTERY factory in GuidFFM.
Windows FFM native bindings
oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java, oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java, oshi-core-java25/src/main/java/oshi/ffm/windows/PowrProfFFM.java
Kernel32FFM: removed local INVALID_HANDLE_VALUE, exposed isInvalidHandle, added FFM downcalls/wrappers for CreateFileW and DeviceIoControl. SetupApiFFM: new FFM wrapper for SetupDi* APIs with detail-buffer probing/enum helpers. PowrProfFFM: battery struct layouts and offset constants added.
Windows power-source implementations & HAL
oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java, oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayerFFM.java, oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java, oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSource.java, oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayer.java
Added FFM-backed WindowsPowerSourceFFM and WindowsHardwareAbstractionLayerFFM. Added JNA-backed WindowsPowerSourceJNA. Converted WindowsPowerSource to abstract and made WindowsHardwareAbstractionLayer non-final; default HAL switched to JNA provider.
Abstract power-source hook & platform adapters
oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java, oshi-core/src/main/java/oshi/hardware/platform/.../*PowerSource*.java, oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java, oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.java
Introduced protected abstract List<PowerSource> queryPowerSources(); updateAttributes() now calls it. Platform PowerSource classes (Linux, Mac, AIX, FreeBSD, OpenBSD, Solaris, etc.) now override queryPowerSources() to delegate to existing static getPowerSources(). Linux/mac JNA/FFM classes add copy constructors and wrap factory results in subclass instances.
FFM COM helpers & GUIDs
oshi-core-java25/src/main/java/oshi/ffm/windows/com/GuidFFM.java
Added GUID factory for battery device class (GUID_DEVCLASS_BATTERY).
Utilities & small API adds
oshi-core/src/main/java/oshi/util/Util.java
Added Util.is64Bit() and supporting IS_64BIT initialization logic.
Misc: errors, changelog
oshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.java, CHANGELOG.md
Updated WinError constants (added ERROR_NO_MORE_ITEMS), adjusted header years, and added CHANGELOG entry for PR #3125.

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>
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰 I hopped through SetupAPI and peered,

I opened handles, never feared.
From Kernel32 to device detail,
FFM fetched each battery tale.
A rabbit cheers — the charge unveiled! ⚡

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 21.05% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Refactor PowerSource hierarchy and add Windows FFM implementation' accurately describes the main changes: refactoring the PowerSource class hierarchy and adding a Windows FFM-based implementation.

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

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

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@codecov

codecov Bot commented Apr 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 33.33333% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.55%. Comparing base (49bf0f5) to head (f207122).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
oshi-core/src/main/java/oshi/util/Util.java 33.33% 3 Missing and 3 partials ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 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.

SetupDiGetDeviceInterfaceDetailSize uses Arena.ofAuto() internally for allocating requiredSize, 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 Arena parameter 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.

SetupDiGetDeviceInterfaceDetail also uses Arena.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

📥 Commits

Reviewing files that changed from the base of the PR and between f274b23 and 921c3ac.

📒 Files selected for processing (21)
  • oshi-core-java25/src/main/java/oshi/ffm/SystemInfo.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/com/GuidFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayerFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdPowerSource.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/windows/WindowsPowerSource.java
  • oshi-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.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayer.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java
  • oshi-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.java
  • oshi-core-java25/src/main/java/oshi/ffm/SystemInfo.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.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/windows/WindowsHardwareAbstractionLayerFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
  • oshi-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.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayerFFM.java
  • oshi-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.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java
  • oshi-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.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/com/GuidFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayerFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
  • oshi-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.java
  • oshi-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.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-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.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java
  • oshi-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 = 259 is the standard enumeration termination code, and ERROR_SUCCESS = 0 is the standard success indicator.

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

119-127: LGTM!

The GUID_DEVCLASS_BATTERY factory 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 static getPowerSources() factory, aligning with the AbstractPowerSource refactoring 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 static getPowerSources() 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 static getPowerSources() factory, aligning FreeBSD power source discovery with the updated AbstractPowerSource flow.

oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.java (1)

55-58: LGTM!

The queryPowerSources() override correctly delegates to the static getPowerSources() factory, aligning Solaris power source discovery with the updated AbstractPowerSource flow.

oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.java (1)

50-53: LGTM!

The queryPowerSources() override correctly delegates to the static getPowerSources() factory, aligning the macOS FFM power source implementation with the updated AbstractPowerSource flow.

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 duplicating buildPowerSource() plumbing.

oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java (1)

177-187: Nice inversion of control.

Moving refresh discovery behind queryPowerSources() keeps updateAttributes() 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 static getPowerSources() factory. This aligns with the new AbstractPowerSource polymorphic dispatch design.


77-77: Correct wrapping of buildPowerSource result.

Wrapping the LinuxPowerSource returned by buildPowerSource() in LinuxPowerSourceJNA ensures the JNA-specific queryPowerSources() 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-specific queryPowerSources() 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 to getPowerSources().


133-267: Good fix for hBattery handle leak.

The finally block at line 265-266 ensures hBattery is properly closed via CloseHandle, addressing the handle leak mentioned in the PR objectives.


196-206: Good optimization: reusable buffer for string queries.

Using a single 1024-byte Memory buffer 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, so Math.abs(psPowerUsageRate) is safe.


286-298: Clean helper method for battery string queries.

The batteryQueryString helper 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 1 for success, 0 for no more items, and -1 for 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, and BATTERY_MANUFACTURE_DATE match 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 hBattery in a finally block (line 316)
  • Closes hdev in a finally block (line 320)
  • Filters non-system and UPS batteries (lines 221-224)
  • Handles query failures gracefully with continue

331-340: LGTM! Clean helper method.

The batteryQueryString helper efficiently reuses the provided bqi and nameBuf segments, returning an empty string on failure.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 921c3ac and 9b4337d.

📒 Files selected for processing (4)
  • CHANGELOG.md
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
  • oshi-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.java
  • oshi-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.java
  • oshi-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.java
  • 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/Kernel32FFM.java
  • oshi-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.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
  • oshi-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).
@dbwiddis
dbwiddis force-pushed the win-ffm-powersupply branch from 9b4337d to 8b4a30a Compare April 8, 2026 00:55

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java (1)

36-38: ⚠️ Potential issue | 🔴 Critical

SP_DEVICE_INTERFACE_DATA layout has incorrect padding before Reserved.

The explicit paddingLayout(4) and withByteAlignment(4) are incorrect. On 64-bit Windows, Reserved (a ULONG_PTR) is 8 bytes at offset 24 (no padding needed since 24 is 8-byte aligned). On 32-bit, Reserved is 4 bytes at offset 24. The current layout places Reserved at 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 SetupDiEnumDeviceInterfaces to reject the buffer when cbSize is written as SP_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: Unused arena parameter in SetupDiGetClassDevs.

The arena parameter 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9b4337d and 8b4a30a.

📒 Files selected for processing (22)
  • CHANGELOG.md
  • oshi-core-java25/src/main/java/oshi/ffm/SystemInfo.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/com/GuidFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayerFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdPowerSource.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/windows/WindowsPowerSource.java
  • oshi-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.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java
  • oshi-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.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java
  • oshi-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.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
  • oshi-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.java
  • 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
📚 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.java
  • oshi-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.java
  • oshi-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.java
  • oshi-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 static getPowerSources() 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 base LinuxPowerSource instances without duplicating the large parameter list. The queryPowerSources() 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 in updateAttributes().


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, and getPowerSources() 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 finally block (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 and getPowerSources() 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 Arena for all memory allocations
  • Properly closes handles via finally blocks (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 for DateTimeException properly 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.bits property provides authoritative bitness when available. The os.arch fallback covers all common 64-bit architectures. This is more reliable than previous approaches.

@dbwiddis
dbwiddis force-pushed the win-ffm-powersupply branch from 8b4a30a to d6dce4c Compare April 8, 2026 01:35

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 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 "" when DeviceIoControl fails, but the caller initializes psDeviceName, psManufacturer, and psSerialNumber to Constants.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

📥 Commits

Reviewing files that changed from the base of the PR and between 8b4a30a and d6dce4c.

📒 Files selected for processing (6)
  • CHANGELOG.md
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/PowrProfFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
  • oshi-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.java
  • 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, 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.java
  • oshi-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.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
  • oshi-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.java
  • 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/hardware/platform/windows/WindowsPowerSourceFFM.java
  • oshi-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.java
  • oshi-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.java
  • oshi-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.h definitions:

  • BATTERY_QUERY_INFORMATION (12 bytes)
  • BATTERY_INFORMATION (36 bytes) with correct padding for Reserved[3]
  • BATTERY_WAIT_STATUS (20 bytes)
  • BATTERY_STATUS (16 bytes)
  • BATTERY_MANUFACTURE_DATE (4 bytes)

The offset() helper cleanly extracts byte offsets using StructLayout.byteOffset with PathElement.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.bits property and falls back to os.arch parsing. 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 WindowsPowerSourceJNA and WindowsPowerSourceFFM subclasses to share this common Windows-specific logic while implementing their own queryPowerSources() 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 InterfaceClassGuid at offset 4 (immediately after cbSize), with Flags at offset 20 and pointer-sized Reserved at offset 24, yielding 32 bytes on 64-bit—matching the native definition.


46-84: Clean SetupAPI wrapper design with appropriate error handling.

  • SetupDiGetClassDevs returns Optional.empty() on invalid handle, avoiding null-pointer issues
  • SetupDiEnumDeviceInterfaces uses 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: cbSize values are correct.

The code correctly sets cbSize to 8 on 64-bit and 6 on 32-bit for SP_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 WindowsPowerSource base constructor, and queryPowerSources() properly delegates to the static factory method, enabling the polymorphic dispatch pattern introduced in AbstractPowerSource.updateAttributes().


124-163: Proper resource management with try-finally blocks.

The code correctly uses nested try-finally blocks to ensure SetupDiDestroyDeviceInfoList(hdev) and Kernel32FFM.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 DateTimeException for invalid day-of-month combinations (e.g., April 31). The estimated time calculation appropriately uses Math.abs(psPowerUsageRate) since rate can be negative (discharging) or positive (charging), and provides a sensible fallback when the OS query fails.

@dbwiddis
dbwiddis force-pushed the win-ffm-powersupply branch from d6dce4c to bf2baf6 Compare April 8, 2026 02:51

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java (1)

203-205: ⚠️ Potential issue | 🟡 Minor

Use a validated max capacity for derived values.

Some firmware reports FullChargedCapacity <= 0. With the raw value here, Line 231 can become NaN/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

📥 Commits

Reviewing files that changed from the base of the PR and between d6dce4c and bf2baf6.

📒 Files selected for processing (6)
  • CHANGELOG.md
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/PowrProfFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
  • oshi-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.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
  • oshi-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.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
  • oshi-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.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
  • oshi-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.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/PowrProfFFM.java
  • 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/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
  • oshi-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
  • oshi-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.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/PowrProfFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
  • oshi-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

@dbwiddis
dbwiddis force-pushed the win-ffm-powersupply branch from bf2baf6 to 4d96ca3 Compare April 8, 2026 03:11
@dbwiddis

dbwiddis commented Apr 8, 2026

Copy link
Copy Markdown
Member Author

@CodeRabbit full review

@coderabbitai

coderabbitai Bot commented Apr 8, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java (1)

286-298: Return Constants.UNKNOWN on query failure for consistency with FFM.

The FFM counterpart (lines 312, 315) returns Constants.UNKNOWN when DeviceIoControl fails or returns an empty string. Returning "" here can overwrite the Constants.UNKNOWN defaults 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

📥 Commits

Reviewing files that changed from the base of the PR and between 49bf0f5 and 4d96ca3.

📒 Files selected for processing (24)
  • CHANGELOG.md
  • oshi-core-java25/src/main/java/oshi/ffm/SystemInfo.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/PowrProfFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/com/GuidFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayerFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdPowerSource.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/windows/WindowsPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java
  • oshi-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.java
  • oshi-core-java25/src/main/java/oshi/ffm/SystemInfo.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSource.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacPowerSourceFFM.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayerFFM.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.java
  • CHANGELOG.md
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/PowrProfFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceFFM.java
  • oshi-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.java
  • oshi-core-java25/src/main/java/oshi/ffm/SystemInfo.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.java
  • oshi-core/src/main/java/oshi/util/Util.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayerFFM.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-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.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java
  • oshi-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.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java
  • oshi-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.java
  • oshi-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.java
  • oshi-core/src/main/java/oshi/util/Util.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
  • oshi-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.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinErrorFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsHardwareAbstractionLayerFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/com/GuidFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/WinNTFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/PowrProfFFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java
  • oshi-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.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSourceJNA.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
  • oshi-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.java
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
  • oshi-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
  • oshi-core-java25/src/main/java/oshi/ffm/windows/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
  • 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/Kernel32FFM.java
  • oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java
  • oshi-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
  • oshi-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.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSource.java
  • oshi-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 StructLayout definitions 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 new AbstractPowerSource dispatch 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 to getPowerSources() 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 AbstractPowerSource query 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 static getPowerSources() method, aligning with the new AbstractPowerSource hook 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 = 259 is properly used for SetupDi enumeration termination (as shown in SetupApiFFM.SetupDiEnumDeviceInterfaces)
  • ERROR_SUCCESS = 0 is the standard success code
oshi-core-java25/src/main/java/oshi/ffm/SystemInfo.java (1)

15-15: LGTM!

The Windows branch now correctly instantiates WindowsHardwareAbstractionLayerFFM, which overrides getPowerSources() 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 final from the class declaration enables WindowsHardwareAbstractionLayerFFM to extend this class, which is the correct design for the FFM subclass pattern used in this PR.


51-54: LGTM!

The getPowerSources() delegation to WindowsPowerSourceJNA.getPowerSources() correctly reflects the renamed class hierarchy where WindowsPowerSource is now abstract and WindowsPowerSourceJNA provides 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 WindowsHardwareAbstractionLayer and only overrides getPowerSources() 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 static getPowerSources() factory methods.


185-216: LGTM!

The updateAttributes() method correctly uses the new queryPowerSources() 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 = 0x80000000 and GENERIC_WRITE = 0x40000000 are correct access flags
  • FILE_SHARE_READ/WRITE, OPEN_EXISTING, and FILE_ATTRIBUTE_NORMAL are standard values
  • INVALID_HANDLE_VALUE = -1L is correct for 64-bit handle validation

Note: GENERIC_READ (0x80000000) has the high bit set, which makes it negative when interpreted as a signed Java int. 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 AbstractPowerSource fields via getters and forwards them to the main constructor. This pattern enables LinuxPowerSourceJNA and LinuxPowerSourceFFM to wrap LinuxPowerSource instances created by buildPowerSource().


75-78: LGTM!

The queryPowerSources() override correctly delegates to the static getPowerSources() 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 final class to an abstract base 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 refactored AbstractPowerSource dispatch pattern. The delegation to getPowerSources() and wrapping of buildPowerSource() results in LinuxPowerSourceFFM instances is consistent with the JNA counterpart.


88-88: LGTM!

Wrapping buildPowerSource(name, props) in a LinuxPowerSourceFFM instance ensures the returned objects have the correct runtime type for the FFM-based queryPowerSources() override.

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

37-39: LGTM!

Making isInvalidHandle public allows SetupApiFFM to reuse it for handle validation. The comparison against WinNTFFM.INVALID_HANDLE_VALUE centralizes the sentinel check.


52-68: LGTM!

The CreateFile wrapper correctly:

  • Passes MemorySegment.NULL for optional lpSecurityAttributes and hTemplateFile
  • Validates the returned handle with isInvalidHandle()
  • Returns Optional.empty() on failure with debug logging

70-83: LGTM!

The DeviceIoControl wrapper now correctly allocates a lpBytesReturned buffer via Arena.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 refactored AbstractPowerSource dispatch 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 LinuxPowerSourceJNA instances
oshi-core-java25/src/main/java/oshi/ffm/windows/SetupApiFFM.java (3)

37-39: LGTM!

The SP_DEVICE_INTERFACE_DATA layout correctly defines:

  • cbSize (DWORD) at offset 0
  • InterfaceClassGuid (16-byte GUID) immediately after
  • Flags (DWORD) at offset 20
  • Reserved (ULONG_PTR via ADDRESS) for pointer-sized alignment

This 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 cbSize initialization (8 for 64-bit, 6 for 32-bit) correctly matches the SP_DEVICE_INTERFACE_DETAIL_DATA structure requirements. Reading the device path via readWideString(detail.asSlice(4)) correctly skips the cbSize field.

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 refactored AbstractPowerSource framework. 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 finally blocks
  • Battery tag validation before querying detailed information
  • Division-by-zero guard via maxCapacitySafe (line 206-207)
  • Date validation with range checks and DateTimeException catch (lines 252-258)
  • Handle leak fix: hBattery is closed in finally (line 292)

306-316: LGTM!

The batteryQueryString helper correctly returns Constants.UNKNOWN on 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 refactored AbstractPowerSource framework.

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant