Skip to content

PdhUtilFFM.getOpenFileDescriptors() fails on Windows, returns -1 #3151

Closed

Description

@dbwiddis

PdhUtilFFM.getOpenFileDescriptors() silently fails and returns -1 on Windows, while the JNA equivalent ProcessInformation.queryHandles() via perfmon) succeeds and returns a valid handle count (e.g. 46684).

The method catches all exceptions and logs at DEBUG level, so the root cause is hidden:

} catch (Throwable t) {
    LOG.debug("PDH getOpenFileDescriptors failed: {}", t.getMessage(), t);
    return -1;
}

Visual inspection of the code shows the JNA path is using the HANDLECOUNT enum from ProcessInformation:

Map<HandleCountProperty, List<Long>> valueListMap = ProcessInformation.queryHandles().getB();
List<Long> valueList = valueListMap.get(HandleCountProperty.HANDLECOUNT);

But you're querying Process instead:

checkSuccess(PdhAddEnglishCounter(query, toWideString(arena, "\\Process(*)\\Handle Count"),

In the JNA side, the enclosing class is intended to signal the appropriate counter instance. I see you refactored all the common callers into one class, which breaks that hint.

public enum HandleCountProperty implements PdhCounterWildcardProperty {

Activity

  1. coderabbitai commented on Apr 13, 2026

    @coderabbitai
    Contributor
    🔗 Related PRs

    #3126 - FFM migration of WindowsOSProcess [merged]
    #3141 - Split WindowsOSProcess into superclass with JNA/FFM subclasses [merged]
    #3154 - Improve API documentation [merged]


    📝 Issue Planner

    Check the box below or use the @coderabbitai plan command to generate an implementation plan and prompts that you can use with your favorite coding assistant.

    • Create Plan

    🧪 Issue enrichment is currently in open beta.

    To disable automatic issue enrichment, add the following to your .coderabbit.yaml:

    issue_enrichment:
      auto_enrich:
        enabled: false

    💬 Have feedback or questions? Drop into our discord!

  2. coderabbitai commented on Apr 13, 2026

    @coderabbitai
    Contributor

    Coding Plan

    Summary

    • Change the FFM PDH query from wildcard \Process(*)\Handle Count to direct \Process(_Total)\Handle Count to match the working JNA implementation pattern
    • Simplify result parsing since the response will contain a single aggregate value instead of thousands of process instances
    • Document the design convention issue where the FFM refactoring lost the semantic hint from class naming (e.g., ProcessInformation → "Process" counter category)
    • Evaluate feasibility of moving counter enums to oshi-common to prevent future divergence between implementations
    Design Choices
    Design Choice 1: Root cause is the wildcard query approach

    Options Considered:

    1. Change FFM to query _Total directly instead of wildcard * - simpler approach matching JNA pattern
    2. Debug and fix the existing wildcard query logic - maintains current approach but more complex to diagnose
    3. Add new PdhGetFormattedCounterValue binding for single-value queries - additional FFM work required

    Chosen Option: 1

    Rationale: Query _Total directly. This aligns with the proven JNA implementation, is simpler (no iteration over all processes), more efficient, and avoids the problematic wildcard query entirely.

    Design Choice 2: Design convention for PDH counter class naming

    Options Considered:

    1. Create separate FFM driver classes mirroring JNA pattern (e.g., ProcessInformationFFM) - maintains design convention but adds complexity
    2. Keep consolidated PdhUtilFFM but ensure counter paths are correct - simpler but loses design hint
    3. Move counter definitions to shared oshi-common module - addresses both implementations

    Chosen Option: 2

    Rationale: Option 2 for the immediate fix (correct the counter path in PdhUtilFFM), with Option 3 evaluated as a follow-on improvement to prevent similar issues.

    💡 User Tips

    Regenerate the plan with different choices with @coderabbitai <feedback>.

    Implementation Steps

    Phase 1: Fix PDH Counter Query in PdhUtilFFM

    Align the FFM implementation with the working JNA approach by changing from a wildcard query to directly querying the _Total aggregate instance.

    Update PDH Counter Path to Query _Total Instance

    Change the PDH counter path from wildcard to aggregate total and simplify the result processing logic.

    • Modify oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java in getOpenFileDescriptors():
      • Change the counter path from \\Process(*)\\Handle Count to \\Process(_Total)\\Handle Count
      • This matches the JNA implementation pattern which queries the pre-aggregated _Total instance
    • Update the result parsing logic:
      • The array result should now contain exactly one element (the _Total instance)
      • Remove the loop that iterates over all instances and manually skips _Total
      • Directly extract and return the single handle count value from the array
    • Maintain the existing error handling and return -1 on failure pattern
    • Keep using PdhGetFormattedCounterArray (still works for single-element results, no new bindings needed)
    🤖 Prompt for AI agents
    Fix the `getOpenFileDescriptors()` method in `PdhUtilFFM.java` to align with the
    working JNA implementation by querying the pre-aggregated `_Total` PDH counter
    instance instead of a wildcard.
    
    - In
    `oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java`,
    update `getOpenFileDescriptors()`:
    - Change the PDH counter path from `\\Process(*)\\Handle Count` to
    `\\Process(_Total)\\Handle Count`
      - Remove the loop that iterates over all process instances and skips `_Total`
    - Since the result array will now contain exactly one element, directly extract
    and return that single handle count value
      - Preserve the existing error handling pattern (return -1 on failure)
    - Continue using `PdhGetFormattedCounterArray` — no new FFM bindings are needed,
    as it works for single-element results
    

    Phase 2: Evaluate Shared Counter Definitions in oshi-common

    Assess feasibility of consolidating PDH counter enums and definitions into the shared oshi-common module to prevent divergence between JNA and FFM implementations.

    Task 1: Assess Architectural Feasibility

    Evaluate whether counter enum definitions can be moved to oshi-common without introducing issues.

    • Review dependency structure: oshi-common is already a dependency of both oshi-core and oshi-core-java25, with no circular dependencies
    • Verify oshi-common constraints: The module enforces no JNA/FFM APIs via native-forbidden-apis.txt, so only pure Java enum/constant definitions can be added
    • Identify candidate enums from oshi-core/src/main/java/oshi/driver/windows/perfmon/:
      • ProcessInformation.HandleCountProperty - defines HANDLECOUNT("Handle Count") counter
      • Other *Information classes with counter enums (e.g., ProcessorInformation, MemoryInformation)
    • Note: PerfmonConstants.java already exists in oshi-common with base constants (PROCESS, MEMORY, etc.) - enums could extend this pattern
    • Document findings as recommendations for future work (not implementing in this ticket)
    Task 2: Document Design Convention

    Add documentation explaining the PDH counter class naming convention to prevent future divergence.

    • In oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java:
      • Add Javadoc comments explaining which PDH counter category each method targets
      • Reference the corresponding JNA driver class for the counter definitions (e.g., ProcessInformation.HandleCountProperty)
    • Consider adding a code comment explaining the _Total instance convention for aggregate counters
    🤖 Prompt for AI agents
    This phase is assessment and documentation only — no functional code changes are
    required.
    
    - Review the dependency structure between `oshi-common`, `oshi-core`, and
    `oshi-core-java25` to confirm no circular dependencies would result from moving
    counter enums to `oshi-common`
    - Review `oshi-common`'s `native-forbidden-apis.txt` to confirm only pure Java
    enum/constant definitions can be added
    - Identify candidate enums in
    `oshi-core/src/main/java/oshi/driver/windows/perfmon/` (e.g.,
    `ProcessInformation.HandleCountProperty`, `ProcessorInformation`,
    `MemoryInformation`) and note how `PerfmonConstants.java` in `oshi-common` could
    be extended
    - Document findings as recommendations for future work (do not implement the
    migration in this ticket)
    - In
    `oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java`, add
    Javadoc comments to each relevant method specifying which PDH counter category
    it targets, referencing the corresponding JNA driver class (e.g.,
    `ProcessInformation.HandleCountProperty`)
    - Add a code comment explaining the `_Total` instance convention for aggregate
    counters
    

    Phase 3: Follow-on Considerations (Documentation Only)

    Document recommended improvements for future work, not to be implemented in this ticket.

    Note Error Diagnostics Improvements

    Document recommendations for better error handling and logging.

    • Current issue: All exceptions are caught and logged at DEBUG level, hiding root cause
    • Recommended improvements for future consideration:
      • Log at WARN level on first failure, DEBUG for subsequent (to surface issues without log spam)
      • Include the specific PDH error code in log messages for easier diagnosis
      • Consider adding a configuration option to control fallback behavior (similar to OSHI_OS_WINDOWS_PERFPROC_DISABLED)
    • Add a code comment or TODO in PdhUtilFFM.java noting this as a potential improvement area
    🤖 Prompt for AI agents
    This phase is documentation only — add a TODO comment in `PdhUtilFFM.java`
    noting future error diagnostics improvements, without changing any functional
    logic.
    
    - In
    `oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java`, add
    a TODO comment in or near the exception handling block noting:
    - Current behavior: all exceptions are caught and logged at DEBUG level, which
    hides root cause
    - Suggested future improvements: log at WARN on first failure and DEBUG for
    subsequent failures; include the specific PDH error code in log messages;
    consider a configuration option to control fallback behavior (similar to
    `OSHI_OS_WINDOWS_PERFPROC_DISABLED`)
    - Do not change any functional error handling logic in this phase
    
    Research

    The OSHI project has two parallel Windows implementations: the JNA-based module (oshi-core) and the FFM-based module (oshi-core-java25). For handle count queries, the JNA implementation in WindowsFileSystem.java delegates to ProcessInformation.queryHandles() which queries the pre-aggregated \Process(_Total)\Handle Count PDH counter directly. The FFM implementation in PdhUtilFFM.java instead uses a wildcard query \Process(*)\Handle Count to get all process instances and manually sums them while skipping _Total. The FFM PDH bindings in PdhFFM.java provide PdhGetFormattedCounterArrayW for array-style queries. Notably, oshi-common already contains PerfmonConstants.java with shared PDH counter object names (e.g., PROCESS = "Process") and WMI fallback class names, which both modules can reference.


    🚀 Next Steps

    🤖 All AI agent prompts combined
    Task: 1
    
    Fix the `getOpenFileDescriptors()` method in `PdhUtilFFM.java` to align with the
    working JNA implementation by querying the pre-aggregated `_Total` PDH counter
    instance instead of a wildcard.
    
    - In
    `oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java`,
    update `getOpenFileDescriptors()`:
    - Change the PDH counter path from `\\Process(*)\\Handle Count` to
    `\\Process(_Total)\\Handle Count`
      - Remove the loop that iterates over all process instances and skips `_Total`
    - Since the result array will now contain exactly one element, directly extract
    and return that single handle count value
      - Preserve the existing error handling pattern (return -1 on failure)
    - Continue using `PdhGetFormattedCounterArray` — no new FFM bindings are needed,
    as it works for single-element results
    ===============================================================================
    
    Task: 2
    
    This phase is assessment and documentation only — no functional code changes are
    required.
    
    - Review the dependency structure between `oshi-common`, `oshi-core`, and
    `oshi-core-java25` to confirm no circular dependencies would result from moving
    counter enums to `oshi-common`
    - Review `oshi-common`'s `native-forbidden-apis.txt` to confirm only pure Java
    enum/constant definitions can be added
    - Identify candidate enums in
    `oshi-core/src/main/java/oshi/driver/windows/perfmon/` (e.g.,
    `ProcessInformation.HandleCountProperty`, `ProcessorInformation`,
    `MemoryInformation`) and note how `PerfmonConstants.java` in `oshi-common` could
    be extended
    - Document findings as recommendations for future work (do not implement the
    migration in this ticket)
    - In
    `oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java`, add
    Javadoc comments to each relevant method specifying which PDH counter category
    it targets, referencing the corresponding JNA driver class (e.g.,
    `ProcessInformation.HandleCountProperty`)
    - Add a code comment explaining the `_Total` instance convention for aggregate
    counters
    ===============================================================================
    
    Task: 3
    
    This phase is documentation only — add a TODO comment in `PdhUtilFFM.java`
    noting future error diagnostics improvements, without changing any functional
    logic.
    
    - In
    `oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java`, add
    a TODO comment in or near the exception handling block noting:
    - Current behavior: all exceptions are caught and logged at DEBUG level, which
    hides root cause
    - Suggested future improvements: log at WARN on first failure and DEBUG for
    subsequent failures; include the specific PDH error code in log messages;
    consider a configuration option to control fallback behavior (similar to
    `OSHI_OS_WINDOWS_PERFPROC_DISABLED`)
    - Do not change any functional error handling logic in this phase
    
    💡 Iterate on the plan with: @coderabbitai <feedback>
    Example Feedback
    - @coderabbitai You can skip phase 3. Add a simple unit test case for phase 2.
    - @coderabbitai For design choice 1 go ahead with option 3 and replan.
    

    💬 Have feedback or questions? Drop into our discord!

  3. dbwiddis commented on Apr 14, 2026

    @dbwiddis
    MemberAuthor

    @coderabbitai In your plan, also note the use of ProcessInformation as the counter name. Evaluate the feasibility of moving the counter enums and WMI query patterns to the oshi-common module so both FFM and JNA implementations can access them.

  4. coderabbitai commented on Apr 14, 2026

    @coderabbitai
    Contributor

    I've updated the plan above based on your feedback. Ready to proceed when you are!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions